From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mp1 ([2001:41d0:2:4a6f::]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)) by ms11 with LMTPS id 4CLkBPKZwl8vDAAA0tVLHw (envelope-from ) for ; Sat, 28 Nov 2020 18:41:54 +0000 Received: from aspmx1.migadu.com ([2001:41d0:2:4a6f::]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)) by mp1 with LMTPS id yE6iAPKZwl8yIAAAbx9fmQ (envelope-from ) for ; Sat, 28 Nov 2020 18:41:54 +0000 Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by aspmx1.migadu.com (Postfix) with ESMTPS id 4D4DA94011A for ; Sat, 28 Nov 2020 18:41:50 +0000 (UTC) Received: from localhost ([::1]:43702 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1kj5AK-0005Wf-2G for larch@yhetil.org; Sat, 28 Nov 2020 13:41:49 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]:51884) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kj56i-0005WN-Pe for guix-patches@gnu.org; Sat, 28 Nov 2020 13:38:05 -0500 Received: from debbugs.gnu.org ([209.51.188.43]:37475) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1kj56i-0003Q7-7f for guix-patches@gnu.org; Sat, 28 Nov 2020 13:38:04 -0500 Received: from Debian-debbugs by debbugs.gnu.org with local (Exim 4.84_2) (envelope-from ) id 1kj56h-0006Y2-Pf for guix-patches@gnu.org; Sat, 28 Nov 2020 13:38:04 -0500 X-Loop: help-debbugs@gnu.org Subject: [bug#44926] [WIP] Add dart-2.8.4 Resent-From: =?UTF-8?Q?Nicol=C3=B2?= Balzarotti Original-Sender: "Debbugs-submit" Resent-CC: guix-patches@gnu.org Resent-Date: Sat, 28 Nov 2020 18:38:01 +0000 Resent-Message-ID: Resent-Sender: help-debbugs@gnu.org X-GNU-PR-Message: report 44926 X-GNU-PR-Package: guix-patches X-GNU-PR-Keywords: To: 44926@debbugs.gnu.org X-Debbugs-Original-To: guix-patches@gnu.org Received: via spool by submit@debbugs.gnu.org id=B.160658863725114 (code B ref -1); Sat, 28 Nov 2020 18:38:01 +0000 Received: (at submit) by debbugs.gnu.org; 28 Nov 2020 18:37:17 +0000 Received: from localhost ([127.0.0.1]:49022 helo=debbugs.gnu.org) by debbugs.gnu.org with esmtp (Exim 4.84_2) (envelope-from ) id 1kj55w-0006X0-Jg for submit@debbugs.gnu.org; Sat, 28 Nov 2020 13:37:17 -0500 Received: from lists.gnu.org ([209.51.188.17]:50882) by debbugs.gnu.org with esmtp (Exim 4.84_2) (envelope-from ) id 1kj4gU-0005uQ-7w for submit@debbugs.gnu.org; Sat, 28 Nov 2020 13:10:58 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]:48348) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kj4gT-0004DN-FZ for guix-patches@gnu.org; Sat, 28 Nov 2020 13:10:58 -0500 Received: from mail-wr1-x42c.google.com ([2a00:1450:4864:20::42c]:38620) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1kj4g0-000312-4s for guix-patches@gnu.org; Sat, 28 Nov 2020 13:10:57 -0500 Received: by mail-wr1-x42c.google.com with SMTP id p8so9144721wrx.5 for ; Sat, 28 Nov 2020 10:10:27 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:subject:date:message-id:mime-version; bh=PoEbjrr42XTPa7Q2KfVA8zFCmTUQCIe0TkD+jxPzgwA=; b=sOLBrvrixhsa0Jb0R2gwZo2vnqzwHTU+7fxAun8R4It2k8Wr9K+FzAwt6Hzt9BKA54 ZASqIPjKFc2lh819mgwDEZLU34abn5toQJ0bObt9xV/Yuj6blPCqcntlDozcFU+ZsTM6 H/TiBHtRPaAQiov6NSFNUt2DgovZQUTDRMD3AuXLwLg4d2kyCB8VTqia9sta1C1LJzGk k4rlE2L4liIW1Y6X7Ud5L8ztl/8oR8QrMFeeM9dnWQNI7GZwE7WdgPPgzok+x7J9JhLF R1cSrswfhM6Bukqo1PsS41KwvNwOe/3ru2pyYQGEcjPfNCpqko8efEFSodhFKzMciE5n OQwg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:subject:date:message-id:mime-version; bh=PoEbjrr42XTPa7Q2KfVA8zFCmTUQCIe0TkD+jxPzgwA=; b=EjitL30bDLE9FzHNl12oRZywQ5P2svDrYl8NFBCmRfSfB1TdYeMl7jY727AKnmMli2 Gj14X2xsWmNSLhPpL+OYcqkMZH6mptmB+nRD1Hde7lWCFT2NQsrzRpOJkrakJhde/XNN mWsE5azVrsKDrpEUbxYHybIhC60yhLyZ2dwVgcTQiguyJ8wBC3VPswQWDsT48t8wr/+/ c82hH0f9XrhMzHc86Xpw+D7YB3QlW9ie27kUccbCNtikri1EOa5ME1/c62xcS6E5XbDT 1o7mVaXzLs7B+73Yfp1N9ofegcfG71213EwM0GPAKwjLCwfQdJ1mjj6yxwjVf6K4cn1T oyOQ== X-Gm-Message-State: AOAM530f54X1SOx5DfdWsr55EouUyrI2FxzpBeeLmLjeDTM6xRaTaoYu 48+JIAadGocv1phvKroZBgRKbPcfk0s= X-Google-Smtp-Source: ABdhPJwz1nHhzMM2LOsG2Nlp3JvbNuO0qJJAmoBOL1BxNo8DLEXIPt6dm5/5Gv4eahsqJRlJWcGz+Q== X-Received: by 2002:a5d:528a:: with SMTP id c10mr16621651wrv.270.1606587025001; Sat, 28 Nov 2020 10:10:25 -0800 (PST) Received: from guixSD (host-79-54-131-134.retail.telecomitalia.it. [79.54.131.134]) by smtp.gmail.com with ESMTPSA id 90sm21059576wrl.60.2020.11.28.10.10.13 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 28 Nov 2020 10:10:20 -0800 (PST) From: =?UTF-8?Q?Nicol=C3=B2?= Balzarotti Date: Sat, 28 Nov 2020 19:10:09 +0100 Message-ID: <87lfelqrni.fsf@guixSD.i-did-not-set--mail-host-address--so-tickle-me> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="=-=-=" Received-SPF: pass client-ip=2a00:1450:4864:20::42c; envelope-from=anothersms@gmail.com; helo=mail-wr1-x42c.google.com X-Mailman-Approved-At: Sat, 28 Nov 2020 13:37:13 -0500 X-BeenThere: debbugs-submit@debbugs.gnu.org X-Mailman-Version: 2.1.18 Precedence: list X-BeenThere: guix-patches@gnu.org List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: guix-patches-bounces+larch=yhetil.org@gnu.org Sender: "Guix-patches" X-Migadu-Flow: FLOW_IN X-Migadu-Spam-Score: -1.17 X-Scanner: ns3122888.ip-94-23-21.eu Authentication-Results: aspmx1.migadu.com; dkim=fail (headers rsa verify failed) header.d=gmail.com header.s=20161025 header.b=sOLBrvri; dmarc=fail reason="SPF not aligned (relaxed)" header.from=gmail.com (policy=none); spf=pass (aspmx1.migadu.com: domain of guix-patches-bounces@gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=guix-patches-bounces@gnu.org X-TUID: zg/uVe5E9DS/ --=-=-= Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable Hi Guix! As announced on guix-devel, I bootstrapped the dart compiler from source. Following patches add dart 2.8.4 (latest release is 2.10, but I wanted to be sure that this work in progress is fine before continuing, as I fear that 4 other steps are required). NOTE: I tagged this as WIP as I've not yet disabled analytics yet (I disabled it from the first added version, but I was wondering if I need to disable it in _each_ version or if just the latest one is fine. Patching all of them will require some time). (Each build takes ~20min on my server and ~60min on my laptop, and there's a dozen of them) Let me know if there are major problems or if I can go on with disabling analytics! Thanks, Nicol=C3=B2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0001-gnu-Add-gn-for-dart-bootstrap.patch >From 1bfa60adabdf7f43b4918ada556fc6981bca07ba Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 14:38:19 +0100 Subject: [PATCH 01/20] gnu: Add gn-for-dart-bootstrap. * gnu/packages/build-tools.scm (gn-for-dart-bootstrap): New variable. --- gnu/packages/build-tools.scm | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/gnu/packages/build-tools.scm b/gnu/packages/build-tools.scm index 3f140efdb3..c58e47dc98 100644 --- a/gnu/packages/build-tools.scm +++ b/gnu/packages/build-tools.scm @@ -177,6 +177,44 @@ files and generates build instructions for the Ninja build system.") ;; X11 license. (license (list license:bsd-3 license:x11))))) +(define-public gn-for-dart-bootstrap + (let ((commit "041ed5e79abc24956f296ca8bc94d04e26cf3d6b") + (revision "1353") + (hash "1zd41zwggamkqy33cra75cfdx82v3spdfym6hj1lbbanabi4mpl7")) + (package + (inherit gn) + (name "gn-for-dart-bootstrap") + (version (git-version "0.0" revision commit)) + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://gn.googlesource.com/gn") + (commit commit))) + (sha256 (base32 hash)) + (file-name (git-file-name name version)))) + (arguments + `(#:tests? #f ;FIXME: How to run? + #:phases (modify-phases %standard-phases + (add-before 'configure 'set-build-environment + (lambda _ + (setenv "CC" "gcc") + (setenv "CXX" "g++") + (setenv "AR" "ar") + #t)) + (replace 'configure + (lambda _ + (invoke "python" "build/gen.py"))) + (replace 'build + (lambda _ + (invoke "ninja" "-C" "out" "gn"))) + (replace 'install + (lambda* (#:key outputs #:allow-other-keys) + (let ((out (assoc-ref outputs "out"))) + (install-file "out/gn" + (string-append out "/bin")) + #t))))))))) + (define-public meson (package (name "meson") -- 2.29.2 --=-=-= Content-Type: text/x-patch; charset=utf-8 Content-Disposition: attachment; filename=0002-gnu-packages-dart.scm-New-file.patch Content-Transfer-Encoding: quoted-printable >From 7c238e089eaeec82cada98f0b7f21698cdbba8b3 Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 14:53:19 +0100 Subject: [PATCH 02/20] gnu: packages: dart.scm: New file. gnu/local.mk: Add it. gnu/packages/dart.scm (dart-pkg): New function. --- gnu/local.mk | 1 + gnu/packages/dart.scm | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 gnu/packages/dart.scm diff --git a/gnu/local.mk b/gnu/local.mk index 14b626c600..359015415c 100644 --- a/gnu/local.mk +++ b/gnu/local.mk @@ -156,6 +156,7 @@ GNU_SYSTEM_MODULES =3D \ %D%/packages/cvassistant.scm \ %D%/packages/cybersecurity.scm \ %D%/packages/cyrus-sasl.scm \ + %D%/packages/dart.scm \ %D%/packages/databases.scm \ %D%/packages/datamash.scm \ %D%/packages/datastructures.scm \ diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm new file mode 100644 index 0000000000..8175998c49 --- /dev/null +++ b/gnu/packages/dart.scm @@ -0,0 +1,41 @@ +;;; GNU Guix --- Functional package management for GNU +;;; Copyright =C2=A9 2020 Nicol=C3=B2 Balzarotti +;;; +;;; This file is part of GNU Guix. +;;; +;;; GNU Guix is free software; you can redistribute it and/or modify it +;;; under the terms of the GNU General Public License as published by +;;; the Free Software Foundation; either version 3 of the License, or (at +;;; your option) any later version. +;;; +;;; GNU Guix is distributed in the hope that it will be useful, but +;;; WITHOUT ANY WARRANTY; without even the implied warranty of +;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;;; GNU General Public License for more details. +;;; +;;; You should have received a copy of the GNU General Public License +;;; along with GNU Guix. If not, see . + +(define-module (gnu packages dart) + #:use-module ((guix licenses) #:prefix license:) + #:use-module (guix build utils) + #:use-module (guix git-download) + #:use-module (guix packages) + #:use-module (guix utils)) + +(define (dart-pkg name tag hash) + (origin + (method git-fetch) + (uri (git-reference + (url (string-append + "https://github.com/dart-lang/" + (string-replace-substring name "-" "_") + ".git")) + (commit tag))) + (file-name + (git-file-name name + (if (> (string-length tag) 9) + (string-take tag 9) + tag))) + (sha256 (base32 hash)))) + --=20 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0003-gnu-dart-Add-dart-zlib.patch >From 32f70481ffce47d67a689c9ab9caf5891de994de Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 15:01:31 +0100 Subject: [PATCH 03/20] gnu: dart: Add dart-zlib. * gnu/packages/dart.scm (dart-zlib): New variable. --- gnu/packages/dart.scm | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 8175998c49..033a5f6bab 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -39,3 +39,13 @@ tag))) (sha256 (base32 hash)))) +(define dart-zlib + (let ((version "c3d0a6190f2f8c924a05ab6cc97b8f975bddd33f") + (hash "0fr3h9krramy0jclbacjnwbn0lzvjm6b809llhaz56mbd90i4yl4")) + (origin + (method git-fetch) + (uri (git-reference + (url "https://chromium.googlesource.com/chromium/src/third_party/zlib.git") + (commit version))) + (sha256 (base32 hash))))) + -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0004-gnu-packages-Add-dart-boringssl.patch >From 4fb1ceee8e18bea6ff7c32fc50e81d56f582b6f9 Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 15:03:35 +0100 Subject: [PATCH 04/20] gnu: packages: Add dart-boringssl. * gnu/packages/dart.scm (dart-boringssl): New variable. --- gnu/packages/dart.scm | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 033a5f6bab..cfafda44f5 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -49,3 +49,13 @@ (commit version))) (sha256 (base32 hash))))) +(define dart-boringssl + (let ((version "d519bf6be0b447fb80fbc539d4bff4479b5482a2") + (hash "137q647ha8x770wv3jj2kgjv3lj9qjcv191m51vkp3a7zqhhaknv")) + (origin + (method git-fetch) + (uri (git-reference + (url "https://boringssl.googlesource.com/boringssl") + (commit version))) + (sha256 (base32 hash))))) + -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0005-gnu-packages-Add-boringssl-gen.patch >From 5de7a8e93e176b3c44c08e707170c06680fb6ed2 Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 15:04:42 +0100 Subject: [PATCH 05/20] gnu: packages: Add boringssl-gen. * gnu/packages/dart.scm (boringssl-gen): New variable. --- gnu/packages/dart.scm | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index cfafda44f5..d5124ce700 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -59,3 +59,13 @@ (commit version))) (sha256 (base32 hash))))) +(define boringssl-gen + (let ((version "d2b56d1b7657e52eb5a1f075968c773aa3e53614") + (hash "1pn2hn0i9fwd27i695q4av3bymm11pmydlbv4hcafslhggq0md19")) + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/boringssl_gen") + (commit version))) + (sha256 (base32 hash))))) + -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0006-gnu-dart-Add-dart-gperftools.patch >From a47d45923567ab4a4b5bc8bba792b9516cbfdf90 Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 15:06:15 +0100 Subject: [PATCH 06/20] gnu: dart: Add dart-gperftools. * gnu/packages/dart.scm (dart-gperftools): New variable. --- gnu/packages/dart.scm | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index d5124ce700..03adf23d63 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -69,3 +69,14 @@ (commit version))) (sha256 (base32 hash))))) +;; TODO: should I take the src from the real gperftools and override the version? +(define dart-gperftools + (let ((version "02eeed29df112728564a5dde6417fa4622b57a06") + (hash "1j5yx7v1g8ljzv5hs2452q736gdf1xm5x9w5d1csm5bjlryxaykm")) + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/gperftools/gperftools.git") + (commit version))) + (sha256 (base32 hash))))) + -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0007-gnu-dart-Add-root-certificates.patch >From 55f0a0f5834edb075e3af79713bf5b73532f505e Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 15:08:26 +0100 Subject: [PATCH 07/20] gnu: dart: Add root-certificates. * gnu/packages/dart.scm (root-certificates): New function. --- gnu/packages/dart.scm | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 03adf23d63..53c108f1f0 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -80,3 +80,11 @@ (commit version))) (sha256 (base32 hash))))) +(define (root-certificates version hash) + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/root_certificates.git") + (commit version))) + (sha256 (base32 hash)))) + -- 2.29.2 --=-=-= Content-Type: text/x-patch; charset=utf-8 Content-Disposition: attachment; filename=0008-gnu-Add-dart-2.0.0-dev.8.0.patch Content-Transfer-Encoding: quoted-printable >From 2065bdfa84d2b08010f98dedc569b095cf7a728d Mon Sep 17 00:00:00 2001 From: nixo Date: Tue, 24 Nov 2020 16:23:06 +0100 Subject: [PATCH 08/20] gnu: Add dart-2.0.0-dev.8.0. * gnu/packages/dart.scm (dart-2.0.0-dev.8.0): New variable. * gnu/packages/patches (dart-2.0.0-dev.8-disable-analytics.patch): New file. * gnu/local.mk: Add it. --- gnu/local.mk | 1 + gnu/packages/dart.scm | 419 +- .../dart-2.0.0-dev.8-disable-analytics.patch | 192411 +++++++++++++++ 3 files changed, 192810 insertions(+), 21 deletions(-) create mode 100644 gnu/packages/patches/dart-2.0.0-dev.8-disable-analytics= .patch diff --git a/gnu/local.mk b/gnu/local.mk index 359015415c..ee4ade0139 100644 --- a/gnu/local.mk +++ b/gnu/local.mk @@ -905,6 +905,7 @@ dist_patch_DATA =3D \ %D%/packages/patches/cursynth-wave-rand.patch \ %D%/packages/patches/cvs-CVE-2017-12836.patch \ %D%/packages/patches/cyrus-sasl-ac-try-run-fix.patch \ + %D%/packages/patches/dart-2.0.0-dev.8-disable-analytics.patch \ %D%/packages/patches/date-output-pkg-config-files.patch \ %D%/packages/patches/datefudge-gettimeofday.patch \ %D%/packages/patches/dbacl-include-locale.h.patch \ diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 53c108f1f0..4918f56d2c 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -18,20 +18,30 @@ =20 (define-module (gnu packages dart) #:use-module ((guix licenses) #:prefix license:) - #:use-module (guix build utils) + #:use-module (guix build-system gnu) #:use-module (guix git-download) #:use-module (guix packages) - #:use-module (guix utils)) + #:use-module (guix utils) + #:use-module (gnu packages) + #:use-module (gnu packages build-tools) + #:use-module (gnu packages gcc) + #:use-module (gnu packages golang) + #:use-module (gnu packages libunwind) + #:use-module (gnu packages ninja) + #:use-module (gnu packages nss) + #:use-module (gnu packages perl) + #:use-module (gnu packages python) + #:use-module (gnu packages python-xyz)) =20 (define (dart-pkg name tag hash) (origin (method git-fetch) (uri (git-reference - (url (string-append - "https://github.com/dart-lang/" - (string-replace-substring name "-" "_") - ".git")) - (commit tag))) + (url (string-append + "https://github.com/dart-lang/" + (string-replace-substring name "-" "_") + ".git")) + (commit tag))) (file-name (git-file-name name (if (> (string-length tag) 9) @@ -41,50 +51,417 @@ =20 (define dart-zlib (let ((version "c3d0a6190f2f8c924a05ab6cc97b8f975bddd33f") - (hash "0fr3h9krramy0jclbacjnwbn0lzvjm6b809llhaz56mbd90i4yl4")) + (hash "0fr3h9krramy0jclbacjnwbn0lzvjm6b809llhaz56mbd90i4yl4")) (origin (method git-fetch) (uri (git-reference - (url "https://chromium.googlesource.com/chromium/src/third_party/zlib= .git") - (commit version))) + (url "https://chromium.googlesource.com/chromium/src/third_par= ty/zlib.git") + (commit version))) (sha256 (base32 hash))))) =20 (define dart-boringssl (let ((version "d519bf6be0b447fb80fbc539d4bff4479b5482a2") - (hash "137q647ha8x770wv3jj2kgjv3lj9qjcv191m51vkp3a7zqhhaknv")) + (hash "137q647ha8x770wv3jj2kgjv3lj9qjcv191m51vkp3a7zqhhaknv")) (origin (method git-fetch) (uri (git-reference - (url "https://boringssl.googlesource.com/boringssl") - (commit version))) + (url "https://boringssl.googlesource.com/boringssl") + (commit version))) (sha256 (base32 hash))))) =20 (define boringssl-gen (let ((version "d2b56d1b7657e52eb5a1f075968c773aa3e53614") - (hash "1pn2hn0i9fwd27i695q4av3bymm11pmydlbv4hcafslhggq0md19")) + (hash "1pn2hn0i9fwd27i695q4av3bymm11pmydlbv4hcafslhggq0md19")) (origin (method git-fetch) (uri (git-reference - (url "https://github.com/dart-lang/boringssl_gen") - (commit version))) + (url "https://github.com/dart-lang/boringssl_gen") + (commit version))) (sha256 (base32 hash))))) =20 ;; TODO: should I take the src from the real gperftools and override the v= ersion? (define dart-gperftools (let ((version "02eeed29df112728564a5dde6417fa4622b57a06") - (hash "1j5yx7v1g8ljzv5hs2452q736gdf1xm5x9w5d1csm5bjlryxaykm")) + (hash "1j5yx7v1g8ljzv5hs2452q736gdf1xm5x9w5d1csm5bjlryxaykm")) (origin (method git-fetch) (uri (git-reference - (url "https://github.com/gperftools/gperftools.git") - (commit version))) + (url "https://github.com/gperftools/gperftools.git") + (commit version))) (sha256 (base32 hash))))) =20 (define (root-certificates version hash) (origin (method git-fetch) (uri (git-reference - (url "https://github.com/dart-lang/root_certificates.git") - (commit version))) + (url "https://github.com/dart-lang/root_certificates.git") + (commit version))) (sha256 (base32 hash)))) =20 +(define-public dart-2.0.0-dev.8.0 + (package + (name "dart") + (version "2.0.0-dev.8.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (file-name (string-append name "-" version)) + (sha256 + (base32 + "17870yvi4flcraw3ihs694g4r0fmmmj2qmz9n4r311pizxzagjkk")) + (modules '((guix build utils))) + ;; Delete a folder containing a pre-build windows .dll + (snippet + '(delete-file-recursively "build/win")) + (patches + (search-patches "dart-2.0.0-dev.8-disable-analytics.patch")))) + (arguments + `(#:configure-flags + ;; FIXME: Do not hardcode the target? Don't know if when fixed this + ;; package will work on other targets + (list "host_cpu=3D\"x64\"" + "target_cpu=3D\"x64\"" + "dart_target_arch=3D\"x64\"" + "target_os=3D\"linux\"" + "dart_runtime_mode=3D\"develop\"" + "dart_debug=3Dfalse" + "is_debug=3Dfalse" + "is_release=3Dtrue" + "is_product=3Dfalse" + "is_clang=3Dfalse" + "use_goma=3Dfalse" + "goma_dir=3D\"None\"" + "dart_use_tcmalloc=3Dtrue" + "dart_use_fallback_root_certificates=3Dtrue" + "dart_zlib_path =3D \"//runtime/bin/zlib\"" + "dart_platform_sdk=3Dfalse" + "is_asan=3Dfalse" + "is_msan=3Dfalse" + "is_tsan=3Dfalse" + "dart_snapshot_kind=3D\"app-jit\"") + #:phases + (modify-phases %standard-phases + ;; no check target. Tests are available, but I should check how = to + ;; run them + (delete 'check) + (add-before 'configure 'add-git-revision + (lambda _ + (with-output-to-file "tools/GIT_REVISION" + (lambda () (display "0"))))) + (add-before 'configure 'add-third-party-src + ;; Copy some deps to third_party, as required by the build syst= em + ;; TODO: LINK THEM INSTEAD OF COPYING + (lambda* (#:key inputs #:allow-other-keys) + (use-modules (ice-9 regex) (ice-9 match)) + ;; place pkg inputs in the right third_party folder + ;; (either pkg or pkgtested) based on their input name + (define (dart-copy-deps-to-third-party-dir pkgdep) + (copy-recursively + (assoc-ref inputs pkgdep) + (let* ((out "third_party/") + (text + (if (string-match "pkgtested" pkgdep) + (string-append out "pkg_tested/" + (regexp-substitute + #f + (string-match "dart-pkgtested-= " pkgdep) + 'post)) + (string-append out "pkg/" + (regexp-substitute + #f + (string-match "dart-pkg-" pkgd= ep) + 'post))))) + (if (string-match "-" text) + (regexp-substitute/global + #f "-" text 'pre "_" 'post) + text)))) + (map (lambda (input) + (let ((pkg (car input))) + ;; Copy only dependencies starting with "dart-" + (when (string-match "dart-" pkg) + (dart-copy-deps-to-third-party-dir pkg)))) + inputs) + ;; Do the same for other required packages + (copy-recursively (assoc-ref inputs "boringssl") + "third_party/boringssl/src") + (copy-recursively (assoc-ref inputs "gperftools") + "third_party/tcmalloc/gperftools") + (copy-recursively (assoc-ref inputs "root-certificates") + "third_party/root_certificates") + (copy-recursively (assoc-ref inputs "zlib") + "third_party/zlib") + (copy-recursively (assoc-ref inputs "observatory-pub-packages= ") + "third_party/observatory_pub_packages"))) + (add-after 'add-third-party-src 'generate-third-party-build-files + (lambda* (#:key inputs #:allow-other-keys) + (with-directory-excursion "third_party/boringssl" + ;; go requires home to be set + (setenv "HOME" "/tmp/") + (invoke (string-append (assoc-ref inputs "python") "/bin/py= thon2") + "src/util/generate_build_files.py" "gn") + (map (lambda (file) + (copy-file + (string-append (assoc-ref inputs "boringssl-gen") "= /" file) + file)) + '("BUILD.gn" "BUILD.generated.gni"))))) + (add-before 'configure 'enable-dtags + ;; adds the RUNPATH + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "build/config/gcc/BUILD.gn" + (("disable-new-dtags") "enable-new-dtags")))) + (replace 'configure + (lambda* (#:key configure-flags #:allow-other-keys) + (let ((args (string-join configure-flags " "))) + (mkdir "out") + ;; Generate ninja build files. + (invoke "gn" "gen" "out/Release" + (string-append "--args=3D" args)) + ;; Print the full list of supported arguments as well as + ;; their current status for convenience. + (format #t "Dumping configure flags...\n") + (invoke "gn" "args" "out/Release" "--list")))) + (replace 'build + (lambda* (#:key configure-flags #:allow-other-keys) + (invoke "ninja" "all" "-C" "out/Release"))) + ;; no install phase + (replace 'install + (lambda* (#:key outputs #:allow-other-keys) + (let ((out (assoc-ref outputs "out"))) + ;; This should depend on the architecture as before + (copy-recursively "out/Release/dart-sdk/" out))))))) + (inputs + `(("zlib" ,dart-zlib) + ("libunwind" ,libunwind) + ("nspr" ,nspr) + ("nss" ,nss) + ("boringssl" ,dart-boringssl) + ("boringssl-gen" ,boringssl-gen) + ("gperftools" ,dart-gperftools) + ("root-certificates" + ,(root-certificates + "16ef64be64c7dfdff2b9f4b910726e635ccc519e" + "1kxadamhz03dlvm3j5xxqjgn0jasgskyjx11ysm3a431ma5j9182")) + ("observatory-pub-packages" + ,(dart-pkg "observatory-pub-packages" "4c282bb240b68f407c8c7779a65= c68eeb0139dc6" + "0p09r24q37i4hyz3n2j75lx9a252zr81jcynap61nfh415xlcv3z")) + ("dart-pkg-args" + ,(dart-pkg "args" "0.13.7" + "0y3f1kaplxmanw5gqm84l9wqx2nl1vrk11m8kdqqwc7n73fc4kdl")) + ("dart-pkg-async" + ,(dart-pkg "async" "2.0.0" + "1r0fqdh633426p2h9ynb126s58l30jj3mj0bzvjigbklam7vfjgc")) + ("dart-pkg-barback" + ,(dart-pkg "barback" "0.15.2+13" + "0n532b2as62nkzq7w9jaxk6gkl78il1kq3q0s1xgcdazmbzx5fb1")) + ("dart-pkg-bazel-worker" + ,(dart-pkg "bazel-worker" "v0.1.4" + "1cc4jvx9qba76ws2l7ijr8kvl8yydfak965gwrgb88f2r1qp2q46")) + ("dart-pkg-charcode" + ,(dart-pkg "charcode" "v1.1.1" + "0907828insqsr0ffyz4n2xns4qc77brnm7zv0a6965b53b84pk8b")) + ("dart-pkg-cli-util" + ,(dart-pkg "cli-util" "0.1.2+1" + "09nqdkyipnb0734ci554gxrl9cic528mlhfad9wibcg6kx7y6gra")) + ("dart-pkg-collection" + ,(dart-pkg "collection" "1.14.3" + "1rdgvrj67vj27k2052h5k31xc6rays4p4j27a122c1ikxnb4i3bh")) + ("dart-pkg-convert" + ,(dart-pkg "convert" "2.0.1" + "1v0b6vgzp6i37jja2d2aim6dmig8xfjhi8b553a1909n5pzqxp2g")) + ("dart-pkg-crypto" + ,(dart-pkg "crypto" "2.0.2+1" + "12v5rw189vrk2n2ryxkf8qcbdx8hf3bf33i552439lzhz0czkvcq")) + ("dart-pkg-csslib" + ,(dart-pkg "csslib" "0.14.1" + "0zlmbg6vwwc4cha8l2xv73klwzdqg6b43qmhlca0f62lr7k6014w")) + ("dart-pkg-dart2js-info" + ,(dart-pkg "dart2js_info" "0.5.5+1" + "05rdp96n9rxkjyw7lmn3a9hlbsaxpdn8wp8qnsfjmqv3i8vcypvj")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.13.0+3" + "1v85510bvjhllr00hgabvn737bh791x1m14qsv7zbxhqnsy2jafj")) + ("dart-pkg-fixnum" + ,(dart-pkg "fixnum" "0.10.5" + "01j7sj4mnkaxam1bpmhvlxl817dcck92xzpk66m7qbccm58c0giw")) + ("dart-pkg-func" + ,(dart-pkg "func" "25eec48146a58967d75330075ab376b3838b18a8" + "0xcfnca5sa5hc62g14xx11qqv9xjamsaqqn1cmldb917qnxb7lkk")) + ("dart-pkg-glob" + ,(dart-pkg "glob" "1.1.5" + "1lbd7lkxvw0q5zvz2hxvc035mxakmzcq08lwwr25v56s9ybavh93")) + ("dart-pkg-html" + ,(dart-pkg "html" "0.13.2" + "0w0gn8camhqhclmlf5g1mp03nssl2gyghqkmcz0zrvkicc1d5r1s")) + ("dart-pkg-http" + ,(dart-pkg "http" "0.11.3+14" + "1a1k8m2gp8a02q9bw40bqj7ad9yx44ap0w4xr7s26lridi7isylc")) + ("dart-pkg-http-multi-server" + ,(dart-pkg "http_multi_server" "2.0.4" + "09x4alr181p6s3zxqflgmhglglxr4aaaz6ys7pp0r715dq50qz4n")) + ("dart-pkg-http-parser" + ,(dart-pkg "http-parser" "3.1.1" + "18p8cqanxbxsxk3wwvisgb1bxdy83vkh3l11h0cys7gxrz6z2g12")) + ("dart-pkg-http-throttle" + ,(dart-pkg "http-throttle" "1.0.1" + "1q0pv1px5rd7zjd799pnq5zcr825ya1yqnxyvdr91rlga621hdbj")) + ("dart-pkg-intl" + ,(dart-pkg "intl" "0.15.2" + "0vd0a3pqmfs03kf12mmg0rrpian0f35ja0x332mr7cx8h9d7pmqx")) + ("dart-pkg-isolate" + ,(dart-pkg "isolate" "1.1.0" + "12m97zhm8qwpraf6nyvj1nawssygrwz0zka7843ayj3vxx6j34xr")) + ("dart-pkg-json-rpc-2" + ,(dart-pkg "json_rpc_2" "2.0.4" + "1q2x6gy7l7agr930k4r6vncfzjcnp43chq9fwxfa0p0nyccnixz3")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.39" + "0wfd6bzfny5bis3r2ygj89kyd2gl618x7hk06qp4h9nvbpsvvz0n")) + ("dart-pkg-logging" + ,(dart-pkg "logging" "0.11.3+1" + "180w376jz2wmfijcfg07ygfpc6i68i4zibw2421xvwcjhi0q07kv")) + ("dart-pkg-markdown" + ,(dart-pkg "markdown" "0.11.4" + "009qw47k3lrl2fkdn378l41dga493alspywrk3z93yy1pqaf1j5n")) + ("dart-pkg-matcher" + ,(dart-pkg "matcher" "0.12.1+4" + "1q0hbcc5ys5zpml7blsyj0d1f42w67vr6x19vxg34sra3bv0h2xx")) + ("dart-pkg-mime" + ,(dart-pkg "mime" "0.9.4" + "1bh4xla0qlaz9cm1qgxqq57l76b2zh5qqk9pax7sc57s79zi1nmz")) + ("dart-pkg-mockito" + ,(dart-pkg "mockito" "2.0.2" + "1q1zlv3fwfjbmwm141wj19vglx15s8xkqzdsqz9hhv6gg7h45gsl")) + ("dart-pkg-mustache4dart" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/valotas/mustache4dart.git") + (commit "v2.1.0"))) + (sha256 (base32 "0wsmg2xvpp2h9rqcg65icymh2s9hifq6v700mni65ky33d= ah9ji1")))) + ("dart-pkg-oauth2" + ,(dart-pkg "oauth2" "1.1.0" + "1519799j61sdka6p1n6ba768v5a8q4q9w6y957dzqigwaf19p9v5")) + ("dart-pkg-path" + ,(dart-pkg "path" "1.4.2" + "0ld39rpzla8wd4c2kx1kycdk66cwypklxki58nb18959j2749fbi")) + ("dart-pkg-plugin" + ,(dart-pkg "plugin" "0.2.0" + "10sgglzpwr9hkdhr6r4d1kvazv49zdhc9cr2asxdk5531347kk9m")) + ("dart-pkg-pool" + ,(dart-pkg "pool" "1.3.3" + "1cljnzsrbjgkif8rj1vxrzp5rz2xak265pasachdcg4yh2hl0y7d")) + ("dart-pkg-protobuf" + ,(dart-pkg "protobuf" "0.5.4" + "1wjb8da0da0gda0f83dl2dvl5w4a6gvq5xcg1yrgg3xjs7gzy8dd")) + ("dart-pkg-pub" + ,(dart-pkg "pub" "cde958f157d3662bf968bcbed05580d5c0355e89" + "1g1cw4c0811l3pvc80fvb7s04shzxvxrcb25195s7kjjfiivgqi4")) + ("dart-pkg-pub-semver" + ,(dart-pkg "pub-semver" "1.3.2" + "15s6zn2qyyfc5lf8ip5h8j3sq5miz4vrzxbgbwi5vv91d53miia8")) + ("dart-pkg-quiver" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/google/quiver-dart.git") + (commit "0.25.0"))) + (sha256 (base32 "02wqrk266s0ias9lfy7l5dh9ni2r697n3z42h4sgzxy7qg= 4rip24")))) + ("dart-pkg-resource" + ,(dart-pkg "resource" "af5a5bf65511943398146cf146e466e5f0b95cb9" + "1jq4bmg65jrpyqxcvbp87d5qqpgmv5ylfz3w1djzimq5jhr9k4vn")) + ("dart-pkg-scheduled-test" + ,(dart-pkg "scheduled-test" "0.12.11+1" + "1xk66f68m443yig5672p0dpack2c0kpkyk2d7f8iaq22q5zq7h1w")) + ("dart-pkg-shelf" + ,(dart-pkg "shelf" "0.6.8" + "0vl4m47yhjvc1nynyzc42bks4mzv877vsy7fbcv9w2fjh05sxhb9")) + ("dart-pkg-shelf-packages-handler" + ,(dart-pkg "shelf-packages-handler" "1.0.3" + "0iccfa713jyg7bb7fx144i5rl0afyfxvb3pi56igw2gdwklq4yck")) + ("dart-pkg-shelf-static" + ,(dart-pkg "shelf-static" "0.2.4" + "1gfyjqvv13d3zpnaahv5fi601ag7mr8crm94xawlvgvpqgpl0hsh")) + ("dart-pkg-shelf-web-socket" + ,(dart-pkg "shelf-web-socket" "0.2.1" + "18krh9bnbshwjjl47k15x9g3r7s5k0yichvn3gdsddjqjgp6vfp8")) + ("dart-pkg-source-map-stack-trace" + ,(dart-pkg "source-map-stack-trace" "1.1.4" + "1cpyq1vdfc623k8cdx673v2kkv112hzsrsyaxd8dd82v23caglva")) + ("dart-pkg-source-maps" + ,(dart-pkg "source-maps" "0.10.4" + "11dmncxgv8q40am73dxlxgzkfaanvgc9p3lds77m96mb1k27zbkf")) + ("dart-pkg-source-span" + ,(dart-pkg "source-span" "1.4.0" + "0gpa15p5rcilgl0paqa7f9fkiks7kyalzl2r0sd37m4cry9cf0vz")) + ("dart-pkg-stack-trace" + ,(dart-pkg "stack-trace" "1.8.2" + "0n21n2dv371bfcw6q83xwb8x26d1rd49cvx5qzm8mi0006h9frzs")) + ("dart-pkg-stream-channel" + ,(dart-pkg "stream-channel" "1.6.2" + "02ixi6vsja2cc22jcflp89v5wsbj45fl23p0sgaayqaj6l1jcxm1")) + ("dart-pkg-string-scanner" + ,(dart-pkg "string-scanner" "1.0.2" + "13hfnc704c9qipcvjinbv1hbq57hs5l2f68kyw282dlrcbbwwksy")) + ("dart-pkg-term-glyph" + ,(dart-pkg "term-glyph" "1.0.0" + "1nxqg345k2zh0yn498mxxdi7v1q3651z5invv0llfvs17ly2h2pz")) + ("dart-pkg-test" + ,(dart-pkg "test" "0.12.24+6" + "1xkmvwx30zm5ci1gn53hf6zrxymlq9cn9waa00k3ihxbd64mxg1k")) + ("dart-pkg-test-reflective-loader" + ,(dart-pkg "test-reflective-loader" "0.1.0" + "1qmbayg6js96lcy9s6grly1y6rh9x5mbyqygnr58zsdypzvhr4hr")) + ("dart-pkg-tuple" + ,(dart-pkg "tuple" "v1.0.1" + "0khkwq1blc90lgdcy4i8ng4nzppmhg31nziw4sc36axwbwdnpc86")) + ("dart-pkg-typed-data" + ,(dart-pkg "typed-data" "1.1.3" + "1zr9la34lib0rdfdf0539hdai2j71kf3s4ynsal7hw4pqvkdwi72")) + ("dart-pkg-unittest" + ,(dart-pkg "test" "0.11.7" + "1xbx2i2glmqlc3cz8x91anhf8d4hsr3bq9j53qliawz8j6q9anf8")) + ("dart-pkg-usage" + ,(dart-pkg "usage" "3.3.0" + "0r8d0q4ij42c7axclwns61cyrxpmk1qpggqfiqfm5vbmh8gpfm3b")) + ("dart-pkg-utf" + ,(dart-pkg "utf" "0.9.0+3" + "07jppjvg8bc8plzq910b8ld32l6x35i8qwy0mdqimydjjaslj78f")) + ("dart-pkg-watcher" + ,(dart-pkg "watcher" "0.9.7+4" + "09jpk98qb5j5250sr9r9ic17gj741yjy1p2j50zzl47a9wydfjly")) + ("dart-pkg-web-socket-channel" + ,(dart-pkg "web-socket-channel" "1.0.6" + "1phb2n3n6npzwl08nnp1aggcjmvwx516b816q4hsx8w190yr4f86")) + ("dart-pkg-yaml" + ,(dart-pkg "yaml" "2.1.12" + "0m2xr36vd2v3yirv1jb5v3dncsczn8n34s9fmqcm2ld979b4vanm")) + ("dart-pkgtested-dart-style" + ,(dart-pkg "dart-style" "1.0.7" + "0qym7z5n4w4jy75fnvcyza3hw0nrm8kli5mv65drr16f8pkr0lcg")) + ("dart-pkgtested-package-config" + ,(dart-pkg "package-config" "1.0.3" + "03w67nb1dhi2yqb63z1301p88hjws1d8azmw8m5ap4zapqdbhzgn")) + ("dart-pkgtested-package-resolver" + ,(dart-pkg "package-resolver" "1.0.2+1" + "0qs7zmxjwqqjkq6mqnz8b3rj142hyz1x0v1innh8n3bwmljgp3w9")= ))) + (native-inputs + `(("python" ,python-2) + ("python2-gyp" ,python2-gyp) + ("perl" ,perl) + ("go" ,go) + ("gn" ,gn-for-dart-bootstrap) + ("ninja" ,ninja) + ("gcc" ,gcc-6))) + (build-system gnu-build-system) + (home-page "https://dart.dev") + (synopsis "The Dart SDK, including the VM, dart2js and core libraries") + (description "Dart is a programming language which is: +@enumerate +@item Optimized for UI +@item Supports hot reload +@item Supported both on desktop and on mobile +@end") + (license license:bsd-3))) diff --git a/gnu/packages/patches/dart-2.0.0-dev.8-disable-analytics.patch = b/gnu/packages/patches/dart-2.0.0-dev.8-disable-analytics.patch new file mode 100644 index 0000000000..763e5503ea --- /dev/null +++ b/gnu/packages/patches/dart-2.0.0-dev.8-disable-analytics.patch @@ -0,0 +1,192411 @@ +From f9843f7af84da47141a2721972c7859cdddfa36f Mon Sep 17 00:00:00 2001 +From: nixo +Date: Tue, 24 Nov 2020 16:59:00 +0100 +Subject: [PATCH] disable analytics + +--- + BUILD.gn | 7 - + pkg/analysis_server/AUTHORS | 6 - + pkg/analysis_server/CHANGELOG.md | 5 - + pkg/analysis_server/CONTRIBUTING.md | 40 - + pkg/analysis_server/LICENSE | 26 - + pkg/analysis_server/README.md | 22 - + pkg/analysis_server/analysis_options.yaml | 8 - + pkg/analysis_server/benchmark/benchmarks.dart | 239 - + .../benchmark/integration/README.md | 69 - + .../benchmark/integration/driver.dart | 315 - + .../integration/input_converter.dart | 399 - + .../instrumentation_input_converter.dart | 146 - + .../benchmark/integration/local_runner.dart | 91 - + .../integration/log_file_input_converter.dart | 82 - + .../benchmark/integration/main.dart | 246 - + .../benchmark/integration/operation.dart | 236 - + .../benchmark/perf/analysis_timing_tests.dart | 161 - + .../benchmark/perf/benchmark_angular.dart | 115 - + .../benchmark/perf/benchmark_flutter.dart | 216 - + .../benchmark/perf/benchmark_scenario.dart | 310 - + .../benchmark/perf/benchmarks_impl.dart | 187 - + .../perf/completion_timing_tests.dart | 85 - + .../benchmark/perf/memory_tests.dart | 133 - + .../benchmark/perf/performance_tests.dart | 76 - + pkg/analysis_server/benchmark/readme.md | 35 - + pkg/analysis_server/bin/server.dart | 13 - + pkg/analysis_server/doc/api.html | 4725 ----- + .../occurrences/occurrences_core.dart | 17 - + .../lib/plugin/edit/assist/assist_core.dart | 90 - + .../lib/plugin/edit/assist/assist_dart.dart | 107 - + .../lib/plugin/edit/fix/fix_core.dart | 88 - + .../lib/plugin/edit/fix/fix_dart.dart | 73 - + .../lib/plugin/protocol/protocol_dart.dart | 216 - + .../lib/protocol/protocol.dart | 673 - + .../lib/protocol/protocol_constants.dart | 258 - + .../lib/protocol/protocol_generated.dart | 15802 ---------------- + .../lib/src/analysis_logger.dart | 55 - + .../lib/src/analysis_server.dart | 1557 -- + .../lib/src/channel/byte_stream_channel.dart | 175 - + .../lib/src/channel/channel.dart | 150 - + pkg/analysis_server/lib/src/collections.dart | 71 - + .../src/computer/computer_closingLabels.dart | 105 - + .../lib/src/computer/computer_highlights.dart | 737 - + .../src/computer/computer_highlights2.dart | 834 - + .../lib/src/computer/computer_hover.dart | 140 - + .../lib/src/computer/computer_outline.dart | 488 - + .../lib/src/computer/computer_overrides.dart | 237 - + .../computer/import_elements_computer.dart | 433 - + .../computer/imported_elements_computer.dart | 129 - + .../lib/src/computer/new_notifications.dart | 45 - + pkg/analysis_server/lib/src/constants.dart | 100 - + .../lib/src/context_manager.dart | 1817 -- + .../lib/src/domain_abstract.dart | 78 - + .../lib/src/domain_analysis.dart | 432 - + .../lib/src/domain_analytics.dart | 60 - + .../lib/src/domain_completion.dart | 298 - + .../lib/src/domain_diagnostic.dart | 75 - + .../lib/src/domain_execution.dart | 147 - + pkg/analysis_server/lib/src/domain_kythe.dart | 114 - + .../lib/src/domain_server.dart | 74 - + .../domains/analysis/implemented_dart.dart | 79 - + .../src/domains/analysis/navigation_dart.dart | 360 - + .../lib/src/domains/analysis/occurrences.dart | 33 - + .../domains/analysis/occurrences_dart.dart | 63 - + .../lib/src/edit/edit_domain.dart | 1062 -- + .../lib/src/operation/operation_analysis.dart | 164 - + .../lib/src/plugin/notification_manager.dart | 365 - + .../lib/src/plugin/plugin_locator.dart | 105 - + .../lib/src/plugin/plugin_manager.dart | 1102 -- + .../lib/src/plugin/plugin_watcher.dart | 134 - + .../lib/src/plugin/request_converter.dart | 46 - + .../lib/src/plugin/result_collector.dart | 124 - + .../lib/src/plugin/result_converter.dart | 46 - + .../lib/src/plugin/result_merger.dart | 846 - + .../lib/src/protocol/protocol_internal.dart | 336 - + .../lib/src/protocol_server.dart | 283 - + .../completion/completion_core.dart | 86 - + .../completion/dart/completion_dart.dart | 97 - + .../lib/src/search/element_references.dart | 93 - + .../lib/src/search/search_domain.dart | 211 - + .../lib/src/search/type_hierarchy.dart | 202 - + .../lib/src/server/diagnostic_server.dart | 16 - + .../lib/src/server/driver.dart | 640 - + .../lib/src/server/http_server.dart | 169 - + .../lib/src/server/stdio_server.dart | 40 - + .../services/completion/completion_core.dart | 75 - + .../completion/completion_performance.dart | 117 - + .../completion/dart/arglist_contributor.dart | 340 - + .../dart/combinator_contributor.dart | 41 - + .../completion/dart/common_usage_sorter.dart | 127 - + .../dart/common_usage_sorter.g.dart | 427 - + .../completion/dart/completion_manager.dart | 278 - + .../completion/dart/contribution_sorter.dart | 24 - + .../dart/field_formal_contributor.dart | 78 - + .../dart/imported_reference_contributor.dart | 86 - + .../dart/inherited_reference_contributor.dart | 134 - + .../completion/dart/keyword_contributor.dart | 706 - + .../completion/dart/label_contributor.dart | 156 - + .../dart/library_member_contributor.dart | 73 - + .../dart/library_prefix_contributor.dart | 48 - + .../dart/local_constructor_contributor.dart | 161 - + .../dart/local_library_contributor.dart | 197 - + .../dart/local_reference_contributor.dart | 517 - + .../dart/named_constructor_contributor.dart | 61 - + .../completion/dart/override_contributor.dart | 150 - + .../dart/static_member_contributor.dart | 131 - + .../completion/dart/suggestion_builder.dart | 302 - + .../dart/type_member_contributor.dart | 411 - + .../completion/dart/uri_contributor.dart | 242 - + .../services/completion/dart/utilities.dart | 237 - + .../dart/variable_name_contributor.dart | 99 - + .../postfix/postfix_completion.dart | 567 - + .../completion/statement/design_notes.md | 144 - + .../statement/statement_completion.dart | 1237 -- + .../lib/src/services/correction/assist.dart | 126 - + .../services/correction/assist_internal.dart | 2617 --- + .../lib/src/services/correction/fix.dart | 260 - + .../src/services/correction/fix_internal.dart | 3284 ---- + .../src/services/correction/levenshtein.dart | 133 - + .../services/correction/name_suggestion.dart | 238 - + .../src/services/correction/namespace.dart | 183 - + .../correction/organize_directives.dart | 250 - + .../correction/selection_analyzer.dart | 142 - + .../src/services/correction/sort_members.dart | 504 - + .../services/correction/source_buffer.dart | 99 - + .../correction/statement_analyzer.dart | 230 - + .../lib/src/services/correction/status.dart | 179 - + .../lib/src/services/correction/strings.dart | 263 - + .../lib/src/services/correction/util.dart | 1530 -- + .../src/services/kythe/kythe_visitors.dart | 1407 -- + .../lib/src/services/kythe/schema.dart | 82 - + .../refactoring/convert_getter_to_method.dart | 127 - + .../refactoring/convert_method_to_getter.dart | 143 - + .../services/refactoring/extract_local.dart | 699 - + .../services/refactoring/extract_method.dart | 1350 -- + .../services/refactoring/inline_local.dart | 213 - + .../services/refactoring/inline_method.dart | 880 - + .../refactoring/naming_conventions.dart | 263 - + .../src/services/refactoring/refactoring.dart | 444 - + .../refactoring/refactoring_internal.dart | 116 - + .../lib/src/services/refactoring/rename.dart | 148 - + .../refactoring/rename_class_member.dart | 345 - + .../refactoring/rename_constructor.dart | 131 - + .../services/refactoring/rename_import.dart | 137 - + .../services/refactoring/rename_label.dart | 45 - + .../services/refactoring/rename_library.dart | 48 - + .../services/refactoring/rename_local.dart | 171 - + .../refactoring/rename_unit_member.dart | 263 - + .../src/services/search/element_visitors.dart | 63 - + .../lib/src/services/search/hierarchy.dart | 162 - + .../src/services/search/search_engine.dart | 171 - + .../search/search_engine_internal.dart | 238 - + .../lib/src/socket_server.dart | 90 - + .../lib/src/status/ast_writer.dart | 243 - + .../lib/src/status/diagnostics.dart | 1229 -- + .../lib/src/status/element_writer.dart | 179 - + pkg/analysis_server/lib/src/status/pages.dart | 189 - + .../lib/src/status/tree_writer.dart | 123 - + .../lib/src/utilities/documentation.dart | 67 - + .../lib/src/utilities/flutter.dart | 267 - + .../lib/src/utilities/null_string_sink.dart | 13 - + .../lib/src/utilities/profiling.dart | 89 - + .../lib/src/watch_manager.dart | 285 - + pkg/analysis_server/lib/starter.dart | 49 - + pkg/analysis_server/pubspec.yaml | 27 - + .../test/abstract_context.dart | 172 - + .../test/abstract_single_unit.dart | 144 - + .../test/analysis/get_errors_test.dart | 150 - + .../test/analysis/get_hover_test.dart | 562 - + .../test/analysis/get_navigation_test.dart | 250 - + .../notification_analysis_options_test.dart | 334 - + .../notification_analyzedFiles_test.dart | 133 - + .../notification_closingLabels_test.dart | 101 - + .../analysis/notification_errors_test.dart | 146 - + .../notification_highlights_test.dart | 960 - + .../notification_highlights_test2.dart | 1111 -- + .../notification_implemented_test.dart | 431 - + .../notification_navigation_test.dart | 1031 - + .../notification_occurrences_test.dart | 257 - + .../analysis/notification_outline_test.dart | 135 - + .../analysis/notification_overrides_test.dart | 577 - + .../test/analysis/reanalyze_test.dart | 75 - + .../analysis/set_priority_files_test.dart | 131 - + .../test/analysis/test_all.dart | 51 - + .../test/analysis/update_content_test.dart | 266 - + .../test/analysis_abstract.dart | 367 - + .../test/analysis_server_test.dart | 210 - + pkg/analysis_server/test/benchmarks_test.dart | 76 - + .../channel/byte_stream_channel_test.dart | 272 - + .../test/channel/test_all.dart | 16 - + pkg/analysis_server/test/completion_test.dart | 2517 --- + .../test/completion_test_support.dart | 203 - + .../test/context_manager_test.dart | 2695 --- + .../test/domain_analysis_test.dart | 790 - + .../test/domain_completion_test.dart | 780 - + .../test/domain_completion_util.dart | 123 - + .../test/domain_diagnostic_test.dart | 58 - + .../test/domain_execution_test.dart | 243 - + .../test/domain_server_test.dart | 81 - + .../test/edit/assists_test.dart | 134 - + pkg/analysis_server/test/edit/fixes_test.dart | 164 - + .../test/edit/format_test.dart | 125 - + .../test/edit/organize_directives_test.dart | 167 - + .../test/edit/postfix_completion_test.dart | 93 - + .../test/edit/refactoring_test.dart | 2016 -- + .../test/edit/sort_members_test.dart | 256 - + .../test/edit/statement_completion_test.dart | 122 - + pkg/analysis_server/test/edit/test_all.dart | 27 - + .../analysis/analysis_options_test.dart | 81 - + .../test/integration/analysis/error_test.dart | 100 - + .../analysis/get_errors_nonStandard_sdk.dart | 99 - + .../integration/analysis/get_errors_test.dart | 36 - + .../integration/analysis/get_hover_test.dart | 189 - + .../analysis/get_imported_elements_test.dart | 135 - + .../get_library_dependencies_test.dart | 47 - + .../analysis/get_navigation_test.dart | 67 - + .../analysis/get_reachable_sources_test.dart | 49 - + .../integration/analysis/highlights_test.dart | 146 - + .../analysis/highlights_test2.dart | 166 - + .../test/integration/analysis/lint_test.dart | 83 - + .../integration/analysis/navigation_test.dart | 136 - + .../analysis/occurrences_test.dart | 68 - + .../integration/analysis/outline_test.dart | 84 - + .../integration/analysis/overrides_test.dart | 122 - + .../analysis/package_root_test.dart | 79 - + .../analysis/reanalyze_concurrent_test.dart | 49 - + .../integration/analysis/reanalyze_test.dart | 40 - + .../analysis/set_analysis_roots_test.dart | 32 - + .../set_general_subscriptions_test.dart | 40 - + .../analysis/set_priority_files_test.dart | 30 - + .../analysis/set_subscriptions_test.dart | 32 - + .../test/integration/analysis/test_all.dart | 66 - + .../analysis/update_content_list_test.dart | 52 - + .../analysis/update_content_test.dart | 107 - + .../analysis/update_options_test.dart | 47 - + .../integration/analytics/enable_test.dart | 33 - + .../analytics/is_enabled_test.dart | 26 - + .../analytics/send_event_test.dart | 31 - + .../analytics/send_timing_test.dart | 31 - + .../test/integration/analytics/test_all.dart | 19 - + .../completion/get_suggestions_test.dart | 118 - + .../test/integration/completion/test_all.dart | 16 - + .../test/integration/coverage.md | 83 - + .../test/integration/coverage_test.dart | 129 - + .../diagnostic/get_diagnostics_test.dart | 30 - + .../diagnostic/get_server_port_test.dart | 37 - + .../test/integration/diagnostic/test_all.dart | 15 - + .../test/integration/edit/format_test.dart | 80 - + .../integration/edit/get_assists_test.dart | 50 - + .../edit/get_available_refactorings_test.dart | 37 - + .../test/integration/edit/get_fixes_test.dart | 60 - + .../edit/get_postfix_completion_test.dart | 52 - + .../edit/get_refactoring_test.dart | 66 - + .../edit/get_statement_completion_test.dart | 47 - + .../edit/import_elements_test.dart | 139 - + ...is_postfix_completion_applicable_test.dart | 41 - + ...ist_postfix_completion_templates_test.dart | 41 - + .../edit/organize_directives_test.dart | 76 - + .../integration/edit/sort_members_test.dart | 64 - + .../test/integration/edit/test_all.dart | 38 - + .../execution/create_context_test.dart | 24 - + .../execution/delete_context_test.dart | 43 - + .../integration/execution/map_uri_test.dart | 40 - + .../execution/set_subscriptions_test.dart | 23 - + .../test/integration/execution/test_all.dart | 19 - + .../kythe/get_kythe_entries_test.dart | 39 - + .../test/integration/kythe/test_all.dart | 13 - + .../search/find_element_references_test.dart | 72 - + .../search/find_member_declarations_test.dart | 51 - + .../search/find_member_references_test.dart | 52 - + .../find_top_level_declarations_test.dart | 56 - + .../search/get_type_hierarchy_test.dart | 275 - + .../test/integration/search/test_all.dart | 25 - + .../integration/server/get_version_test.dart | 20 - + ...et_subscriptions_invalid_service_test.dart | 30 - + .../server/set_subscriptions_test.dart | 64 - + .../integration/server/shutdown_test.dart | 31 - + .../test/integration/server/status_test.dart | 50 - + .../test/integration/server/test_all.dart | 25 - + .../support/integration_test_methods.dart | 2240 --- + .../support/integration_tests.dart | 1003 - + .../support/protocol_matchers.dart | 2644 --- + .../test/integration/test_all.dart | 35 - + pkg/analysis_server/test/mock_sdk.dart | 438 - + pkg/analysis_server/test/mocks.dart | 320 - + .../test/plugin/protocol_dart_test.dart | 461 - + pkg/analysis_server/test/plugin/test_all.dart | 16 - + .../test/protocol_server_test.dart | 196 - + pkg/analysis_server/test/protocol_test.dart | 270 - + .../test/search/abstract_search_domain.dart | 113 - + .../test/search/element_references_test.dart | 674 - + .../test/search/member_declarations_test.dart | 157 - + .../test/search/member_references_test.dart | 114 - + .../test/search/search_result_test.dart | 55 - + pkg/analysis_server/test/search/test_all.dart | 26 - + .../search/top_level_declarations_test.dart | 82 - + .../test/search/type_hierarchy_test.dart | 1055 -- + .../dart/arglist_contributor_test.dart | 1019 - + .../dart/combinator_contributor_test.dart | 153 - + .../dart/common_usage_sorter_test.dart | 148 - + .../dart/completion_contributor_util.dart | 589 - + .../dart/completion_manager_test.dart | 91 - + .../dart/field_formal_contributor_test.dart | 197 - + .../imported_reference_contributor_test.dart | 4294 ----- + .../inherited_reference_contributor_test.dart | 607 - + .../dart/keyword_contributor_test.dart | 1826 -- + .../dart/label_contributor_test.dart | 320 - + .../dart/library_member_contributor_test.dart | 251 - + .../dart/library_prefix_contributor_test.dart | 329 - + .../local_constructor_contributor_test.dart | 3975 ---- + .../dart/local_library_contributor_test.dart | 282 - + .../local_reference_contributor_test.dart | 4585 ----- + .../named_constructor_contributor_test.dart | 171 - + .../dart/override_contributor_test.dart | 112 - + .../dart/static_member_contributor_test.dart | 285 - + .../services/completion/dart/test_all.dart | 52 - + .../dart/type_member_contributor_test.dart | 4027 ---- + .../completion/dart/uri_contributor_test.dart | 682 - + .../dart/variable_name_contributor_test.dart | 244 - + .../postfix/postfix_completion_test.dart | 709 - + .../services/completion/postfix/test_all.dart | 13 - + .../statement/statement_completion_test.dart | 1912 -- + .../completion/statement/test_all.dart | 13 - + .../test/services/completion/test_all.dart | 17 - + .../test/services/correction/assist_test.dart | 4443 ----- + .../test/services/correction/change_test.dart | 296 - + .../test/services/correction/fix_test.dart | 6753 ------- + .../services/correction/levenshtein_test.dart | 66 - + .../correction/name_suggestion_test.dart | 369 - + .../correction/organize_directives_test.dart | 321 - + .../correction/sort_members_test.dart | 810 - + .../test/services/correction/status_test.dart | 235 - + .../services/correction/strings_test.dart | 175 - + .../test/services/correction/test_all.dart | 32 - + .../test/services/correction/util_test.dart | 252 - + .../test/services/linter/linter_test.dart | 79 - + .../test/services/linter/test_all.dart | 13 - + .../refactoring/abstract_refactoring.dart | 175 - + .../services/refactoring/abstract_rename.dart | 75 - + .../convert_getter_to_method_test.dart | 163 - + .../convert_method_to_getter_test.dart | 215 - + .../refactoring/extract_local_test.dart | 1346 -- + .../refactoring/extract_method_test.dart | 2886 --- + .../refactoring/inline_local_test.dart | 639 - + .../refactoring/inline_method_test.dart | 1761 -- + .../refactoring/naming_conventions_test.dart | 754 - + .../refactoring/rename_class_member_test.dart | 894 - + .../refactoring/rename_constructor_test.dart | 249 - + .../refactoring/rename_import_test.dart | 230 - + .../refactoring/rename_label_test.dart | 83 - + .../refactoring/rename_library_test.dart | 91 - + .../refactoring/rename_local_test.dart | 545 - + .../refactoring/rename_unit_member_test.dart | 607 - + .../test/services/refactoring/test_all.dart | 40 - + .../test/services/search/hierarchy_test.dart | 362 - + .../services/search/search_engine_test.dart | 422 - + .../test/services/search/test_all.dart | 18 - + .../test/services/test_all.dart | 21 - + .../test/socket_server_test.dart | 142 - + .../computer/closingLabels_computer_test.dart | 346 - + .../import_elements_computer_test.dart | 343 - + .../imported_elements_computer_test.dart | 400 - + .../src/computer/outline_computer_test.dart | 1022 - + .../test/src/computer/test_all.dart | 20 - + .../test/src/domain_abstract_test.dart | 105 - + .../src/plugin/notification_manager_test.dart | 511 - + .../test/src/plugin/plugin_locator_test.dart | 96 - + .../test/src/plugin/plugin_manager_test.dart | 918 - + .../test/src/plugin/plugin_watcher_test.dart | 187 - + .../src/plugin/protocol_test_utilities.dart | 192 - + .../src/plugin/request_converter_test.dart | 82 - + .../src/plugin/result_collector_test.dart | 110 - + .../src/plugin/result_converter_test.dart | 128 - + .../test/src/plugin/result_merger_test.dart | 738 - + .../test/src/plugin/test_all.dart | 27 - + pkg/analysis_server/test/src/test_all.dart | 24 - + .../test/src/utilities/flutter_test.dart | 156 - + .../test/src/utilities/flutter_util.dart | 205 - + .../test/src/utilities/profiling_test.dart | 30 - + .../test/src/utilities/test_all.dart | 15 - + .../test/src/watch_manager_test.dart | 350 - + .../test/stress/replay/operation.dart | 80 - + .../test/stress/replay/replay.dart | 707 - + .../test/stress/utilities/git.dart | 551 - + .../test/stress/utilities/logger.dart | 49 - + .../test/stress/utilities/server.dart | 1081 -- + pkg/analysis_server/test/test_all.dart | 61 - + .../timing/completion/completion_simple.dart | 111 - + .../test/timing/timing_framework.dart | 312 - + .../tool/instrumentation/log/log.dart | 1195 -- + .../tool/instrumentation/log_viewer.dart | 129 - + .../tool/instrumentation/page/log_page.dart | 331 - + .../instrumentation/page/page_writer.dart | 317 - + .../tool/instrumentation/page/stats_page.dart | 265 - + .../tool/instrumentation/page/task_page.dart | 168 - + .../tool/instrumentation/server.dart | 238 - + pkg/analysis_server/tool/spec/api.dart | 528 - + .../tool/spec/check_all_test.dart | 23 - + .../tool/spec/codegen_analysis_server.dart | 137 - + .../tool/spec/codegen_dart.dart | 49 - + .../tool/spec/codegen_dart_protocol.dart | 1326 -- + .../tool/spec/codegen_inttest_methods.dart | 275 - + .../tool/spec/codegen_java.dart | 301 - + .../tool/spec/codegen_java_types.dart | 744 - + .../tool/spec/codegen_matchers.dart | 191 - + .../tool/spec/codegen_protocol_constants.dart | 170 - + pkg/analysis_server/tool/spec/from_html.dart | 609 - + .../tool/spec/generate_all.dart | 40 - + pkg/analysis_server/tool/spec/generate_files | 61 - + .../spec/generated/java/AnalysisServer.java | 757 - + .../java/types/AddContentOverlay.java | 132 - + .../generated/java/types/AnalysisError.java | 251 - + .../java/types/AnalysisErrorFixes.java | 138 - + .../java/types/AnalysisErrorSeverity.java | 32 - + .../java/types/AnalysisErrorType.java | 42 - + .../generated/java/types/AnalysisOptions.java | 287 - + .../generated/java/types/AnalysisService.java | 49 - + .../generated/java/types/AnalysisStatus.java | 136 - + .../java/types/ChangeContentOverlay.java | 142 - + .../generated/java/types/ClosingLabel.java | 156 - + .../java/types/CompletionSuggestion.java | 574 - + .../java/types/CompletionSuggestionKind.java | 64 - + .../generated/java/types/ContextData.java | 195 - + .../spec/generated/java/types/Element.java | 297 - + .../generated/java/types/ElementKind.java | 76 - + .../generated/java/types/ExecutableFile.java | 134 - + .../generated/java/types/ExecutableKind.java | 34 - + .../java/types/ExecutionService.java | 28 - + .../types/ExtractLocalVariableFeedback.java | 221 - + .../types/ExtractLocalVariableOptions.java | 152 - + .../java/types/ExtractMethodFeedback.java | 272 - + .../java/types/ExtractMethodOptions.java | 261 - + .../spec/generated/java/types/FileKind.java | 30 - + .../generated/java/types/FoldingKind.java | 36 - + .../generated/java/types/FoldingRegion.java | 153 - + .../java/types/GeneralAnalysisService.java | 29 - + .../generated/java/types/HighlightRegion.java | 157 - + .../java/types/HighlightRegionType.java | 319 - + .../java/types/HoverInformation.java | 372 - + .../java/types/ImplementedClass.java | 134 - + .../java/types/ImplementedMember.java | 134 - + .../java/types/ImportedElements.java | 158 - + .../types/InlineLocalVariableFeedback.java | 132 - + .../java/types/InlineMethodFeedback.java | 155 - + .../java/types/InlineMethodOptions.java | 152 - + .../spec/generated/java/types/KytheEntry.java | 202 - + .../spec/generated/java/types/KytheVName.java | 200 - + .../generated/java/types/LinkedEditGroup.java | 165 - + .../java/types/LinkedEditSuggestion.java | 135 - + .../java/types/LinkedEditSuggestionKind.java | 34 - + .../spec/generated/java/types/Location.java | 191 - + .../generated/java/types/MoveFileOptions.java | 120 - + .../java/types/NavigationRegion.java | 179 - + .../java/types/NavigationTarget.java | 220 - + .../generated/java/types/Occurrences.java | 166 - + .../spec/generated/java/types/Outline.java | 207 - + .../java/types/OverriddenMember.java | 134 - + .../generated/java/types/OverrideMember.java | 186 - + .../spec/generated/java/types/Position.java | 134 - + .../java/types/PostfixTemplateDescriptor.java | 153 - + .../spec/generated/java/types/PubStatus.java | 115 - + .../java/types/RefactoringFeedback.java | 85 - + .../generated/java/types/RefactoringKind.java | 44 - + .../types/RefactoringMethodParameter.java | 242 - + .../types/RefactoringMethodParameterKind.java | 32 - + .../java/types/RefactoringOptions.java | 85 - + .../java/types/RefactoringProblem.java | 159 - + .../types/RefactoringProblemSeverity.java | 55 - + .../java/types/RemoveContentOverlay.java | 113 - + .../generated/java/types/RenameFeedback.java | 172 - + .../generated/java/types/RenameOptions.java | 120 - + .../generated/java/types/RequestError.java | 155 - + .../java/types/RequestErrorCode.java | 182 - + .../generated/java/types/SearchResult.java | 182 - + .../java/types/SearchResultKind.java | 61 - + .../generated/java/types/ServerService.java | 28 - + .../generated/java/types/SourceChange.java | 182 - + .../spec/generated/java/types/SourceEdit.java | 186 - + .../generated/java/types/SourceFileEdit.java | 163 - + .../java/types/TypeHierarchyItem.java | 271 - + .../tool/spec/implied_types.dart | 89 - + pkg/analysis_server/tool/spec/spec_input.html | 3975 ---- + pkg/analysis_server/tool/spec/to_html.dart | 831 - + pkg/analysis_server_client/CHANGELOG.md | 5 - + pkg/analysis_server_client/LICENSE | 26 - + pkg/analysis_server_client/README.md | 13 - + .../lib/analysis_server_client.dart | 101 - + pkg/analysis_server_client/pubspec.yaml | 13 - + .../test/analysis_server_client_test.dart | 97 - + pkg/analyzer/README.md | 2 - + pkg/analyzer/lib/src/codegen/tools.dart | 2 - + pkg/analyzer_cli/lib/src/driver.dart | 58 +- + pkg/analyzer_cli/lib/src/options.dart | 55 +- + pkg/analyzer_cli/pubspec.yaml | 1 - + pkg/analyzer_cli/test/options_test.dart | 23 - + .../support/integration_test_methods.dart | 815 - + .../support/integration_tests.dart | 15 - + pkg/front_end/testing.json | 1 - + pkg/microlytics/example/simple.dart | 26 - + pkg/microlytics/lib/channels.dart | 53 - + pkg/microlytics/lib/html_channels.dart | 14 - + pkg/microlytics/lib/io_channels.dart | 20 - + pkg/microlytics/lib/microlytics.dart | 57 - + pkg/microlytics/pubspec.yaml | 8 - + .../test/dart_microlytics_test.dart | 114 - + pkg/microlytics/test/test_channel.dart | 19 - + pkg/pkg.status | 15 - + pkg/telemetry/LICENSE | 26 - + pkg/telemetry/README.md | 51 - + pkg/telemetry/analysis_options.yaml | 10 - + pkg/telemetry/lib/crash_reporting.dart | 94 - + pkg/telemetry/lib/telemetry.dart | 126 - + pkg/telemetry/pubspec.yaml | 16 - + pkg/telemetry/test/crash_reporting_test.dart | 41 - + pkg/telemetry/test/telemetry_test.dart | 31 - + runtime/observatory/lib/app.dart | 3 +- + .../observatory/lib/src/app/analytics.dart | 31 - + runtime/observatory/observatory_sources.gni | 1 - + sdk/BUILD.gn | 11 - + tests/lib/analyzer/analyze_library.status | 1 - + tools/bots/dartdoc_footer.html | 13 - + tools/bots/test_matrix.json | 30 - + tools/bots/try_benchmarks.sh | 1 - + utils/analysis_server/.gitignore | 3 - + utils/analysis_server/BUILD.gn | 10 - + 525 files changed, 8 insertions(+), 187921 deletions(-) + delete mode 100644 pkg/analysis_server/AUTHORS + delete mode 100644 pkg/analysis_server/CHANGELOG.md + delete mode 100644 pkg/analysis_server/CONTRIBUTING.md + delete mode 100644 pkg/analysis_server/LICENSE + delete mode 100644 pkg/analysis_server/README.md + delete mode 100644 pkg/analysis_server/analysis_options.yaml + delete mode 100644 pkg/analysis_server/benchmark/benchmarks.dart + delete mode 100644 pkg/analysis_server/benchmark/integration/README.md + delete mode 100644 pkg/analysis_server/benchmark/integration/driver.dart + delete mode 100644 pkg/analysis_server/benchmark/integration/input_conver= ter.dart + delete mode 100644 pkg/analysis_server/benchmark/integration/instrumentat= ion_input_converter.dart + delete mode 100644 pkg/analysis_server/benchmark/integration/local_runner= .dart + delete mode 100644 pkg/analysis_server/benchmark/integration/log_file_inp= ut_converter.dart + delete mode 100644 pkg/analysis_server/benchmark/integration/main.dart + delete mode 100644 pkg/analysis_server/benchmark/integration/operation.da= rt + delete mode 100644 pkg/analysis_server/benchmark/perf/analysis_timing_tes= ts.dart + delete mode 100644 pkg/analysis_server/benchmark/perf/benchmark_angular.d= art + delete mode 100644 pkg/analysis_server/benchmark/perf/benchmark_flutter.d= art + delete mode 100644 pkg/analysis_server/benchmark/perf/benchmark_scenario.= dart + delete mode 100644 pkg/analysis_server/benchmark/perf/benchmarks_impl.dart + delete mode 100644 pkg/analysis_server/benchmark/perf/completion_timing_t= ests.dart + delete mode 100644 pkg/analysis_server/benchmark/perf/memory_tests.dart + delete mode 100644 pkg/analysis_server/benchmark/perf/performance_tests.d= art + delete mode 100644 pkg/analysis_server/benchmark/readme.md + delete mode 100644 pkg/analysis_server/bin/server.dart + delete mode 100644 pkg/analysis_server/doc/api.html + delete mode 100644 pkg/analysis_server/lib/plugin/analysis/occurrences/oc= currences_core.dart + delete mode 100644 pkg/analysis_server/lib/plugin/edit/assist/assist_core= .dart + delete mode 100644 pkg/analysis_server/lib/plugin/edit/assist/assist_dart= .dart + delete mode 100644 pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart + delete mode 100644 pkg/analysis_server/lib/plugin/edit/fix/fix_dart.dart + delete mode 100644 pkg/analysis_server/lib/plugin/protocol/protocol_dart.= dart + delete mode 100644 pkg/analysis_server/lib/protocol/protocol.dart + delete mode 100644 pkg/analysis_server/lib/protocol/protocol_constants.da= rt + delete mode 100644 pkg/analysis_server/lib/protocol/protocol_generated.da= rt + delete mode 100644 pkg/analysis_server/lib/src/analysis_logger.dart + delete mode 100644 pkg/analysis_server/lib/src/analysis_server.dart + delete mode 100644 pkg/analysis_server/lib/src/channel/byte_stream_channe= l.dart + delete mode 100644 pkg/analysis_server/lib/src/channel/channel.dart + delete mode 100644 pkg/analysis_server/lib/src/collections.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/computer_closingL= abels.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/computer_highligh= ts.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/computer_highligh= ts2.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/computer_hover.da= rt + delete mode 100644 pkg/analysis_server/lib/src/computer/computer_outline.= dart + delete mode 100644 pkg/analysis_server/lib/src/computer/computer_override= s.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/import_elements_c= omputer.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/imported_elements= _computer.dart + delete mode 100644 pkg/analysis_server/lib/src/computer/new_notifications= .dart + delete mode 100644 pkg/analysis_server/lib/src/constants.dart + delete mode 100644 pkg/analysis_server/lib/src/context_manager.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_abstract.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_analysis.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_analytics.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_completion.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_diagnostic.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_execution.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_kythe.dart + delete mode 100644 pkg/analysis_server/lib/src/domain_server.dart + delete mode 100644 pkg/analysis_server/lib/src/domains/analysis/implement= ed_dart.dart + delete mode 100644 pkg/analysis_server/lib/src/domains/analysis/navigatio= n_dart.dart + delete mode 100644 pkg/analysis_server/lib/src/domains/analysis/occurrenc= es.dart + delete mode 100644 pkg/analysis_server/lib/src/domains/analysis/occurrenc= es_dart.dart + delete mode 100644 pkg/analysis_server/lib/src/edit/edit_domain.dart + delete mode 100644 pkg/analysis_server/lib/src/operation/operation_analys= is.dart + delete mode 100644 pkg/analysis_server/lib/src/plugin/notification_manage= r.dart + delete mode 100644 pkg/analysis_server/lib/src/plugin/plugin_locator.dart + delete mode 100644 pkg/analysis_server/lib/src/plugin/plugin_manager.dart + delete mode 100644 pkg/analysis_server/lib/src/plugin/plugin_watcher.dart + delete mode 100644 pkg/analysis_server/lib/src/plugin/request_converter.d= art + delete mode 100644 pkg/analysis_server/lib/src/plugin/result_collector.da= rt + delete mode 100644 pkg/analysis_server/lib/src/plugin/result_converter.da= rt + delete mode 100644 pkg/analysis_server/lib/src/plugin/result_merger.dart + delete mode 100644 pkg/analysis_server/lib/src/protocol/protocol_internal= .dart + delete mode 100644 pkg/analysis_server/lib/src/protocol_server.dart + delete mode 100644 pkg/analysis_server/lib/src/provisional/completion/com= pletion_core.dart + delete mode 100644 pkg/analysis_server/lib/src/provisional/completion/dar= t/completion_dart.dart + delete mode 100644 pkg/analysis_server/lib/src/search/element_references.= dart + delete mode 100644 pkg/analysis_server/lib/src/search/search_domain.dart + delete mode 100644 pkg/analysis_server/lib/src/search/type_hierarchy.dart + delete mode 100644 pkg/analysis_server/lib/src/server/diagnostic_server.d= art + delete mode 100644 pkg/analysis_server/lib/src/server/driver.dart + delete mode 100644 pkg/analysis_server/lib/src/server/http_server.dart + delete mode 100644 pkg/analysis_server/lib/src/server/stdio_server.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/comple= tion_core.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/comple= tion_performance.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/a= rglist_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/c= ombinator_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/c= ommon_usage_sorter.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/c= ommon_usage_sorter.g.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/c= ompletion_manager.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/c= ontribution_sorter.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/f= ield_formal_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/i= mported_reference_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/i= nherited_reference_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/k= eyword_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/l= abel_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/l= ibrary_member_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/l= ibrary_prefix_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/l= ocal_constructor_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/l= ocal_library_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/l= ocal_reference_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/n= amed_constructor_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/o= verride_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/s= tatic_member_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/s= uggestion_builder.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/t= ype_member_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/u= ri_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/u= tilities.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/dart/v= ariable_name_contributor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/postfi= x/postfix_completion.dart + delete mode 100644 pkg/analysis_server/lib/src/services/completion/statem= ent/design_notes.md + delete mode 100644 pkg/analysis_server/lib/src/services/completion/statem= ent/statement_completion.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/assist= .dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/assist= _internal.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/fix.da= rt + delete mode 100644 pkg/analysis_server/lib/src/services/correction/fix_in= ternal.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/levens= htein.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/name_s= uggestion.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/namesp= ace.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/organi= ze_directives.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/select= ion_analyzer.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/sort_m= embers.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/source= _buffer.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/statem= ent_analyzer.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/status= .dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/string= s.dart + delete mode 100644 pkg/analysis_server/lib/src/services/correction/util.d= art + delete mode 100644 pkg/analysis_server/lib/src/services/kythe/kythe_visit= ors.dart + delete mode 100644 pkg/analysis_server/lib/src/services/kythe/schema.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/conve= rt_getter_to_method.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/conve= rt_method_to_getter.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/extra= ct_local.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/extra= ct_method.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/inlin= e_local.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/inlin= e_method.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/namin= g_conventions.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/refac= toring.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/refac= toring_internal.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_class_member.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_constructor.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_import.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_label.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_library.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_local.dart + delete mode 100644 pkg/analysis_server/lib/src/services/refactoring/renam= e_unit_member.dart + delete mode 100644 pkg/analysis_server/lib/src/services/search/element_vi= sitors.dart + delete mode 100644 pkg/analysis_server/lib/src/services/search/hierarchy.= dart + delete mode 100644 pkg/analysis_server/lib/src/services/search/search_eng= ine.dart + delete mode 100644 pkg/analysis_server/lib/src/services/search/search_eng= ine_internal.dart + delete mode 100644 pkg/analysis_server/lib/src/socket_server.dart + delete mode 100644 pkg/analysis_server/lib/src/status/ast_writer.dart + delete mode 100644 pkg/analysis_server/lib/src/status/diagnostics.dart + delete mode 100644 pkg/analysis_server/lib/src/status/element_writer.dart + delete mode 100644 pkg/analysis_server/lib/src/status/pages.dart + delete mode 100644 pkg/analysis_server/lib/src/status/tree_writer.dart + delete mode 100644 pkg/analysis_server/lib/src/utilities/documentation.da= rt + delete mode 100644 pkg/analysis_server/lib/src/utilities/flutter.dart + delete mode 100644 pkg/analysis_server/lib/src/utilities/null_string_sink= .dart + delete mode 100644 pkg/analysis_server/lib/src/utilities/profiling.dart + delete mode 100644 pkg/analysis_server/lib/src/watch_manager.dart + delete mode 100644 pkg/analysis_server/lib/starter.dart + delete mode 100644 pkg/analysis_server/pubspec.yaml + delete mode 100644 pkg/analysis_server/test/abstract_context.dart + delete mode 100644 pkg/analysis_server/test/abstract_single_unit.dart + delete mode 100644 pkg/analysis_server/test/analysis/get_errors_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/get_hover_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/get_navigation_test.= dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_analysi= s_options_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_analyze= dFiles_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_closing= Labels_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_errors_= test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_highlig= hts_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_highlig= hts_test2.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_impleme= nted_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_navigat= ion_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_occurre= nces_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_outline= _test.dart + delete mode 100644 pkg/analysis_server/test/analysis/notification_overrid= es_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/reanalyze_test.dart + delete mode 100644 pkg/analysis_server/test/analysis/set_priority_files_t= est.dart + delete mode 100644 pkg/analysis_server/test/analysis/test_all.dart + delete mode 100644 pkg/analysis_server/test/analysis/update_content_test.= dart + delete mode 100644 pkg/analysis_server/test/analysis_abstract.dart + delete mode 100644 pkg/analysis_server/test/analysis_server_test.dart + delete mode 100644 pkg/analysis_server/test/benchmarks_test.dart + delete mode 100644 pkg/analysis_server/test/channel/byte_stream_channel_t= est.dart + delete mode 100644 pkg/analysis_server/test/channel/test_all.dart + delete mode 100644 pkg/analysis_server/test/completion_test.dart + delete mode 100644 pkg/analysis_server/test/completion_test_support.dart + delete mode 100644 pkg/analysis_server/test/context_manager_test.dart + delete mode 100644 pkg/analysis_server/test/domain_analysis_test.dart + delete mode 100644 pkg/analysis_server/test/domain_completion_test.dart + delete mode 100644 pkg/analysis_server/test/domain_completion_util.dart + delete mode 100644 pkg/analysis_server/test/domain_diagnostic_test.dart + delete mode 100644 pkg/analysis_server/test/domain_execution_test.dart + delete mode 100644 pkg/analysis_server/test/domain_server_test.dart + delete mode 100644 pkg/analysis_server/test/edit/assists_test.dart + delete mode 100644 pkg/analysis_server/test/edit/fixes_test.dart + delete mode 100644 pkg/analysis_server/test/edit/format_test.dart + delete mode 100644 pkg/analysis_server/test/edit/organize_directives_test= .dart + delete mode 100644 pkg/analysis_server/test/edit/postfix_completion_test.= dart + delete mode 100644 pkg/analysis_server/test/edit/refactoring_test.dart + delete mode 100644 pkg/analysis_server/test/edit/sort_members_test.dart + delete mode 100644 pkg/analysis_server/test/edit/statement_completion_tes= t.dart + delete mode 100644 pkg/analysis_server/test/edit/test_all.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/analysis= _options_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/error_te= st.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_erro= rs_nonStandard_sdk.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_erro= rs_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_hove= r_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_impo= rted_elements_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_libr= ary_dependencies_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_navi= gation_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/get_reac= hable_sources_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/highligh= ts_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/highligh= ts_test2.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/lint_tes= t.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/navigati= on_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/occurren= ces_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/outline_= test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/override= s_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/package_= root_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/reanalyz= e_concurrent_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/reanalyz= e_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/set_anal= ysis_roots_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/set_gene= ral_subscriptions_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/set_prio= rity_files_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/set_subs= criptions_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/test_all= .dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/update_c= ontent_list_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/update_c= ontent_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analysis/update_o= ptions_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analytics/enable_= test.dart + delete mode 100644 pkg/analysis_server/test/integration/analytics/is_enab= led_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analytics/send_ev= ent_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analytics/send_ti= ming_test.dart + delete mode 100644 pkg/analysis_server/test/integration/analytics/test_al= l.dart + delete mode 100644 pkg/analysis_server/test/integration/completion/get_su= ggestions_test.dart + delete mode 100644 pkg/analysis_server/test/integration/completion/test_a= ll.dart + delete mode 100644 pkg/analysis_server/test/integration/coverage.md + delete mode 100644 pkg/analysis_server/test/integration/coverage_test.dart + delete mode 100644 pkg/analysis_server/test/integration/diagnostic/get_di= agnostics_test.dart + delete mode 100644 pkg/analysis_server/test/integration/diagnostic/get_se= rver_port_test.dart + delete mode 100644 pkg/analysis_server/test/integration/diagnostic/test_a= ll.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/format_test.= dart + delete mode 100644 pkg/analysis_server/test/integration/edit/get_assists_= test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/get_availabl= e_refactorings_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/get_fixes_te= st.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/get_postfix_= completion_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/get_refactor= ing_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/get_statemen= t_completion_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/import_eleme= nts_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/is_postfix_c= ompletion_applicable_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/list_postfix= _completion_templates_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/organize_dir= ectives_test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/sort_members= _test.dart + delete mode 100644 pkg/analysis_server/test/integration/edit/test_all.dart + delete mode 100644 pkg/analysis_server/test/integration/execution/create_= context_test.dart + delete mode 100644 pkg/analysis_server/test/integration/execution/delete_= context_test.dart + delete mode 100644 pkg/analysis_server/test/integration/execution/map_uri= _test.dart + delete mode 100644 pkg/analysis_server/test/integration/execution/set_sub= scriptions_test.dart + delete mode 100644 pkg/analysis_server/test/integration/execution/test_al= l.dart + delete mode 100644 pkg/analysis_server/test/integration/kythe/get_kythe_e= ntries_test.dart + delete mode 100644 pkg/analysis_server/test/integration/kythe/test_all.da= rt + delete mode 100644 pkg/analysis_server/test/integration/search/find_eleme= nt_references_test.dart + delete mode 100644 pkg/analysis_server/test/integration/search/find_membe= r_declarations_test.dart + delete mode 100644 pkg/analysis_server/test/integration/search/find_membe= r_references_test.dart + delete mode 100644 pkg/analysis_server/test/integration/search/find_top_l= evel_declarations_test.dart + delete mode 100644 pkg/analysis_server/test/integration/search/get_type_h= ierarchy_test.dart + delete mode 100644 pkg/analysis_server/test/integration/search/test_all.d= art + delete mode 100644 pkg/analysis_server/test/integration/server/get_versio= n_test.dart + delete mode 100644 pkg/analysis_server/test/integration/server/set_subscr= iptions_invalid_service_test.dart + delete mode 100644 pkg/analysis_server/test/integration/server/set_subscr= iptions_test.dart + delete mode 100644 pkg/analysis_server/test/integration/server/shutdown_t= est.dart + delete mode 100644 pkg/analysis_server/test/integration/server/status_tes= t.dart + delete mode 100644 pkg/analysis_server/test/integration/server/test_all.d= art + delete mode 100644 pkg/analysis_server/test/integration/support/integrati= on_test_methods.dart + delete mode 100644 pkg/analysis_server/test/integration/support/integrati= on_tests.dart + delete mode 100644 pkg/analysis_server/test/integration/support/protocol_= matchers.dart + delete mode 100644 pkg/analysis_server/test/integration/test_all.dart + delete mode 100644 pkg/analysis_server/test/mock_sdk.dart + delete mode 100644 pkg/analysis_server/test/mocks.dart + delete mode 100644 pkg/analysis_server/test/plugin/protocol_dart_test.dart + delete mode 100644 pkg/analysis_server/test/plugin/test_all.dart + delete mode 100644 pkg/analysis_server/test/protocol_server_test.dart + delete mode 100644 pkg/analysis_server/test/protocol_test.dart + delete mode 100644 pkg/analysis_server/test/search/abstract_search_domain= .dart + delete mode 100644 pkg/analysis_server/test/search/element_references_tes= t.dart + delete mode 100644 pkg/analysis_server/test/search/member_declarations_te= st.dart + delete mode 100644 pkg/analysis_server/test/search/member_references_test= .dart + delete mode 100644 pkg/analysis_server/test/search/search_result_test.dart + delete mode 100644 pkg/analysis_server/test/search/test_all.dart + delete mode 100644 pkg/analysis_server/test/search/top_level_declarations= _test.dart + delete mode 100644 pkg/analysis_server/test/search/type_hierarchy_test.da= rt + delete mode 100644 pkg/analysis_server/test/services/completion/dart/argl= ist_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/comb= inator_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/comm= on_usage_sorter_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/comp= letion_contributor_util.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/comp= letion_manager_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/fiel= d_formal_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/impo= rted_reference_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/inhe= rited_reference_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/keyw= ord_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/labe= l_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/libr= ary_member_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/libr= ary_prefix_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/loca= l_constructor_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/loca= l_library_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/loca= l_reference_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/name= d_constructor_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/over= ride_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/stat= ic_member_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/test= _all.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/type= _member_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/uri_= contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/dart/vari= able_name_contributor_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/postfix/p= ostfix_completion_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/postfix/t= est_all.dart + delete mode 100644 pkg/analysis_server/test/services/completion/statement= /statement_completion_test.dart + delete mode 100644 pkg/analysis_server/test/services/completion/statement= /test_all.dart + delete mode 100644 pkg/analysis_server/test/services/completion/test_all.= dart + delete mode 100644 pkg/analysis_server/test/services/correction/assist_te= st.dart + delete mode 100644 pkg/analysis_server/test/services/correction/change_te= st.dart + delete mode 100644 pkg/analysis_server/test/services/correction/fix_test.= dart + delete mode 100644 pkg/analysis_server/test/services/correction/levenshte= in_test.dart + delete mode 100644 pkg/analysis_server/test/services/correction/name_sugg= estion_test.dart + delete mode 100644 pkg/analysis_server/test/services/correction/organize_= directives_test.dart + delete mode 100644 pkg/analysis_server/test/services/correction/sort_memb= ers_test.dart + delete mode 100644 pkg/analysis_server/test/services/correction/status_te= st.dart + delete mode 100644 pkg/analysis_server/test/services/correction/strings_t= est.dart + delete mode 100644 pkg/analysis_server/test/services/correction/test_all.= dart + delete mode 100644 pkg/analysis_server/test/services/correction/util_test= .dart + delete mode 100644 pkg/analysis_server/test/services/linter/linter_test.d= art + delete mode 100644 pkg/analysis_server/test/services/linter/test_all.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/abstract= _refactoring.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/abstract= _rename.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/convert_= getter_to_method_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/convert_= method_to_getter_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/extract_= local_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/extract_= method_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/inline_l= ocal_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/inline_m= ethod_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/naming_c= onventions_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_c= lass_member_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_c= onstructor_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_i= mport_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_l= abel_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_l= ibrary_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_l= ocal_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/rename_u= nit_member_test.dart + delete mode 100644 pkg/analysis_server/test/services/refactoring/test_all= .dart + delete mode 100644 pkg/analysis_server/test/services/search/hierarchy_tes= t.dart + delete mode 100644 pkg/analysis_server/test/services/search/search_engine= _test.dart + delete mode 100644 pkg/analysis_server/test/services/search/test_all.dart + delete mode 100644 pkg/analysis_server/test/services/test_all.dart + delete mode 100644 pkg/analysis_server/test/socket_server_test.dart + delete mode 100644 pkg/analysis_server/test/src/computer/closingLabels_co= mputer_test.dart + delete mode 100644 pkg/analysis_server/test/src/computer/import_elements_= computer_test.dart + delete mode 100644 pkg/analysis_server/test/src/computer/imported_element= s_computer_test.dart + delete mode 100644 pkg/analysis_server/test/src/computer/outline_computer= _test.dart + delete mode 100644 pkg/analysis_server/test/src/computer/test_all.dart + delete mode 100644 pkg/analysis_server/test/src/domain_abstract_test.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/notification_manag= er_test.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/plugin_locator_tes= t.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/plugin_manager_tes= t.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/plugin_watcher_tes= t.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/protocol_test_util= ities.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/request_converter_= test.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/result_collector_t= est.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/result_converter_t= est.dart + delete mode 100644 pkg/analysis_server/test/src/plugin/result_merger_test= .dart + delete mode 100644 pkg/analysis_server/test/src/plugin/test_all.dart + delete mode 100644 pkg/analysis_server/test/src/test_all.dart + delete mode 100644 pkg/analysis_server/test/src/utilities/flutter_test.da= rt + delete mode 100644 pkg/analysis_server/test/src/utilities/flutter_util.da= rt + delete mode 100644 pkg/analysis_server/test/src/utilities/profiling_test.= dart + delete mode 100644 pkg/analysis_server/test/src/utilities/test_all.dart + delete mode 100644 pkg/analysis_server/test/src/watch_manager_test.dart + delete mode 100644 pkg/analysis_server/test/stress/replay/operation.dart + delete mode 100644 pkg/analysis_server/test/stress/replay/replay.dart + delete mode 100644 pkg/analysis_server/test/stress/utilities/git.dart + delete mode 100644 pkg/analysis_server/test/stress/utilities/logger.dart + delete mode 100644 pkg/analysis_server/test/stress/utilities/server.dart + delete mode 100644 pkg/analysis_server/test/test_all.dart + delete mode 100644 pkg/analysis_server/test/timing/completion/completion_= simple.dart + delete mode 100644 pkg/analysis_server/test/timing/timing_framework.dart + delete mode 100644 pkg/analysis_server/tool/instrumentation/log/log.dart + delete mode 100644 pkg/analysis_server/tool/instrumentation/log_viewer.da= rt + delete mode 100644 pkg/analysis_server/tool/instrumentation/page/log_page= .dart + delete mode 100644 pkg/analysis_server/tool/instrumentation/page/page_wri= ter.dart + delete mode 100644 pkg/analysis_server/tool/instrumentation/page/stats_pa= ge.dart + delete mode 100644 pkg/analysis_server/tool/instrumentation/page/task_pag= e.dart + delete mode 100644 pkg/analysis_server/tool/instrumentation/server.dart + delete mode 100644 pkg/analysis_server/tool/spec/api.dart + delete mode 100644 pkg/analysis_server/tool/spec/check_all_test.dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_analysis_server.= dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_dart.dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_dart_protocol.da= rt + delete mode 100644 pkg/analysis_server/tool/spec/codegen_inttest_methods.= dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_java.dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_java_types.dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_matchers.dart + delete mode 100644 pkg/analysis_server/tool/spec/codegen_protocol_constan= ts.dart + delete mode 100644 pkg/analysis_server/tool/spec/from_html.dart + delete mode 100644 pkg/analysis_server/tool/spec/generate_all.dart + delete mode 100755 pkg/analysis_server/tool/spec/generate_files + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/AnalysisS= erver.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Add= ContentOverlay.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisError.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisErrorFixes.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisErrorSeverity.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisErrorType.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisService.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ana= lysisStatus.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Cha= ngeContentOverlay.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Clo= singLabel.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Com= pletionSuggestion.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Com= pletionSuggestionKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Con= textData.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ele= ment.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ele= mentKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Exe= cutableFile.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Exe= cutableKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Exe= cutionService.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ext= ractLocalVariableFeedback.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ext= ractLocalVariableOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ext= ractMethodFeedback.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ext= ractMethodOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Fil= eKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Fol= dingKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Fol= dingRegion.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Gen= eralAnalysisService.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Hig= hlightRegion.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Hig= hlightRegionType.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Hov= erInformation.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Imp= lementedClass.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Imp= lementedMember.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Imp= ortedElements.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Inl= ineLocalVariableFeedback.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Inl= ineMethodFeedback.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Inl= ineMethodOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Kyt= heEntry.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Kyt= heVName.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Lin= kedEditGroup.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Lin= kedEditSuggestion.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Lin= kedEditSuggestionKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Loc= ation.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Mov= eFileOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Nav= igationRegion.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Nav= igationTarget.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Occ= urrences.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Out= line.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ove= rriddenMember.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ove= rrideMember.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Pos= ition.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Pos= tfixTemplateDescriptor.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Pub= Status.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringFeedback.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringMethodParameter.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringMethodParameterKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringProblem.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ref= actoringProblemSeverity.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Rem= oveContentOverlay.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ren= ameFeedback.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ren= ameOptions.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Req= uestError.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Req= uestErrorCode.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Sea= rchResult.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Sea= rchResultKind.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Ser= verService.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Sou= rceChange.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Sou= rceEdit.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Sou= rceFileEdit.java + delete mode 100644 pkg/analysis_server/tool/spec/generated/java/types/Typ= eHierarchyItem.java + delete mode 100644 pkg/analysis_server/tool/spec/implied_types.dart + delete mode 100644 pkg/analysis_server/tool/spec/spec_input.html + delete mode 100644 pkg/analysis_server/tool/spec/to_html.dart + delete mode 100644 pkg/analysis_server_client/CHANGELOG.md + delete mode 100644 pkg/analysis_server_client/LICENSE + delete mode 100644 pkg/analysis_server_client/README.md + delete mode 100644 pkg/analysis_server_client/lib/analysis_server_client.= dart + delete mode 100644 pkg/analysis_server_client/pubspec.yaml + delete mode 100644 pkg/analysis_server_client/test/analysis_server_client= _test.dart + delete mode 100644 pkg/analyzer_plugin/test/integration/support/integrati= on_test_methods.dart + delete mode 100644 pkg/microlytics/example/simple.dart + delete mode 100644 pkg/microlytics/lib/channels.dart + delete mode 100644 pkg/microlytics/lib/html_channels.dart + delete mode 100644 pkg/microlytics/lib/io_channels.dart + delete mode 100644 pkg/microlytics/lib/microlytics.dart + delete mode 100644 pkg/microlytics/pubspec.yaml + delete mode 100644 pkg/microlytics/test/dart_microlytics_test.dart + delete mode 100644 pkg/microlytics/test/test_channel.dart + delete mode 100644 pkg/telemetry/LICENSE + delete mode 100644 pkg/telemetry/README.md + delete mode 100644 pkg/telemetry/analysis_options.yaml + delete mode 100644 pkg/telemetry/lib/crash_reporting.dart + delete mode 100644 pkg/telemetry/lib/telemetry.dart + delete mode 100644 pkg/telemetry/pubspec.yaml + delete mode 100644 pkg/telemetry/test/crash_reporting_test.dart + delete mode 100644 pkg/telemetry/test/telemetry_test.dart + delete mode 100644 runtime/observatory/lib/src/app/analytics.dart + delete mode 100644 utils/analysis_server/.gitignore + delete mode 100644 utils/analysis_server/BUILD.gn + +diff --git a/BUILD.gn b/BUILD.gn +index 80e3bdd3757..0f7746d8c92 100644 +--- a/BUILD.gn ++++ b/BUILD.gn +@@ -21,7 +21,6 @@ group("most") { + testonly =3D true + } + deps =3D [ +- ":analysis_server", + ":create_sdk", + ":dart2js", + ":dartanalyzer", +@@ -107,12 +106,6 @@ group("dartfmt") { + ] + } +=20 +-group("analysis_server") { +- deps =3D [ +- "utils/analysis_server", +- ] +-} +- + # This is the target that is built on the dart2js build bots. + # It must depend on anything that is required by the dart2js + # test suites. +diff --git a/pkg/analysis_server/AUTHORS b/pkg/analysis_server/AUTHORS +deleted file mode 100644 +index e8063a8cd6e..00000000000 +--- a/pkg/analysis_server/AUTHORS ++++ /dev/null +@@ -1,6 +0,0 @@ +-# Below is a list of people and organizations that have contributed +-# to the project. Names should be added to the list like so: +-# +-# Name/Organization +- +-Google Inc. +diff --git a/pkg/analysis_server/CHANGELOG.md b/pkg/analysis_server/CHANGE= LOG.md +deleted file mode 100644 +index 2a2d63cf8e6..00000000000 +--- a/pkg/analysis_server/CHANGELOG.md ++++ /dev/null +@@ -1,5 +0,0 @@ +-# Changelog +- +-## 0.0.1 +- +-- Initial version +diff --git a/pkg/analysis_server/CONTRIBUTING.md b/pkg/analysis_server/CON= TRIBUTING.md +deleted file mode 100644 +index 242f214b5e7..00000000000 +--- a/pkg/analysis_server/CONTRIBUTING.md ++++ /dev/null +@@ -1,40 +0,0 @@ +-## Contributing +- +-Contributions welcome! Please follow the guide in [Contributing][contribu= ting]. +- +-## Building +- +-If you want to build Dart yourself, here is a guide to +-[getting the source, preparing your machine to build the SDK, and +-building][building]. +- +-There are more documents on our [wiki](https://github.com/dart-lang/sdk/w= iki). +-Once set up to build the SDK, run: +- +-``` +-./tools/build.py -mrelease create_sdk +-``` +- +-## Running tests +- +-To run analyzer tests: +- +-``` +-./tools/test.py -mrelease pkg/analyzer/test/ +-``` +- +-To run all analysis server tests: +- +-``` +-./tools/test.py -mrelease pkg/analysis_server/test/ +-``` +- +-To run just the analysis server integration tests: +- +-``` +-./tools/test.py -mrelease pkg/analysis_server/test/integration/ +-``` +- +- +-[building]: https://github.com/dart-lang/sdk/wiki/Building +-[contributing]: https://github.com/dart-lang/sdk/wiki/Contributing +diff --git a/pkg/analysis_server/LICENSE b/pkg/analysis_server/LICENSE +deleted file mode 100644 +index 5c60afea399..00000000000 +--- a/pkg/analysis_server/LICENSE ++++ /dev/null +@@ -1,26 +0,0 @@ +-Copyright 2014, the Dart project authors. All rights reserved. +-Redistribution and use in source and binary forms, with or without +-modification, are permitted provided that the following conditions are +-met: +- +- * Redistributions of source code must retain the above copyright +- notice, this list of conditions and the following disclaimer. +- * Redistributions in binary form must reproduce the above +- copyright notice, this list of conditions and the following +- disclaimer in the documentation and/or other materials provided +- with the distribution. +- * Neither the name of Google Inc. nor the names of its +- contributors may be used to endorse or promote products derived +- from this software without specific prior written permission. +- +-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +diff --git a/pkg/analysis_server/README.md b/pkg/analysis_server/README.md +deleted file mode 100644 +index d596f5c47af..00000000000 +--- a/pkg/analysis_server/README.md ++++ /dev/null +@@ -1,22 +0,0 @@ +-# analysis_server +- +-A long-running process that provides analysis results to other tools. +- +-The analysis server is designed to provide on-going analysis of one or mo= re code +-bases as those code bases are changing. +- +-## Using the server +- +-The analysis server is not intended to be used stand-alone, and therefore= does +-not have a human-friendly user interface. +- +-Clients (typically tools, such as an editor) are expected to run the anal= ysis +-server in a separate process and communicate with it using a JSON protoco= l. The +-protocol is specified in the file [`analysis_server/doc/api.html`][api]. +- +-## Features and bugs +- +-Please file feature requests and bugs at the [issue tracker][tracker]. +- +-[tracker]: https://github.com/dart-lang/sdk/issues +-[api]: https://htmlpreview.github.io/?https://github.com/dart-lang/sdk/bl= ob/master/pkg/analysis_server/doc/api.html +diff --git a/pkg/analysis_server/analysis_options.yaml b/pkg/analysis_serv= er/analysis_options.yaml +deleted file mode 100644 +index 9bacf2b50aa..00000000000 +--- a/pkg/analysis_server/analysis_options.yaml ++++ /dev/null +@@ -1,8 +0,0 @@ +-analyzer: +- strong-mode: true +-linter: +- rules: +- - empty_constructor_bodies +- - empty_statements +- - unnecessary_brace_in_string_interps +- - valid_regexps +diff --git a/pkg/analysis_server/benchmark/benchmarks.dart b/pkg/analysis_= server/benchmark/benchmarks.dart +deleted file mode 100644 +index 63eb6720e32..00000000000 +--- a/pkg/analysis_server/benchmark/benchmarks.dart ++++ /dev/null +@@ -1,239 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +-import 'dart:math' as math; +- +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:args/command_runner.dart'; +-import 'package:intl/intl.dart'; +-import 'package:path/path.dart' as path; +- +-import 'perf/benchmarks_impl.dart'; +- +-Future main(List args) async { +- final List benchmarks =3D [ +- new ColdAnalysisBenchmark(), +- new AnalysisBenchmark() +- ]; +- +- CommandRunner runner =3D new CommandRunner( +- 'benchmark', 'A benchmark runner for the analysis server.'); +- runner.addCommand(new ListCommand(benchmarks)); +- runner.addCommand(new RunCommand(benchmarks)); +- runner.run(args); +-} +- +-class ListCommand extends Command { +- final List benchmarks; +- +- ListCommand(this.benchmarks) { +- argParser.addFlag('machine', +- negatable: false, help: 'Emit the list of benchmarks as json.'); +- } +- +- @override +- String get name =3D> 'list'; +- +- @override +- String get description =3D> 'List available benchmarks.'; +- +- @override +- String get invocation =3D> '${runner.executableName} $name'; +- +- void run() { +- if (argResults['machine']) { +- final Map map =3D { +- 'benchmarks': benchmarks.map((b) =3D> b.toJson()).toList() +- }; +- print(new JsonEncoder.withIndent(' ').convert(map)); +- } else { +- for (Benchmark benchmark in benchmarks) { +- print('${benchmark.id}: ${benchmark.description}'); +- } +- } +- } +-} +- +-class RunCommand extends Command { +- final List benchmarks; +- +- RunCommand(this.benchmarks) { +- argParser.addFlag('quick', +- negatable: false, +- help: 'Run a quick version of the benchmark. This is not useful f= or ' +- 'gathering accurate times,\nbut can be used to validate that = the ' +- 'benchmark works.'); +- argParser.addFlag('preview-dart-2', +- negatable: false, +- help: 'Benchmark against the Dart 2.0 front end implementation.'); +- argParser.addOption('repeat', +- defaultsTo: '10', help: 'The number of times to repeat the benchm= ark.'); +- } +- +- @override +- String get name =3D> 'run'; +- +- @override +- String get description =3D> 'Run a given benchmark.'; +- +- @override +- String get invocation =3D> '${runner.executableName} $name '; +- +- Future run() async { +- if (argResults.rest.isEmpty) { +- printUsage(); +- exit(1); +- } +- +- final String benchmarkId =3D argResults.rest.first; +- final int repeatCount =3D int.parse(argResults['repeat']); +- final bool quick =3D argResults['quick']; +- final bool previewDart2 =3D argResults['preview-dart-2']; +- +- final Benchmark benchmark =3D +- benchmarks.firstWhere((b) =3D> b.id =3D=3D benchmarkId, orElse: (= ) { +- print("Benchmark '$benchmarkId' not found."); +- exit(1); +- }); +- +- int actualIterations =3D repeatCount; +- if (benchmark.maxIterations > 0) { +- actualIterations =3D math.min(benchmark.maxIterations, repeatCount); +- } +- +- try { +- BenchMarkResult result; +- Stopwatch time =3D new Stopwatch()..start(); +- print('Running $benchmarkId $actualIterations times...'); +- +- for (int iteration =3D 0; iteration < actualIterations; iteration++= ) { +- BenchMarkResult newResult =3D await benchmark.run( +- quick: quick, +- previewDart2: previewDart2, +- ); +- print(' $newResult'); +- result =3D result =3D=3D null ? newResult : result.combine(newRes= ult); +- } +- +- time.stop(); +- print('Finished in ${time.elapsed.inSeconds} seconds.\n'); +- Map m =3D {'benchmark': benchmarkId, 'result': result.toJson()}; +- print(JSON.encode(m)); +- } catch (error, st) { +- print('$benchmarkId threw exception: $error'); +- print(st); +- exit(1); +- } +- } +-} +- +-abstract class Benchmark { +- final String id; +- final String description; +- final bool enabled; +- +- /// One of 'memory', 'cpu', or 'group'. +- final String kind; +- +- Benchmark(this.id, this.description, {this.enabled: true, this.kind: 'c= pu'}); +- +- Future run({bool quick: false, bool previewDart2: fals= e}); +- +- int get maxIterations =3D> 0; +- +- Map toJson() =3D> +- {'id': id, 'description': description, 'enabled': enabled, 'kind': = kind}; +- +- String toString() =3D> '$id: $description'; +-} +- +-class BenchMarkResult { +- static final NumberFormat nf =3D new NumberFormat.decimalPattern(); +- +- /// One of 'bytes', 'micros', or 'compound'. +- final String kindName; +- +- final int value; +- +- BenchMarkResult(this.kindName, this.value); +- +- BenchMarkResult combine(BenchMarkResult other) { +- return new BenchMarkResult(kindName, math.min(value, other.value)); +- } +- +- Map toJson() =3D> {kindName: value}; +- +- String toString() =3D> '$kindName: ${nf.format(value)}'; +-} +- +-class CompoundBenchMarkResult extends BenchMarkResult { +- final String name; +- +- CompoundBenchMarkResult(this.name) : super('compound', 0); +- +- Map results =3D {}; +- +- void add(String name, BenchMarkResult result) { +- results[name] =3D result; +- } +- +- BenchMarkResult combine(BenchMarkResult other) { +- BenchMarkResult _combine(BenchMarkResult a, BenchMarkResult b) { +- if (a =3D=3D null) return b; +- if (b =3D=3D null) return a; +- return a.combine(b); +- } +- +- CompoundBenchMarkResult o =3D other as CompoundBenchMarkResult; +- +- CompoundBenchMarkResult combined =3D new CompoundBenchMarkResult(name= ); +- List keys =3D +- (new Set()..addAll(results.keys)..addAll(o.results.keys)).toList(= ); +- +- for (String key in keys) { +- combined.add(key, _combine(results[key], o.results[key])); +- } +- +- return combined; +- } +- +- Map toJson() { +- Map m =3D {}; +- for (String key in results.keys) { +- m['$name-$key'] =3D results[key].toJson(); +- } +- return m; +- } +- +- String toString() =3D> '${toJson()}'; +-} +- +-List getProjectRoots({bool quick: false}) { +- String script =3D Platform.script.toFilePath(windows: Platform.isWindow= s); +- String pkgPath =3D path.normalize(path.join(path.dirname(script), '..',= '..')); +- return [path.join(pkgPath, quick ? 'meta' : 'analysis_server')]; +-} +- +-String get analysisServerSrcPath { +- String script =3D Platform.script.toFilePath(windows: Platform.isWindow= s); +- String pkgPath =3D path.normalize(path.join(path.dirname(script), '..',= '..')); +- return path.join(pkgPath, 'analysis_server'); +-} +- +-void deleteServerCache() { +- // ~/.dartServer/.analysis-driver/ +- ResourceProvider resourceProvider =3D PhysicalResourceProvider.INSTANCE; +- Folder stateLocation =3D resourceProvider.getStateLocation('.analysis-d= river'); +- try { +- if (stateLocation.exists) { +- stateLocation.delete(); +- } +- } catch (e) { +- // ignore any exception +- } +-} +diff --git a/pkg/analysis_server/benchmark/integration/README.md b/pkg/ana= lysis_server/benchmark/integration/README.md +deleted file mode 100644 +index 9955c11ce06..00000000000 +--- a/pkg/analysis_server/benchmark/integration/README.md ++++ /dev/null +@@ -1,69 +0,0 @@ +-# Running Benchmarks +- +-There are two entry points for running benchmarks: +-* **main.dart** - a general Dart application for running performance benc= hmarks +-* **local_runner.dart** - an example Dart application +-which sets up the local environment +-and then calls main.dart to run performance benchmarks +- +-## local_runner.dart +- +-This Dart application is one example for running performance benchmarks. +-When run, this application 1) extracts a branch from a git repository +-into a temporary directory, and 2) creates a symlink to the out or xcodeb= uild +-directory for proper package-root package resolution. +-Once setup is complete, this applications calls main.dart +- +-The required command line arguments are +-* **gitDir** =3D a path to the git repository containing the initial targ= et source +-* **branch** =3D the branch containing the initial target source +-* **inputFile** =3D the instrumentation or log file +- +-Additional arguments are passed directly to main.dart. +-For example, if the log was recorded on one machine and is played back on= another, +-then you might need to specify -m, +-to map the source paths for playback. +-When specifying additional arguments, any occurrences of @tmpSrcDir@ +-will be replaced with the absolute path of the temporary directory +-into which the source was extracted. +- +-## main.dart +- +-This Dart application reads an instrumentation or local log file produced= by +-analysis server, "replays" that interaction with the analysis server, +-compares the notifications and responses with what was recorded in the lo= g, +-and produces a report. It assumes that the environment for playback has +-already been setup. +-The required command line arguments are +-* **-i, --input ** +-The input file specifying how this client should interact with the server. +-If the input file name is "stdin", then the instructions are read from st= din. +-* **-m, --map ,** +-This option defines a mapping from the original source directory +-when the instrumentation or log file was generated +-to the target source directory used during performance testi= ng. +-Multiple mappings can be specified. +-WARNING: The contents of the target directory will be modified +-* **-t, --tmpSrcDir ** +-The temporary directory containing source used during performance measure= ment. +-WARNING: The contents of the target directory will be modified +-* **-d, --diagnosticPort** localhost port on which server +- will provide diagnostic web pages +-* **-v, --verbose** Verbose logging +-* **--vv** Extra verbose logging +-* **-h, --help** Print this help information +- +-For each request recorded in the input file, +-the application sends a corresponding request to the analysis server +-and waits up to 60 seconds for a response to that request. +-If a response in not received in that time, then the application exits. +-Any responses that are received are compared with the recorded response. +- +-For each analysis-complete notification recorded in the input file, +-the application waits for the corresponding analysis-complete notification +-from the running analysis server. +-While it is waiting for an analysis-complete notification, +-the application monitors the stream of notifications. +-If there is a period of more than 60 seconds during which no communication +-is received from the server, the application assumes that the server is h= ung +-and exits. +diff --git a/pkg/analysis_server/benchmark/integration/driver.dart b/pkg/a= nalysis_server/benchmark/integration/driver.dart +deleted file mode 100644 +index da928396139..00000000000 +--- a/pkg/analysis_server/benchmark/integration/driver.dart ++++ /dev/null +@@ -1,315 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:math' show max, sqrt; +- +-import 'package:logging/logging.dart'; +- +-import '../../test/integration/support/integration_test_methods.dart'; +-import '../../test/integration/support/integration_tests.dart'; +-import 'operation.dart'; +- +-final SPACE =3D ' '.codeUnitAt(0); +- +-void _printColumn(StringBuffer sb, String text, int keyLen, +- {bool rightJustified: false}) { +- if (!rightJustified) { +- sb.write(text); +- sb.write(','); +- } +- for (int i =3D text.length; i < keyLen; ++i) { +- sb.writeCharCode(SPACE); +- } +- if (rightJustified) { +- sb.write(text); +- sb.write(','); +- } +- sb.writeCharCode(SPACE); +-} +- +-/** +- * [Driver] launches and manages an instance of analysis server, +- * reads a stream of operations, sends requests to analysis server +- * based upon those operations, and evaluates the results. +- */ +-class Driver extends IntegrationTestMixin { +- /** +- * The amount of time to give the server to respond to a shutdown reque= st +- * before forcibly terminating it. +- */ +- static const Duration SHUTDOWN_TIMEOUT =3D const Duration(seconds: 5); +- +- final Logger logger =3D new Logger('Driver'); +- +- /** +- * The diagnostic port for Analysis Server or `null` if none. +- */ +- final int diagnosticPort; +- +- /** +- * A flag indicating whether the server is running. +- */ +- bool running =3D false; +- +- @override +- Server server; +- +- /** +- * The results collected while running analysis server. +- */ +- final Results results =3D new Results(); +- +- /** +- * The [Completer] for [runComplete]. +- */ +- Completer _runCompleter =3D new Completer(); +- +- Driver({this.diagnosticPort}); +- +- /** +- * Return a [Future] that completes with the [Results] of running +- * the analysis server once all operations have been performed. +- */ +- Future get runComplete =3D> _runCompleter.future; +- +- /** +- * Perform the given operation. +- * Return a [Future] that completes when the next operation can be perf= ormed, +- * or `null` if the next operation can be performed immediately +- */ +- Future perform(Operation op) { +- return op.perform(this); +- } +- +- /** +- * Send a command to the server. An 'id' will be automatically assigne= d. +- * The returned [Future] will be completed when the server acknowledges= the +- * command with a response. If the server acknowledges the command wit= h a +- * normal (non-error) response, the future will be completed with the '= result' +- * field from the response. If the server acknowledges the command wit= h an +- * error response, the future will be completed with an error. +- */ +- Future> send( +- String method, Map params) { +- return server.send(method, params); +- } +- +- /** +- * Launch the analysis server. +- * Return a [Future] that completes when analysis server has started. +- */ +- Future startServer() async { +- logger.log(Level.FINE, 'starting server'); +- initializeInttestMixin(); +- server =3D new Server(); +- Completer serverConnected =3D new Completer(); +- onServerConnected.listen((_) { +- logger.log(Level.FINE, 'connected to server'); +- serverConnected.complete(); +- }); +- running =3D true; +- return server +- .start(diagnosticPort: diagnosticPort /*profileServer: true*/) +- .then((params) { +- server.listenToOutput(dispatchNotification); +- server.exitCode.then((_) { +- logger.log(Level.FINE, 'server stopped'); +- running =3D false; +- _resultsReady(); +- }); +- return serverConnected.future; +- }); +- } +- +- /** +- * Shutdown the analysis server if it is running. +- */ +- Future stopServer([Duration timeout =3D SHUTDOWN_TIMEOUT]) async { +- if (running) { +- logger.log(Level.FINE, 'requesting server shutdown'); +- // Give the server a short time to comply with the shutdown request= ; if it +- // doesn't exit, then forcibly terminate it. +- sendServerShutdown(); +- await server.exitCode.timeout(timeout, onTimeout: () { +- return server.kill('server failed to exit'); +- }); +- } +- _resultsReady(); +- } +- +- /** +- * If not already complete, signal the completer with the collected res= ults. +- */ +- void _resultsReady() { +- if (!_runCompleter.isCompleted) { +- _runCompleter.complete(results); +- } +- } +-} +- +-/** +- * [Measurement] tracks elapsed time for a given operation. +- */ +-class Measurement { +- final String tag; +- final bool notification; +- final List elapsedTimes =3D new List(); +- int errorCount =3D 0; +- int unexpectedResultCount =3D 0; +- +- Measurement(this.tag, this.notification); +- +- int get count =3D> elapsedTimes.length; +- +- void printSummary(int keyLen) { +- int count =3D 0; +- Duration maxTime =3D elapsedTimes[0]; +- Duration minTime =3D elapsedTimes[0]; +- int totalTimeMicros =3D 0; +- for (Duration elapsed in elapsedTimes) { +- ++count; +- int timeMicros =3D elapsed.inMicroseconds; +- maxTime =3D maxTime.compareTo(elapsed) > 0 ? maxTime : elapsed; +- minTime =3D minTime.compareTo(elapsed) < 0 ? minTime : elapsed; +- totalTimeMicros +=3D timeMicros; +- } +- int meanTime =3D (totalTimeMicros / count).round(); +- List sorted =3D elapsedTimes.toList()..sort(); +- Duration time90th =3D sorted[(sorted.length * 0.90).round() - 1]; +- Duration time99th =3D sorted[(sorted.length * 0.99).round() - 1]; +- int differenceFromMeanSquared =3D 0; +- for (Duration elapsed in elapsedTimes) { +- int timeMicros =3D elapsed.inMicroseconds; +- int differenceFromMean =3D timeMicros - meanTime; +- differenceFromMeanSquared +=3D differenceFromMean * differenceFromM= ean; +- } +- double variance =3D differenceFromMeanSquared / count; +- int standardDeviation =3D sqrt(variance).round(); +- +- StringBuffer sb =3D new StringBuffer(); +- _printColumn(sb, tag, keyLen); +- _printColumn(sb, count.toString(), 6, rightJustified: true); +- _printColumn(sb, errorCount.toString(), 6, rightJustified: true); +- _printColumn(sb, unexpectedResultCount.toString(), 6, rightJustified:= true); +- _printDuration(sb, new Duration(microseconds: meanTime)); +- _printDuration(sb, time90th); +- _printDuration(sb, time99th); +- _printDuration(sb, new Duration(microseconds: standardDeviation)); +- _printDuration(sb, minTime); +- _printDuration(sb, maxTime); +- _printDuration(sb, new Duration(microseconds: totalTimeMicros)); +- print(sb.toString()); +- } +- +- void record(bool success, Duration elapsed) { +- if (!success) { +- ++errorCount; +- } +- elapsedTimes.add(elapsed); +- } +- +- void recordUnexpectedResults() { +- ++unexpectedResultCount; +- } +- +- void _printDuration(StringBuffer sb, Duration duration) { +- _printColumn(sb, duration.inMilliseconds.toString(), 15, +- rightJustified: true); +- } +-} +- +-/** +- * [Results] contains information gathered by [Driver] +- * while running the analysis server +- */ +-class Results { +- Map measurements =3D new Map(= ); +- +- /** +- * Display results on stdout. +- */ +- void printResults() { +- print(''); +- print('=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D'); +- print(''); +- List keys =3D measurements.keys.toList()..sort(); +- int keyLen =3D keys.fold(0, (int len, String key) =3D> max(len, key.l= ength)); +- _printGroupHeader('Request/Response', keyLen); +- int totalCount =3D 0; +- int totalErrorCount =3D 0; +- int totalUnexpectedResultCount =3D 0; +- for (String tag in keys) { +- Measurement m =3D measurements[tag]; +- if (!m.notification) { +- m.printSummary(keyLen); +- totalCount +=3D m.count; +- totalErrorCount +=3D m.errorCount; +- totalUnexpectedResultCount +=3D m.unexpectedResultCount; +- } +- } +- _printTotals( +- keyLen, totalCount, totalErrorCount, totalUnexpectedResultCount); +- print(''); +- _printGroupHeader('Notifications', keyLen); +- for (String tag in keys) { +- Measurement m =3D measurements[tag]; +- if (m.notification) { +- m.printSummary(keyLen); +- } +- } +- +- /// TODO(danrubel) *** print warnings if driver caches are not empty = **** +- print(''' +- +-(1) uxr =3D UneXpected Results or responses received from the server +- that do not match the recorded response for that request. +-(2) all times in milliseconds'''); +- } +- +- /** +- * Record the elapsed time for the given operation. +- */ +- void record(String tag, Duration elapsed, +- {bool notification: false, bool success: true}) { +- Measurement measurement =3D measurements[tag]; +- if (measurement =3D=3D null) { +- measurement =3D new Measurement(tag, notification); +- measurements[tag] =3D measurement; +- } +- measurement.record(success, elapsed); +- } +- +- void recordUnexpectedResults(String tag) { +- measurements[tag].recordUnexpectedResults(); +- } +- +- void _printGroupHeader(String groupName, int keyLen) { +- StringBuffer sb =3D new StringBuffer(); +- _printColumn(sb, groupName, keyLen); +- _printColumn(sb, 'count', 6, rightJustified: true); +- _printColumn(sb, 'error', 6, rightJustified: true); +- _printColumn(sb, 'uxr(1)', 6, rightJustified: true); +- sb.write(' '); +- _printColumn(sb, 'mean(2)', 15); +- _printColumn(sb, '90th', 15); +- _printColumn(sb, '99th', 15); +- _printColumn(sb, 'std-dev', 15); +- _printColumn(sb, 'minimum', 15); +- _printColumn(sb, 'maximum', 15); +- _printColumn(sb, 'total', 15); +- print(sb.toString()); +- } +- +- void _printTotals(int keyLen, int totalCount, int totalErrorCount, +- int totalUnexpectedResultCount) { +- StringBuffer sb =3D new StringBuffer(); +- _printColumn(sb, 'Totals', keyLen); +- _printColumn(sb, totalCount.toString(), 6, rightJustified: true); +- _printColumn(sb, totalErrorCount.toString(), 6, rightJustified: true); +- _printColumn(sb, totalUnexpectedResultCount.toString(), 6, +- rightJustified: true); +- print(sb.toString()); +- } +-} +diff --git a/pkg/analysis_server/benchmark/integration/input_converter.dar= t b/pkg/analysis_server/benchmark/integration/input_converter.dart +deleted file mode 100644 +index 70999d504aa..00000000000 +--- a/pkg/analysis_server/benchmark/integration/input_converter.dart ++++ /dev/null +@@ -1,399 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:logging/logging.dart'; +-import 'package:path/path.dart' as path; +- +-import 'instrumentation_input_converter.dart'; +-import 'log_file_input_converter.dart'; +-import 'operation.dart'; +- +-/** +- * Common input converter superclass for sharing implementation. +- */ +-abstract class CommonInputConverter extends Converter { +- static final ERROR_PREFIX =3D 'Server responded with an error: '; +- final Logger logger =3D new Logger('InstrumentationInputConverter'); +- final Set eventsSeen =3D new Set(); +- +- /** +- * A mapping from request/response id to request json +- * for those requests for which a response has not been processed. +- */ +- final Map requestMap =3D {}; +- +- /** +- * A mapping from request/response id to a completer +- * for those requests for which a response has not been processed. +- * The completer is called with the actual json response +- * when it becomes available. +- */ +- final Map responseCompleters =3D {}; +- +- /** +- * A mapping from request/response id to the actual response result +- * for those responses that have not been processed. +- */ +- final Map responseMap =3D {}; +- +- /** +- * A mapping of current overlay content +- * parallel to what is in the analysis server +- * so that we can update the file system. +- */ +- final Map overlays =3D {}; +- +- /** +- * The prefix used to determine if a request parameter is a file path. +- */ +- final String rootPrefix =3D path.rootPrefix(path.current); +- +- /** +- * A mapping of source path prefixes +- * from location where instrumentation or log file was generated +- * to the target location of the source using during performance measur= ement. +- */ +- final PathMap srcPathMap; +- +- /** +- * The root directory for all source being modified +- * during performance measurement. +- */ +- final String tmpSrcDirPath; +- +- CommonInputConverter(this.tmpSrcDirPath, this.srcPathMap); +- +- Map asMap(dynamic value) =3D> value as Map; +- +- /** +- * Return an operation for the notification or `null` if none. +- */ +- Operation convertNotification(Map json) { +- String event =3D json['event']; +- if (event =3D=3D SERVER_NOTIFICATION_STATUS) { +- // {"event":"server.status","params":{"analysis":{"isAnalyzing":fal= se}}} +- Map params =3D asMap(json['params']); +- if (params !=3D null) { +- Map analysis =3D asMap(params['analysis']); +- if (analysis !=3D null && analysis['isAnalyzing'] =3D=3D false) { +- return new WaitForAnalysisCompleteOperation(); +- } +- } +- } +- if (event =3D=3D SERVER_NOTIFICATION_CONNECTED) { +- // {"event":"server.connected","params":{"version":"1.7.0"}} +- return new StartServerOperation(); +- } +- if (eventsSeen.add(event)) { +- logger.log(Level.INFO, 'Ignored notification: $event\n $json'); +- } +- return null; +- } +- +- /** +- * Return an operation for the request or `null` if none. +- */ +- Operation convertRequest(Map origJson) { +- Map json =3D asMap(translateSrcPaths(origJson)); +- requestMap[json['id']] =3D json; +- String method =3D json['method']; +- // Sanity check operations that modify source +- // to ensure that the operation is on source in temp space +- if (method =3D=3D ANALYSIS_REQUEST_UPDATE_CONTENT) { +- // Track overlays in parallel with the analysis server +- // so that when an overlay is removed, the file can be updated on d= isk +- Request request =3D new Request.fromJson(json); +- var params =3D new AnalysisUpdateContentParams.fromRequest(request); +- params.files.forEach((String filePath, change) { +- if (change is AddContentOverlay) { +- String content =3D change.content; +- if (content =3D=3D null) { +- throw 'expected new overlay content\n$json'; +- } +- overlays[filePath] =3D content; +- } else if (change is ChangeContentOverlay) { +- String content =3D overlays[filePath]; +- if (content =3D=3D null) { +- throw 'expected cached overlay content\n$json'; +- } +- overlays[filePath] =3D SourceEdit.applySequence(content, change= .edits); +- } else if (change is RemoveContentOverlay) { +- String content =3D overlays.remove(filePath); +- if (content =3D=3D null) { +- throw 'expected cached overlay content\n$json'; +- } +- if (!path.isWithin(tmpSrcDirPath, filePath)) { +- throw 'found path referencing source outside temp space\n$fil= ePath\n$json'; +- } +- new File(filePath).writeAsStringSync(content); +- } else { +- throw 'unknown overlay change $change\n$json'; +- } +- }); +- return new RequestOperation(this, json); +- } +- // Track performance for completion notifications +- if (method =3D=3D COMPLETION_REQUEST_GET_SUGGESTIONS) { +- return new CompletionRequestOperation(this, json); +- } +- // TODO(danrubel) replace this with code +- // that just forwards the translated request +- if (method =3D=3D ANALYSIS_REQUEST_GET_HOVER || +- method =3D=3D ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS || +- method =3D=3D ANALYSIS_REQUEST_SET_PRIORITY_FILES || +- method =3D=3D ANALYSIS_REQUEST_SET_SUBSCRIPTIONS || +- method =3D=3D ANALYSIS_REQUEST_UPDATE_OPTIONS || +- method =3D=3D EDIT_REQUEST_GET_ASSISTS || +- method =3D=3D EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS || +- method =3D=3D EDIT_REQUEST_GET_FIXES || +- method =3D=3D EDIT_REQUEST_GET_REFACTORING || +- method =3D=3D EDIT_REQUEST_SORT_MEMBERS || +- method =3D=3D EXECUTION_REQUEST_CREATE_CONTEXT || +- method =3D=3D EXECUTION_REQUEST_DELETE_CONTEXT || +- method =3D=3D EXECUTION_REQUEST_MAP_URI || +- method =3D=3D EXECUTION_REQUEST_SET_SUBSCRIPTIONS || +- method =3D=3D SEARCH_REQUEST_FIND_ELEMENT_REFERENCES || +- method =3D=3D SEARCH_REQUEST_FIND_MEMBER_DECLARATIONS || +- method =3D=3D SERVER_REQUEST_GET_VERSION || +- method =3D=3D SERVER_REQUEST_SET_SUBSCRIPTIONS) { +- return new RequestOperation(this, json); +- } +- throw 'unknown request: $method\n $json'; +- } +- +- /** +- * Return an operation for the recorded/expected response. +- */ +- Operation convertResponse(Map json) { +- return new ResponseOperation(this, asMap(requestMap.remove(json['id']= )), +- asMap(translateSrcPaths(json))); +- } +- +- void logOverlayContent() { +- logger.log(Level.WARNING, '${overlays.length} overlays'); +- List allPaths =3D overlays.keys.toList()..sort(); +- for (String filePath in allPaths) { +- logger.log(Level.WARNING, 'overlay $filePath\n${overlays[filePath]}= '); +- } +- } +- +- /** +- * Process an error response from the server by either +- * completing the associated completer in the [responseCompleters] +- * or stashing it in [responseMap] if no completer exists. +- */ +- void processErrorResponse(String id, exception) { +- var result =3D exception; +- if (exception is UnimplementedError) { +- if (exception.message.startsWith(ERROR_PREFIX)) { +- result =3D JSON.decode(exception.message.substring(ERROR_PREFIX.l= ength)); +- } +- } +- processResponseResult(id, result); +- } +- +- /** +- * Process the expected response by completing the given completer +- * with the result if it has already been received, +- * or caching the completer to be completed when the server +- * returns the associated result. +- * Return a future that completes when the response is received +- * or `null` if the response has already been received +- * and the completer completed. +- */ +- Future processExpectedResponse(String id, Completer completer) { +- if (responseMap.containsKey(id)) { +- logger.log(Level.INFO, 'processing cached response $id'); +- completer.complete(responseMap.remove(id)); +- return null; +- } else { +- logger.log(Level.INFO, 'waiting for response $id'); +- responseCompleters[id] =3D completer; +- return completer.future; +- } +- } +- +- /** +- * Process a success response result from the server by either +- * completing the associated completer in the [responseCompleters] +- * or stashing it in [responseMap] if no completer exists. +- * The response result may be `null`. +- */ +- void processResponseResult(String id, result) { +- Completer completer =3D responseCompleters[id]; +- if (completer !=3D null) { +- logger.log(Level.INFO, 'processing response $id'); +- completer.complete(result); +- } else { +- logger.log(Level.INFO, 'caching response $id'); +- responseMap[id] =3D result; +- } +- } +- +- /** +- * Recursively translate source paths in the specified JSON to reference +- * the temporary source used during performance measurement rather than +- * the original source when the instrumentation or log file was generat= ed. +- */ +- translateSrcPaths(json) { +- if (json is String) { +- return srcPathMap.translate(json); +- } +- if (json is List) { +- List result =3D []; +- for (int i =3D 0; i < json.length; ++i) { +- result.add(translateSrcPaths(json[i])); +- } +- return result; +- } +- if (json is Map) { +- Map result =3D new Map(); +- json.forEach((origKey, value) { +- result[translateSrcPaths(origKey)] =3D translateSrcPaths(value); +- }); +- return result; +- } +- return json; +- } +-} +- +-/** +- * [InputConverter] converts an input stream +- * into a series of operations to be sent to the analysis server. +- * The input stream can be either an instrumentation or log file. +- */ +-class InputConverter extends Converter { +- final Logger logger =3D new Logger('InputConverter'); +- +- /** +- * A mapping of source path prefixes +- * from location where instrumentation or log file was generated +- * to the target location of the source using during performance measur= ement. +- */ +- final PathMap srcPathMap; +- +- /** +- * The root directory for all source being modified +- * during performance measurement. +- */ +- final String tmpSrcDirPath; +- +- /** +- * The number of lines read before the underlying converter was determi= ned +- * or the end of file was reached. +- */ +- int headerLineCount =3D 0; +- +- /** +- * The underlying converter used to translate lines into operations +- * or `null` if it has not yet been determined. +- */ +- Converter converter; +- +- /** +- * [active] is `true` if converting lines to operations +- * or `false` if an exception has occurred. +- */ +- bool active =3D true; +- +- InputConverter(this.tmpSrcDirPath, this.srcPathMap); +- +- @override +- Operation convert(String line) { +- if (!active) { +- return null; +- } +- if (converter !=3D null) { +- try { +- return converter.convert(line); +- } catch (e) { +- active =3D false; +- rethrow; +- } +- } +- if (headerLineCount =3D=3D 20) { +- throw 'Failed to determine input file format'; +- } +- if (InstrumentationInputConverter.isFormat(line)) { +- converter =3D new InstrumentationInputConverter(tmpSrcDirPath, srcP= athMap); +- } else if (LogFileInputConverter.isFormat(line)) { +- converter =3D new LogFileInputConverter(tmpSrcDirPath, srcPathMap); +- } +- if (converter !=3D null) { +- return converter.convert(line); +- } +- logger.log(Level.INFO, 'skipped input line: $line'); +- return null; +- } +- +- @override +- _InputSink startChunkedConversion(outSink) { +- return new _InputSink(this, outSink); +- } +-} +- +-/** +- * A container of [PathMapEntry]s used to translate a source path in the = log +- * before it is sent to the analysis server. +- */ +-class PathMap { +- final List entries =3D []; +- +- void add(String oldSrcPrefix, String newSrcPrefix) { +- entries.add(new PathMapEntry(oldSrcPrefix, newSrcPrefix)); +- } +- +- String translate(String original) { +- String result =3D original; +- for (PathMapEntry entry in entries) { +- result =3D entry.translate(result); +- } +- return result; +- } +-} +- +-/** +- * An entry in [PathMap] used to translate a source path in the log +- * before it is sent to the analysis server. +- */ +-class PathMapEntry { +- final String oldSrcPrefix; +- final String newSrcPrefix; +- +- PathMapEntry(this.oldSrcPrefix, this.newSrcPrefix); +- +- String translate(String original) { +- return original.startsWith(oldSrcPrefix) +- ? '$newSrcPrefix${original.substring(oldSrcPrefix.length)}' +- : original; +- } +-} +- +-class _InputSink extends ChunkedConversionSink { +- final Converter converter; +- final outSink; +- +- _InputSink(this.converter, this.outSink); +- +- @override +- void add(String line) { +- Operation op =3D converter.convert(line); +- if (op !=3D null) { +- outSink.add(op); +- } +- } +- +- @override +- void close() { +- outSink.close(); +- } +-} +diff --git a/pkg/analysis_server/benchmark/integration/instrumentation_inp= ut_converter.dart b/pkg/analysis_server/benchmark/integration/instrumentati= on_input_converter.dart +deleted file mode 100644 +index 7a875942643..00000000000 +--- a/pkg/analysis_server/benchmark/integration/instrumentation_input_conv= erter.dart ++++ /dev/null +@@ -1,146 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:logging/logging.dart'; +- +-import 'input_converter.dart'; +-import 'operation.dart'; +- +-final int COLON =3D ':'.codeUnitAt(0); +- +-/** +- * [InstrumentationInputConverter] converts an instrumentation stream +- * into a series of operations to be sent to the analysis server. +- */ +-class InstrumentationInputConverter extends CommonInputConverter { +- final Set codesSeen =3D new Set(); +- +- /** +- * [readBuffer] holds the contents of the file being read from disk +- * as recorded in the instrumentation log +- * or `null` if not converting a "Read" entry. +- */ +- StringBuffer readBuffer =3D null; +- +- InstrumentationInputConverter(String tmpSrcDirPath, PathMap srcPathMap) +- : super(tmpSrcDirPath, srcPathMap); +- +- @override +- Operation convert(String line) { +- List fields; +- try { +- fields =3D _parseFields(line); +- if (fields.length < 2) { +- if (readBuffer !=3D null) { +- readBuffer.writeln(fields.length =3D=3D 1 ? fields[0] : ''); +- return null; +- } +- throw 'Failed to process line:\n$line'; +- } +- if (readBuffer !=3D null) { +- readBuffer =3D null; +- } +- } catch (e, s) { +- throw new AnalysisException( +- 'Failed to parse line\n$line', new CaughtException(e, s)); +- } +- // int timeStamp =3D int.parse(fields[0], onError: (_) =3D> -1); +- String opCode =3D fields[1]; +- if (opCode =3D=3D InstrumentationService.TAG_NOTIFICATION) { +- return convertNotification(decodeJson(line, fields[2])); +- } else if (opCode =3D=3D 'Read') { +- // 1434096943209:Read:/some/file/path:1434095535000: +- //String filePath =3D fields[2]; +- readBuffer =3D new StringBuffer(fields.length > 4 ? fields[4] : ''); +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_REQUEST) { +- return convertRequest(decodeJson(line, fields[2])); +- } else if (opCode =3D=3D InstrumentationService.TAG_RESPONSE) { +- // 1434096937454:Res:{"id"::"0","result"::{"version"::"1.7.0"}} +- return convertResponse(decodeJson(line, fields[2])); +- } else if (opCode =3D=3D InstrumentationService.TAG_ANALYSIS_TASK) { +- // 1434096943208:Task:/Users/ +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_LOG_ENTRY) { +- // 1434096937454:Res:{"id"::"0","result"::{"version"::"1.7.0"}} +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_PERFORMANCE) { +- //1434096960092:Perf:analysis_full:16884:context_id=3D0 +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_SUBPROCESS_START)= { +- // 1434096938634:SPStart:0:/Users/da +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_SUBPROCESS_RESULT= ) { +- // 1434096939068:SPResult:0:0:"{\"packages\"::{\"rpi_lidar\"::\"/Us= ers +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_VERSION) { +- // 1434096937358:Ver:1421765742287333878467:org.dartlang.dartplugin +- return null; +- } else if (opCode =3D=3D InstrumentationService.TAG_WATCH_EVENT) { +- // 1434097460414:Watch:/some/file/path +- return null; +- } +- if (codesSeen.add(opCode)) { +- logger.log( +- Level.WARNING, 'Ignored instrumentation op code: $opCode\n $li= ne'); +- } +- return null; +- } +- +- Map decodeJson(String line, String text) { +- try { +- return asMap(JSON.decode(text)); +- } catch (e, s) { +- throw new AnalysisException( +- 'Failed to decode JSON: $text\n$line', new CaughtException(e, s= )); +- } +- } +- +- /** +- * Determine if the given line is from an instrumentation file. +- * For example: +- * `1433175833005:Ver:1421765742287333878467:org.dartlang.dartplugin:0.= 0.0:1.6.2:1.11.0-edge.131698` +- */ +- static bool isFormat(String line) { +- List fields =3D _parseFields(line); +- if (fields.length < 2) return false; +- int timeStamp =3D int.parse(fields[0], onError: (_) =3D> -1); +- String opCode =3D fields[1]; +- return timeStamp > 0 && opCode =3D=3D 'Ver'; +- } +- +- /** +- * Extract fields from the given [line]. +- */ +- static List _parseFields(String line) { +- List fields =3D new List(); +- int index =3D 0; +- StringBuffer sb =3D new StringBuffer(); +- while (index < line.length) { +- int code =3D line.codeUnitAt(index); +- if (code =3D=3D COLON) { +- // Embedded colons are doubled +- int next =3D index + 1; +- if (next < line.length && line.codeUnitAt(next) =3D=3D COLON) { +- sb.write(':'); +- ++index; +- } else { +- fields.add(sb.toString()); +- sb.clear(); +- } +- } else { +- sb.writeCharCode(code); +- } +- ++index; +- } +- if (sb.isNotEmpty) { +- fields.add(sb.toString()); +- } +- return fields; +- } +-} +diff --git a/pkg/analysis_server/benchmark/integration/local_runner.dart b= /pkg/analysis_server/benchmark/integration/local_runner.dart +deleted file mode 100644 +index 28ef5bb9136..00000000000 +--- a/pkg/analysis_server/benchmark/integration/local_runner.dart ++++ /dev/null +@@ -1,91 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:path/path.dart'; +- +-import 'main.dart' as performance; +- +-// Local driver for performance measurement +- +-main(List args) { +- /* +- * Parse arguments +- */ +- if (args.length < 3) printHelp('Expected 3 arguments'); +- var gitDir =3D new Directory(args[0]); +- if (!gitDir.existsSync()) printHelp('${gitDir.path} does not exist'); +- if (!new Directory(join(gitDir.path, '.git')).existsSync()) +- printHelp('${gitDir.path} does not appear to be a local git repositor= y'); +- var branch =3D args[1]; +- var inputFile =3D new File(args[2]); +- if (!inputFile.existsSync()) printHelp('${inputFile.path} does not exis= t'); +- /* +- * Create a new temp directory +- */ +- var tmpDir =3D new Directory( +- join(Directory.systemTemp.path, 'analysis_server_perf_target')); +- if (!tmpDir.path.contains('tmp')) throw 'invalid tmp directory\n $tmpD= ir'; +- print('Extracting target analysis environment into\n ${tmpDir.path}'); +- if (tmpDir.existsSync()) tmpDir.deleteSync(recursive: true); +- tmpDir.createSync(recursive: true); +- /* +- * Setup the initial target source in the temp directory +- */ +- var tarFilePath =3D join(tmpDir.path, 'targetSrc.tar'); +- var result =3D Process.runSync('git', ['archive', branch, '-o', tarFile= Path], +- workingDirectory: gitDir.path); +- if (result.exitCode !=3D 0) throw 'failed to obtain target source: $res= ult'; +- var tmpSrcDirPath =3D join(tmpDir.path, 'targetSrc'); +- new Directory(tmpSrcDirPath).createSync(); +- result =3D Process.runSync('tar', ['-xf', tarFilePath], +- workingDirectory: tmpSrcDirPath); +- if (result.exitCode !=3D 0) throw 'failed to extract target source: $re= sult'; +- /* +- * Symlink the out or xcodebuild directory +- */ +- var outDirName =3D 'out'; +- if (!new Directory(join(gitDir.path, outDirName)).existsSync()) { +- outDirName =3D 'xcodebuild'; +- } +- if (!new Directory(join(gitDir.path, outDirName)).existsSync()) { +- throw 'failed to find out or xcodebuild directory'; +- } +- result =3D Process.runSync('ln', +- ['-s', join(gitDir.path, outDirName), join(tmpSrcDirPath, outDirNam= e)]); +- if (result.exitCode !=3D 0) throw 'failed to link out or xcodebuild: $r= esult'; +- /* +- * Collect arguments +- */ +- var perfArgs =3D [ +- '-i${inputFile.path}', +- '-t$tmpSrcDirPath', +- ]; +- for (int index =3D 3; index < args.length; ++index) { +- perfArgs.add(args[index].replaceAll('@tmpSrcDir@', tmpSrcDirPath)); +- } +- perfArgs.add('-m${gitDir.path},$tmpSrcDirPath'); +- /* +- * Launch the performance analysis tool +- */ +- performance.main(perfArgs); +-} +- +-/// Print help and exit +-void printHelp([String errMsg]) { +- if (errMsg !=3D null) { +- print(''); +- print('Error: $errMsg'); +- print(''); +- } +- print('''Required arguments: +-gitDir =3D a path to the git repository containing the initial target sou= rce +-branch =3D the branch containing the initial target source +-inputFile =3D the instrumentation or log file +- +-Optional arguments:'''); +- print(performance.argParser.usage); +- exit(1); +-} +diff --git a/pkg/analysis_server/benchmark/integration/log_file_input_conv= erter.dart b/pkg/analysis_server/benchmark/integration/log_file_input_conve= rter.dart +deleted file mode 100644 +index 79d3d6e955c..00000000000 +--- a/pkg/analysis_server/benchmark/integration/log_file_input_converter.d= art ++++ /dev/null +@@ -1,82 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import 'package:analyzer/exception/exception.dart'; +-import 'package:logging/logging.dart'; +- +-import 'input_converter.dart'; +-import 'operation.dart'; +- +-const CONNECTED_MSG_FRAGMENT =3D ' <=3D {"event":"server.connected"'; +-const RECEIVED_FRAGMENT =3D ' <=3D {'; +-const SENT_FRAGMENT =3D ' =3D> {'; +-final int NINE =3D '9'.codeUnitAt(0); +-final int ZERO =3D '0'.codeUnitAt(0); +- +-/** +- * [LogFileInputConverter] converts a log file stream +- * into a series of operations to be sent to the analysis server. +- */ +-class LogFileInputConverter extends CommonInputConverter { +- LogFileInputConverter(String tmpSrcDirPath, PathMap srcPathMap) +- : super(tmpSrcDirPath, srcPathMap); +- +- @override +- Operation convert(String line) { +- try { +- String timeStampString =3D _parseTimeStamp(line); +- String data =3D line.substring(timeStampString.length); +- if (data.startsWith(RECEIVED_FRAGMENT)) { +- Map json =3D asMap(JSON.decode(data.substring(4)= )); +- if (json.containsKey('event')) { +- return convertNotification(json); +- } else { +- return convertResponse(json); +- } +- } else if (data.startsWith(SENT_FRAGMENT)) { +- Map json =3D asMap(JSON.decode(data.substring(4)= )); +- if (json.containsKey('method')) { +- return convertRequest(json); +- } +- return null; +- } +- logger.log(Level.INFO, 'unknown input line: $line'); +- return null; +- } catch (e, s) { +- throw new AnalysisException( +- 'Failed to parse line\n $line', new CaughtException(e, s)); +- } +- } +- +- /** +- * Determine if the given line is from an instrumentation file. +- * For example: +- * `1428347977499 <=3D {"event":"server.connected","params":{"version":= "1.6.0"}}` +- */ +- static bool isFormat(String line) { +- String timeStampString =3D _parseTimeStamp(line); +- int start =3D timeStampString.length; +- int end =3D start + CONNECTED_MSG_FRAGMENT.length; +- return (10 < start && end < line.length) && +- line.substring(start, end) =3D=3D CONNECTED_MSG_FRAGMENT; +- } +- +- /** +- * Parse the given line and return the millisecond timestamp or `null` +- * if it cannot be determined. +- */ +- static String _parseTimeStamp(String line) { +- int index =3D 0; +- while (index < line.length) { +- int code =3D line.codeUnitAt(index); +- if (code < ZERO || NINE < code) { +- return line.substring(0, index); +- } +- ++index; +- } +- return line; +- } +-} +diff --git a/pkg/analysis_server/benchmark/integration/main.dart b/pkg/ana= lysis_server/benchmark/integration/main.dart +deleted file mode 100644 +index 0760b171fab..00000000000 +--- a/pkg/analysis_server/benchmark/integration/main.dart ++++ /dev/null +@@ -1,246 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:args/args.dart'; +-import 'package:logging/logging.dart'; +-import 'package:path/path.dart' as path; +- +-import 'driver.dart'; +-import 'input_converter.dart'; +-import 'operation.dart'; +- +-/** +- * Launch and interact with the analysis server. +- */ +-main(List rawArgs) { +- Logger logger =3D new Logger('Performance Measurement Client'); +- logger.onRecord.listen((LogRecord rec) { +- print(rec.message); +- }); +- PerfArgs args =3D parseArgs(rawArgs); +- +- Driver driver =3D new Driver(diagnosticPort: args.diagnosticPort); +- Stream stream =3D openInput(args); +- StreamSubscription subscription; +- subscription =3D stream.listen((Operation op) { +- Future future =3D driver.perform(op); +- if (future !=3D null) { +- logger.log(Level.FINE, 'pausing operations for ${op.runtimeType}'); +- subscription.pause(future.then((_) { +- logger.log(Level.FINE, 'resuming operations'); +- })); +- } +- }, onDone: () { +- subscription.cancel(); +- driver.stopServer(SHUTDOWN_TIMEOUT); +- }, onError: (e, s) { +- subscription.cancel(); +- logger.log(Level.SEVERE, '$e\n$s'); +- driver.stopServer(SHUTDOWN_TIMEOUT); +- }); +- driver.runComplete.then((Results results) { +- results.printResults(); +- }).whenComplete(() { +- return subscription.cancel(); +- }); +-} +- +-const DIAGNOSTIC_PORT_OPTION =3D 'diagnosticPort'; +-const HELP_CMDLINE_OPTION =3D 'help'; +-const INPUT_CMDLINE_OPTION =3D 'input'; +-const MAP_OPTION =3D 'map'; +- +-/** +- * The amount of time to give the server to respond to a shutdown request +- * before forcibly terminating it. +- */ +-const Duration SHUTDOWN_TIMEOUT =3D const Duration(seconds: 25); +- +-const TMP_SRC_DIR_OPTION =3D 'tmpSrcDir'; +-const VERBOSE_CMDLINE_OPTION =3D 'verbose'; +-const VERY_VERBOSE_CMDLINE_OPTION =3D 'vv'; +- +-ArgParser _argParser; +- +-ArgParser get argParser { +- _argParser =3D new ArgParser(); +- +- _argParser.addOption(INPUT_CMDLINE_OPTION, +- abbr: 'i', +- help: '\n' +- 'The input file specifying how this client should interact with= the server.\n' +- 'If the input file name is "stdin", then the instructions are r= ead from standard input.'); +- _argParser.addOption(MAP_OPTION, +- abbr: 'm', +- allowMultiple: true, +- splitCommas: false, +- help: ',\n' +- 'This option defines a mapping from the original source directo= ry \n' +- 'when the instrumentation or log file was generated\n' +- 'to the target source directory used during perfor= mance testing.\n' +- 'Multiple mappings can be specified.\n' +- 'WARNING: The contents of the target directory will be modified= '); +- _argParser.addOption(TMP_SRC_DIR_OPTION, +- abbr: 't', +- help: '\n' +- 'The temporary directory containing source used during performa= nce measurement.\n' +- 'WARNING: The contents of the target directory will be modified= '); +- _argParser.addOption(DIAGNOSTIC_PORT_OPTION, +- abbr: 'd', +- help: 'localhost port on which server will provide diagnostic web p= ages'); +- _argParser.addFlag(VERBOSE_CMDLINE_OPTION, +- abbr: 'v', help: 'Verbose logging', negatable: false); +- _argParser.addFlag(VERY_VERBOSE_CMDLINE_OPTION, +- help: 'Extra verbose logging', negatable: false); +- _argParser.addFlag(HELP_CMDLINE_OPTION, +- abbr: 'h', help: 'Print this help information', negatable: false); +- return _argParser; +-} +- +-/** +- * Open and return the input stream specifying how this client +- * should interact with the analysis server. +- */ +-Stream openInput(PerfArgs args) { +- var logger =3D new Logger('openInput'); +- Stream> inputRaw; +- if (args.inputPath =3D=3D 'stdin') { +- inputRaw =3D stdin; +- } else { +- inputRaw =3D new File(args.inputPath).openRead(); +- } +- for (PathMapEntry entry in args.srcPathMap.entries) { +- logger.log( +- Level.INFO, +- 'mapping source path\n' +- ' from ${entry.oldSrcPrefix}\n to ${entry.newSrcPrefix}'); +- } +- logger.log(Level.INFO, 'tmpSrcDir: ${args.tmpSrcDirPath}'); +- return inputRaw +- .transform(SYSTEM_ENCODING.decoder) +- .transform(new LineSplitter()) +- .transform(new InputConverter(args.tmpSrcDirPath, args.srcPathMap)); +-} +- +-/** +- * Parse the command line arguments. +- */ +-PerfArgs parseArgs(List rawArgs) { +- ArgResults args; +- PerfArgs perfArgs =3D new PerfArgs(); +- try { +- args =3D argParser.parse(rawArgs); +- } on Exception catch (e) { +- print(e); +- printHelp(); +- exit(1); +- } +- +- bool showHelp =3D args[HELP_CMDLINE_OPTION] || args.rest.isNotEmpty; +- +- bool isMissing(key) =3D> args[key] =3D=3D null || args[key].isEmpty; +- +- perfArgs.inputPath =3D args[INPUT_CMDLINE_OPTION]; +- if (isMissing(INPUT_CMDLINE_OPTION)) { +- print('missing $INPUT_CMDLINE_OPTION argument'); +- showHelp =3D true; +- } +- +- for (String pair in args[MAP_OPTION]) { +- if (pair is String) { +- int index =3D pair.indexOf(','); +- if (index !=3D -1 && pair.indexOf(',', index + 1) =3D=3D -1) { +- String oldSrcPrefix =3D _withTrailingSeparator(pair.substring(0, = index)); +- String newSrcPrefix =3D _withTrailingSeparator(pair.substring(ind= ex + 1)); +- if (new Directory(newSrcPrefix).existsSync()) { +- perfArgs.srcPathMap.add(oldSrcPrefix, newSrcPrefix); +- continue; +- } +- } +- } +- print('must specifiy $MAP_OPTION ,'); +- showHelp =3D true; +- } +- +- perfArgs.tmpSrcDirPath =3D _withTrailingSeparator(args[TMP_SRC_DIR_OPTI= ON]); +- if (isMissing(TMP_SRC_DIR_OPTION)) { +- print('missing $TMP_SRC_DIR_OPTION argument'); +- showHelp =3D true; +- } +- +- String portText =3D args[DIAGNOSTIC_PORT_OPTION]; +- if (portText !=3D null) { +- perfArgs.diagnosticPort =3D int.parse(portText, onError: (s) { +- print('invalid $DIAGNOSTIC_PORT_OPTION: $s'); +- showHelp =3D true; +- }); +- } +- +- if (args[VERY_VERBOSE_CMDLINE_OPTION] || rawArgs.contains('-vv')) { +- Logger.root.level =3D Level.FINE; +- } else if (args[VERBOSE_CMDLINE_OPTION]) { +- Logger.root.level =3D Level.INFO; +- } else { +- Logger.root.level =3D Level.WARNING; +- } +- +- if (showHelp) { +- printHelp(); +- exit(1); +- } +- +- return perfArgs; +-} +- +-void printHelp() { +- print(''); +- print('Launch and interact with the AnalysisServer'); +- print(''); +- print(argParser.usage); +-} +- +-/** +- * Ensure that the given path has a trailing separator +- */ +-String _withTrailingSeparator(String dirPath) { +- if (dirPath !=3D null && dirPath.length > 4) { +- if (!dirPath.endsWith(path.separator)) { +- return '$dirPath${path.separator}'; +- } +- } +- return dirPath; +-} +- +-/** +- * The performance measurement arguments specified on the command line. +- */ +-class PerfArgs { +- /** +- * The file path of the instrumentation or log file +- * used to drive performance measurement, +- * or 'stdin' if this information should be read from standard input. +- */ +- String inputPath; +- +- /** +- * A mapping from the original source directory +- * when the instrumentation or log file was generated +- * to the target source directory used during performance testing. +- */ +- final PathMap srcPathMap =3D new PathMap(); +- +- /** +- * The temporary directory containing source used during performance me= asurement. +- */ +- String tmpSrcDirPath; +- +- /** +- * The diagnostic port for Analysis Server or `null` if none. +- */ +- int diagnosticPort; +-} +diff --git a/pkg/analysis_server/benchmark/integration/operation.dart b/pk= g/analysis_server/benchmark/integration/operation.dart +deleted file mode 100644 +index 75cf2a7edc9..00000000000 +--- a/pkg/analysis_server/benchmark/integration/operation.dart ++++ /dev/null +@@ -1,236 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:logging/logging.dart'; +- +-import 'driver.dart'; +-import 'input_converter.dart'; +- +-/** +- * A [CompletionRequestOperation] tracks response time along with +- * the first and last completion notifications. +- */ +-class CompletionRequestOperation extends RequestOperation { +- Driver driver; +- StreamSubscription subscription; +- String notificationId; +- Stopwatch stopwatch; +- bool firstNotification =3D true; +- +- CompletionRequestOperation( +- CommonInputConverter converter, Map json) +- : super(converter, json); +- +- @override +- Future perform(Driver driver) { +- this.driver =3D driver; +- subscription =3D driver.onCompletionResults.listen(processNotificatio= n); +- return super.perform(driver); +- } +- +- void processNotification(CompletionResultsParams event) { +- if (event.id =3D=3D notificationId) { +- Duration elapsed =3D stopwatch.elapsed; +- if (firstNotification) { +- firstNotification =3D false; +- driver.results.record('completion notification first', elapsed, +- notification: true); +- } +- if (event.isLast) { +- subscription.cancel(); +- driver.results.record('completion notification last', elapsed, +- notification: true); +- } +- } +- } +- +- @override +- void processResult( +- String id, Map result, Stopwatch stopwatch) { +- notificationId =3D result['id']; +- this.stopwatch =3D stopwatch; +- super.processResult(id, result, stopwatch); +- } +-} +- +-/** +- * An [Operation] represents an action such as sending a request to the s= erver. +- */ +-abstract class Operation { +- Future perform(Driver driver); +-} +- +-/** +- * A [RequestOperation] sends a [JSON] request to the server. +- */ +-class RequestOperation extends Operation { +- final CommonInputConverter converter; +- final Map json; +- +- RequestOperation(this.converter, this.json); +- +- @override +- Future perform(Driver driver) { +- Stopwatch stopwatch =3D new Stopwatch(); +- String originalId =3D json['id']; +- String method =3D json['method']; +- json['clientRequestTime'] =3D new DateTime.now().millisecondsSinceEpo= ch; +- driver.logger.log(Level.FINE, 'Sending request: $method\n $json'); +- stopwatch.start(); +- +- void recordResult(bool success, result) { +- Duration elapsed =3D stopwatch.elapsed; +- driver.results.record(method, elapsed, success: success); +- driver.logger +- .log(Level.FINE, 'Response received: $method : $elapsed\n $res= ult'); +- } +- +- driver +- .send(method, converter.asMap(json['params'])) +- .then((Map result) { +- recordResult(true, result); +- processResult(originalId, result, stopwatch); +- }).catchError((exception) { +- recordResult(false, exception); +- converter.processErrorResponse(originalId, exception); +- }); +- return null; +- } +- +- void processResult( +- String id, Map result, Stopwatch stopwatch) { +- converter.processResponseResult(id, result); +- } +-} +- +-/** +- * A [ResponseOperation] waits for a [JSON] response from the server. +- */ +-class ResponseOperation extends Operation { +- static final Duration responseTimeout =3D new Duration(seconds: 60); +- final CommonInputConverter converter; +- final Map requestJson; +- final Map responseJson; +- final Completer completer =3D new Completer(); +- Driver driver; +- +- ResponseOperation(this.converter, this.requestJson, this.responseJson) { +- completer.future.then(_processResult).timeout(responseTimeout); +- } +- +- @override +- Future perform(Driver driver) { +- this.driver =3D driver; +- return converter.processExpectedResponse(responseJson['id'], complete= r); +- } +- +- bool _equal(expectedResult, actualResult) { +- if (expectedResult is Map && actualResult is Map) { +- if (expectedResult.length =3D=3D actualResult.length) { +- return expectedResult.keys.every((key) { +- return key =3D=3D +- 'fileStamp' || // fileStamp values will not be the same= across runs +- _equal(expectedResult[key], actualResult[key]); +- }); +- } +- } else if (expectedResult is List && actualResult is List) { +- if (expectedResult.length =3D=3D actualResult.length) { +- for (int i =3D 0; i < expectedResult.length; ++i) { +- if (!_equal(expectedResult[i], actualResult[i])) { +- return false; +- } +- } +- return true; +- } +- } +- return expectedResult =3D=3D actualResult; +- } +- +- /** +- * Compare the expected and actual server response result. +- */ +- void _processResult(actualResult) { +- var expectedResult =3D responseJson['result']; +- if (!_equal(expectedResult, actualResult)) { +- var expectedError =3D responseJson['error']; +- String format(value) { +- String text =3D '\n$value'; +- if (text.endsWith('\n')) { +- text =3D text.substring(0, text.length - 1); +- } +- return text.replaceAll('\n', '\n '); +- } +- +- String message =3D 'Request:${format(requestJson)}\n' +- 'expected result:${format(expectedResult)}\n' +- 'expected error:${format(expectedError)}\n' +- 'but received:${format(actualResult)}'; +- driver.results.recordUnexpectedResults(requestJson['method']); +- converter.logOverlayContent(); +- if (expectedError =3D=3D null) { +- converter.logger.log(Level.SEVERE, message); +- } else { +- throw message; +- } +- } +- } +-} +- +-class StartServerOperation extends Operation { +- @override +- Future perform(Driver driver) { +- return driver.startServer(); +- } +-} +- +-class WaitForAnalysisCompleteOperation extends Operation { +- @override +- Future perform(Driver driver) { +- DateTime start =3D new DateTime.now(); +- driver.logger.log(Level.FINE, 'waiting for analysis to complete'); +- StreamSubscription subscription; +- Timer timer; +- Completer completer =3D new Completer(); +- bool isAnalyzing =3D false; +- subscription =3D driver.onServerStatus.listen((ServerStatusParams par= ams) { +- if (params.analysis !=3D null) { +- if (params.analysis.isAnalyzing) { +- isAnalyzing =3D true; +- } else { +- subscription.cancel(); +- timer.cancel(); +- DateTime end =3D new DateTime.now(); +- Duration delta =3D end.difference(start); +- driver.logger.log(Level.FINE, 'analysis complete after $delta'); +- completer.complete(); +- driver.results.record('analysis complete', delta, notification:= true); +- } +- } +- }); +- timer =3D new Timer.periodic(new Duration(milliseconds: 20), (_) { +- if (!isAnalyzing) { +- // TODO (danrubel) revisit this once source change requests are i= mplemented +- subscription.cancel(); +- timer.cancel(); +- driver.logger.log(Level.INFO, 'analysis never started'); +- completer.complete(); +- return; +- } +- // Timeout if no communication received within the last 60 seconds. +- double currentTime =3D driver.server.currentElapseTime; +- double lastTime =3D driver.server.lastCommunicationTime; +- if (currentTime - lastTime > 60) { +- subscription.cancel(); +- timer.cancel(); +- String message =3D 'gave up waiting for analysis to complete'; +- driver.logger.log(Level.WARNING, message); +- completer.completeError(message); +- } +- }); +- return completer.future; +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart= b/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart +deleted file mode 100644 +index 79330458007..00000000000 +--- a/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart ++++ /dev/null +@@ -1,161 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:args/args.dart'; +-import 'package:test/test.dart'; +- +-import 'performance_tests.dart'; +- +-/** +- * Pass in the directory of the source to be analyzed as option `--source= `, +- * optionally specify a priority file with `--priority` and the specific +- * test to run with `--metric`. If no test is specified, the default is +- * `analysis`. +- */ +-main(List arguments) { +- ArgParser parser =3D _createArgParser(); +- var args =3D parser.parse(arguments); +- if (args[SOURCE_OPTION] =3D=3D null) { +- print('path to source directory must be specified'); +- exit(1); +- } +- source =3D args[SOURCE_OPTION]; +- priorityFile =3D args[PRIORITY_FILE_OPTION]; +- List names =3D args[METRIC_NAME_OPTION] as List; +- for (var name in names) { +- metricNames.add(name as String); +- } +- +- var test; +- +- if (metricNames.isEmpty) { +- test =3D new AnalysisTimingTest(); +- } else { +- test =3D new SubscriptionTimingTest(); +- } +- +- Future.wait([test.test_timing()]); +-} +- +-const DEFAULT_METRIC =3D 'analysis'; +-const METRIC_NAME_OPTION =3D 'metric'; +-const PRIORITY_FILE_OPTION =3D 'priority'; +-const SOURCE_OPTION =3D 'source'; +- +-final metricNames =3D []; +-String priorityFile; +-String source; +- +-ArgParser _createArgParser() =3D> new ArgParser() +- ..addOption(METRIC_NAME_OPTION, +- help: 'metric name (defaults to `analysis`)', allowMultiple: true) +- ..addOption(SOURCE_OPTION, help: 'full path to source directory for ana= lysis') +- ..addOption(PRIORITY_FILE_OPTION, +- help: '(optional) full path to a priority file'); +- +-/** +- * AnalysisTimingTest measures the time taken by the analysis server to f= ully analyze +- * the given directory. Measurement is started after setting the analysis= root, and +- * analysis is considered complete on receiving the `"isAnalyzing": false= ` message +- * from the analysis server. +- */ +-class AnalysisTimingTest extends AbstractTimingTest { +- Future test_timing() async { +- // Set root after subscribing to avoid empty notifications. +- await init(source); +- +- setAnalysisRoot(); +- stopwatch.start(); +- await analysisFinished; +- print('analysis completed in ${stopwatch.elapsed}'); +- +- await shutdown(); +- } +-} +- +-class Metric { +- List timings =3D []; +- Stream eventStream; +- AnalysisService service; +- String name; +- Metric(this.name, this.service, this.eventStream); +- String toString() =3D> '$name: $service, ${eventStream.runtimeType}, $t= imings'; +-} +- +-/** +- * SubscriptionTimingTest measures the time taken by the analysis server = to return +- * information for navigation, semantic highlighting, outline, get occurr= ences, +- * overrides, folding and implemented. These timings are wrt to the speci= fied priority file +- * - the file that is currently opened and has focus in the editor. Measu= re the time from +- * when the client subscribes for the notifications till there is a respo= nse from the server. +- * Does not wait for analysis to be complete before subscribing for notif= ications. +- */ +-class SubscriptionTimingTest extends AbstractTimingTest { +- List _metrics; +- +- List get metrics =3D> _metrics ??=3D metricNames.map(getMetric)= .toList(); +- +- Metric getMetric(String name) { +- switch (name) { +- case 'folding': +- return new Metric(name, AnalysisService.FOLDING, onAnalysisFoldin= g); +- case 'highlighting': +- return new Metric( +- name, AnalysisService.HIGHLIGHTS, onAnalysisHighlights); +- case 'implemented': +- return new Metric( +- name, AnalysisService.IMPLEMENTED, onAnalysisImplemented); +- case 'navigation': +- return new Metric( +- name, AnalysisService.NAVIGATION, onAnalysisNavigation); +- case 'outline': +- return new Metric(name, AnalysisService.OUTLINE, onAnalysisOutlin= e); +- case 'occurences': +- return new Metric( +- name, AnalysisService.OCCURRENCES, onAnalysisOccurrences); +- case 'overrides': +- return new Metric(name, AnalysisService.OVERRIDES, onAnalysisOver= rides); +- } +- print('no metric found for $name'); +- exit(1); +- return null; // Won't get here. +- } +- +- Future test_timing() async { +-// debugStdio(); +- +- expect(metrics, isNotEmpty); +- expect(priorityFile, isNotNull, +- reason: 'A priority file must be specified for ' +- '${metrics.first.name} testing.'); +- +- await init(source); +- stopwatch.start(); +- +- metrics.forEach((Metric m) =3D> m.eventStream.listen((_) { +- m.timings.add( +- new Duration(milliseconds: stopwatch.elapsed.inMilliseconds= )); +- })); +- +- var subscriptions =3D >{}; +- metrics.forEach((Metric m) =3D> subscriptions[m.service] =3D [priorit= yFile]); +- +- sendAnalysisSetSubscriptions(subscriptions); +- +- // Set root after subscribing to avoid empty notifications. +- setAnalysisRoot(); +- +- sendAnalysisSetPriorityFiles([priorityFile]); +- +- await analysisFinished; +- print('analysis completed in ${stopwatch.elapsed}'); +- metrics.forEach((Metric m) =3D> print('${m.name} timings: ${m.timings= }')); +- +- await shutdown(); +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/benchmark_angular.dart b/p= kg/analysis_server/benchmark/perf/benchmark_angular.dart +deleted file mode 100644 +index c93138d86ba..00000000000 +--- a/pkg/analysis_server/benchmark/perf/benchmark_angular.dart ++++ /dev/null +@@ -1,115 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'benchmark_scenario.dart'; +-import 'memory_tests.dart'; +- +-main(List args) async { +- int length =3D args.length; +- if (length < 1) { +- print( +- 'Usage: dart benchmark_local.dart path_to_np8080 (an example ngda= rt project)' +- ' [benchmark_id]'); +- return; +- } +- paths =3D new PathHolder(projectPath: args[0]); +- String id =3D args.length >=3D 2 ? args[1] : null; +- if (id =3D=3D null) { +- for (String id in benchmarks.keys) { +- BenchmarkFunction benchmark =3D benchmarks[id]; +- await benchmark(id); +- } +- } else { +- BenchmarkFunction benchmark =3D benchmarks[id]; +- if (benchmark !=3D null) { +- benchmark(id); +- } +- } +-} +- +-const Map benchmarks =3D +- const { +- 'ng-initialAnalysis': run_ng_initialAnalysis, +- 'ng-change-dart': run_ng_change_dart, +- 'ng-change-html': run_ng_change_html, +- 'ng-memory-initialAnalysis': run_ng_memory_initialAnalysis, +-}; +- +-PathHolder paths; +- +-Future run_ng_change_dart(String id) async { +- String description =3D r''' +-1. Open 'packages/np8080'. +-2. Add an @Output to the class +-3. Measure the time to finish analysis. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- List times =3D await new BenchmarkScenario().waitAnalyze_change_an= alyze( +- roots: [paths.packageNp8080], +- file: paths.editorDart, +- fileChange: new FileChange( +- afterStr: 'showPreview =3D false;', +- insertStr: '@Output() EventEmitter myEventEmitter;'), +- numOfRepeats: 10); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_ng_change_html(String id) async { +- String description =3D r''' +-1. Open 'packages/np8080'. +-2. Change the contents of a mustache +-3. Measure the time to finish analysis. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- List times =3D await new BenchmarkScenario().waitAnalyze_change_an= alyze( +- roots: [paths.packageNp8080], +- file: paths.editorHtml, +- fileChange: new FileChange( +- afterStr: 'note.lastModified', afterStrBack: 4, insertStr: 'New= Name'), +- numOfRepeats: 4); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_ng_initialAnalysis(String id) async { +- String description =3D r''' +-1. Start server, set 'package/np8080' analysis roots. +-2. Measure the time to finish initial analysis. +-3. Shutdown the server. +-4. Go to (1). +-'''; +- List times =3D await BenchmarkScenario.start_waitInitialAnalysis_s= hutdown( +- roots: [paths.packageNp8080], numOfRepeats: 5); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_ng_memory_initialAnalysis(String id) async { +- String description =3D r''' +-1. Start server, set 'package/np8080' as the analysis root. +-2. Measure the memory usage after finishing initial analysis. +-3. Shutdown the server. +-4. Go to (1). +-'''; +- List sizes =3D await AnalysisServerMemoryUsageTest +- .start_waitInitialAnalysis_shutdown( +- roots: [paths.packageNp8080], numOfRepeats: 3); +- printMemoryResults(id, description, sizes); +-} +- +-typedef BenchmarkFunction(String id); +- +-class PathHolder { +- String editorHtml; +- String editorDart; +- String packageNp8080; +- +- PathHolder({String projectPath}) { +- editorHtml =3D '$projectPath/lib/editor/editor_component.html'; +- editorDart =3D '$projectPath/lib/editor/editor_component.dart'; +- packageNp8080 =3D projectPath; +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/benchmark_flutter.dart b/p= kg/analysis_server/benchmark/perf/benchmark_flutter.dart +deleted file mode 100644 +index 2e47a2b3bf8..00000000000 +--- a/pkg/analysis_server/benchmark/perf/benchmark_flutter.dart ++++ /dev/null +@@ -1,216 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-import 'benchmark_scenario.dart'; +-import 'memory_tests.dart'; +- +-main(List args) async { +- int length =3D args.length; +- if (length < 1) { +- print('Usage: dart benchmark_local.dart path_to_flutter_checkout' +- ' [benchmark_id]'); +- return; +- } +- paths =3D new PathHolder(flutterPath: args[0]); +- String id =3D args.length >=3D 2 ? args[1] : null; +- if (id =3D=3D null) { +- for (String id in benchmarks.keys) { +- BenchmarkFunction benchmark =3D benchmarks[id]; +- await benchmark(id); +- } +- } else { +- BenchmarkFunction benchmark =3D benchmarks[id]; +- if (benchmark !=3D null) { +- benchmark(id); +- } +- } +-} +- +-const Map benchmarks =3D +- const { +- 'flutter-initialAnalysis-1': run_flutter_initialAnalysis_1, +- 'flutter-initialAnalysis-2': run_flutter_initialAnalysis_2, +- 'flutter-change-1': run_flutter_change_1, +- 'flutter-change-2': run_flutter_change_2, +- 'flutter-completion-1': run_flutter_completion_1, +- 'flutter-completion-2': run_flutter_completion_2, +- 'flutter-refactoring-1': run_flutter_refactoring_1, +- 'flutter-memory-initialAnalysis-1': run_flutter_memory_initialAnalysis_= 1, +- 'flutter-memory-initialAnalysis-2': run_flutter_memory_initialAnalysis_= 2, +-}; +- +-PathHolder paths; +- +-Future run_flutter_change_1(String id) async { +- String description =3D r''' +-1. Open 'packages/flutter'. +-2. Change a method body in lib/src/painting/colors.dart +-3. Measure the time to finish analysis. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- List times =3D await new BenchmarkScenario().waitAnalyze_change_an= alyze( +- roots: [paths.packageFlutter], +- file: '${paths.packageFlutter}/lib/src/painting/colors.dart', +- fileChange: new FileChange( +- afterStr: 'final double h =3D hue % 360;', insertStr: 'print(12= 345);'), +- numOfRepeats: 10); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_flutter_change_2(String id) async { +- String description =3D r''' +-1. Open 'packages/flutter'. +-2. Change the name of a public method in lib/src/painting/colors.dart +-3. Measure the time to finish analysis. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- List times =3D await new BenchmarkScenario().waitAnalyze_change_an= alyze( +- roots: [paths.packageFlutter], +- file: '${paths.packageFlutter}/lib/src/painting/colors.dart', +- fileChange: new FileChange( +- afterStr: 'withValue(dou', afterStrBack: 4, insertStr: 'NewName= '), +- numOfRepeats: 5); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_flutter_completion_1(String id) async { +- String description =3D r''' +-1. Open 'packages/flutter'. +-2. Change a method body in packages/flutter/lib/src/material/button.dart +-3. Request code completion in this method and measure time to get results. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- String completionMarker =3D 'print(12345);'; +- List times =3D await new BenchmarkScenario() +- .waitAnalyze_change_getCompletion( +- roots: [paths.packageFlutter], +- file: '${paths.packageFlutter}/lib/src/material/button.dart', +- fileChange: new FileChange( +- afterStr: 'Widget build(BuildContext context) {', +- insertStr: completionMarker), +- completeAfterStr: completionMarker, +- numOfRepeats: 10); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_flutter_completion_2(String id) async { +- String description =3D r''' +-1. Open 'packages/flutter'. +-2. Change the name of a public method in lib/src/rendering/layer.dart +-3. Request code completion in this method and measure time to get results. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- List times =3D await new BenchmarkScenario() +- .waitAnalyze_change_getCompletion( +- roots: [paths.packageFlutter], +- file: '${paths.packageFlutter}/lib/src/rendering/layer.dart', +- fileChange: new FileChange( +- replaceWhat: 'void removeAllChildren() {', +- replaceWith: 'void removeAllChildren2() {print(12345);paren= t.'), +- completeAfterStr: 'print(12345);parent.', +- numOfRepeats: 5); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_flutter_initialAnalysis_1(String id) async { +- String description =3D r''' +-1. Start server, set 'hello_world' analysis root. +-2. Measure the time to finish initial analysis. +-3. Shutdown the server. +-4. Go to (1). +-'''; +- List times =3D await BenchmarkScenario.start_waitInitialAnalysis_s= hutdown( +- roots: [paths.exampleHelloWorld], numOfRepeats: 5); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_flutter_initialAnalysis_2(String id) async { +- String description =3D r''' +-1. Start server, set 'hello_world' and 'flutter_gallery' analysis roots. +-2. Measure the time to finish initial analysis. +-3. Shutdown the server. +-4. Go to (1). +-'''; +- List times =3D await BenchmarkScenario.start_waitInitialAnalysis_s= hutdown( +- roots: [paths.exampleHelloWorld, paths.exampleGallery], numOfRepeat= s: 5); +- printBenchmarkResults(id, description, times); +-} +- +-Future run_flutter_memory_initialAnalysis_1(String id) async { +- String description =3D r''' +-1. Start server, set 'packages/flutter' as the analysis root. +-2. Measure the memory usage after finishing initial analysis. +-3. Shutdown the server. +-4. Go to (1). +-'''; +- List sizes =3D await AnalysisServerMemoryUsageTest +- .start_waitInitialAnalysis_shutdown( +- roots: [paths.packageFlutter], numOfRepeats: 3); +- printMemoryResults(id, description, sizes); +-} +- +-Future run_flutter_memory_initialAnalysis_2(String id) async { +- String description =3D r''' +-1. Start server, set 'packages/flutter' and 'packages/flutter_markdown' a= nalysis roots. +-2. Measure the memory usage after finishing initial analysis. +-3. Shutdown the server. +-4. Go to (1). +-'''; +- List sizes =3D await AnalysisServerMemoryUsageTest +- .start_waitInitialAnalysis_shutdown( +- roots: [paths.packageFlutter, paths.packageMarkdown], +- numOfRepeats: 3); +- printMemoryResults(id, description, sizes); +-} +- +-Future run_flutter_refactoring_1(String id) async { +- String description =3D r''' +-1. Open 'packages/flutter'. +-2. Change the name of a public method in lib/src/rendering/layer.dart +-3. Request rename refactoring for `getSourcesWithFullName` and measure ti= me to get results. +-4. Rollback changes to the file and wait for analysis. +-5. Go to (2). +-'''; +- List times =3D await new BenchmarkScenario() +- .waitAnalyze_change_getRefactoring( +- roots: [paths.packageFlutter], +- file: '${paths.packageFlutter}/lib/src/rendering/layer.dart', +- fileChange: new FileChange( +- replaceWhat: 'void removeAllChildren() {', +- replaceWith: 'void removeAllChildren2() {'), +- refactoringAtStr: 'addToScene(ui.SceneBuilder builder', +- refactoringKind: RefactoringKind.RENAME, +- refactoringOptions: new RenameOptions('addToScene2'), +- numOfRepeats: 5); +- printBenchmarkResults(id, description, times); +-} +- +-typedef BenchmarkFunction(String id); +- +-class PathHolder { +- String exampleHelloWorld; +- String exampleGallery; +- String exampleStocks; +- String packageFlutter; +- String packageMarkdown; +- String packageSprites; +- +- PathHolder({String flutterPath}) { +- exampleHelloWorld =3D '$flutterPath/examples/hello_world'; +- exampleGallery =3D '$flutterPath/examples/flutter_gallery'; +- exampleStocks =3D '$flutterPath/examples/stocks'; +- packageFlutter =3D '$flutterPath/packages/flutter'; +- packageMarkdown =3D '$flutterPath/packages/flutter_markdown'; +- packageSprites =3D '$flutterPath/packages/flutter_sprites'; +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/benchmark_scenario.dart b/= pkg/analysis_server/benchmark/perf/benchmark_scenario.dart +deleted file mode 100644 +index 930bc0e7cd3..00000000000 +--- a/pkg/analysis_server/benchmark/perf/benchmark_scenario.dart ++++ /dev/null +@@ -1,310 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +-import 'dart:math'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +- +-import '../../test/integration/support/integration_tests.dart'; +-import 'performance_tests.dart'; +- +-void printBenchmarkResults(String id, String description, List times= ) { +- int minTime =3D times.fold(1 << 20, min); +- String now =3D new DateTime.now().toUtc().toIso8601String(); +- print('$now =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D $id'); +- print('times: $times'); +- print('min_time: $minTime'); +- print(description.trim()); +- print('--------------------'); +- print(''); +- print(''); +-} +- +-class BenchmarkScenario extends AbstractTimingTest { +- /** +- * Init. +- * - Start Analysis Server. +- * - Set the analysis [roots]. +- * - Wait for analysis to complete. +- * - Make [file] the priority file. +- * +- * Measurement. +- * - Change the [file] according to the [fileChange]. +- * - Record the time to finish analysis. +- * +- * Repeat. +- * - Undo changes to the [file]. +- * - Repeat measurement [numOfRepeats] times. +- */ +- Future> waitAnalyze_change_analyze( +- {List roots, +- String file, +- FileChange fileChange, +- int numOfRepeats}) async { +- outOfTestExpect(roots, isNotNull, reason: 'roots'); +- outOfTestExpect(file, isNotNull, reason: 'file'); +- outOfTestExpect(fileChange, isNotNull, reason: 'fileChange'); +- outOfTestExpect(numOfRepeats, isNotNull, reason: 'numOfRepeats'); +- // Initialize Analysis Server. +- await super.setUp(); +- await subscribeToStatusNotifications(); +- // Set roots and analyze. +- await sendAnalysisSetAnalysisRoots(roots, []); +- await analysisFinished; +- // Make the file priority. +- await sendAnalysisSetPriorityFiles([file]); +- // Repeat. +- List times =3D []; +- for (int i =3D 0; i < numOfRepeats; i++) { +- // Update and wait for analysis. +- Stopwatch stopwatch =3D new Stopwatch()..start(); +- await _applyFileChange(file, fileChange); +- await analysisFinished; +- times.add(stopwatch.elapsed.inMilliseconds); +- // Remove the overlay and analyze. +- await sendAnalysisUpdateContent({file: new RemoveContentOverlay()}); +- await analysisFinished; +- } +- // Done. +- await shutdown(); +- return times; +- } +- +- /** +- * Init. +- * 1. Start Analysis Server. +- * 2. Set the analysis [roots]. +- * 3. Wait for analysis to complete. +- * 4. Make [file] the priority file. +- * +- * Measurement. +- * 5. Change the [file] according to the [fileChange]. +- * 6. Request [completeAfterStr] in the updated file content. +- * 7. Record the time to get completion results. +- * 8. Undo changes to the [file] and analyze. +- * 9. Go to (5). +- */ +- Future> waitAnalyze_change_getCompletion( +- {List roots, +- String file, +- FileChange fileChange, +- String completeAfterStr, +- int numOfRepeats}) async { +- outOfTestExpect(roots, isNotNull, reason: 'roots'); +- outOfTestExpect(file, isNotNull, reason: 'file'); +- outOfTestExpect(fileChange, isNotNull, reason: 'fileChange'); +- outOfTestExpect(completeAfterStr, isNotNull, reason: 'completeAfterSt= r'); +- outOfTestExpect(numOfRepeats, isNotNull, reason: 'numOfRepeats'); +- // Initialize Analysis Server. +- await super.setUp(); +- await subscribeToStatusNotifications(); +- // Set roots and analyze. +- await sendAnalysisSetAnalysisRoots(roots, []); +- await analysisFinished; +- // Make the file priority. +- await sendAnalysisSetPriorityFiles([file]); +- // Repeat. +- List times =3D []; +- for (int i =3D 0; i < numOfRepeats; i++) { +- String updatedContent =3D await _applyFileChange(file, fileChange); +- // Measure completion time. +- int completionOffset =3D +- _indexOfEnd(file, updatedContent, completeAfterStr); +- Duration completionDuration =3D +- await _measureCompletionTime(file, completionOffset); +- times.add(completionDuration.inMilliseconds); +- // Remove the overlay and analyze. +- await sendAnalysisUpdateContent({file: new RemoveContentOverlay()}); +- await analysisFinished; +- } +- // Done. +- await shutdown(); +- return times; +- } +- +- /** +- * Init. +- * 1. Start Analysis Server. +- * 2. Set the analysis [roots]. +- * 3. Wait for analysis to complete. +- * 4. Make [file] the priority file. +- * +- * Measurement. +- * 5. Change the [file] according to the [fileChange]. +- * 6. Request [refactoringAtStr] in the updated file content. +- * 7. Record the time to get refactoring. +- * 8. Undo changes to the [file] and analyze. +- * 9. Go to (5). +- */ +- Future> waitAnalyze_change_getRefactoring( +- {List roots, +- String file, +- FileChange fileChange, +- String refactoringAtStr, +- RefactoringKind refactoringKind, +- RefactoringOptions refactoringOptions, +- int numOfRepeats}) async { +- outOfTestExpect(roots, isNotNull, reason: 'roots'); +- outOfTestExpect(file, isNotNull, reason: 'file'); +- outOfTestExpect(fileChange, isNotNull, reason: 'fileChange'); +- outOfTestExpect(refactoringAtStr, isNotNull, reason: 'refactoringAtSt= r'); +- outOfTestExpect(refactoringKind, isNotNull, reason: 'refactoringKind'= ); +- outOfTestExpect(refactoringOptions, isNotNull, +- reason: 'refactoringOptions'); +- outOfTestExpect(numOfRepeats, isNotNull, reason: 'numOfRepeats'); +- // Initialize Analysis Server. +- await super.setUp(); +- await subscribeToStatusNotifications(); +- // Set roots and analyze. +- await sendAnalysisSetAnalysisRoots(roots, []); +- await analysisFinished; +- // Make the file priority. +- await sendAnalysisSetPriorityFiles([file]); +- // Repeat. +- List times =3D []; +- for (int i =3D 0; i < numOfRepeats; i++) { +- String updatedContent =3D await _applyFileChange(file, fileChange); +- // Measure time to get refactoring. +- int refactoringOffset =3D _indexOf(file, updatedContent, refactorin= gAtStr); +- Duration refactoringDuration =3D await _measureRefactoringTime( +- file, refactoringOffset, refactoringKind, refactoringOptions); +- times.add(refactoringDuration.inMilliseconds); +- // Remove the overlay and analyze. +- await sendAnalysisUpdateContent({file: new RemoveContentOverlay()}); +- await analysisFinished; +- } +- // Done. +- await shutdown(); +- return times; +- } +- +- /** +- * Compute updated content of the [file] as described by [desc], add ov= erlay +- * for the [file], and return the updated content. +- */ +- Future _applyFileChange(String file, FileChange desc) async { +- String originalContent =3D _getFileContent(file); +- String updatedContent; +- if (desc.afterStr !=3D null) { +- int offset =3D _indexOfEnd(file, originalContent, desc.afterStr); +- offset -=3D desc.afterStrBack; +- updatedContent =3D originalContent.substring(0, offset) + +- desc.insertStr + +- originalContent.substring(offset); +- } else if (desc.replaceWhat !=3D null) { +- int offset =3D _indexOf(file, originalContent, desc.replaceWhat); +- updatedContent =3D originalContent.substring(0, offset) + +- desc.replaceWith + +- originalContent.substring(offset + desc.replaceWhat.length); +- } +- await sendAnalysisUpdateContent( +- {file: new AddContentOverlay(updatedContent)}); +- return updatedContent; +- } +- +- Future _measureCompletionTime(String file, int offset) async { +- Stopwatch stopwatch =3D new Stopwatch(); +- stopwatch.start(); +- Completer completer =3D new Completer(); +- var completionSubscription =3D onCompletionResults.listen((_) { +- completer.complete(stopwatch.elapsed); +- }); +- try { +- await sendCompletionGetSuggestions(file, offset); +- return await completer.future; +- } finally { +- completionSubscription.cancel(); +- } +- } +- +- Future _measureRefactoringTime( +- String file, +- int offset, +- RefactoringKind refactoringKind, +- RefactoringOptions refactoringOptions) async { +- Stopwatch stopwatch =3D new Stopwatch(); +- stopwatch.start(); +- await sendEditGetRefactoring(refactoringKind, file, offset, 0, false, +- options: refactoringOptions); +- return stopwatch.elapsed; +- } +- +- /** +- * 1. Start Analysis Server. +- * 2. Set the analysis [roots]. +- * 3. Wait for analysis to complete. +- * 4. Record the time to finish analysis. +- * 5. Shutdown. +- * 6. Go to (1). +- */ +- static Future> start_waitInitialAnalysis_shutdown( +- {List roots, int numOfRepeats}) async { +- outOfTestExpect(roots, isNotNull, reason: 'roots'); +- outOfTestExpect(numOfRepeats, isNotNull, reason: 'numOfRepeats'); +- // Repeat. +- List times =3D []; +- for (int i =3D 0; i < numOfRepeats; i++) { +- BenchmarkScenario instance =3D new BenchmarkScenario(); +- // Initialize Analysis Server. +- await instance.setUp(); +- await instance.subscribeToStatusNotifications(); +- // Set roots and analyze. +- Stopwatch stopwatch =3D new Stopwatch()..start(); +- await instance.sendAnalysisSetAnalysisRoots(roots, []); +- await instance.analysisFinished; +- times.add(stopwatch.elapsed.inMilliseconds); +- // Stop the server. +- await instance.shutdown(); +- } +- return times; +- } +- +- static String _getFileContent(String path) { +- File file =3D new File(path); +- outOfTestExpect(file.existsSync(), isTrue, +- reason: 'File $path does not exist.'); +- return file.readAsStringSync(); +- } +- +- /** +- * Return the index of [what] in [where] in the [file], fail if not fou= nd. +- */ +- static int _indexOf(String file, String where, String what) { +- int index =3D where.indexOf(what); +- outOfTestExpect(index, isNot(-1), reason: 'Cannot find |$what| in $fi= le.'); +- return index; +- } +- +- /** +- * Return the end index if [what] in [where] in the [file], fail if not= found. +- */ +- static int _indexOfEnd(String file, String where, String what) { +- return _indexOf(file, where, what) + what.length; +- } +-} +- +-class FileChange { +- final String afterStr; +- final int afterStrBack; +- final String insertStr; +- final String replaceWhat; +- final String replaceWith; +- +- FileChange( +- {this.afterStr, +- this.afterStrBack: 0, +- this.insertStr, +- this.replaceWhat, +- this.replaceWith}) { +- if (afterStr !=3D null) { +- outOfTestExpect(insertStr, isNotNull, reason: 'insertStr'); +- } else if (replaceWhat !=3D null) { +- outOfTestExpect(replaceWith, isNotNull, reason: 'replaceWith'); +- } +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/benchmarks_impl.dart b/pkg= /analysis_server/benchmark/perf/benchmarks_impl.dart +deleted file mode 100644 +index 9a42862f084..00000000000 +--- a/pkg/analysis_server/benchmark/perf/benchmarks_impl.dart ++++ /dev/null +@@ -1,187 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:path/path.dart' as path; +- +-import '../../test/integration/support/integration_tests.dart'; +-import '../benchmarks.dart'; +-import 'memory_tests.dart'; +- +-/// benchmarks: +-/// - analysis-server-cold-analysis +-/// - analysis-server-cold-memory +-class ColdAnalysisBenchmark extends Benchmark { +- ColdAnalysisBenchmark() +- : super( +- 'analysis-server-cold', +- 'Analysis server benchmarks of a large project on start-up, n= o ' +- 'existing driver cache.', +- kind: 'group'); +- +- int get maxIterations =3D> 3; +- +- @override +- Future run( +- {bool quick: false, bool previewDart2: false}) async { +- if (!quick) { +- deleteServerCache(); +- } +- +- Stopwatch stopwatch =3D new Stopwatch()..start(); +- +- AnalysisServerMemoryUsageTest test =3D new AnalysisServerMemoryUsageT= est(); +- await test.setUp(previewDart2: previewDart2); +- await test.subscribeToStatusNotifications(); +- await test.sendAnalysisSetAnalysisRoots(getProjectRoots(quick: quick)= , []); +- await test.analysisFinished; +- +- stopwatch.stop(); +- int usedBytes =3D test.getMemoryUsage(); +- +- CompoundBenchMarkResult result =3D new CompoundBenchMarkResult(id); +- result.add('analysis', +- new BenchMarkResult('micros', stopwatch.elapsedMicroseconds)); +- result.add('memory', new BenchMarkResult('bytes', usedBytes)); +- +- await test.shutdown(); +- +- return result; +- } +-} +- +-/// benchmarks: +-/// - analysis-server-warm-analysis +-/// - analysis-server-warm-memory +-/// - analysis-server-edit +-/// - analysis-server-completion +-class AnalysisBenchmark extends Benchmark { +- AnalysisBenchmark() +- : super( +- 'analysis-server', +- 'Analysis server benchmarks of a large project, with an exist= ing ' +- 'driver cache.', +- kind: 'group'); +- +- @override +- Future run( +- {bool quick: false, bool previewDart2: false}) async { +- Stopwatch stopwatch =3D new Stopwatch()..start(); +- +- AnalysisServerMemoryUsageTest test =3D new AnalysisServerMemoryUsageT= est(); +- await test.setUp(previewDart2: previewDart2); +- await test.subscribeToStatusNotifications(); +- await test.sendAnalysisSetAnalysisRoots(getProjectRoots(quick: quick)= , []); +- await test.analysisFinished; +- +- stopwatch.stop(); +- int usedBytes =3D test.getMemoryUsage(); +- +- CompoundBenchMarkResult result =3D new CompoundBenchMarkResult(id); +- result.add('warm-analysis', +- new BenchMarkResult('micros', stopwatch.elapsedMicroseconds)); +- result.add('warm-memory', new BenchMarkResult('bytes', usedBytes)); +- +- if (!quick) { +- // change timing +- final int editMicros =3D await _calcEditTiming(test); +- result.add('edit', new BenchMarkResult('micros', editMicros)); +- +- // code completion +- final int completionMicros =3D await _calcCompletionTiming(test); +- result.add('completion', new BenchMarkResult('micros', completionMi= cros)); +- } +- +- await test.shutdown(); +- +- return result; +- } +- +- Future _calcEditTiming( +- AbstractAnalysisServerIntegrationTest test) async { +- const int kGroupCount =3D 5; +- +- final String filePath =3D +- path.join(analysisServerSrcPath, 'lib/src/analysis_server.dart'); +- String contents =3D new File(filePath).readAsStringSync(); +- +- await test +- .sendAnalysisUpdateContent({filePath: new AddContentOverlay(conte= nts)}); +- +- final Stopwatch stopwatch =3D new Stopwatch()..start(); +- +- for (int i =3D 0; i < kGroupCount; i++) { +- int startIndex =3D i * (contents.length ~/ (kGroupCount + 2)); +- int index =3D contents.indexOf(';', startIndex); +- contents =3D contents.substring(0, index + 1) + +- ' ' + +- contents.substring(index + 1); +- test.sendAnalysisUpdateContent( +- {filePath: new AddContentOverlay(contents)}); +- await test.analysisFinished; +- } +- +- stopwatch.stop(); +- +- return stopwatch.elapsedMicroseconds ~/ kGroupCount; +- } +- +- Future _calcCompletionTiming( +- AbstractAnalysisServerIntegrationTest test) async { +- const int kGroupCount =3D 10; +- +- final String filePath =3D +- path.join(analysisServerSrcPath, 'lib/src/analysis_server.dart'); +- String contents =3D new File(filePath).readAsStringSync(); +- +- await test +- .sendAnalysisUpdateContent({filePath: new AddContentOverlay(conte= nts)}); +- +- int completionCount =3D 0; +- final Stopwatch stopwatch =3D new Stopwatch()..start(); +- +- Future _complete(int offset) async { +- CompletionGetSuggestionsResult result =3D +- await test.sendCompletionGetSuggestions(filePath, offset); +- +- Future future =3D test.onCompletionResults +- .where((CompletionResultsParams params) =3D> +- params.id =3D=3D result.id && params.isLast) +- .first; +- await future; +- +- completionCount++; +- } +- +- for (int i =3D 0; i < kGroupCount; i++) { +- int startIndex =3D i * (contents.length ~/ (kGroupCount + 2)); +- // Look for a line with a period in it that ends with a semi-colon. +- int index =3D +- contents.indexOf(new RegExp(r'\..*;$', multiLine: true), startI= ndex); +- +- await _complete(index - 10); +- await _complete(index - 1); +- await _complete(index); +- await _complete(index + 1); +- await _complete(index + 10); +- +- if (i + 1 < kGroupCount) { +- // mutate +- index =3D contents.indexOf(';', index); +- contents =3D contents.substring(0, index + 1) + +- ' ' + +- contents.substring(index + 1); +- await test.sendAnalysisUpdateContent( +- {filePath: new AddContentOverlay(contents)}); +- } +- } +- +- stopwatch.stop(); +- +- return stopwatch.elapsedMicroseconds ~/ completionCount; +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/completion_timing_tests.da= rt b/pkg/analysis_server/benchmark/perf/completion_timing_tests.dart +deleted file mode 100644 +index 0a1204195b9..00000000000 +--- a/pkg/analysis_server/benchmark/perf/completion_timing_tests.dart ++++ /dev/null +@@ -1,85 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:args/args.dart'; +-import 'package:test/test.dart'; +- +-import 'performance_tests.dart'; +- +-const COMPLETION_OFFSET =3D 'offset'; +-const PRIORITY_FILE_OPTION =3D 'priority'; +-const SOURCE_OPTION =3D 'source'; +- +-/** +- * Pass in the directory of the source to be analyzed as option `--source= `, +- * specify a priority file with `--priority` and an offset for completions +- * with a `--offset`. +- */ +-main(List arguments) async { +- ArgParser parser =3D _createArgParser(); +- var args =3D parser.parse(arguments); +- if (args[SOURCE_OPTION] =3D=3D null) { +- print('path to source directory must be specified'); +- exit(1); +- } +- +- int offset =3D int.parse(args[COMPLETION_OFFSET]); +- String priorityFile =3D args[PRIORITY_FILE_OPTION]; +- String source =3D args[SOURCE_OPTION]; +- +- CompletionTimingTest test =3D +- new CompletionTimingTest(offset, priorityFile, source); +- await test.test_timing(); +-} +- +-ArgParser _createArgParser() =3D> new ArgParser() +- ..addOption(SOURCE_OPTION, help: 'full path to source directory for ana= lysis') +- ..addOption(PRIORITY_FILE_OPTION, help: 'full path to a priority file') +- ..addOption(COMPLETION_OFFSET, help: 'offset in file for code completio= ns'); +- +-/** +- * CompletionTimingTest measures the time taken for the analysis server t= o respond with +- * completion suggestions for a given file and offset. The time measured = starts when +- * the analysis root is set and is done when the completion suggestions a= re received +- * from the server. The test does not wait for analysis to be complete be= fore asking for +- * completions. +- */ +-class CompletionTimingTest extends AbstractTimingTest { +- final int offset; +- final String priorityFile; +- final String source; +- +- List timings =3D []; +- +- CompletionTimingTest(this.offset, this.priorityFile, this.source); +- +- Future test_timing() async { +-// debugStdio(); +- +- expect(priorityFile, isNotNull, +- reason: 'A priority file must be specified for completion testing= .'); +- expect(offset, isNotNull, +- reason: 'An offset must be specified for completion testing.'); +- +- await init(source); +- stopwatch.start(); +- +- onCompletionResults.listen((_) { +- timings.add(new Duration(milliseconds: stopwatch.elapsed.inMillisec= onds)); +- }); +- +- setAnalysisRoot(); +- sendAnalysisSetPriorityFiles([priorityFile]); +- sendCompletionGetSuggestions(priorityFile, offset); +- +- await analysisFinished; +- +- print('analysis completed in ${stopwatch.elapsed}'); +- print('completion received at : $timings'); +- await shutdown(); +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/memory_tests.dart b/pkg/an= alysis_server/benchmark/perf/memory_tests.dart +deleted file mode 100644 +index 1971bf575ec..00000000000 +--- a/pkg/analysis_server/benchmark/perf/memory_tests.dart ++++ /dev/null +@@ -1,133 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +-import 'dart:math'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +- +-import '../../test/integration/support/integration_tests.dart'; +- +-void printMemoryResults(String id, String description, List sizes) { +- int minMemory =3D sizes.fold(sizes.first, min); +- int maxMemory =3D sizes.fold(sizes.first, max); +- String now =3D new DateTime.now().toUtc().toIso8601String(); +- print('$now =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D $id'); +- print('memory: $sizes'); +- print('min_memory: $minMemory'); +- print('max_memory: $maxMemory'); +- print(description.trim()); +- print('--------------------'); +- print(''); +- print(''); +-} +- +-/** +- * Base class for analysis server memory usage tests. +- */ +-class AnalysisServerMemoryUsageTest +- extends AbstractAnalysisServerIntegrationTest { +- static const int vmServicePort =3D 12345; +- +- int getMemoryUsage() { +- ProcessResult result =3D _run('curl', [ +- 'localhost:$vmServicePort/_getAllocationProfile\?isolateId=3Disolat= es/root\&gc=3Dfull' +- ]); +- Map json =3D JSON.decode(result.stdout); +- Map heaps =3D json['result']['heaps']; +- int newSpace =3D heaps['new']['used']; +- int oldSpace =3D heaps['old']['used']; +- return newSpace + oldSpace; +- } +- +- /** +- * Send the server an 'analysis.setAnalysisRoots' command directing it = to +- * analyze [sourceDirectory]. +- */ +- Future setAnalysisRoot() =3D> +- sendAnalysisSetAnalysisRoots([sourceDirectory.path], []); +- +- /** +- * The server is automatically started before every test. +- */ +- @override +- Future setUp({bool previewDart2: false}) { +- onAnalysisErrors.listen((AnalysisErrorsParams params) { +- currentAnalysisErrors[params.file] =3D params.errors; +- }); +- onServerError.listen((ServerErrorParams params) { +- // A server error should never happen during an integration test. +- fail('${params.message}\n${params.stackTrace}'); +- }); +- Completer serverConnected =3D new Completer(); +- onServerConnected.listen((_) { +- outOfTestExpect(serverConnected.isCompleted, isFalse); +- serverConnected.complete(); +- }); +- return startServer( +- servicesPort: vmServicePort, +- previewDart2: previewDart2, +- ).then((_) { +- server.listenToOutput(dispatchNotification); +- server.exitCode.then((_) { +- skipShutdown =3D true; +- }); +- return serverConnected.future; +- }); +- } +- +- /** +- * After every test, the server is stopped. +- */ +- Future shutdown() async =3D> await shutdownIfNeeded(); +- +- /** +- * Enable [ServerService.STATUS] notifications so that [analysisFinishe= d] +- * can be used. +- */ +- Future subscribeToStatusNotifications() async { +- await sendServerSetSubscriptions([ServerService.STATUS]); +- } +- +- /** +- * Synchronously run the given [executable] with the given [arguments].= Return +- * the result of running the process. +- */ +- ProcessResult _run(String executable, List arguments) { +- return Process.runSync(executable, arguments, +- stderrEncoding: UTF8, stdoutEncoding: UTF8); +- } +- +- /** +- * 1. Start Analysis Server. +- * 2. Set the analysis [roots]. +- * 3. Wait for analysis to complete. +- * 4. Record the heap size after analysis is finished. +- * 5. Shutdown. +- * 6. Go to (1). +- */ +- static Future> start_waitInitialAnalysis_shutdown( +- {List roots, int numOfRepeats}) async { +- outOfTestExpect(roots, isNotNull, reason: 'roots'); +- outOfTestExpect(numOfRepeats, isNotNull, reason: 'numOfRepeats'); +- // Repeat. +- List sizes =3D []; +- for (int i =3D 0; i < numOfRepeats; i++) { +- AnalysisServerMemoryUsageTest test =3D new AnalysisServerMemoryUsag= eTest(); +- // Initialize Analysis Server. +- await test.setUp(); +- await test.subscribeToStatusNotifications(); +- // Set roots and analyze. +- await test.sendAnalysisSetAnalysisRoots(roots, []); +- await test.analysisFinished; +- sizes.add(test.getMemoryUsage()); +- // Stop the server. +- await test.shutdown(); +- } +- return sizes; +- } +-} +diff --git a/pkg/analysis_server/benchmark/perf/performance_tests.dart b/p= kg/analysis_server/benchmark/perf/performance_tests.dart +deleted file mode 100644 +index 540678ca652..00000000000 +--- a/pkg/analysis_server/benchmark/perf/performance_tests.dart ++++ /dev/null +@@ -1,76 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +- +-import '../../test/integration/support/integration_tests.dart'; +- +-/** +- * Base class for analysis server performance tests. +- */ +-abstract class AbstractAnalysisServerPerformanceTest +- extends AbstractAnalysisServerIntegrationTest { +- /** +- * Stopwatch for timing results; +- */ +- Stopwatch stopwatch =3D new Stopwatch(); +- +- /** +- * Send the server an 'analysis.setAnalysisRoots' command directing it = to +- * analyze [sourceDirectory]. +- */ +- Future setAnalysisRoot() =3D> +- sendAnalysisSetAnalysisRoots([sourceDirectory.path], []); +- +- /** +- * The server is automatically started before every test. +- */ +- @override +- Future setUp() { +- onAnalysisErrors.listen((AnalysisErrorsParams params) { +- currentAnalysisErrors[params.file] =3D params.errors; +- }); +- onServerError.listen((ServerErrorParams params) { +- // A server error should never happen during an integration test. +- fail('${params.message}\n${params.stackTrace}'); +- }); +- Completer serverConnected =3D new Completer(); +- onServerConnected.listen((_) { +- outOfTestExpect(serverConnected.isCompleted, isFalse); +- serverConnected.complete(); +- }); +- return startServer(checked: false).then((_) { +- server.listenToOutput(dispatchNotification); +- server.exitCode.then((_) { +- skipShutdown =3D true; +- }); +- return serverConnected.future; +- }); +- } +- +- /** +- * After every test, the server is stopped. +- */ +- Future shutdown() async =3D> await shutdownIfNeeded(); +- +- /** +- * Enable [ServerService.STATUS] notifications so that [analysisFinishe= d] +- * can be used. +- */ +- Future subscribeToStatusNotifications() async { +- await sendServerSetSubscriptions([ServerService.STATUS]); +- } +-} +- +-class AbstractTimingTest extends AbstractAnalysisServerPerformanceTest { +- Future init(String source) async { +- await super.setUp(); +- sourceDirectory =3D new Directory(source); +- return subscribeToStatusNotifications(); +- } +-} +diff --git a/pkg/analysis_server/benchmark/readme.md b/pkg/analysis_server= /benchmark/readme.md +deleted file mode 100644 +index 24eb7ece492..00000000000 +--- a/pkg/analysis_server/benchmark/readme.md ++++ /dev/null +@@ -1,35 +0,0 @@ +-# Analysis Server Benchmarks +- +-## How to run the benchmarks +- +-To see a list of all available benchmarks, run: +- +-``` +-dart benchmark/benchmarks.dart list +-``` +- +-To run an individual benchmark, run: +- +-``` +-dart benchmark/benchmarks.dart run +-``` +- +-## How they're tested +- +-In order to make sure that our benchmarks don't regress in terms of their +-ability to run, we create one unit test per benchmark, and run those tests +-as part of our normal CI test suite. +- +-To save time on the CI, we only run one iteration of each benchmark +-(`--repeat=3D1`), and we run the benchmark on a smaller data set (`--quic= k`). +- +-See `test/benchmark_test.dart`. +- +-## To add a new benchmark +- +-Register the new benchmark in the `main()` method of benchmark/benchmarks= .dart. +- +-## On the bots +- +-Our benchmarks run on a continuous performance testing system. Currently,= the +-benchmarks need to be manually registered ahead of time. +diff --git a/pkg/analysis_server/bin/server.dart b/pkg/analysis_server/bin= /server.dart +deleted file mode 100644 +index f0d075f6f8d..00000000000 +--- a/pkg/analysis_server/bin/server.dart ++++ /dev/null +@@ -1,13 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/starter.dart'; +- +-/** +- * Create and run an analysis server. +- */ +-void main(List args) { +- ServerStarter starter =3D new ServerStarter(); +- starter.start(args); +-} +diff --git a/pkg/analysis_server/doc/api.html b/pkg/analysis_server/doc/ap= i.html +deleted file mode 100644 +index 6528f6d2a99..00000000000 +--- a/pkg/analysis_server/doc/api.html ++++ /dev/null +@@ -1,4725 +0,0 @@ +- +- +- Analysis Server API Specification +- +- +-

Analysis Server API Specification

+-

Version +- 1.18.4 +-

+-

+- This document contains a specification of the API provided by the +- analysis server. The API in this document is currently under +- development. Changes to the API will be accompanied by an update to the +- protocol version number according to the principles of semantic +- versioning (semver.org). +-

+-

Overview

+-

+- The analysis server API is a bi-directional client-server +- API. The API is independent of the transport mechanism used, but +- is heavily influenced by a model in which sockets or character +- streams are used to transport JSON-RPC encoded information. +-

+-

Transport Mechanism

+-

+- The characters passed to the server are expected to be encoded +- using UTF-8. +-

+-

+- When character streams are used as the transport, messages are +- delineated by newlines. This means, in particular, that the JSON +- encoding process must not introduce newlines within a +- message. Note however that newlines are used in this document +- for readability. +-

+-

+- It is the client's responsibility to read output from the server to +- avoid its blocking. +-

+-

+- To ease interoperability with Lisp-based clients (which may not +- be able to easily distinguish between empty lists, empty maps, +- and null), client-to-server communication is allowed to replace +- any instance of "{}" or "[]" with null. The +- server will always properly represent empty lists as +- "[]" and empty maps as "{}". +-

+-

Communication Structure

+-

+- Clients can make a request of the server and the server will +- provide a response for each request that it receives. While many +- of the requests that can be made by a client are informational +- in nature, we have chosen to always return a response so that +- clients can know whether the request was received and was +- correct. +-

+-

+- There is no guarantee concerning the order in which responses +- will be returned, but there is a guarantee that the server will +- process requests in the order in which they are sent as long as +- the transport mechanism also makes this guarantee. Responses can +- be returned in an order that is different from the order in +- which the requests were received because some requests take +- longer to process than others. +-

+-

+- Every request is required to have two fields and may have two +- additional optional fields. The first required field is the =E2=80=98id= =E2=80=99 +- field, which is only used by the server to associate a response +- with the request that generated the response. The second +- required field is the =E2=80=98method=E2=80=99 field, which is used to = determine +- what the server is being requested to do. One optional field is +- the =E2=80=98params=E2=80=99 field, whose structure is dependent on the= method +- being requested. The structure of this field is described with +- each request for which it is required. The other optional field +- is the 'clientRequestTime' field, which is a number indicating +- the time at which the client made the request (milliseconds +- since epoch). Providing clientRequestTime helps us track +- how responsive analysis server is to client requests +- and better address any issues that occur. +-

+-

+- Every response has up to three fields. The first field is the +- =E2=80=98id=E2=80=99 field, which is always present and whose value is = the +- identifier that was passed to the request that generated the +- response. The second field is the =E2=80=98error=E2=80=99 field, which = is only +- present if an error was encountered while processing the +- request. The third field is the =E2=80=98result=E2=80=99 field, whose s= tructure +- is dependent on the method being responded to, and is described +- with each request that will produce it. +-

+-

+- The server can also communicate to the clients by sending a +- notification. The purpose of these notifications is to provide +- information to clients as it becomes available rather than to +- require that clients poll for it. Unless explicitly stated, all +- notifications are designed to return the complete information +- available at the time the notification is sent; clients are not +- required to update previously communicated +- results. Consequently, the server can and should return partial +- results before all results are available. For example, the +- syntactic errors for a file can be returned as soon as the +- syntactic analysis is complete, and both syntactic and semantic +- errors can be returned together at a later time. +-

+-

+- Each notification has two fields. The first field is the =E2=80=98event= =E2=80=99 +- field, which identifies the kind of notification. The second +- field is the =E2=80=98params=E2=80=99 field, whose structure is depende= nt on the +- kind of notification being sent. The structure of this field is +- described with each notification. +-

+-

+- In order to be backward compatible, clients should ignore fields that w= ere +- not specified in the version of the API on which they were based. Clien= ts +- should also use the server.getVersion request to test that the version = of +- the server supports an API before using it. +-

+-

Eventual Consistency

+-

+- The analysis server satisfies requests under the principle of +- eventual +- consistency. +- That is, in some cases it may return responses with the currently avail= able +- results while it's catching up with unprocessed changes. +-

+-

Domains

+-

+- For convenience, the API is divided into domains. Each domain is specif= ied +- in a separate section below. The specifications of the API=E2=80=99s re= fer to data +- structures beyond the standard JSON primitives. These data structures a= re +- documented in the section titled Types. +-

+- +-

Server

+- +-

Analysis

+- +-

Completion

+- +-

Search

+- +-

Edit

+- +-

Execution

+- +-

Diagnostic

+- +-

Command-line Arguments

+-

+- The command-line arguments that can be passed to the server. +-

+-

Options

+-
+-
+-
--client-id
+-
+-

+- Specifies an identifier associated with the client. Used when +- generating error reports. +-

+-

+- Clients are strongly encouraged to provide this information in +- order to improve the quality of information that can be provided +- to them. +-

+-
+-
+-
+-
--client-version
+-
+-

+- Specifies the version of the client that is communicating with +- the server. Used when generating error reports. +-

+-

+- Clients are strongly encouraged to provide this information in +- order to improve the quality of information that can be provided +- to them. +-

+-
+-
+-
+-
--no-error-notification
+-
+-

Deprecated: clients should no longer pass this option in<= /p> +- Disable notifications about errors (see analysis.error). If this +- flag is not specified then notifications will be sent for all +- errors produced for all files in the actual analysis roots. +-

+-
+-
+-
--no-index
+-
+-

Deprecated: clients should no longer pass this option in<= /p> +- This flag used to disable the server from generating an index, but = now +- it has no effect. +-

+-
+-
+-
--file-read-mode
+-
+-

Deprecated: clients should no longer pass this option in<= /p> +- An enumeration of the ways files can be read from disk. Some clients +- normalize end of line characters which would make the file offset a= nd +- range information incorrect. The default option is as-is, = but +- can also be set to normalize-eol-always. The default option +- (as-is) reads files as they are on disk. The +- normalize-eol-always option does the following: +-

    +-
  • '\r\n' is converted to '\n';
  • +-
  • '\r' by itself is converted to '\n';
  • +-
  • this happens regardless of the OS editor is running on.
  • +-
+-
+-
+-
+-

Domains

+-

server domain

+-

+- The server domain contains API=E2=80=99s related to the execution of +- the server. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-

Requests

server.getVersion
request: {
+-  "id": String
+-  "method": "server.getVersion"
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "version": String
+-  }
+-}
+-

Return the version number of the analysis server.

+-=20=20=20=20 +-

returns:

version: String
+-=20=20=20=20=20=20=20=20 +-

The version number of the analysis server.

+-
server.shutdown
request: {
+-  "id": String
+-  "method": "server.shutdown"
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Cleanly shutdown the analysis server. Requests that are +- received after this request will not be processed. Requests +- that were received before this request, but for which a +- response has not yet been sent, will not be responded to. No +- further responses or notifications will be sent after the +- response to this request has been sent. +-

+-
= server.setSubscriptions
request: {
+-  "id": String
+-  "method": "server.setSubscriptions"
+-  "params": {
+-    "subscriptions": List<Serve=
rService>
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Subscribe for services. All previous subscriptions are +- replaced by the given set of services. +-

+-

+- It is an error if any of the elements in the list are not +- valid services. If there is an error, then the current +- subscriptions will remain unchanged. +-

+-=20=20=20=20 +-

parameters:

subscriptions: List<<= a href=3D"#type_ServerService">ServerService>
+-=20=20=20=20=20=20=20=20 +-

A list of the services being subscribed to.

+-

Notifications

server.connected
notification: {
+-  "event": "server.connected"
+-  "params": {
+-    "version": String
+-    "pid": int
+-    "sessionId": optional Str=
ing
+-  }
+-}
+-

+- Reports that the server is running. This notification is +- issued once after the server has started running but before +- any requests are processed to let the client know that it +- started correctly. +-

+-

+- It is not possible to subscribe to or unsubscribe from this +- notification. +-

+-=20=20=20=20 +-

parameters:

version: String
=
+-=20=20=20=20=20=20=20=20 +-

The version number of the analysis server.

+-
pid: int
+-=20=20=20=20=20=20=20=20 +-

The process id of the analysis server process.

+-
sessionId: String (optional)
+-=20=20=20=20=20=20=20=20 +-

The session id for this session.

+-
server.error
notification:=
 {
+-  "event": "server.error"
+-  "params": {
+-    "isFatal": bool
+-    "message": String
+-    "stackTrace": String
+-  }
+-}
+-

+- Reports that an unexpected error has occurred while +- executing the server. This notification is not used for +- problems with specific requests (which are returned as part +- of the response) but is used for exceptions that occur while +- performing other tasks, such as analysis or preparing +- notifications. +-

+-

+- It is not possible to subscribe to or unsubscribe from this +- notification. +-

+-=20=20=20=20 +-

parameters:

isFatal: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the error is a fatal error, meaning that the +- server will shutdown automatically after sending this +- notification. +-

+-
message: String
+-=20=20=20=20=20=20=20=20 +-

+- The error message indicating what kind of error was +- encountered. +-

+-
stackTrace: String
+-=20=20=20=20=20=20=20=20 +-

+- The stack trace associated with the generation of the +- error, used for debugging the server. +-

+-
server.status
notificatio=
n: {
+-  "event": "server.status"
+-  "params": {
+-    "analysis": optional AnalysisStatus
+-    "pub": optional PubStatus
+-  }
+-}
+-

+- Reports the current status of the server. Parameters are +- omitted if there has been no change in the status +- represented by that parameter. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "STATUS" in +- the list of services passed in a server.setSubscriptions +- request. +-

+-=20=20=20=20 +-

parameters:

analysis: AnalysisStatus (option= al)
+-=20=20=20=20=20=20=20=20 +-

+- The current status of analysis, including whether +- analysis is being performed and if so what is being +- analyzed. +-

+-
pub: PubSta= tus (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The current status of pub execution, indicating whether we are +- currently running pub. +-

+-
+-

analysis domain

+-

+- The analysis domain contains API=E2=80=99s related to the analysis of +- files. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-

Requests

analysis.getErrors
request: {
+-  "id": String
+-  "method": "analysis.getErrors"
+-  "params": {
+-    "file": FilePath
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "errors": List<AnalysisErro=
r>
+-  }
+-}
+-

+- Return the errors associated with the given file. If the +- errors for the given file have not yet been computed, or the +- most recently computed errors for the given file are out of +- date, then the response for this request will be delayed +- until they have been computed. If some or all of the errors +- for the file cannot be computed, then the subset of the +- errors that can be computed will be returned and the +- response will contain an error to indicate why the errors +- could not be computed. If the content of the file changes after this +- request was received but before a response could be sent, then an +- error of type CONTENT_MODIFIED will be generated. +-

+-

+- This request is intended to be used by clients that cannot +- asynchronously apply updated error information. Clients that +- can apply error information as it becomes available +- should use the information provided by the 'analysis.errors' +- notification. +-

+-

+- If a request is made for a file which does not exist, or +- which is not currently subject to analysis (e.g. because it +- is not associated with any analysis root specified to +- analysis.setAnalysisRoots), an error of type +- GET_ERRORS_INVALID_FILE will be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file for which errors are being requested. +-

+-

returns:

errors: List&= lt;AnalysisError>
+-=20=20=20=20=20=20=20=20 +-

+- The errors associated with the file. +-

+-
analysis.getHover
request: {
+-  "id": String
+-  "method": "analysis.getHover"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "hovers": List<HoverInfo=
rmation>
+-  }
+-}
+-

+- Return the hover information associate with the given +- location. If some or all of the hover information is not +- available at the time this request is processed the +- information will be omitted from the response. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file in which hover information is being requested. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset for which hover information is being requested. +-

+-

returns:

hovers: List&= lt;HoverInformation>
+-=20=20=20=20=20=20=20=20 +-

+- The hover information associated with the +- location. The list will be empty if no information +- could be determined for the location. The list can +- contain multiple items if the file is being analyzed +- in multiple contexts in conflicting ways (such as a +- part that is included in multiple libraries). +-

+-
analysis.getLibraryDependencies
request: {
+-  "id": String
+-  "method": "analysis.getLibraryDependencies"
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "libraries": List<FilePath&g=
t;
+-    "packageMap": Map<String, Map<String, List<FilePath>>>
+-  }
+-}
+-

+- Return library dependency information for use in client-side indexi= ng +- and package URI resolution. +-

+-

+- Clients that are only using the libraries field should consider usi= ng the +- analyzedFiles notification instead. +-

+-=20=20=20=20 +-

returns:

libraries: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the paths of library elements referenced by +- files in existing analysis roots. +-

+-
packageMap: Map<String, Map<Strin= g, List<FilePath>>>
+-=20=20=20=20=20=20=20=20 +-

+- A mapping from context source roots to package maps which map +- package names to source directories for use in client-side +- package URI resolution. +-

+-
analysis.getNavigation
req=
uest: {
+-  "id": String
+-  "method": "analysis.getNavigation"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-    "length": int
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "files": List<FilePath>
+-    "targets": List<Navigati=
onTarget>
+-    "regions": List<Navigati=
onRegion>
+-  }
+-}
+-

+- Return the navigation information associated with the given region = of +- the given file. If the navigation information for the given file has +- not yet been computed, or the most recently computed navigation +- information for the given file is out of date, then the response for +- this request will be delayed until it has been computed. If the +- content of the file changes after this request was received but bef= ore +- a response could be sent, then an error of type +- CONTENT_MODIFIED will be generated. +-

+-

+- If a navigation region overlaps (but extends either before or after) +- the given region of the file it will be included in the result. This +- means that it is theoretically possible to get the same navigation +- region in response to multiple requests. Clients can avoid this by +- always choosing a region that starts at the beginning of a line and +- ends at the end of a (possibly different) line in the file. +-

+-

+- If a request is made for a file which does not exist, or +- which is not currently subject to analysis (e.g. because it +- is not associated with any analysis root specified to +- analysis.setAnalysisRoots), an error of type +- GET_NAVIGATION_INVALID_FILE will be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file in which navigation information is being requested. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region for which navigation information is be= ing +- requested. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region for which navigation information is be= ing +- requested. +-

+-

returns:

files: List&l= t;FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the paths of files that are referenced by the navigat= ion +- targets. +-

+-
targets: List<NavigationTarget>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the navigation targets that are referenced by the +- navigation regions. +-

+-
regions: List<NavigationRegion>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the navigation regions within the requested region of +- the file. +-

+-
analysis.getReachableSources
request: {
+-  "id": String
+-  "method": "analysis.getReachableSources"
+-  "params": {
+-    "file": FilePath
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "sources": Map<String, List<String>>
+-  }
+-}
+-

+- Return the transitive closure of reachable sources for a given file. +-

+-

+- If a request is made for a file which does not exist, or +- which is not currently subject to analysis (e.g. because it +- is not associated with any analysis root specified to +- analysis.setAnalysisRoots), an error of type +- GET_REACHABLE_SOURCES_INVALID_FILE will be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file for which reachable source information is being reques= ted. +-

+-

returns:

sources: Map&= lt;String, List<String>>
+-=20=20=20=20=20=20=20=20 +-

+- A mapping from source URIs to directly reachable source URIs. F= or +- example, +- a file "foo.dart" that imports "bar.dart" would have the corres= ponding +- mapping +- { "file:///foo.dart" : ["file:///bar.dart"] }. If "bar.dart" has +- further imports +- (or exports) there will be a mapping from the URI "file:///bar.= dart" +- to them. +- To check if a specific URI is reachable from a given file, clie= nts can +- check +- for its presence in the resulting key set. +-

+-
analysis.reanalyze
request: {
+-  "id": String
+-  "method": "analysis.reanalyze"
+-  "params": {
+-    "roots": optional List<=
;FilePath>
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Force the re-analysis of everything contained in the specified +- analysis roots. This will cause all previously computed analysis +- results to be discarded and recomputed, and will cause all subscrib= ed +- notifications to be re-sent. +-

+-

+- If no analysis roots are provided, then all current analysis roots +- will be re-analyzed. If an empty list of analysis roots is provided, +- then nothing will be re-analyzed. If the list contains one or more +- paths that are not currently analysis roots, then an error of type +- INVALID_ANALYSIS_ROOT will be generated. +-

+-=20=20=20=20 +-

parameters:

roots: List<FilePath> (optiona= l)
+-=20=20=20=20=20=20=20=20 +-

+- A list of the analysis roots that are to be re-analyzed. +-

+-
analysis.setAnalysisRoots
request: { +- "id": String +- "method": "analysis.setAnalysisRoots" +- "params": { +- "included": List<FilePath> +- "excluded": List<FilePath> +- "packageRoots": optional = Map<FilePath, = FilePath> +- } +-}
response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Sets the root paths used to determine which files to analyze. The s= et +- of files to be analyzed are all of the files in one of the root pat= hs +- that are not either explicitly or implicitly excluded. A file is +- explicitly excluded if it is in one of the excluded paths. A file is +- implicitly excluded if it is in a subdirectory of one of the root +- paths where the name of the subdirectory starts with a period (that +- is, a hidden directory). +-

+-

+- Note that this request determines the set of requested +- analysis roots. The actual set of analysis roots at any +- given time is the intersection of this set with the set of +- files and directories actually present on the +- filesystem. When the filesystem changes, the actual set of +- analysis roots is automatically updated, but the set of +- requested analysis roots is unchanged. This means that if +- the client sets an analysis root before the root becomes +- visible to server in the filesystem, there is no error; once +- the server sees the root in the filesystem it will start +- analyzing it. Similarly, server will stop analyzing files +- that are removed from the file system but they will remain +- in the set of requested roots. +-

+-

+- If an included path represents a file, then server will look +- in the directory containing the file for a pubspec.yaml +- file. If none is found, then the parents of the directory +- will be searched until such a file is found or the root of +- the file system is reached. If such a file is found, it will +- be used to resolve package: URI=E2=80=99s within the file. +-

+-=20=20=20=20 +-

parameters:

included: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the files and directories that should be +- analyzed. +-

+-
excluded: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the files and directories within the +- included directories that should not be analyzed. +-

+-
packageRoots: Map<FilePath, FilePath> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A mapping from source directories to package roots +- that should override the normal package: URI resolution +- mechanism. +-

+-

+- If a package root is a directory, then +- the analyzer will behave as though the associated +- source directory in the map contains a special +- pubspec.yaml file which resolves any package: URI to the +- corresponding path within that package root directory. The +- effect is the same as specifying the package root directory as +- a "--package_root" parameter to the Dart VM when +- executing any Dart file inside the source directory. +-

+-

+- If a package root is a file, then the analyzer +- will behave as though that file is a ".packages" file in the +- source directory. The effect is the same as specifying the file +- as a "--packages" parameter to the Dart VM when +- executing any Dart file inside the source directory. +-

+-

+- Files in any directories that are not overridden by this +- mapping have their package: URI's resolved using the +- normal pubspec.yaml mechanism. If this field is absent, +- or the empty map is specified, that indicates that the +- normal pubspec.yaml mechanism should always be used. +-

+-
analysis.setGeneralSubscriptions
request: {
+-  "id": String
+-  "method": "analysis.setGeneralSubscriptions"
+-  "params": {
+-    "subscriptions": List<GeneralAnalysisService>
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Subscribe for general services (that is, services that are not +- specific to individual files). All previous subscriptions are repla= ced +- by the given set of services. +-

+-

+- It is an error if any of the elements in the list are not valid +- services. If there is an error, then the current subscriptions will +- remain unchanged. +-

+-=20=20=20=20 +-

parameters:

subscriptions: List<<= a href=3D"#type_GeneralAnalysisService">GeneralAnalysisService><= /dt>
+-=20=20=20=20=20=20=20=20 +-

A list of the services being subscribed to.

+-
analysis.setPriorityFiles
request: { +- "id": String +- "method": "analysis.setPriorityFiles" +- "params": { +- "files": List<FilePath> +- } +-}
response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Set the priority files to the files in the given list. A +- priority file is a file that is given priority when +- scheduling which analysis work to do first. The list +- typically contains those files that are visible to the user +- and those for which analysis results will have the biggest +- impact on the user experience. The order of the files within +- the list is significant: the first file will be given higher +- priority than the second, the second higher priority than +- the third, and so on. +-

+-

+- Note that this request determines the set of requested +- priority files. The actual set of priority files is the +- intersection of the requested set of priority files with the +- set of files currently subject to analysis. (See +- analysis.setSubscriptions for a description of files that +- are subject to analysis.) +-

+-

+- If a requested priority file is a directory it is ignored, +- but remains in the set of requested priority files so that +- if it later becomes a file it can be included in the set of +- actual priority files. +-

+-=20=20=20=20 +-

parameters:

files: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- The files that are to be a priority for analysis. +-

+-
analysis.setSubscriptions
request: { +- "id": String +- "method": "analysis.setSubscriptions" +- "params": { +- "subscriptions": Map<Anal= ysisService, List<FilePath>> +- } +-}
response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Subscribe for services that are specific to individual files. +- All previous subscriptions are replaced by the current set of +- subscriptions. If a given service is not included as a key in the m= ap +- then no files will be subscribed to the service, exactly as if the +- service had been included in the map with an explicit empty list of +- files. +-

+-

+- Note that this request determines the set of requested +- subscriptions. The actual set of subscriptions at any given +- time is the intersection of this set with the set of files +- currently subject to analysis. The files currently subject +- to analysis are the set of files contained within an actual +- analysis root but not excluded, plus all of the files +- transitively reachable from those files via import, export +- and part directives. (See analysis.setAnalysisRoots for an +- explanation of how the actual analysis roots are +- determined.) When the actual analysis roots change, the +- actual set of subscriptions is automatically updated, but +- the set of requested subscriptions is unchanged. +-

+-

+- If a requested subscription is a directory it is ignored, +- but remains in the set of requested subscriptions so that if +- it later becomes a file it can be included in the set of +- actual subscriptions. +-

+-

+- It is an error if any of the keys in the map are not valid +- services. If there is an error, then the existing +- subscriptions will remain unchanged. +-

+-=20=20=20=20 +-

parameters:

subscriptions: Map<AnalysisService, List<FilePath>>
+-=20=20=20=20=20=20=20=20 +-

+- A table mapping services to a list of the files being +- subscribed to the service. +-

+-
analysis.updateContent
req=
uest: {
+-  "id": String
+-  "method": "analysis.updateContent"
+-  "params": {
+-    "files": Map<FilePath, AddContentOverlay | ChangeContentOverlay | RemoveContentOverlay>
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-  }
+-}
+-

+- Update the content of one or more files. Files that were +- previously updated but not included in this update remain +- unchanged. This effectively represents an overlay of the +- filesystem. The files whose content is overridden are +- therefore seen by server as being files with the given +- content, even if the files do not exist on the filesystem or +- if the file path represents the path to a directory on the +- filesystem. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

files: Map<FilePath, AddConte= ntOverlay | ChangeContentOverlay= | RemoveContentOverlay><= /b>
+-=20=20=20=20=20=20=20=20 +-

+- A table mapping the files whose content has changed to a +- description of the content change. +-

+-

returns:

analysis.updateOptions
+-

Deprecated: all of the options can be set by users in +- an analysis options file.

+-

+- Update the options controlling analysis based on the given +- set of options. Any options that are not included in the +- analysis options will not be changed. If there are options +- in the analysis options that are not valid, they will be +- silently ignored. +-

+-=20=20=20=20 +-

parameters:

options: AnalysisOptions
+-=20=20=20=20=20=20=20=20 +-

+- The options that are to be used to control analysis. +-

+-

Notifications

analysis.analyzedFile= s
notification: {
+-  "event": "analysis.analyzedFiles"
+-  "params": {
+-    "directories": List<FilePath=
>
+-  }
+-}
+-

+- Reports the paths of the files that are being analyzed. +-

+-

+- This notification is not subscribed to by default. Clients can +- subscribe by including the value "ANALYZED_FILES" in the l= ist +- of services passed in an analysis.setGeneralSubscriptions request. +-

+-=20=20=20=20 +-

parameters:

directories: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the paths of the files that are being analyzed. +-

+-
analysis.errors
notific=
ation: {
+-  "event": "analysis.errors"
+-  "params": {
+-    "file": FilePath
+-    "errors": List<AnalysisErro=
r>
+-  }
+-}
+-

+- Reports the errors associated with a given file. The set of +- errors included in the notification is always a complete +- list that supersedes any previously reported errors. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the errors. +-

+-
errors: List<AnalysisError>
+-=20=20=20=20=20=20=20=20 +-

+- The errors contained in the file. +-

+-
analysis.flushResults
=
notification: {
+-  "event": "analysis.flushResults"
+-  "params": {
+-    "files": List<FilePath>
+-  }
+-}
+-

+- Reports that any analysis results that were previously +- associated with the given files should be considered to be +- invalid because those files are no longer being analyzed, +- either because the analysis root that contained it is no +- longer being analyzed or because the file no longer exists. +-

+-

+- If a file is included in this notification and at some later +- time a notification with results for the file is received, +- clients should assume that the file is once again being +- analyzed and the information should be processed. +-

+-

+- It is not possible to subscribe to or unsubscribe from this +- notification. +-

+-=20=20=20=20 +-

parameters:

files: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- The files that are no longer being analyzed. +-

+-
analysis.folding
notif=
ication: {
+-  "event": "analysis.folding"
+-  "params": {
+-    "file": FilePath
+-    "regions": List<FoldingRegi=
on>
+-  }
+-}
+-

+- Reports the folding regions associated with a given +- file. Folding regions can be nested, but will not be +- overlapping. Nesting occurs when a foldable element, such as +- a method, is nested inside another foldable element such as +- a class. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "FOLDING" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the folding regions. +-

+-
regions: List<FoldingRegion>
+-=20=20=20=20=20=20=20=20 +-

+- The folding regions contained in the file. +-

+-
analysis.highlights
notification: { +- "event": "analysis.highlights" +- "params": { +- "file": FilePath +- "regions": List<Highlight= Region> +- } +-}
+-

+- Reports the highlight regions associated with a given file. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "HIGHLIGHTS" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the highlight regions. +-

+-
regions: List<HighlightRegion>
+-=20=20=20=20=20=20=20=20 +-

+- The highlight regions contained in the file. Each +- highlight region represents a particular syntactic or +- semantic meaning associated with some range. Note that +- the highlight regions that are returned can overlap +- other highlight regions if there is more than one +- meaning associated with a particular region. +-

+-
analysis.implemented
notification: { +- "event": "analysis.implemented" +- "params": { +- "file": FilePath +- "classes": List<Implemen= tedClass> +- "members": List<Impleme= ntedMember> +- } +-}
+-

+- Reports the classes that are implemented or extended and +- class members that are implemented or overridden in a file. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "IMPLEMENTED" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file with which the implementations are associated. +-

+-
classes: List<ImplementedClass>
+-=20=20=20=20=20=20=20=20 +-

+- The classes defined in the file that are implemented or extende= d. +-

+-
members: List<ImplementedMember>
+-=20=20=20=20=20=20=20=20 +-

+- The member defined in the file that are implemented or overridd= en. +-

+-
analysis.invalidate
notification: { +- "event": "analysis.invalidate" +- "params": { +- "file": FilePath +- "offset": int +- "length": int +- "delta": int +- } +-}
+-

+- Reports that the navigation information associated with a region of= a +- single file has become invalid and should be re-requested. +-

+-

+- This notification is not subscribed to by default. Clients can +- subscribe by including the value "INVALIDATE" in the list = of +- services passed in an analysis.setSubscriptions request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file whose information has been invalidated. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the invalidated region. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the invalidated region. +-

+-
delta: int
+-=20=20=20=20=20=20=20=20 +-

+- The delta to be applied to the offsets in information that foll= ows +- the invalidated region in order to update it so that it doesn't +- need to be re-requested. +-

+-
analysis.navigation
notification: { +- "event": "analysis.navigation" +- "params": { +- "file": FilePath +- "regions": List<Navigati= onRegion> +- "targets": List<Navigati= onTarget> +- "files": List<FilePath> +- } +-}
+-

+- Reports the navigation targets associated with a given file. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "NAVIGATION" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the navigation regions. +-

+-
regions: List<NavigationRegion>
+-=20=20=20=20=20=20=20=20 +-

+- The navigation regions contained in the file. +- The regions are sorted by their offsets. +- Each navigation region represents a list of targets +- associated with some range. The lists will usually +- contain a single target, but can contain more in the +- case of a part that is included in multiple libraries +- or in Dart code that is compiled against multiple +- versions of a package. Note that the navigation +- regions that are returned do not overlap other +- navigation regions. +-

+-
targets: List<NavigationTarget>
+-=20=20=20=20=20=20=20=20 +-

+- The navigation targets referenced in the file. +- They are referenced by NavigationRegions by their +- index in this array. +-

+-
files: List<FilePath>
+-=20=20=20=20=20=20=20=20 +-

+- The files containing navigation targets referenced in the file. +- They are referenced by NavigationTargets by their +- index in this array. +-

+-
analysis.occurrences
notification: { +- "event": "analysis.occurrences" +- "params": { +- "file": FilePath +- "occurrences": List<Occurrenc= es> +- } +-}
+-

+- Reports the occurrences of references to elements within a +- single file. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "OCCURRENCES" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file in which the references occur. +-

+-
occurrences: List<Occurrences>
+-=20=20=20=20=20=20=20=20 +-

+- The occurrences of references to elements within the +- file. +-

+-
analysis.outline
notif=
ication: {
+-  "event": "analysis.outline"
+-  "params": {
+-    "file": FilePath
+-    "kind": FileKind
+-    "libraryName": optional S=
tring
+-    "outline": Outline
+-  }
+-}
+-

+- Reports the outline associated with a single file. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "OUTLINE" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file with which the outline is associated. +-

+-
kind: FileKi= nd
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the file. +-

+-
libraryName: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the library defined by the file using a "library" +- directive, or referenced by a "part of" directive. If both +- "library" and "part of" directives are present, then the +- "library" directive takes precedence. +- This field will be omitted if the file has neither "library" +- nor "part of" directives. +-

+-
outline: Outl= ine
+-=20=20=20=20=20=20=20=20 +-

+- The outline associated with the file. +-

+-
analysis.overrides
n=
otification: {
+-  "event": "analysis.overrides"
+-  "params": {
+-    "file": FilePath
+-    "overrides": List<Override&g=
t;
+-  }
+-}
+-

+- Reports the overriding members in a file. +-

+-

+- This notification is not subscribed to by default. Clients +- can subscribe by including the value "OVERRIDES" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file with which the overrides are associated. +-

+-
overrides: List<Override>
+-=20=20=20=20=20=20=20=20 +-

+- The overrides associated with the file. +-

+-
+-

completion domain<= /h2> +-

+- The code completion domain contains commands related to +- getting code completion suggestions. +-

+-=20=20 +-=20=20 +-

Requests

completion.getSuggestions
request: { +- "id": String +- "method": "completion.getSuggestions" +- "params": { +- "file": FilePath +- "offset": int +- } +-}
response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "id": CompletionId
+-  }
+-}
+-

+- Request that completion suggestions for the given offset in +- the given file be returned. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the point at which suggestions are +- to be made. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset within the file at which suggestions are to +- be made. +-

+-

returns:

id: CompletionId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier used to associate results with this +- completion request. +-

+-

Notifications

completion.results
notification: {
+-  "event": "completion.results"
+-  "params": {
+-    "id": CompletionId
+-    "replacementOffset": int
+-    "replacementLength": int
+-    "results": List<Comp=
letionSuggestion>
+-    "isLast": bool
+-  }
+-}
+-

+- Reports the completion suggestions that should be presented +- to the user. The set of suggestions included in the +- notification is always a complete list that supersedes any +- previously reported suggestions. +-

+-=20=20=20=20 +-

parameters:

id: CompletionId
+-=20=20=20=20=20=20=20=20 +-

+- The id associated with the completion. +-

+-
replacementOffset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the start of the text to be +- replaced. This will be different than the offset used +- to request the completion suggestions if there was a +- portion of an identifier before the original +- offset. In particular, the replacementOffset will be +- the offset of the beginning of said identifier. +-

+-
replacementLength: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the text to be replaced if the remainder +- of the identifier containing the cursor is to be +- replaced when the suggestion is applied (that is, the +- number of characters in the existing identifier). +-

+-
results: List<CompletionSuggestion>
+-=20=20=20=20=20=20=20=20 +-

+- The completion suggestions being reported. The +- notification contains all possible completions at the +- requested cursor position, even those that do not match +- the characters the user has already typed. This allows +- the client to respond to further keystrokes from the +- user without having to make additional requests. +-

+-
isLast: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if this is that last set of results that will be +- returned for the indicated completion. +-

+-
+-

search domain

+-

+- The search domain contains commands related to searches that +- can be performed against the code base. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-

Requests

search.findElementReferences
request: {
+-  "id": String
+-  "method": "search.findElementReferences"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-    "includePotential": bool
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "id": optional SearchId
+-    "element": optional Element
+-  }
+-}
+-

+- Perform a search for references to the element defined or +- referenced at the given offset in the given file. +-

+-

+- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the declaration of or reference to +- the element used to define the search. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset within the file of the declaration of or +- reference to the element. +-

+-
includePotential: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if potential matches are to be included in the +- results. +-

+-

returns:

id: SearchId (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The identifier used to associate results with this +- search request. +-

+-

+- If no element was found at the given location, this +- field will be absent, and no results will be reported +- via the search.results notification. +-

+-
element: Elem= ent (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The element referenced or defined at the given offset +- and whose references will be returned in the search +- results. +-

+-

+- If no element was found at the given location, this +- field will be absent. +-

+-
search.findMemberDeclarations
request: {
+-  "id": String
+-  "method": "search.findMemberDeclarations"
+-  "params": {
+-    "name": String
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "id": SearchId
+-  }
+-}
+-

+- Perform a search for declarations of members whose name is +- equal to the given name. +-

+-

+- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the declarations to be found. +-

+-

returns:

id: SearchId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier used to associate results with this +- search request. +-

+-
search.findMemberReferences
request: {
+-  "id": String
+-  "method": "search.findMemberReferences"
+-  "params": {
+-    "name": String
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "id": SearchId
+-  }
+-}
+-

+- Perform a search for references to members whose name is +- equal to the given name. This search does not check to see +- that there is a member defined with the given name, so it is +- able to find references to undefined members as well. +-

+-

+- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the references to be found. +-

+-

returns:

id: SearchId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier used to associate results with this +- search request. +-

+-
search.findTopLevelDeclarations
request: {
+-  "id": String
+-  "method": "search.findTopLevelDeclarations"
+-  "params": {
+-    "pattern": String
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "id": SearchId
+-  }
+-}
+-

+- Perform a search for declarations of top-level elements +- (classes, typedefs, getters, setters, functions and fields) +- whose name matches the given pattern. +-

+-

+- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

pattern: String
=
+-=20=20=20=20=20=20=20=20 +-

+- The regular expression used to match the names of the +- declarations to be found. +-

+-

returns:

id: SearchId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier used to associate results with this +- search request. +-

+-
search.getTypeHierarchy
r=
equest: {
+-  "id": String
+-  "method": "search.getTypeHierarchy"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-    "superOnly": optional bool
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "hierarchyItems": optional List<TypeHierarchyItem>
+-  }
+-}
+-

+- Return the type hierarchy of the class declared or +- referenced at the given location. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the declaration or reference to the +- type for which a hierarchy is being requested. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the name of the type within the file. +-

+-
superOnly: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if the client is only requesting superclasses and +- interfaces hierarchy. +-

+-

returns:

hierarchyItem= s: List<TypeHierarchyItem> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A list of the types in the requested hierarchy. The +- first element of the list is the item representing the +- type for which the hierarchy was requested. The index of +- other elements of the list is unspecified, but +- correspond to the integers used to reference supertype +- and subtype items within the items. +-

+-

+- This field will be absent if the code at the given file +- and offset does not represent a type, or if the file has +- not been sufficiently analyzed to allow a type hierarchy +- to be produced. +-

+-

Notifications

search.results
notification: {
+-  "event": "search.results"
+-  "params": {
+-    "id": SearchId
+-    "results": List<SearchResult=
>
+-    "isLast": bool
+-  }
+-}
+-

+- Reports some or all of the results of performing a requested +- search. Unlike other notifications, this notification +- contains search results that should be added to any +- previously received search results associated with the same +- search id. +-

+-=20=20=20=20 +-

parameters:

id: SearchId
+-=20=20=20=20=20=20=20=20 +-

+- The id associated with the search. +-

+-
results: List<SearchResult>
+-=20=20=20=20=20=20=20=20 +-

+- The search results being reported. +-

+-
isLast: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if this is that last set of results that will be +- returned for the indicated search. +-

+-
+-

edit domain

+-

+- The edit domain contains commands related to edits that can be +- applied to the code. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-

Requests

edit.format
request: {
+-  "id": String
+-  "method": "edit.format"
+-  "params": {
+-    "file": FilePath
+-    "selectionOffset": int
+-    "selectionLength": int
+-    "lineLength": optional int
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "edits": List<SourceEdit&g=
t;
+-    "selectionOffset": int
+-    "selectionLength": int
+-  }
+-}
+-

+- Format the contents of a single file. The currently selected region= of +- text is passed in so that the selection can be preserved across the +- formatting operation. The updated selection will be as close to +- matching the original as possible, but whitespace at the beginning = or +- end of the selected region will be ignored. If preserving selection +- information is not required, zero (0) can be specified for both the +- selection offset and selection length. +-

+-

+- If a request is made for a file which does not exist, or which is n= ot +- currently subject to analysis (e.g. because it is not associated wi= th +- any analysis root specified to analysis.setAnalysisRoots), an error= of +- type FORMAT_INVALID_FILE will be generated. If the source +- contains syntax errors, an error of type FORMAT_WITH_ERRORS +- will be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the code to be formatted. +-

+-
selectionOffset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the current selection in the file. +-

+-
selectionLength: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the current selection in the file. +-

+-
lineLength: int (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The line length to be used by the formatter. +-

+-

returns:

edits: List&l= t;SourceEdit>
+-=20=20=20=20=20=20=20=20 +-

+- The edit(s) to be applied in order to format the code. The list +- will be empty if the code was already formatted (there are no +- changes). +-

+-
selectionOffset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the selection after formatting the code. +-

+-
selectionLength: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the selection after formatting the code. +-

+-
edit.getAssists
request: {
+-  "id": String
+-  "method": "edit.getAssists"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-    "length": int
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "assists": List<SourceChange=
>
+-  }
+-}
+-

+- Return the set of assists that are available at the given +- location. An assist is distinguished from a refactoring +- primarily by the fact that it affects a single file and does +- not require user input in order to be performed. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the code for which assists are being +- requested. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the code for which assists are being +- requested. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the code for which assists are being +- requested. +-

+-

returns:

assists: List= <SourceChange>
+-=20=20=20=20=20=20=20=20 +-

+- The assists that are available at the given location. +-

+-
edit.getAvailableRefactorings
request: {
+-  "id": String
+-  "method": "edit.getAvailableRefactorings"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-    "length": int
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "kinds": List<Refactoring=
Kind>
+-  }
+-}
+-

+- Get a list of the kinds of refactorings that are valid for +- the given selection in the given file. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the code on which the refactoring +- would be based. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the code on which the refactoring would be +- based. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the code on which the refactoring would be +- based. +-

+-

returns:

kinds: List&l= t;RefactoringKind>
+-=20=20=20=20=20=20=20=20 +-

+- The kinds of refactorings that are valid for the given +- selection. +-

+-
edit.getFixes
request: {
+-  "id": String
+-  "method": "edit.getFixes"
+-  "params": {
+-    "file": FilePath
+-    "offset": int
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "fixes": List<Analysis=
ErrorFixes>
+-  }
+-}
+-

+- Return the set of fixes that are available for the errors at +- a given offset in a given file. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the errors for which fixes are being +- requested. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset used to select the errors for which fixes +- will be returned. +-

+-

returns:

fixes: List&l= t;AnalysisErrorFixes>
<= dd> +-=20=20=20=20=20=20=20=20 +-

+- The fixes that are available for the errors at the given offset. +-

+-
edit.getRefactoring
request: {
+-  "id": String
+-  "method": "edit.getRefactoring"
+-  "params": {
+-    "kind": RefactoringKind
+-    "file": FilePath
+-    "offset": int
+-    "length": int
+-    "validateOnly": bool
+-    "options": optional RefactoringOptions
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "initialProblems": List<RefactoringProblem>
+-    "optionsProblems": List<RefactoringProblem>
+-    "finalProblems": List<=
RefactoringProblem>
+-    "feedback": optional RefactoringFeedback
+-    "change": optional SourceChange
+-    "potentialEdits": optional List<String>
+-  }
+-}
+-

+- Get the changes required to perform a refactoring. +-

+-

+- If another refactoring request is received during the processing +- of this one, an error of type REFACTORING_REQUEST_CANCELLED +- will be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

kind: RefactoringKind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of refactoring to be performed. +-

+-
file: FilePa= th
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the code involved in the +- refactoring. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region involved in the refactoring. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region involved in the refactoring. +-

+-
validateOnly: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the client is only requesting that the values of +- the options be validated and no change be generated. +-

+-
options: RefactoringOptions (optional)
+-=20=20=20=20=20=20=20=20 +-

+- Data used to provide values provided by the user. The +- structure of the data is dependent on the kind of +- refactoring being performed. The data that is expected is +- documented in the section titled Refa= ctorings, labeled as +- "Options". This field can be omitted if the refactoring +- does not require any options or if the values of those +- options are not known. +-

+-

returns:

initialProble= ms: List<RefactoringProblem>=
+-=20=20=20=20=20=20=20=20 +-

+- The initial status of the refactoring, i.e. problems related to +- the context in which the refactoring is requested. +- The array will be empty if there are no known problems. +-

+-
optionsProblems: List<RefactoringProblem>
+-=20=20=20=20=20=20=20=20 +-

+- The options validation status, i.e. problems in the given optio= ns, +- such as light-weight validation of a new name, flags +- compatibility, etc. +- The array will be empty if there are no known problems. +-

+-
finalProblems: List<RefactoringProblem>
+-=20=20=20=20=20=20=20=20 +-

+- The final status of the refactoring, i.e. problems identified in +- the result of a full, potentially expensive validation and / or +- change creation. +- The array will be empty if there are no known problems. +-

+-
feedback: RefactoringFeedback (optional)
+-=20=20=20=20=20=20=20=20 +-

+- Data used to provide feedback to the user. The structure +- of the data is dependent on the kind of refactoring +- being created. The data that is returned is documented +- in the section titled Refactorings, labeled as +- "Feedback". +-

+-
change: = SourceChange (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The changes that are to be applied to affect the +- refactoring. This field will be omitted if there are +- problems that prevent a set of changes from being +- computed, such as having no options specified for a +- refactoring that requires them, or if only validation +- was requested. +-

+-
potentialEdits: List<String> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The ids of source edits that are not known to be valid. An edit= is +- not known to be valid if there was insufficient type information +- for the server to be able to determine whether or not the code +- needs to be modified, such as when a member is being renamed and +- there is a reference to a member from an unknown type. This fie= ld +- will be omitted if the change field is omitted or if there are = no +- potential edits for the refactoring. +-

+-
edit.sortMembers
request: {
+-  "id": String
+-  "method": "edit.sortMembers"
+-  "params": {
+-    "file": FilePath
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "edit": SourceFileEdit
+-  }
+-}
+-

+- Sort all of the directives, unit and class members +- of the given Dart file. +-

+-

+- If a request is made for a file that does not exist, does not belong +- to an analysis root or is not a Dart file, +- SORT_MEMBERS_INVALID_FILE will be generated. +-

+-

+- If the Dart file has scan or parse errors, +- SORT_MEMBERS_PARSE_ERRORS will be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The Dart file to sort. +-

+-

returns:

edit: SourceFileEdit
+-=20=20=20=20=20=20=20=20 +-

+- The file edit that is to be applied to the given file to effect +- the sorting. +-

+-
edit.organizeDirectives
r=
equest: {
+-  "id": String
+-  "method": "edit.organizeDirectives"
+-  "params": {
+-    "file": FilePath
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "edit": SourceFileEdit
+-  }
+-}
+-

+- Organizes all of the directives - removes unused imports and sorts +- directives of the given Dart file according to the +- Dart Sty= le +- Guide. +-

+-

+- If a request is made for a file that does not exist, does not belong +- to an analysis root or is not a Dart file, +- FILE_NOT_ANALYZED will be generated. +-

+-

+- If directives of the Dart file cannot be organized, for example +- because it has scan or parse errors, or by other reasons, +- ORGANIZE_DIRECTIVES_ERROR will be generated. The message +- will provide details about the reason. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The Dart file to organize directives in. +-

+-

returns:

edit: SourceFileEdit
+-=20=20=20=20=20=20=20=20 +-

+- The file edit that is to be applied to the given file to effect +- the organizing. +-

+-
+-

execution domain +-

+- The execution domain contains commands related to providing an execut= ion +- or debugging experience. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-

Requests

execution.createContext
r=
equest: {
+-  "id": String
+-  "method": "execution.createContext"
+-  "params": {
+-    "contextRoot": FilePath
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "id": ExecutionContextId<=
/a>
+-  }
+-}
+-

+- Create an execution context for the executable file with the given +- path. The context that is created will persist until +- execution.deleteContext is used to delete it. Clients, therefore, a= re +- responsible for managing the lifetime of execution contexts. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

contextRoot: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The path of the Dart or HTML file that will be launched, or the +- path of the directory containing the file. +-

+-

returns:

id: ExecutionContextId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier used to refer to the execution context that was +- created. +-

+-
execution.deleteContext
r=
equest: {
+-  "id": String
+-  "method": "execution.deleteContext"
+-  "params": {
+-    "id": ExecutionContextId<=
/a>
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Delete the execution context with the given identifier. The context= id +- is no longer valid after this command. The server is allowed to re-= use +- ids when they are no longer valid. +-

+-=20=20=20=20 +-

parameters:

id: ExecutionContextId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier of the execution context that is to be deleted. +-

+-
execution.mapUri
request: {
+-  "id": String
+-  "method": "execution.mapUri"
+-  "params": {
+-    "id": ExecutionContextId<=
/a>
+-    "file": optional FilePath
+-    "uri": optional String
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "file": optional FilePath
+-    "uri": optional String
+-  }
+-}
+-

+- Map a URI from the execution context to the file that it corresponds +- to, or map a file to the URI that it corresponds to in the execution +- context. +-

+-

+- Exactly one of the file and uri fields must be provided. If both +- fields are provided, then an error of type INVALID_PARAMETER +- will be generated. Similarly, if neither field is provided, then an +- error of type INVALID_PARAMETER will be generated. +-

+-

+- If the file field is provided and the value is not the path of a fi= le +- (either the file does not exist or the path references something ot= her +- than a file), then an error of type INVALID_PARAMETER will +- be generated. +-

+-

+- If the uri field is provided and the value is not a valid URI or if +- the URI references something that is not a file (either a file that +- does not exist or something other than a file), then an error of ty= pe +- INVALID_PARAMETER will be generated. +-

+-

+- If the contextRoot used to create the execution context does not +- exist, then an error of type INVALID_EXECUTION_CONTEXT will +- be generated. +-

+-=20=20=20=20 +-=20=20=20=20 +-

parameters:

id: ExecutionContextId
+-=20=20=20=20=20=20=20=20 +-

+- The identifier of the execution context in which the URI is to = be +- mapped. +-

+-
file: FilePa= th (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The path of the file to be mapped into a URI. +-

+-
uri: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The URI to be mapped into a file path. +-

+-

returns:

file: FilePath (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The file to which the URI was mapped. This field is omitted if = the +- uri field was not given in the request. +-

+-
uri: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The URI to which the file path was mapped. This field is omitted +- if the file field was not given in the request. +-

+-
execution.setSubscriptions
request: {
+-  "id": String
+-  "method": "execution.setSubscriptions"
+-  "params": {
+-    "subscriptions": List<Ex=
ecutionService>
+-  }
+-}

response: {
+-  "id": String
+-  "error": optional RequestError
+-}
+-

+- Deprecated: the analysis server no longer fires +- LAUNCH_DATA events. +-

+-

+- Subscribe for services. All previous subscriptions are replaced by = the +- given set of services. +-

+-

+- It is an error if any of the elements in the list are not valid +- services. If there is an error, then the current subscriptions will +- remain unchanged. +-

+-=20=20=20=20 +-

parameters:

subscriptions: List<<= a href=3D"#type_ExecutionService">ExecutionService>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the services being subscribed to. +-

+-

Notifications

execution.launchData
+-

+- Reports information needed to allow a single file to be launched. +-

+-

+- This notification is not subscribed to by default. Clients can +- subscribe by including the value "LAUNCH_DATA" in the list of servi= ces +- passed in an execution.setSubscriptions request. +-

+-=20=20=20=20 +-

parameters:

file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file for which launch data is being provided. This will eit= her +- be a Dart library or an HTML file. +-

+-
kind: = ExecutableKind (optional)
=
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the executable file. This field is omitted if the f= ile +- is not a Dart file. +-

+-
referencedFiles: List<FilePath> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A list of the Dart files that are referenced by the file. This +- field is omitted if the file is not an HTML file. +-

+-
+-

diagnostic domain<= /h2> +-

+- The diagnostic domain contains server diagnostics APIs. +-

+-=20=20 +-=20=20 +-

Requests

diagnostic.getDiagnostics
request: { +- "id": String +- "method": "diagnostic.getDiagnostics" +-}
response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "contexts": List<ContextData<=
/a>>
+-  }
+-}
+-

Return server diagnostics.

+-=20=20=20=20 +-

returns:

contexts: List<ContextData>
+-=20=20=20=20=20=20=20=20 +-

The list of analysis contexts.

+-
diagnostic.getServerPort
request: { +- "id": String +- "method": "diagnostic.getServerPort" +-}
response: {
+-  "id": String
+-  "error": optional RequestError
+-  "result": {
+-    "port": int
+-  }
+-}
+-

+- Return the port of the diagnostic web server. If the server is not = running +- this call will start the server. If unable to start the diagnostic = web +- server, +- this call will return an error of DEBUG_PORT_COULD_NOT_BE_OPENE= D. +-

+-=20=20=20=20 +-

returns:

port: int
+-=20=20=20=20=20=20=20=20 +-

The diagnostic server port.

+-
+- +- +- +-

Types

+-

+- This section contains descriptions of the data types referenced +- in the API=E2=80=99s of the various domains. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-
AddCo= ntentOverlay: object
+-

+- A directive to begin overlaying the contents of a file. The supplied +- content will be used for analysis in place of the file contents in = the +- filesystem. +-

+-

+- If this directive is used on a file that already has a file content +- overlay, the old overlay is discarded and replaced with the new one. +-

+-=20=20=20=20 +-
type =3D "add"
+-=20=20=20=20=20=20=20=20 +-
content: String
+-=20=20=20=20=20=20=20=20 +-

+- The new content of the file. +-

+-
AnalysisError: object
+-

+- An indication of an error, warning, or hint that was produced by the +- analysis. +-

+-=20=20=20=20 +-
severity: AnalysisErrorSeverity
+-=20=20=20=20=20=20=20=20 +-

+- The severity of the error. +-

+-
type: AnalysisErrorType
+-=20=20=20=20=20=20=20=20 +-

+- The type of the error. +-

+-
location: Lo= cation
+-=20=20=20=20=20=20=20=20 +-

+- The location associated with the error. +-

+-
message: String
+-=20=20=20=20=20=20=20=20 +-

+- The message to be displayed for this error. The message should +- indicate what is wrong with the code and why it is wrong. +-

+-
correction: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The correction message to be displayed for this error. The corr= ection +- message should indicate how the user can fix the error. The fie= ld is +- omitted if there is no correction message associated with the e= rror +- code. +-

+-
code: String
+-=20=20=20=20=20=20=20=20 +-

+- The name, as a string, of the error code associated with this e= rror. +-

+-
hasFix: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A hint to indicate to interested clients that this error has an +- associated fix (or fixes). The absence of this field implies th= ere +- are not known to be fixes. Note that since the operation to cal= culate +- whether fixes apply needs to be performant it is possible that +- complicated tests will be skipped and a false negative returned= . For +- this reason, this attribute should be treated as a "hint". Desp= ite the +- possibility of false negatives, no false positives should be re= turned. +- If a client sees this flag set they can proceed with the confid= ence +- that there are in fact associated fixes. +-

+-
AnalysisErrorFixes: object
+-

+- A list of fixes associated with a specific error. +-

+-=20=20=20=20 +-
error: Analy= sisError
+-=20=20=20=20=20=20=20=20 +-

+- The error with which the fixes are associated. +-

+-
fixes: List<SourceChange>
+-=20=20=20=20=20=20=20=20 +-

+- The fixes associated with the error. +-

+-
AnalysisErrorSeverity: String
+-

+- An enumeration of the possible severities of analysis errors. +-

+-=20=20=20=20 +-
INFO
WARNING
ERROR
AnalysisErrorType: String
+-

+- An enumeration of the possible types of analysis errors. +-

+-=20=20=20=20 +-
CHECKED_MODE_COMPILE_TIME_ERROR
COMPILE_TIME_ERROR
HINT
LINT
STATIC_TYPE_WARNING
STATIC_WARNING
SYNTACTIC_ERROR
TODO
AnalysisOptions: object
+-

Deprecated: the only reference to this type has been +- deprecated.

+-

+- A set of options controlling what kind of analysis is to be +- performed. If the value of a field is omitted the value of the +- option will not be changed. +-

+-=20=20=20=20 +-
enableAsync: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

Deprecated: this feature is always enabled.

+-

+- True if the client wants to enable support for the +- proposed async feature. +-

+-
enableDeferr= edLoading: bool (optional)<= /dt>
+-=20=20=20=20=20=20=20=20 +-

Deprecated: this feature is always enabled.

+-

+- True if the client wants to enable support for the +- proposed deferred loading feature. +-

+-
enableEnums<= /span>: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

Deprecated: this feature is always enabled.

+-

+- True if the client wants to enable support for the +- proposed enum feature. +-

+-
enableNullAw= areOperators: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

Deprecated: this feature is always enabled.

+-

+- True if the client wants to enable support for the +- proposed "null aware operators" feature. +-

+-
enableSuperMixins: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if the client wants to enable support for the +- proposed "less restricted mixins" proposal (DEP 34). +-

+-
generateDart2jsHints: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if hints that are specific to dart2js should be +- generated. This option is ignored if generateHints is false. +-

+-
generateHints: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if hints should be generated as part of generating +- errors and warnings. +-

+-
generateLints: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if lints should be generated as part of generating +- errors and warnings. +-

+-
AnalysisService: String
+-

+- An enumeration of the services provided by the analysis domain that +- are related to a specific list of files. +-

+-=20=20=20=20 +-
CLOSING_LABELS
FOLDING<= /dt>
HIGHLIGHTS
IMPLEMENTED
=
INVALIDATE
+-=20=20=20=20=20=20=20=20 +-

+- This service is not currently implemented and will become a +- GeneralAnalysisService in a future release. +-

+-
NAVIGATION
OCCURRE= NCES
OUTLINE
OVERRIDES
=
Anal= ysisStatus: object
+-

+- An indication of the current state of analysis. +-

+-=20=20=20=20 +-
isAnalyzing: bool
+-=20=20=20=20=20=20=20=20 +-

True if analysis is currently being performed.

+-
analysisTarget: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the current target of analysis. This field is +- omitted if analyzing is false. +-

+-
ChangeContentOverlay: object
+-

+- A directive to modify an existing file content overlay. One or more= ranges +- of text are deleted from the old file content overlay and replaced = with +- new text. +-

+-

+- The edits are applied in the order in which they occur in the list.= This +- means that the offset of each edit must be correct under the assump= tion +- that all previous edits have been applied. +-

+-

+- It is an error to use this overlay on a file that does not yet have= a file +- content overlay or that has had its overlay removed via +- RemoveContentOverlay. +-

+-

+- If any of the edits cannot be applied due to its offset or length b= eing +- out of range, an INVALID_OVERLAY_CHANGE error will be repo= rted. +-

+-=20=20=20=20 +-
type =3D "change"
+-=20=20=20=20=20=20=20=20 +-
edits: List<SourceEdit>
+-=20=20=20=20=20=20=20=20 +-

+- The edits to be applied to the file. +-

+-
ClosingLabel: object
+-

+- A label that is associated with a range of code that may be useful = to +- render at the end of the range to aid code readability. For example= , a +- constructor call that spans multiple lines may result in a closing = label +- to allow the constructor type/name to be rendered alongside the clo= sing +- parenthesis. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the construct being labelled. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the whole construct to be labelled. +-

+-
label: String
+-=20=20=20=20=20=20=20=20 +-

+- The label associated with this range that should be displayed t= o the +- user. +-

+-
CompletionId: String
+-=20=20=20=20 +-

+- An identifier used to associate completion results with a +- completion request. +-

+-
CompletionSuggestion: object
+-

+- A suggestion for how to complete partially entered text. Many of the +- fields are optional, depending on the kind of element being suggest= ed. +-

+-=20=20=20=20 +-
kind: CompletionSuggestionKind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of element being suggested. +-

+-
relevance: int
+-=20=20=20=20=20=20=20=20 +-

+- The relevance of this completion suggestion where a higher numb= er +- indicates a higher relevance. +-

+-
completion: String
+-=20=20=20=20=20=20=20=20 +-

+- The identifier to be inserted if the suggestion is selected. If= the +- suggestion is for a method or function, the client might want to +- additionally insert a template for the parameters. The informat= ion +- required in order to do so is contained in other fields. +-

+-
selectionOffset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset, relative to the beginning of the completion, of whe= re the +- selection should be placed after insertion. +-

+-
selectionLength: int
+-=20=20=20=20=20=20=20=20 +-

+- The number of characters that should be selected after insertio= n. +-

+-
isDeprecated: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the suggested element is deprecated. +-

+-
isPotential: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the element is not known to be valid for the target. Th= is +- happens if the type of the target is dynamic. +-

+-
docSummary: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- An abbreviated version of the Dartdoc associated with the eleme= nt +- being suggested, This field is omitted if there is no Dartdoc +- associated with the element. +-

+-
docComplete: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The Dartdoc associated with the element being suggested. This f= ield is +- omitted if there is no Dartdoc associated with the element. +-

+-
declaringType: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The class that declares the element being suggested. This field= is +- omitted if the suggested element is not a member of a class. +-

+-
defaultArgumentListString: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A default String for use in generating argument list source con= tents +- on the client side. +-

+-
defaultArgumentListTextRanges: List<= int> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- Pairs of offsets and lengths describing 'defaultArgumentListStr= ing' +- text ranges suitable for use by clients to set up linked edits = of +- default argument source contents. For example, given an argumen= t list +- string 'x, y', the corresponding text range [0, 1, 3, 1], indic= ates +- two text ranges of length 1, starting at offsets 0 and 3. Clien= ts can +- use these ranges to treat the 'x' and 'y' values specially for = linked +- edits. +-

+-
element: Elem= ent (optional)
+-=20=20=20=20=20=20=20=20 +-

+- Information about the element reference being suggested. +-

+-
returnType: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The return type of the getter, function or method or the type o= f the +- field being suggested. This field is omitted if the suggested e= lement +- is not a getter, function or method. +-

+-
parameterNames: List<String> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The names of the parameters of the function or method being sug= gested. +- This field is omitted if the suggested element is not a setter, +- function or method. +-

+-
parameterTypes: List<String> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The types of the parameters of the function or method being sug= gested. +- This field is omitted if the parameterNames field is omitted. +-

+-
requiredParameterCount: int (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The number of required parameters for the function or method be= ing +- suggested. This field is omitted if the parameterNames field is +- omitted. +-

+-
hasNamedParameters: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if the function or method being suggested has at least one= named +- parameter. This field is omitted if the parameterNames field is +- omitted. +-

+-
parameterName: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the optional parameter being suggested. This field = is +- omitted if the suggestion is not the addition of an optional ar= gument +- within an argument list. +-

+-
parameterType: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The type of the options parameter being suggested. This field is +- omitted if the parameterName field is omitted. +-

+-
importUri: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The import to be added if the suggestion is out of scope and ne= eds +- an import to be added to be in scope. +-

+-
CompletionSuggestionKind: String
+-

+- An enumeration of the kinds of elements that can be included in a +- completion suggestion. +-

+-=20=20=20=20 +-
ARGUMENT_LIST
+-=20=20=20=20=20=20=20=20 +-

+- A list of arguments for the method or function that is being +- invoked. For this suggestion kind, the completion field is a +- textual representation of the invocation and the parameterNames, +- parameterTypes, and requiredParameterCount attributes are defin= ed. +-

+-
IMPORT
IDENTIFIER<= /dt>
+-=20=20=20=20=20=20=20=20 +-

+- The element identifier should be inserted at the completion +- location. For example "someMethod" in import 'myLib.dart' s= how +- someMethod;. For suggestions of this kind, the element +- attribute is defined and the completion field is the element's +- identifier. +-

+-
INVOCATION
+-=20=20=20=20=20=20=20=20 +-

+- The element is being invoked at the completion location. For +- example, 'someMethod' in x.someMethod();. For suggesti= ons +- of this kind, the element attribute is defined and the completi= on +- field is the element's identifier. +-

+-
KEYWORD
+-=20=20=20=20=20=20=20=20 +-

+- A keyword is being suggested. For suggestions of this kind, the +- completion is the keyword. +-

+-
NAMED_ARGUMENT
+-=20=20=20=20=20=20=20=20 +-

+- A named argument for the current call site is being suggested. = For +- suggestions of this kind, the completion is the named argument +- identifier including a trailing ':' and a space. +-

+-
OPTIONAL_ARGUMENT
= PARAMETER
ContextData: object
+-

+- Information about an analysis context. +-

+-=20=20=20=20 +-
name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the context. +-

+-
explicitFileCount: int
+-=20=20=20=20=20=20=20=20 +-

+- Explicitly analyzed files. +-

+-
implicitFileCount: int
+-=20=20=20=20=20=20=20=20 +-

+- Implicitly analyzed files. +-

+-
workItemQueueLength: int
+-=20=20=20=20=20=20=20=20 +-

+- The number of work items in the queue. +-

+-
cacheEntryExceptions: List<String>= ;
+-=20=20=20=20=20=20=20=20 +-

+- Exceptions associated with cache entries. +-

+-
Element: object
+-

+- Information about an element (something that can be declared in cod= e). +-

+-=20=20=20=20 +-
kind: ElementK= ind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the element. +-

+-
name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the element. This is typically used as the label in= the +- outline. +-

+-
location: Lo= cation (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The location of the name in the declaration of the element. +-

+-
flags: int
+-=20=20=20=20=20=20=20=20 +-

+- A bit-map containing the following flags: +-

+-
    +-
  • +- 0x01 - set if the element is explicitly or implicitly abstract +-
  • +-
  • +- 0x02 - set if the element was declared to be =E2=80=98const= =E2=80=99 +-
  • +-
  • +- 0x04 - set if the element was declared to be =E2=80=98final= =E2=80=99 +-
  • +-
  • +- 0x08 - set if the element is a static member of a class or is= a +- top-level function or field +-
  • +-
  • +- 0x10 - set if the element is private +-
  • +-
  • +- 0x20 - set if the element is deprecated +-
  • +-
+-
parameters: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The parameter list for the element. If the element is not a met= hod or +- function this field will not be defined. If the element doesn't= have +- parameters (e.g. getter), this field will not be defined. If the +- element has zero parameters, this field will have a value of "(= )". +-

+-
returnType: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The return type of the element. If the element is not a method = or +- function this field will not be defined. If the element does no= t have +- a declared return type, this field will contain an empty string. +-

+-
typeParameters: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The type parameter list for the element. If the element doesn't= have +- type parameters, this field will not be defined. +-

+-
ElementKind: String
+-

+- An enumeration of the kinds of elements. +-

+-=20=20=20=20 +-
CLASS
CLASS_TYPE_ALIAS<= /dt>
COMPILATION_UNIT
CONSTRUCTO= R
CONSTRUCTOR_INVOCATION
EN= UM
ENUM_CONSTANT
FIELD
=
FILE
FUNCTION
FUNCTION_INVOCATION
FUNCTION_TYPE_ALIAS
=
GETTER
LABEL
LIBRARY
LOCAL_VARIABLE
METHOD
PARAMETER
PREFIX
SETTER
TOP_LEVEL_VARIABLE
TYPE_PARAMETER
UNIT_TEST_GROU= P
UNIT_TEST_TEST
UNKNOWN
Ex= ecutableFile: object
+-

+- A description of an executable file. +-

+-=20=20=20=20 +-
file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The path of the executable file. +-

+-
kind: = ExecutableKind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the executable file. +-

+-
ExecutableKind: String
+-

+- An enumeration of the kinds of executable files. +-

+-=20=20=20=20 +-
CLIENT
EITHER
NOT_EXECUTABLE
SERVER
=
ExecutionC= ontextId: String
+-=20=20=20=20 +-

+- The identifier for a execution context. +-

+-
Exe= cutionService: String
+-

+- An enumeration of the services provided by the execution +- domain. +-

+-=20=20=20=20 +-
LAUNCH_DATA
FileKind: String
+-

+- An enumeration of the kinds of files. +-

+-=20=20=20=20 +-
LIBRARY
PART
<= /dd>
FilePath: String=
+-=20=20=20=20 +-

+- The absolute, normalized path of a file. +-

+-

+- If the format of a file path in a request is not valid, e.g. the pa= th is +- not absolute or is not normalized, then an error of type +- INVALID_FILE_PATH_FORMAT will be generated. +-

+-
FoldingK= ind: String
+-

+- An enumeration of the kinds of folding regions. +-

+-=20=20=20=20 +-
COMMENT
CLASS_MEMBER
DIRECTIVES
DOCUMENTATION_COMM= ENT
TOP_LEVEL_DECLARATION
FoldingRegion: object
+-

+- A description of a region that can be folded. +-

+-=20=20=20=20 +-
kind: FoldingK= ind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the region. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region to be folded. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region to be folded. +-

+-
GeneralAnalysisService: String
+-

+- An enumeration of the services provided by the analysis domain that= are +- general in nature (that is, are not specific to some list of files). +-

+-=20=20=20=20 +-
ANALYZED_FILES
HighlightRegion: object
+-

+- A description of a region that could have special highlighting asso= ciated +- with it. +-

+-=20=20=20=20 +-
type: = HighlightRegionType
+-=20=20=20=20=20=20=20=20 +-

+- The type of highlight associated with the region. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region to be highlighted. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region to be highlighted. +-

+-
HighlightRegionType: String
+-

+- An enumeration of the kinds of highlighting that can be applied to = files. +-

+-=20=20=20=20 +-
ANNOTATION
BUILT_IN
CLASS
COMMENT_BLOCK
COMMENT_DOCUMENTATION
COMMENT_END_OF_= LINE
CONSTRUCTOR
DIRECTIVE<= /dt>
DYNAMIC_TYPE
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
DYNAMIC_LOCAL_VARIABLE_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
DYNAMIC_LOCAL_VARIABLE_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
DYNAMIC_PARAMETER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
DYNAMIC_PARAMETER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
ENUM
ENUM_CONSTANT=
FIELD
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
FIELD_STATIC
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
FUNCTION
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
FUNCTION_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
FUNCTION_TYPE_ALIAS
GETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
IDENTIFIER_DEFAULT
IMPORT_PREFIX
INSTANCE_FIELD_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_FIELD_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_GETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_GETTER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_METHOD_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_METHOD_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_SETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INSTANCE_SETTER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
INVALID_STRING_ESCAPE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
KEYWORD
LABEL
=
LIBRARY_NAME
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
LITERAL_BOOLEAN
LI= TERAL_DOUBLE
LITERAL_INTEGER
LITERAL_LIST
LITERAL_MAP
= LITERAL_STRING
LOCAL_FUNCTION_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
LOCAL_FUNCTION_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
LOCAL_VARIABLE
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
LOCAL_VARIABLE_DECLARATION
LOCAL_VARIABLE_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
METHOD
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
METHOD_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
METHOD_DECLARATION_STATIC
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
METHOD_STATIC
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
PARAMETER
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
SETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
TOP_LEVEL_VARIABLE
+-=20=20=20=20=20=20=20=20 +-

Only for version 1 of highlight.

+-
PARAMETER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
PARAMETER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_FIELD_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_GETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_GETTER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_METHOD_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_METHOD_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_SETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
STATIC_SETTER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_FUNCTION_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_FUNCTION_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_GETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_GETTER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_SETTER_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_SETTER_REFERENCE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TOP_LEVEL_VARIABLE_DECLARATION
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
TYPE_NAME_DYNAMIC
= TYPE_PARAMETER
UNRESOLVED_INSTANCE_MEMBER_REFERENCE=
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
VALID_STRING_ESCAPE
+-=20=20=20=20=20=20=20=20 +-

Only for version 2 of highlight.

+-
HoverInformation: object
+-

+- The hover information associated with a specific location. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the range of characters that encompasses the +- cursor position and has the same hover information as the +- cursor position. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the range of characters that encompasses the +- cursor position and has the same hover information as the +- cursor position. +-

+-
containingLibraryPath: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The path to the defining compilation unit of the library +- in which the referenced element is declared. This data is +- omitted if there is no referenced element, or if the +- element is declared inside an HTML file. +-

+-
containingLibraryName: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the library in which the referenced element is +- declared. This data is omitted if there is no referenced +- element, or if the element is declared inside an HTML +- file. +-

+-
containingClassDescription: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A human-readable description of the class declaring the element +- being referenced. This data is omitted if there is no referenced +- element, or if the element is not a class member. +-

+-
dartdoc: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The dartdoc associated with the referenced element. Other +- than the removal of the comment delimiters, including +- leading asterisks in the case of a block comment, the +- dartdoc is unprocessed markdown. This data is omitted if +- there is no referenced element, or if the element has no +- dartdoc. +-

+-
elementDescription: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A human-readable description of the element being +- referenced. This data is omitted if there is no referenced +- element. +-

+-
elementKind: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A human-readable description of the kind of element being +- referenced (such as "class" or "function type +- alias"). This data is omitted if there is no referenced +- element. +-

+-
isDeprecated: bool (optional)
+-=20=20=20=20=20=20=20=20 +-

+- True if the referenced element is deprecated. +-

+-
parameter: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- A human-readable description of the parameter +- corresponding to the expression being hovered over. This +- data is omitted if the location is not in an argument to a +- function. +-

+-
propagatedType: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the propagated type of the expression. This +- data is omitted if the location does not correspond to an +- expression or if there is no propagated type information. +-

+-
staticType: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the static type of the expression. This data +- is omitted if the location does not correspond to an +- expression. +-

+-
ImplementedClass: object
+-

+- A description of a class that is implemented or extended. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the name of the implemented class. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the name of the implemented class. +-

+-
ImplementedMember: object
+-

+- A description of a class member that is implemented or overridden. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the name of the implemented member. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the name of the implemented member. +-

+-
ImportedElements: object
+-

+- A description of the elements that are referenced in a region of a = file +- that come from a single imported library. +-

+-=20=20=20=20 +-
path: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The absolute and normalized path of the file containing the lib= rary. +-

+-
prefix: String
+-=20=20=20=20=20=20=20=20 +-

+- The prefix that was used when importing the library into the or= iginal +- source. +-

+-
elements: List<String>
+-=20=20=20=20=20=20=20=20 +-

+- The names of the elements imported from the library. +-

+-
KytheEntry: object
+-

+- This object matches the format and documentation of the Entry object +- documented in the +- Kythe S= torage +- Model. +-

+-=20=20=20=20 +-
source: KytheVN= ame
+-=20=20=20=20=20=20=20=20 +-

+- The ticket of the source node. +-

+-
kind: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- An edge label. The schema defines which labels are meaningful. +-

+-
target: Ky= theVName (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The ticket of the target node. +-

+-
fact: String
+-=20=20=20=20=20=20=20=20 +-

+- A fact label. The schema defines which fact labels are meaningf= ul. +-

+-
value: List<int> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The String value of the fact. +-

+-
KytheVName: object
+-

+- This object matches the format and documentation of the Vector-Name= object +- documented in the +- Kythe +- Storage Model. +-

+-=20=20=20=20 +-
signature: String
+-=20=20=20=20=20=20=20=20 +-

+- An opaque signature generated by the analyzer. +-

+-
corpus: String
+-=20=20=20=20=20=20=20=20 +-

+- The corpus of source code this KytheVName belongs to. +- Loosely, a corpus is a collection of related files, such as the +- contents of a given source repository. +-

+-
root: String
+-=20=20=20=20=20=20=20=20 +-

+- A corpus-specific root label, typically a directory path or pro= ject +- identifier, denoting a distinct subset of the corpus. This may = also be +- used to designate virtual collections like generated files. +-

+-
path: String
+-=20=20=20=20=20=20=20=20 +-

+- A path-structured label describing the =E2=80=9Clocation=E2=80= =9D of the named object +- relative to the corpus and the root. +-

+-
language: String
+-=20=20=20=20=20=20=20=20 +-

+- The language this name belongs to. +-

+-
LinkedEditGroup: object
+-

+- A collection of positions that should be linked (edited simultaneou= sly) +- for the purposes of updating code after a source change. For exampl= e, if a +- set of edits introduced a new variable name, the group would contai= n all +- of the positions of the variable name so that if the client wanted = to let +- the user edit the variable name after the operation, all occurrence= s of +- the name could be edited simultaneously. +-

+-=20=20=20=20 +-
positions: List<Position>
+-=20=20=20=20=20=20=20=20 +-

+- The positions of the regions that should be edited simultaneous= ly. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the regions that should be edited simultaneously. +-

+-
suggestions: List<LinkedEditSuggestion>
+-=20=20=20=20=20=20=20=20 +-

+- Pre-computed suggestions for what every region might want to be +- changed to. +-

+-
LinkedEditSuggestion: object
+-

+- A suggestion of a value that could be used to replace all of the li= nked +- edit regions in a LinkedEditGroup= . +-

+-=20=20=20=20 +-
value: String
+-=20=20=20=20=20=20=20=20 +-

+- The value that could be used to replace all of the linked edit +- regions. +-

+-
kind: LinkedEditSuggestionKind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of value being proposed. +-

+-
LinkedEditSuggestionKind: String
+-

+- An enumeration of the kind of values that can be suggested for a li= nked +- edit. +-

+-=20=20=20=20 +-
METHOD
PARAMETER
TYPE
VARIABLE
Location: object
=
+-

+- A location (character range) within a file. +-

+-=20=20=20=20 +-
file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the range. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the range. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the range. +-

+-
startLine: int
+-=20=20=20=20=20=20=20=20 +-

+- The one-based index of the line containing the first character = of the +- range. +-

+-
startColumn: int
+-=20=20=20=20=20=20=20=20 +-

+- The one-based index of the column containing the first characte= r of +- the range. +-

+-
NavigationRegion: object
+-

+- A description of a region from which the user can navigate to the +- declaration of an element. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region from which the user can navigate. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region from which the user can navigate. +-

+-
targets: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The indexes of the targets (in the enclosing navigation respons= e) to +- which the given region is bound. By opening the target, clients= can +- implement one form of navigation. This list cannot be empty. +-

+-
NavigationTarget: object
+-

+- A description of a target to which the user can navigate. +-

+-=20=20=20=20 +-
kind: ElementK= ind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the element. +-

+-
fileIndex: int
+-=20=20=20=20=20=20=20=20 +-

+- The index of the file (in the enclosing navigation response) to +- navigate to. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region to which the user can navigate. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region to which the user can navigate. +-

+-
startLine: int
+-=20=20=20=20=20=20=20=20 +-

+- The one-based index of the line containing the first character = of the +- region. +-

+-
startColumn: int
+-=20=20=20=20=20=20=20=20 +-

+- The one-based index of the column containing the first characte= r of +- the region. +-

+-
Occurrences: object
+-

+- A description of the references to a single element within a single= file. +-

+-=20=20=20=20 +-
element: Element
+-=20=20=20=20=20=20=20=20 +-

+- The element that was referenced. +-

+-
offsets: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The offsets of the name of the referenced element within the fi= le. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the name of the referenced element. +-

+-
Outline: object
+-

+- An node in the outline structure of a file. +-

+-=20=20=20=20 +-
element: Element
+-=20=20=20=20=20=20=20=20 +-

+- A description of the element represented by this node. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the first character of the element. This is diffe= rent +- than the offset in the Element, which is the offset of the name= of the +- element. It can be used, for example, to map locations in the f= ile +- back to an outline. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the element. +-

+-
children: List<Outline> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The children of the node. The field will be omitted if the node= has no +- children. +-

+-
OverriddenMember: object
+-

+- A description of a member that is being overridden. +-

+-=20=20=20=20 +-
element: Element
+-=20=20=20=20=20=20=20=20 +-

+- The element that is being overridden. +-

+-
className: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the class in which the member is defined. +-

+-
Override: object
+-

+- A description of a member that overrides an inherited member. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the name of the overriding member. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the name of the overriding member. +-

+-
superclassMember: OverriddenMember (optional)=
+-=20=20=20=20=20=20=20=20 +-

+- The member inherited from a superclass that is overridden +- by the overriding member. The field is omitted if there is +- no superclass member, in which case there must be at least +- one interface member. +-

+-
interfaceMembers: List<OverriddenMember> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The members inherited from interfaces that are overridden +- by the overriding member. The field is omitted if there +- are no interface members, in which case there must be a +- superclass member. +-

+-
Position: object
+-

+- A position within a file. +-

+-=20=20=20=20 +-
file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the position. +-

+-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the position. +-

+-
PostfixTemplateDescriptor: object
+-

+- The description of a postfix completion template. +-

+-=20=20=20=20 +-
name: String
+-=20=20=20=20=20=20=20=20 +-

+- The template name, shown in the UI. +-

+-
key: String
+-=20=20=20=20=20=20=20=20 +-

+- The unique template key, not shown in the UI. +-

+-
example: String
+-=20=20=20=20=20=20=20=20 +-

+- A short example of the transformation performed when the templa= te is +- applied. +-

+-
PubStatus: object
+-

+- An indication of the current state of pub execution. +-

+-=20=20=20=20 +-
isListingPackageDirs: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the server is currently running pub to produce a list of +- package directories. +-

+-
RefactoringFeedback: object
+-

+- An abstract superclass of all refactoring feedbacks. +-

+-=20=20=20=20 +-
RefactoringKind: String
+-

+- An enumeration of the kinds of refactorings that can be created. +-

+-=20=20=20=20 +-
CONVERT_GETTER_TO_METHOD
CONVERT_METHOD_TO_GETTER
EXTRACT_LOCAL_VARIABLE
EXTRACT_METHOD
INLINE_LOCAL_= VARIABLE
INLINE_METHOD
MOVE= _FILE
RENAME
SORT_MEMBERS
RefactoringMethodParameter: object
+-=20=20=20=20 +-

+- A description of a parameter in a method refactoring. +-

+-=20=20=20=20 +-
id: String (op= tional)
+-=20=20=20=20=20=20=20=20 +-

+- The unique identifier of the parameter. Clients may omit this f= ield +- for the parameters they want to add. +-

+-
kind: RefactoringMethodParameterKind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of the parameter. +-

+-
type: String
+-=20=20=20=20=20=20=20=20 +-

+- The type that should be given to the parameter, or the return t= ype of +- the parameter's function type. +-

+-
name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name that should be given to the parameter. +-

+-
parameters: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The parameter list of the parameter's function type. If the par= ameter +- is not of a function type, this field will not be defined. If t= he +- function type has zero parameters, this field will have a value= of +- '()'. +-

+-
RefactoringMethodParameterKind: String
+-

+- An enumeration of the kinds of parameters. +-

+-=20=20=20=20 +-
REQUIRED
POSITIONAL
NAMED
RefactoringOptions: object
+-

+- An abstract superclass of all refactoring options. +-

+-=20=20=20=20 +-
RefactoringProblem: object
+-

+- A description of a problem related to a refactoring. +-

+-=20=20=20=20 +-
severity: RefactoringProblemSeverity
+-=20=20=20=20=20=20=20=20 +-

+- The severity of the problem being represented. +-

+-
message: String
+-=20=20=20=20=20=20=20=20 +-

+- A human-readable description of the problem being represented. +-

+-
location: Lo= cation (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The location of the problem being represented. This field is om= itted +- unless there is a specific location associated with the problem= (such +- as a location where an element being renamed will be shadowed). +-

+-
RefactoringProblemSeverity: String
+-

+- An enumeration of the severities of problems that can be returned b= y the +- refactoring requests. +-

+-=20=20=20=20 +-
INFO
+-=20=20=20=20=20=20=20=20 +-

+- A minor code problem. No example, because it is not used yet. +-

+-
WARNING
+-=20=20=20=20=20=20=20=20 +-

+- A minor code problem. For example names of local variables shou= ld be +- camel case and start with a lower case letter. Staring the name= of a +- variable with an upper case is OK from the language point of vi= ew, but +- it is nice to warn the user. +-

+-
ERROR
+-=20=20=20=20=20=20=20=20 +-

+- The refactoring technically can be performed, but there is a lo= gical +- problem. For example the name of a local variable being extract= ed +- conflicts with another name in the scope, or duplicate paramete= r names +- in the method being extracted, or a conflict between a paramete= r name +- and a local variable, etc. In some cases the location of the pr= oblem +- is also provided, so the IDE can show user the location and the +- problem, and let the user decide whether they want to perform t= he +- refactoring. For example the name conflict might be expected, a= nd the +- user wants to fix it afterwards. +-

+-
FATAL
+-=20=20=20=20=20=20=20=20 +-

+- A fatal error, which prevents performing the refactoring. For e= xample +- the name of a local variable being extracted is not a valid +- identifier, or selection is not a valid expression. +-

+-
RemoveContentOverlay: object
+-

+- A directive to remove an existing file content overlay. After proce= ssing +- this directive, the file contents will once again be read from the = file +- system. +-

+-

+- If this directive is used on a file that doesn't currently have a c= ontent +- overlay, it has no effect. +-

+-=20=20=20=20 +-
type =3D "remove"
+-=20=20=20=20=20=20=20=20 +-
RequestError: object
+-

+- An indication of a problem with the execution of the server, +- typically in response to a request. +-

+-=20=20=20=20 +-
code: Req= uestErrorCode
+-=20=20=20=20=20=20=20=20 +-

+- A code that uniquely identifies the error that occurred. +-

+-
message: String
+-=20=20=20=20=20=20=20=20 +-

+- A short description of the error. +-

+-
stackTrace: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The stack trace associated with processing the request, +- used for debugging the server. +-

+-
RequestErrorCode: String
+-

+- An enumeration of the types of errors that can occur in the +- execution of the server. +-

+-=20=20=20=20 +-
CONTENT_MODIFIED
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.getErrors" or "analysis.getNavigation" request cou= ld +- not be satisfied because the content of the file changed before +- the requested results could be computed. +-

+-
DEBUG_PORT_COULD_NOT_BE_OPENED
+-=20=20=20=20=20=20=20=20 +-

+- The server was unable to open a port for the diagnostic server. +-

+-
FILE_NOT_ANALYZED
+-=20=20=20=20=20=20=20=20 +-

+- A request specified a FilePath which does not match a file in +- an analysis root, or the requested operation is not available +- for the file. +-

+-
FORMAT_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "edit.format" request specified a FilePath +- which does not match a Dart file in an analysis root. +-

+-
FORMAT_WITH_ERRORS
+-=20=20=20=20=20=20=20=20 +-

+- An "edit.format" request specified a file that contains syntax +- errors. +-

+-
GET_ERRORS_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.getErrors" request specified a FilePath +- which does not match a file currently subject to +- analysis. +-

+-
GET_IMPORTED_ELEMENTS_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.getImportedElements" request specified a FilePath = that +- does not match a file currently subject to analysis. +-

+-
GET_KYTHE_ENTRIES_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.getKytheEntries" request specified a FilePath that= does +- not match a file that is currently subject to analysis. +-

+-
GET_NAVIGATION_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.getNavigation" request specified a FilePath +- which does not match a file currently subject to +- analysis. +-

+-
GET_REACHABLE_SOURCES_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.getReachableSources" request specified a FilePath +- which does not match a file currently subject to +- analysis. +-

+-
IMPORT_ELEMENTS_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "edit.importElements" request specified a FilePath that does= not +- match a file currently subject to analysis. +-

+-
INVALID_ANALYSIS_ROOT
+-=20=20=20=20=20=20=20=20 +-

+- A path passed as an argument to a request (such as +- analysis.reanalyze) is required to be an analysis root, but isn= 't. +-

+-
INVALID_EXECUTION_CONTEXT
+-=20=20=20=20=20=20=20=20 +-

+- The context root used to create an execution context does not +- exist. +-

+-
INVALID_FILE_PATH_FORMAT
+-=20=20=20=20=20=20=20=20 +-

+- The format of the given file path is invalid, e.g. is not +- absolute and normalized. +-

+-
INVALID_OVERLAY_CHANGE
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.updateContent" request contained a +- ChangeContentOverlay object which can't be applied, due +- to an edit having an offset or length that is out of +- range. +-

+-
INVALID_PARAMETER
+-=20=20=20=20=20=20=20=20 +-

+- One of the method parameters was invalid. +-

+-
INVALID_REQUEST
+-=20=20=20=20=20=20=20=20 +-

+- A malformed request was received. +-

+-
ORGANIZE_DIRECTIVES_ERROR
+-=20=20=20=20=20=20=20=20 +-

+- An "edit.organizeDirectives" request specified a Dart file that +- cannot be analyzed. The reason is described in the message. +-

+-
REFACTORING_REQUEST_CANCELLED
+-=20=20=20=20=20=20=20=20 +-

+- Another refactoring request was received during processing of +- this one. +-

+-
SERVER_ALREADY_STARTED
+-=20=20=20=20=20=20=20=20 +-

+- The analysis server has already been started (and hence +- won't accept new connections). +-

+-

+- This error is included for future expansion; at present +- the analysis server can only speak to one client at a +- time so this error will never occur. +-

+-
SERVER_ERROR
+-=20=20=20=20=20=20=20=20 +-

+- An internal error occurred in the analysis server. +- Also see the server.error notification. +-

+-
SORT_MEMBERS_INVALID_FILE
+-=20=20=20=20=20=20=20=20 +-

+- An "edit.sortMembers" request specified a FilePath +- which does not match a Dart file in an analysis root. +-

+-
SORT_MEMBERS_PARSE_ERRORS
+-=20=20=20=20=20=20=20=20 +-

+- An "edit.sortMembers" request specified a Dart file that has +- scan or parse errors. +-

+-
UNANALYZED_PRIORITY_FILES
+-=20=20=20=20=20=20=20=20 +-

+- An "analysis.setPriorityFiles" request includes one or +- more files that are not being analyzed. +-

+-

+- This is a legacy error; it will be removed before the +- API reaches version 1.0. +-

+-=20=20=20=20=20=20=20=20 +-
UNKNOWN_REQUEST
+-=20=20=20=20=20=20=20=20 +-

+- A request was received which the analysis server does +- not recognize, or cannot handle in its current +- configuration. +-

+-
UNKNOWN_SOURCE
+-=20=20=20=20=20=20=20=20 +-

+- The analysis server was requested to perform an action +- on a source that does not exist. +-

+-
UNSUPPORTED_FEATURE
+-=20=20=20=20=20=20=20=20 +-

+- The analysis server was requested to perform an action +- which is not supported. +-

+-

+- This is a legacy error; it will be removed before the +- API reaches version 1.0. +-

+-=20=20=20=20=20=20=20=20 +-
SearchId: String
+-=20=20=20=20 +-

+- An identifier used to associate search results with a search +- request. +-

+-
SearchR= esult: object
+-

+- A single result from a search request. +-

+-=20=20=20=20 +-
location: Locatio= n
+-=20=20=20=20=20=20=20=20 +-

+- The location of the code that matched the search criteria. +-

+-
kind: SearchResultKind
+-=20=20=20=20=20=20=20=20 +-

+- The kind of element that was found or the kind of +- reference that was found. +-

+-
isPotential: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the result is a potential match but cannot be +- confirmed to be a match. For example, if all references to +- a method m defined in some class were requested, and a +- reference to a method m from an unknown class were found, +- it would be marked as being a potential match. +-

+-
path: List<Element>
+-=20=20=20=20=20=20=20=20 +-

+- The elements that contain the result, starting with the +- most immediately enclosing ancestor and ending with the +- library. +-

+-
SearchResultKind: String
+-

+- An enumeration of the kinds of search results returned by the +- search domain. +-

+-=20=20=20=20 +-
DECLARATION
+-=20=20=20=20=20=20=20=20 +-

+- The declaration of an element. +-

+-
INVOCATION
+-=20=20=20=20=20=20=20=20 +-

+- The invocation of a function or method. +-

+-
READ
+-=20=20=20=20=20=20=20=20 +-

+- A reference to a field, parameter or variable where it is being= read. +-

+-
READ_WRITE
+-=20=20=20=20=20=20=20=20 +-

+- A reference to a field, parameter or variable where it is being= read +- and written. +-

+-
REFERENCE
+-=20=20=20=20=20=20=20=20 +-

+- A reference to an element. +-

+-
UNKNOWN
+-=20=20=20=20=20=20=20=20 +-

+- Some other kind of search result. +-

+-
WRITE
+-=20=20=20=20=20=20=20=20 +-

+- A reference to a field, parameter or variable where it is being +- written. +-

+-
ServerService: String
+-

+- An enumeration of the services provided by the server domain. +-

+-=20=20=20=20 +-
STATUS
SourceChange: object
+-

+- A description of a set of edits that implement a single conceptual = change. +-

+-=20=20=20=20 +-
message: String
+-=20=20=20=20=20=20=20=20 +-

+- A human-readable description of the change to be applied. +-

+-
edits: List<SourceFileEdit>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the edits used to effect the change, grouped by file. +-

+-
linkedEditGroups: List<LinkedEditGroup>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the linked editing groups used to customize the chang= es that +- were made. +-

+-
selection: P= osition (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The position that should be selected after the edits have been +- applied. +-

+-
SourceEdit: object
+-

+- A description of a single change to a single file. +-

+-=20=20=20=20 +-
offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset of the region to be modified. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the region to be modified. +-

+-
replacement: String
+-=20=20=20=20=20=20=20=20 +-

+- The code that is to replace the specified region in the origina= l code. +-

+-
id: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- An identifier that uniquely identifies this source edit from ot= her +- edits in the same response. This field is omitted unless a cont= aining +- structure needs to be able to identify the edit for some reason. +-

+-

+- For example, some refactoring operations can produce edits that= might +- not be appropriate (referred to as potential edits). Such edits= will +- have an id so that they can be referenced. Edits in the same re= sponse +- that do not need to be referenced will not have an id. +-

+-
SourceFileEdit: object
+-

+- A description of a set of changes to a single file. +-

+-=20=20=20=20 +-
file: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The file containing the code to be modified. +-

+-
fileStamp: long
+-=20=20=20=20=20=20=20=20 +-

+- The modification stamp of the file at the moment when the chang= e was +- created, in milliseconds since the "Unix epoch". Will be -1 if = the +- file did not exist and should be created. The client may use th= is +- field to make sure that the file was not changed since then, so= it is +- safe to apply the change. +-

+-
edits: List<SourceEdit>
+-=20=20=20=20=20=20=20=20 +-

+- A list of the edits used to effect the change. +-

+-
TypeHierarchyItem: object
+-

+- A representation of a class in a type hierarchy. +-

+-=20=20=20=20 +-
classElement: Elem= ent
+-=20=20=20=20=20=20=20=20 +-

+- The class element represented by this item. +-

+-
displayName: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name to be displayed for the class. This field will be +- omitted if the display name is the same as the name of the +- element. The display name is different if there is +- additional type information to be displayed, such as type +- arguments. +-

+-
memberElement: Element (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The member in the class corresponding to the member on +- which the hierarchy was requested. This field will be +- omitted if the hierarchy was not requested for a member or +- if the class does not have a corresponding member. +-

+-
superclass: int (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The index of the item representing the superclass of +- this class. This field will be omitted if this item +- represents the class Object. +-

+-
interfaces: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The indexes of the items representing the interfaces +- implemented by this class. The list will be empty if +- there are no implemented interfaces. +-

+-
mixins: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The indexes of the items representing the mixins +- referenced by this class. The list will be empty if +- there are no classes mixed in to this class. +-

+-
subclasses: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The indexes of the items representing the subtypes of +- this class. The list will be empty if there are no +- subtypes or if this item represents a supertype of the +- pivot type. +-

+-
+- +-

Refactorings

+-

+- This section contains additional information for each kind of +- refactoring. In addition to a brief description of the +- refactoring, there is a specification of the feedback that is +- provided when a refactoring is requested using the +- edit.getRefactoring request (designed to improve the UX) +- and the options that may be provided to edit.getRefactoring. +-

+-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-=20=20 +-
CONVERT_GETTER_TO_METHOD
+-

+- Convert a getter into a method by removing the keyword get +- and adding an empty parameter list. +-

+-

+- It is an error if the range contains anything other than all +- or part of the name of a single getter. +-

+-

Feedback:

none

Options:

none

CONVERT_METHOD_TO_GETTER
+-

+- Convert a method into a getter by adding the keyword get and +- removing the parameter list. +-

+-

+- It is an error if the range contains anything other than all +- or part of the name of a single method or if the method has +- a non-empty parameter list. +-

+-

Feedback:

none

Options:

none

EXTRACT_LOCAL_VARIABLE
+-

+- Create a local variable initialized by the expression that covers +- the specified selection. +-

+-

+- It is an error if the selection range is not covered by a +- complete expression. +-

+-=20=20=20=20 +-=20=20=20=20 +-

Feedback:

coveringExpressionOffsets:= List<int> (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The offsets of the expressions that cover the specified +- selection, from the down most to the up most. +-

+-
coveringExpressionLengths: List<int&= gt; (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The lengths of the expressions that cover the specified +- selection, from the down most to the up most. +-

+-
names: List<String>
+-=20=20=20=20=20=20=20=20 +-

+- The proposed names for the local variable. +-

+-
offsets: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The offsets of the expressions that would be replaced by +- a reference to the variable. +-

+-
lengths: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The lengths of the expressions that would be replaced by +- a reference to the variable. The lengths correspond to +- the offsets. In other words, for a given expression, if +- the offset of that expression is offsets[i], then +- the length of that expression is lengths[i]. +-

+-

Options:

name: String<= /b>
+-=20=20=20=20=20=20=20=20 +-

+- The name that the local variable should be given. +-

+-
extractAll: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if all occurrences of the expression within the +- scope in which the variable will be defined should be +- replaced by a reference to the local variable. The +- expression used to initiate the refactoring will always +- be replaced. +-

+-
EXTRACT_METHOD
+-

+- Create a method whose body is the specified expression or +- list of statements, possibly augmented with a return +- statement. +-

+-

+- It is an error if the range contains anything other than a +- complete expression (no partial expressions are allowed) or +- a complete sequence of statements. +-

+-=20=20=20=20 +-=20=20=20=20 +-

Feedback:

offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset to the beginning of the expression or +- statements that will be extracted. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the expression or statements that will be +- extracted. +-

+-
returnType: String
+-=20=20=20=20=20=20=20=20 +-

+- The proposed return type for the method. +- If the returned element does not have a declared return type, +- this field will contain an empty string. +-

+-
names: List<String>
+-=20=20=20=20=20=20=20=20 +-

+- The proposed names for the method. +-

+-
canCreateGetter: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if a getter could be created rather than a method. +-

+-
parameters: List<RefactoringMethodParameter>
+-=20=20=20=20=20=20=20=20 +-

+- The proposed parameters for the method. +-

+-
offsets: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The offsets of the expressions or statements that would +- be replaced by an invocation of the method. +-

+-
lengths: List<int>
+-=20=20=20=20=20=20=20=20 +-

+- The lengths of the expressions or statements that would +- be replaced by an invocation of the method. The lengths +- correspond to the offsets. In other words, for a given +- expression (or block of statements), if the offset of +- that expression is offsets[i], then the length +- of that expression is lengths[i]. +-

+-

Options:

returnType: S= tring
+-=20=20=20=20=20=20=20=20 +-

+- The return type that should be defined for the method. +-

+-
createGetter: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if a getter should be created rather than a +- method. It is an error if this field is true and the +- list of parameters is non-empty. +-

+-
name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name that the method should be given. +-

+-
parameters: List<RefactoringMethodParameter>
+-=20=20=20=20=20=20=20=20 +-

+- The parameters that should be defined for the method. +-

+-

+- It is an error if a REQUIRED or NAMED parameter follows a +- POSITIONAL parameter. +- It is an error if a REQUIRED or POSITIONAL parameter follows a +- NAMED parameter. +-

+-
    +-
  • +- To change the order and/or update proposed parameters, add +- parameters with the same identifiers as proposed. +-
  • +-
  • To add new parameters, omit their identifier.
  • +-
  • To remove some parameters, omit them in this list.
  • +-
+-
extractAll: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if all occurrences of the expression or statements +- should be replaced by an invocation of the method. The +- expression or statements used to initiate the +- refactoring will always be replaced. +-

+-
INLINE_LOCAL_VARIABLE
=
+-

+- Inline the initializer expression of a local variable in +- place of any references to that variable. +-

+-

+- It is an error if the range contains anything other than all +- or part of the name of a single local variable. +-

+-=20=20=20=20 +-

Feedback:

name: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the variable being inlined. +-

+-
occurrences: int
+-=20=20=20=20=20=20=20=20 +-

+- The number of times the variable occurs. +-

+-

Options:

none

INLINE_METHOD
+-

+- Inline a method in place of one or all references to that +- method. +-

+-

+- It is an error if the range contains anything other than all +- or part of the name of a single method. +-

+-=20=20=20=20 +-=20=20=20=20 +-

Feedback:

className: String (optional)
+-=20=20=20=20=20=20=20=20 +-

+- The name of the class enclosing the method being inlined. +- If not a class member is being inlined, this field will be abse= nt. +-

+-
methodName: String
+-=20=20=20=20=20=20=20=20 +-

+- The name of the method (or function) being inlined. +-

+-
isDeclaration: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the declaration of the method is selected. +- So all references should be inlined. +-

+-

Options:

deleteSource:= bool
+-=20=20=20=20=20=20=20=20 +-

+- True if the method being inlined should be removed. +- It is an error if this field is true and inlineAll is false. +-

+-
inlineAll: bool
+-=20=20=20=20=20=20=20=20 +-

+- True if all invocations of the method should be inlined, +- or false if only the invocation site used to create this +- refactoring should be inlined. +-

+-
MOVE_FILE
+-

+- Move the given file and update all of the references to that file +- and from it. The move operation is supported in general case - for +- renaming a file in the same folder, moving it to a different folder +- or both. +-

+-

+- The refactoring must be activated before an actual file moving +- operation is performed. +-

+-

+- The "offset" and "length" fields from the request are ignored, but = the +- file specified in the request specifies the file to be moved. +-

+-=20=20=20=20 +-

Feedback:

none

Options:

<= b>newFile: FilePath
+-=20=20=20=20=20=20=20=20 +-

+- The new file path to which the given file is being moved. +-

+-
RENAME
+-

+- Rename a given element and all of the references to that +- element. +-

+-

+- It is an error if the range contains anything other than all +- or part of the name of a single function (including methods, +- getters and setters), variable (including fields, parameters +- and local variables), class or function type. +-

+-=20=20=20=20 +-=20=20=20=20 +-

Feedback:

offset: int
+-=20=20=20=20=20=20=20=20 +-

+- The offset to the beginning of the name selected to be +- renamed. +-

+-
length: int
+-=20=20=20=20=20=20=20=20 +-

+- The length of the name selected to be renamed. +-

+-
elementKindName: String
+-=20=20=20=20=20=20=20=20 +-

+- The human-readable description of the kind of element being +- renamed (such as "class" or "function type +- alias"). +-

+-
oldName: String
+-=20=20=20=20=20=20=20=20 +-

+- The old name of the element before the refactoring. +-

+-

Options:

newName: Stri= ng
+-=20=20=20=20=20=20=20=20 +-

+- The name that the element should have after the +- refactoring. +-

+-
+-

Errors

+-

+- This section contains a list of all of the errors that are +- produced by the server and the data that is returned with each. +-

+-

+- TODO: TBD +-

+-

Index

+-

Domains

server (=E2=86=91)
Requests
Notifications
  • <= a href=3D"#notification_server.connected">connected
  • error
  • status

analysis (=E2=86=91)

completion= (=E2=86=91)

Requests
Notifications

search (=E2=86=91)

edit (=E2=86=91)

execution (=E2=86=91)

diagnostic (=E2=86=91)

Types (=E2=86=91)

Refactorings (=E2=86=91)

+- +- +- +\ No newline at end of file +diff --git a/pkg/analysis_server/lib/plugin/analysis/occurrences/occurrenc= es_core.dart b/pkg/analysis_server/lib/plugin/analysis/occurrences/occurren= ces_core.dart +deleted file mode 100644 +index 22a85fd8135..00000000000 +--- a/pkg/analysis_server/lib/plugin/analysis/occurrences/occurrences_core= .dart ++++ /dev/null +@@ -1,17 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart' show Occur= rences; +- +-/** +- * An object used to record occurrences into. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class OccurrencesCollector { +- /** +- * Record a new element occurrences. +- */ +- void addOccurrences(Occurrences occurrences); +-} +diff --git a/pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart b= /pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart +deleted file mode 100644 +index f4d1e6254e5..00000000000 +--- a/pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart ++++ /dev/null +@@ -1,90 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show SourceChange; +-import 'package:analyzer_plugin/utilities/assist/assist.dart'; +- +-/** +- * A description of a single proposed assist. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class Assist { +- /** +- * An empty list of assists. +- */ +- static const List EMPTY_LIST =3D const []; +- +- /** +- * A comparator that can be used to sort assists by their relevance. Th= e most +- * relevant assists will be sorted before assists with a lower relevanc= e. +- */ +- static final Comparator SORT_BY_RELEVANCE =3D +- (Assist firstAssist, Assist secondAssist) =3D> +- firstAssist.kind.priority - secondAssist.kind.priority; +- +- /** +- * A description of the assist being proposed. +- */ +- final AssistKind kind; +- +- /** +- * The change to be made in order to apply the assist. +- */ +- final SourceChange change; +- +- /** +- * Initialize a newly created assist to have the given [kind] and [chan= ge]. +- */ +- Assist(this.kind, this.change); +- +- @override +- String toString() { +- return 'Assist(kind=3D$kind, change=3D$change)'; +- } +-} +- +-/** +- * An object used to provide context information for [AssistContributor]s. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class AssistContext { +- /** +- * The analysis driver used to access analysis results. +- */ +- AnalysisDriver get analysisDriver; +- +- /** +- * The length of the selection. +- */ +- int get selectionLength; +- +- /** +- * The start of the selection. +- */ +- int get selectionOffset; +- +- /** +- * The source to get assists in. +- */ +- Source get source; +-} +- +-/** +- * An object used to produce assists for a specific location. +- * +- * Clients may implement this class when implementing plugins. +- */ +-abstract class AssistContributor { +- /** +- * Completes with a list of assists for the given [context]. +- */ +- Future> computeAssists(AssistContext context); +-} +diff --git a/pkg/analysis_server/lib/plugin/edit/assist/assist_dart.dart b= /pkg/analysis_server/lib/plugin/edit/assist/assist_dart.dart +deleted file mode 100644 +index 44198cd69d3..00000000000 +--- a/pkg/analysis_server/lib/plugin/edit/assist/assist_dart.dart ++++ /dev/null +@@ -1,107 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/plugin/edit/assist/assist_core.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * An object used to provide context information for [DartAssistContribut= or]s. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class DartAssistContext { +- /** +- * The analysis driver used to access analysis results. +- */ +- AnalysisDriver get analysisDriver; +- +- /** +- * The provider for parsed or resolved ASTs. +- */ +- AstProvider get astProvider; +- +- /** +- * The length of the selection. +- */ +- int get selectionLength; +- +- /** +- * The start of the selection. +- */ +- int get selectionOffset; +- +- /** +- * The source to get assists in. +- */ +- Source get source; +- +- /** +- * The [CompilationUnit] to compute assists in. +- */ +- CompilationUnit get unit; +-} +- +-/** +- * An [AssistContributor] that can be used to contribute assists for Dart= files. +- * +- * Clients may extend this class when implementing plugins. +- */ +-abstract class DartAssistContributor implements AssistContributor { +- @override +- Future> computeAssists(AssistContext context) async { +- AnalysisDriver driver =3D context.analysisDriver; +- Source source =3D context.source; +- if (!AnalysisEngine.isDartFileName(source.fullName)) { +- return Assist.EMPTY_LIST; +- } +- CompilationUnit unit =3D (await driver.getResult(source.fullName)).un= it; +- if (unit =3D=3D null) { +- return Assist.EMPTY_LIST; +- } +- DartAssistContext dartContext =3D new _DartAssistContextImpl( +- new AstProviderForDriver(driver), context, unit); +- return internalComputeAssists(dartContext); +- } +- +- /** +- * Completes with a list of assists for the given [context]. +- */ +- Future> internalComputeAssists(DartAssistContext context); +-} +- +-/** +- * The implementation of [DartAssistContext]. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class _DartAssistContextImpl implements DartAssistContext { +- @override +- final AstProvider astProvider; +- +- final AssistContext _context; +- +- @override +- final CompilationUnit unit; +- +- _DartAssistContextImpl(this.astProvider, this._context, this.unit); +- +- @override +- AnalysisDriver get analysisDriver =3D> _context.analysisDriver; +- +- @override +- int get selectionLength =3D> _context.selectionLength; +- +- @override +- int get selectionOffset =3D> _context.selectionOffset; +- +- @override +- Source get source =3D> _context.source; +-} +diff --git a/pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart b/pkg/a= nalysis_server/lib/plugin/edit/fix/fix_core.dart +deleted file mode 100644 +index 91a813f8214..00000000000 +--- a/pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart ++++ /dev/null +@@ -1,88 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show SourceChange; +-import 'package:analyzer_plugin/utilities/fixes/fixes.dart'; +- +-/** +- * A description of a single proposed fix for some problem. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class Fix { +- /** +- * An empty list of fixes. +- */ +- static const List EMPTY_LIST =3D const []; +- +- /** +- * A comparator that can be used to sort fixes by their relevance. The = most +- * relevant fixes will be sorted before fixes with a lower relevance. +- */ +- static final Comparator SORT_BY_RELEVANCE =3D +- (Fix firstFix, Fix secondFix) =3D> +- firstFix.kind.priority - secondFix.kind.priority; +- +- /** +- * A description of the fix being proposed. +- */ +- final FixKind kind; +- +- /** +- * The change to be made in order to apply the fix. +- */ +- final SourceChange change; +- +- /** +- * Initialize a newly created fix to have the given [kind] and [change]. +- */ +- Fix(this.kind, this.change); +- +- @override +- String toString() { +- return 'Fix(kind=3D$kind, change=3D$change)'; +- } +-} +- +-/** +- * An object used to provide context information for [FixContributor]s. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class FixContext { +- /** +- * The analysis driver used to access analysis results. +- */ +- AnalysisDriver get analysisDriver; +- +- /** +- * The error to fix, should be reported by the given [analysisDriver]. +- */ +- AnalysisError get error; +- +- /** +- * The [ResourceProvider] to access files and folders. +- */ +- ResourceProvider get resourceProvider; +-} +- +-/** +- * An object used to produce fixes for a specific error. Fix contributors= are +- * long-lived objects and must not retain any state between invocations of +- * [computeFixes]. +- * +- * Clients may implement this class when implementing plugins. +- */ +-abstract class FixContributor { +- /** +- * Return a list of fixes for the given [context]. +- */ +- Future> computeFixes(FixContext context); +-} +diff --git a/pkg/analysis_server/lib/plugin/edit/fix/fix_dart.dart b/pkg/a= nalysis_server/lib/plugin/edit/fix/fix_dart.dart +deleted file mode 100644 +index e5b0f1f5625..00000000000 +--- a/pkg/analysis_server/lib/plugin/edit/fix/fix_dart.dart ++++ /dev/null +@@ -1,73 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/plugin/edit/fix/fix_core.dart'; +-import 'package:analysis_server/src/services/correction/fix_internal.dart' +- show DartFixContextImpl; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/top_level_declaration.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * Complete with top-level declarations with the given [name]. +- */ +-typedef Future> GetTopLevelDeclarations( +- String name); +- +-/** +- * An object used to provide context information for [DartFixContributor]= s. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class DartFixContext implements FixContext { +- /** +- * The provider for parsed or resolved ASTs. +- */ +- AstProvider get astProvider; +- +- /** +- * The function to get top-level declarations from. +- */ +- GetTopLevelDeclarations get getTopLevelDeclarations; +- +- /** +- * The [CompilationUnit] to compute fixes in. +- */ +- CompilationUnit get unit; +-} +- +-/** +- * A [FixContributor] that can be used to contribute fixes for errors in = Dart +- * files. +- * +- * Clients may extend this class when implementing plugins. +- */ +-abstract class DartFixContributor implements FixContributor { +- @override +- Future> computeFixes(FixContext context) async { +- AnalysisDriver driver =3D context.analysisDriver; +- Source source =3D context.error.source; +- if (!AnalysisEngine.isDartFileName(source.fullName)) { +- return Fix.EMPTY_LIST; +- } +- CompilationUnit unit =3D (await driver.getResult(source.fullName)).un= it; +- if (unit =3D=3D null) { +- return Fix.EMPTY_LIST; +- } +- DartFixContext dartContext =3D +- new DartFixContextImpl(context, new AstProviderForDriver(driver),= unit); +- return internalComputeFixes(dartContext); +- } +- +- /** +- * Return a list of fixes for the given [context]. +- */ +- Future> internalComputeFixes(DartFixContext context); +-} +diff --git a/pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart b/= pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart +deleted file mode 100644 +index 10272553807..00000000000 +--- a/pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart ++++ /dev/null +@@ -1,216 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Utilities for converting Dart entities into analysis server's protocol +- * entities. +- */ +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analyzer/dart/element/element.dart' as engine; +-import 'package:analyzer/src/generated/utilities_dart.dart' as engine; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * Return a protocol [Element] corresponding to the given [engine.Element= ]. +- */ +-Element convertElement(engine.Element element) { +- String name =3D element.displayName; +- String elementTypeParameters =3D _getTypeParametersString(element); +- String elementParameters =3D _getParametersString(element); +- String elementReturnType =3D getReturnTypeString(element); +- ElementKind kind =3D convertElementToElementKind(element); +- return new Element( +- kind, +- name, +- Element.makeFlags( +- isPrivate: element.isPrivate, +- isDeprecated: element.isDeprecated, +- isAbstract: _isAbstract(element), +- isConst: _isConst(element), +- isFinal: _isFinal(element), +- isStatic: _isStatic(element)), +- location: newLocation_fromElement(element), +- typeParameters: elementTypeParameters, +- parameters: elementParameters, +- returnType: elementReturnType); +-} +- +-/** +- * Return a protocol [ElementKind] corresponding to the given +- * [engine.ElementKind]. +- * +- * This does not take into account that an instance of [ClassElement] can= be an +- * enum and an instance of [FieldElement] can be an enum constant. +- * Use [convertElementToElementKind] where possible. +- */ +-ElementKind convertElementKind(engine.ElementKind kind) { +- if (kind =3D=3D engine.ElementKind.CLASS) { +- return ElementKind.CLASS; +- } +- if (kind =3D=3D engine.ElementKind.COMPILATION_UNIT) { +- return ElementKind.COMPILATION_UNIT; +- } +- if (kind =3D=3D engine.ElementKind.CONSTRUCTOR) { +- return ElementKind.CONSTRUCTOR; +- } +- if (kind =3D=3D engine.ElementKind.FIELD) { +- return ElementKind.FIELD; +- } +- if (kind =3D=3D engine.ElementKind.FUNCTION) { +- return ElementKind.FUNCTION; +- } +- if (kind =3D=3D engine.ElementKind.FUNCTION_TYPE_ALIAS) { +- return ElementKind.FUNCTION_TYPE_ALIAS; +- } +- if (kind =3D=3D engine.ElementKind.GETTER) { +- return ElementKind.GETTER; +- } +- if (kind =3D=3D engine.ElementKind.LABEL) { +- return ElementKind.LABEL; +- } +- if (kind =3D=3D engine.ElementKind.LIBRARY) { +- return ElementKind.LIBRARY; +- } +- if (kind =3D=3D engine.ElementKind.LOCAL_VARIABLE) { +- return ElementKind.LOCAL_VARIABLE; +- } +- if (kind =3D=3D engine.ElementKind.METHOD) { +- return ElementKind.METHOD; +- } +- if (kind =3D=3D engine.ElementKind.PARAMETER) { +- return ElementKind.PARAMETER; +- } +- if (kind =3D=3D engine.ElementKind.PREFIX) { +- return ElementKind.PREFIX; +- } +- if (kind =3D=3D engine.ElementKind.SETTER) { +- return ElementKind.SETTER; +- } +- if (kind =3D=3D engine.ElementKind.TOP_LEVEL_VARIABLE) { +- return ElementKind.TOP_LEVEL_VARIABLE; +- } +- if (kind =3D=3D engine.ElementKind.TYPE_PARAMETER) { +- return ElementKind.TYPE_PARAMETER; +- } +- return ElementKind.UNKNOWN; +-} +- +-/** +- * Return an [ElementKind] corresponding to the given [engine.Element]. +- */ +-ElementKind convertElementToElementKind(engine.Element element) { +- if (element is engine.ClassElement && element.isEnum) { +- return ElementKind.ENUM; +- } +- if (element is engine.FieldElement && +- element.isEnumConstant && +- // MyEnum.values and MyEnum.one.index return isEnumConstant =3D true +- // so these additional checks are necessary. +- // TODO(danrubel) MyEnum.values is constant, but is a list +- // so should it return isEnumConstant =3D true? +- // MyEnum.one.index is final but *not* constant +- // so should it return isEnumConstant =3D true? +- // Or should we return ElementKind.ENUM_CONSTANT here +- // in either or both of these cases? +- element.type !=3D null && +- element.type.element =3D=3D element.enclosingElement) { +- return ElementKind.ENUM_CONSTANT; +- } +- return convertElementKind(element.kind); +-} +- +-String _getParametersString(engine.Element element) { +- // TODO(scheglov) expose the corresponding feature from ExecutableEleme= nt +- List parameters; +- if (element is engine.ExecutableElement) { +- // valid getters don't have parameters +- if (element.kind =3D=3D engine.ElementKind.GETTER && +- element.parameters.isEmpty) { +- return null; +- } +- parameters =3D element.parameters; +- } else if (element is engine.FunctionTypeAliasElement) { +- parameters =3D element.parameters; +- } else { +- return null; +- } +- StringBuffer sb =3D new StringBuffer(); +- String closeOptionalString =3D ''; +- for (engine.ParameterElement parameter in parameters) { +- if (sb.isNotEmpty) { +- sb.write(', '); +- } +- if (closeOptionalString.isEmpty) { +- engine.ParameterKind kind =3D parameter.parameterKind; +- if (kind =3D=3D engine.ParameterKind.NAMED) { +- sb.write('{'); +- closeOptionalString =3D '}'; +- } +- if (kind =3D=3D engine.ParameterKind.POSITIONAL) { +- sb.write('['); +- closeOptionalString =3D ']'; +- } +- } +- parameter.appendToWithoutDelimiters(sb); +- } +- sb.write(closeOptionalString); +- return '(' + sb.toString() + ')'; +-} +- +-String _getTypeParametersString(engine.Element element) { +- List typeParameters; +- if (element is engine.ClassElement) { +- typeParameters =3D element.typeParameters; +- } else if (element is engine.FunctionTypeAliasElement) { +- typeParameters =3D element.typeParameters; +- } +- if (typeParameters =3D=3D null || typeParameters.isEmpty) { +- return null; +- } +- return '<${typeParameters.join(', ')}>'; +-} +- +-bool _isAbstract(engine.Element element) { +- // TODO(scheglov) add isAbstract to Element API +- if (element is engine.ClassElement) { +- return element.isAbstract; +- } +- if (element is engine.MethodElement) { +- return element.isAbstract; +- } +- if (element is engine.PropertyAccessorElement) { +- return element.isAbstract; +- } +- return false; +-} +- +-bool _isConst(engine.Element element) { +- // TODO(scheglov) add isConst to Element API +- if (element is engine.ConstructorElement) { +- return element.isConst; +- } +- if (element is engine.VariableElement) { +- return element.isConst; +- } +- return false; +-} +- +-bool _isFinal(engine.Element element) { +- // TODO(scheglov) add isFinal to Element API +- if (element is engine.VariableElement) { +- return element.isFinal; +- } +- return false; +-} +- +-bool _isStatic(engine.Element element) { +- // TODO(scheglov) add isStatic to Element API +- if (element is engine.ExecutableElement) { +- return element.isStatic; +- } +- if (element is engine.PropertyInducingElement) { +- return element.isStatic; +- } +- return false; +-} +diff --git a/pkg/analysis_server/lib/protocol/protocol.dart b/pkg/analysis= _server/lib/protocol/protocol.dart +deleted file mode 100644 +index df989b1d9f5..00000000000 +--- a/pkg/analysis_server/lib/protocol/protocol.dart ++++ /dev/null +@@ -1,673 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Support for client code that needs to interact with the requests, resp= onses +- * and notifications that are part of the analysis server's wire protocol. +- */ +-import 'dart:convert' hide JsonDecoder; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart'; +- +-export 'package:analyzer_plugin/protocol/protocol.dart' show Enum; +- +-/** +- * A [RequestHandler] that supports [startup] and [shutdown] methods. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class DomainHandler implements RequestHandler { +- /** +- * Perform any operations associated with the shutdown of the domain. I= t is +- * not guaranteed that this method will be called. If it is, it will be +- * called after the last [Request] has been made. +- */ +- void shutdown() {} +- +- /** +- * Perform any operations associated with the startup of the domain. Th= is +- * will be called before the first [Request]. +- */ +- void startup() {} +-} +- +-/** +- * A notification that can be sent from the server about an event that oc= curred. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class Notification { +- /** +- * The name of the JSON attribute containing the name of the event that +- * triggered the notification. +- */ +- static const String EVENT =3D 'event'; +- +- /** +- * The name of the JSON attribute containing the result values. +- */ +- static const String PARAMS =3D 'params'; +- +- /** +- * The name of the event that triggered the notification. +- */ +- final String event; +- +- /** +- * A table mapping the names of notification parameters to their values= , or +- * `null` if there are no notification parameters. +- */ +- final Map params; +- +- /** +- * Initialize a newly created [Notification] to have the given [event] = name. +- * If [params] is provided, it will be used as the params; otherwise no +- * params will be used. +- */ +- Notification(this.event, [this.params]); +- +- /** +- * Initialize a newly created instance based on the given JSON data. +- */ +- factory Notification.fromJson(Map json) { +- return new Notification(json[Notification.EVENT], +- json[Notification.PARAMS] as Map); +- } +- +- /** +- * Return a table representing the structure of the Json object that wi= ll be +- * sent to the client to represent this response. +- */ +- Map toJson() { +- Map jsonObject =3D {}; +- jsonObject[EVENT] =3D event; +- if (params !=3D null) { +- jsonObject[PARAMS] =3D params; +- } +- return jsonObject; +- } +-} +- +-/** +- * A request that was received from the client. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class Request { +- /** +- * The name of the JSON attribute containing the id of the request. +- */ +- static const String ID =3D 'id'; +- +- /** +- * The name of the JSON attribute containing the name of the request. +- */ +- static const String METHOD =3D 'method'; +- +- /** +- * The name of the JSON attribute containing the request parameters. +- */ +- static const String PARAMS =3D 'params'; +- +- /** +- * The name of the optional JSON attribute indicating the time (millise= conds +- * since epoch) at which the client made the request. +- */ +- static const String CLIENT_REQUEST_TIME =3D 'clientRequestTime'; +- +- /** +- * The unique identifier used to identify this request. +- */ +- final String id; +- +- /** +- * The method being requested. +- */ +- final String method; +- +- /** +- * A table mapping the names of request parameters to their values. +- */ +- final Map params; +- +- /** +- * The time (milliseconds since epoch) at which the client made the req= uest +- * or `null` if this information is not provided by the client. +- */ +- final int clientRequestTime; +- +- /** +- * Initialize a newly created [Request] to have the given [id] and [met= hod] +- * name. If [params] is supplied, it is used as the "params" map for the +- * request. Otherwise an empty "params" map is allocated. +- */ +- Request(this.id, this.method, +- [Map params, this.clientRequestTime]) +- : params =3D params ?? {}; +- +- /** +- * Return a request parsed from the given json, or `null` if the [data]= is +- * not a valid json representation of a request. The [data] is expected= to +- * have the following format: +- * +- * { +- * 'clientRequestTime': millisecondsSinceEpoch +- * 'id': String, +- * 'method': methodName, +- * 'params': { +- * paramter_name: value +- * } +- * } +- * +- * where both the parameters and clientRequestTime are optional. +- * +- * The parameters can contain any number of name/value pairs. The +- * clientRequestTime must be an int representing the time at which the = client +- * issued the request (milliseconds since epoch). +- */ +- factory Request.fromJson(Map result) { +- var id =3D result[Request.ID]; +- var method =3D result[Request.METHOD]; +- if (id is! String || method is! String) { +- return null; +- } +- var time =3D result[Request.CLIENT_REQUEST_TIME]; +- if (time !=3D null && time is! int) { +- return null; +- } +- var params =3D result[Request.PARAMS]; +- if (params is Map || params =3D=3D null) { +- return new Request(id, method, params as Map, time); +- } else { +- return null; +- } +- } +- +- /** +- * Return a request parsed from the given [data], or `null` if the [dat= a] is +- * not a valid json representation of a request. The [data] is expected= to +- * have the following format: +- * +- * { +- * 'clientRequestTime': millisecondsSinceEpoch +- * 'id': String, +- * 'method': methodName, +- * 'params': { +- * paramter_name: value +- * } +- * } +- * +- * where both the parameters and clientRequestTime are optional. +- * +- * The parameters can contain any number of name/value pairs. The +- * clientRequestTime must be an int representing the time at which the = client +- * issued the request (milliseconds since epoch). +- */ +- factory Request.fromString(String data) { +- try { +- var result =3D JSON.decode(data); +- if (result is Map) { +- return new Request.fromJson(result as Map); +- } +- return null; +- } catch (exception) { +- return null; +- } +- } +- +- @override +- int get hashCode { +- return id.hashCode; +- } +- +- @override +- bool operator =3D=3D(Object other) { +- return other is Request && +- id =3D=3D other.id && +- method =3D=3D other.method && +- clientRequestTime =3D=3D other.clientRequestTime && +- _equalMaps(params, other.params); +- } +- +- /** +- * Return a table representing the structure of the Json object that wi= ll be +- * sent to the client to represent this response. +- */ +- Map toJson() { +- Map jsonObject =3D {}; +- jsonObject[ID] =3D id; +- jsonObject[METHOD] =3D method; +- if (params.isNotEmpty) { +- jsonObject[PARAMS] =3D params; +- } +- if (clientRequestTime !=3D null) { +- jsonObject[CLIENT_REQUEST_TIME] =3D clientRequestTime; +- } +- return jsonObject; +- } +- +- bool _equalLists(List first, List second) { +- if (first =3D=3D null) { +- return second =3D=3D null; +- } +- if (second =3D=3D null) { +- return false; +- } +- int length =3D first.length; +- if (length !=3D second.length) { +- return false; +- } +- for (int i =3D 0; i < length; i++) { +- if (!_equalObjects(first[i], second[i])) { +- return false; +- } +- } +- return true; +- } +- +- bool _equalMaps(Map first, Map second) { +- if (first =3D=3D null) { +- return second =3D=3D null; +- } +- if (second =3D=3D null) { +- return false; +- } +- if (first.length !=3D second.length) { +- return false; +- } +- for (var key in first.keys) { +- if (!second.containsKey(key)) { +- return false; +- } +- if (!_equalObjects(first[key], second[key])) { +- return false; +- } +- } +- return true; +- } +- +- bool _equalObjects(Object first, Object second) { +- if (first =3D=3D null) { +- return second =3D=3D null; +- } +- if (second =3D=3D null) { +- return false; +- } +- if (first is Map) { +- if (second is Map) { +- return _equalMaps(first, second); +- } +- return false; +- } +- if (first is List) { +- if (second is List) { +- return _equalLists(first, second); +- } +- return false; +- } +- return first =3D=3D second; +- } +-} +- +-/** +- * An exception that occurred during the handling of a request that requi= res +- * that an error be returned to the client. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RequestFailure implements Exception { +- /** +- * The response to be returned as a result of the failure. +- */ +- final Response response; +- +- /** +- * Initialize a newly created exception to return the given reponse. +- */ +- RequestFailure(this.response); +-} +- +-/** +- * An object that can handle requests and produce responses for them. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class RequestHandler { +- /** +- * Attempt to handle the given [request]. If the request is not recogni= zed by +- * this handler, return `null` so that other handlers will be given a c= hance +- * to handle it. Otherwise, return the response that should be passed b= ack to +- * the client. +- */ +- Response handleRequest(Request request); +-} +- +-/** +- * A response to a request. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class Response { +- /** +- * The [Response] instance that is returned when a real [Response] cann= ot +- * be provided at the moment. +- */ +- static final Response DELAYED_RESPONSE =3D new Response('DELAYED_RESPON= SE'); +- +- /** +- * The name of the JSON attribute containing the id of the request for = which +- * this is a response. +- */ +- static const String ID =3D 'id'; +- +- /** +- * The name of the JSON attribute containing the error message. +- */ +- static const String ERROR =3D 'error'; +- +- /** +- * The name of the JSON attribute containing the result values. +- */ +- static const String RESULT =3D 'result'; +- +- /** +- * The unique identifier used to identify the request that this respons= e is +- * associated with. +- */ +- final String id; +- +- /** +- * The error that was caused by attempting to handle the request, or `n= ull` if +- * there was no error. +- */ +- final RequestError error; +- +- /** +- * A table mapping the names of result fields to their values. Should = be +- * `null` if there is no result to send. +- */ +- Map result; +- +- /** +- * Initialize a newly created instance to represent a response to a req= uest +- * with the given [id]. If [_result] is provided, it will be used as t= he +- * result; otherwise an empty result will be used. If an [error] is pr= ovided +- * then the response will represent an error condition. +- */ +- Response(this.id, {Map result, this.error}) : result = =3D result; +- +- /** +- * Create and return the `DEBUG_PORT_COULD_NOT_BE_OPENED` error respons= e. +- */ +- Response.debugPortCouldNotBeOpened(Request request, dynamic error) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.DEBUG_PORT_COULD_NOT_BE_OPENED, '$error'= )); +- +- /** +- * Initialize a newly created instance to represent the FILE_NOT_ANALYZ= ED +- * error condition. +- */ +- Response.fileNotAnalyzed(Request request, String file) +- : this(request.id, +- error: new RequestError(RequestErrorCode.FILE_NOT_ANALYZED, +- 'File is not analyzed: $file.')); +- +- /** +- * Initialize a newly created instance to represent the FORMAT_INVALID_= FILE +- * error condition. +- */ +- Response.formatInvalidFile(Request request) +- : this(request.id, +- error: new RequestError(RequestErrorCode.FORMAT_INVALID_FILE, +- 'Error during `edit.format`: invalid file.')); +- +- /** +- * Initialize a newly created instance to represent the FORMAT_WITH_ERR= OR +- * error condition. +- */ +- Response.formatWithErrors(Request request) +- : this(request.id, +- error: new RequestError(RequestErrorCode.FORMAT_WITH_ERRORS, +- 'Error during `edit.format`: source contains syntax error= s.')); +- +- /** +- * Initialize a newly created instance based on the given JSON data. +- */ +- factory Response.fromJson(Map json) { +- try { +- Object id =3D json[Response.ID]; +- if (id is! String) { +- return null; +- } +- Object error =3D json[Response.ERROR]; +- RequestError decodedError; +- if (error is Map) { +- decodedError =3D new RequestError.fromJson( +- new ResponseDecoder(null), '.error', error); +- } +- Object result =3D json[Response.RESULT]; +- Map decodedResult; +- if (result is Map) { +- decodedResult =3D result as Map; +- } +- return new Response(id, error: decodedError, result: decodedResult); +- } catch (exception) { +- return null; +- } +- } +- +- /** +- * Initialize a newly created instance to represent the +- * GET_ERRORS_INVALID_FILE error condition. +- */ +- Response.getErrorsInvalidFile(Request request) +- : this(request.id, +- error: new RequestError(RequestErrorCode.GET_ERRORS_INVALID_F= ILE, +- 'Error during `analysis.getErrors`: invalid file.')); +- +- /** +- * Initialize a newly created instance to represent the +- * GET_IMPORTED_ELEMENTS_INVALID_FILE error condition. +- */ +- Response.getImportedElementsInvalidFile(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.GET_IMPORTED_ELEMENTS_INVALID_FILE, +- 'Error during `analysis.getImportedElements`: invalid fil= e.')); +- +- /** +- * Initialize a newly created instance to represent the +- * GET_KYTHE_ENTRIES_INVALID_FILE error condition. +- */ +- Response.getKytheEntriesInvalidFile(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.GET_KYTHE_ENTRIES_INVALID_FILE, +- 'Error during `analysis.getKytheEntries`: invalid file.')= ); +- +- /** +- * Initialize a newly created instance to represent the +- * GET_NAVIGATION_INVALID_FILE error condition. +- */ +- Response.getNavigationInvalidFile(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.GET_NAVIGATION_INVALID_FILE, +- 'Error during `analysis.getNavigation`: invalid file.')); +- +- /** +- * Initialize a newly created instance to represent the +- * GET_REACHABLE_SOURCES_INVALID_FILE error condition. +- */ +- Response.getReachableSourcesInvalidFile(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.GET_REACHABLE_SOURCES_INVALID_FILE, +- 'Error during `analysis.getReachableSources`: invalid fil= e.')); +- +- /** +- * Initialize a newly created instance to represent the +- * IMPORT_ELEMENTS_INVALID_FILE error condition. +- */ +- Response.importElementsInvalidFile(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.IMPORT_ELEMENTS_INVALID_FILE, +- 'Error during `edit.importElements`: invalid file.')); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by an analysis.reanalyze [request] that specifies an analysis root t= hat is +- * not in the current list of analysis roots. +- */ +- Response.invalidAnalysisRoot(Request request, String rootPath) +- : this(request.id, +- error: new RequestError(RequestErrorCode.INVALID_ANALYSIS_ROO= T, +- "Invalid analysis root: $rootPath")); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a [request] that specifies an execution context whose context roo= t does +- * not exist. +- */ +- Response.invalidExecutionContext(Request request, String contextId) +- : this(request.id, +- error: new RequestError(RequestErrorCode.INVALID_EXECUTION_CO= NTEXT, +- "Invalid execution context: $contextId")); +- +- /** +- * Initialize a newly created instance to represent the +- * INVALID_FILE_PATH_FORMAT error condition. +- */ +- Response.invalidFilePathFormat(Request request, path) +- : this(request.id, +- error: new RequestError(RequestErrorCode.INVALID_FILE_PATH_FO= RMAT, +- 'Invalid file path format: $path')); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a [request] that had invalid parameter. [path] is the path to the +- * invalid parameter, in Javascript notation (e.g. "foo.bar" means that= the +- * parameter "foo" contained a key "bar" whose value was the wrong type= ). +- * [expectation] is a description of the type of data that was expected. +- */ +- Response.invalidParameter(Request request, String path, String expectat= ion) +- : this(request.id, +- error: new RequestError(RequestErrorCode.INVALID_PARAMETER, +- "Invalid parameter '$path'. $expectation.")); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a malformed request. +- */ +- Response.invalidRequestFormat() +- : this('', +- error: new RequestError( +- RequestErrorCode.INVALID_REQUEST, 'Invalid request')); +- +- /** +- * Initialize a newly created instance to represent the +- * ORGANIZE_DIRECTIVES_ERROR error condition. +- */ +- Response.organizeDirectivesError(Request request, String message) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.ORGANIZE_DIRECTIVES_ERROR, message)); +- +- /** +- * Initialize a newly created instance to represent the +- * REFACTORING_REQUEST_CANCELLED error condition. +- */ +- Response.refactoringRequestCancelled(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.REFACTORING_REQUEST_CANCELLED, +- 'The `edit.getRefactoring` request was cancelled.')); +- +- /** +- * Initialize a newly created instance to represent the SERVER_ERROR er= ror +- * condition. +- */ +- factory Response.serverError(Request request, exception, stackTrace) { +- RequestError error =3D +- new RequestError(RequestErrorCode.SERVER_ERROR, exception.toStrin= g()); +- if (stackTrace !=3D null) { +- error.stackTrace =3D stackTrace.toString(); +- } +- return new Response(request.id, error: error); +- } +- +- /** +- * Initialize a newly created instance to represent the +- * SORT_MEMBERS_INVALID_FILE error condition. +- */ +- Response.sortMembersInvalidFile(Request request) +- : this(request.id, +- error: new RequestError(RequestErrorCode.SORT_MEMBERS_INVALID= _FILE, +- 'Error during `edit.sortMembers`: invalid file.')); +- +- /** +- * Initialize a newly created instance to represent the +- * SORT_MEMBERS_PARSE_ERRORS error condition. +- */ +- Response.sortMembersParseErrors(Request request, int numErrors) +- : this(request.id, +- error: new RequestError(RequestErrorCode.SORT_MEMBERS_PARSE_E= RRORS, +- 'Error during `edit.sortMembers`: file has $numErrors sca= n/parse errors.')); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a `analysis.setPriorityFiles` [request] that includes one or more= files +- * that are not being analyzed. +- */ +- Response.unanalyzedPriorityFiles(String requestId, String fileNames) +- : this(requestId, +- error: new RequestError(RequestErrorCode.UNANALYZED_PRIORITY_= FILES, +- "Unanalyzed files cannot be a priority: '$fileNames'")); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a [request] that cannot be handled by any known handlers. +- */ +- Response.unknownRequest(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.UNKNOWN_REQUEST, 'Unknown request')); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a [request] referencing a source that does not exist. +- */ +- Response.unknownSource(Request request) +- : this(request.id, +- error: new RequestError( +- RequestErrorCode.UNKNOWN_SOURCE, 'Unknown source')); +- +- /** +- * Initialize a newly created instance to represent an error condition = caused +- * by a [request] for a service that is not supported. +- */ +- Response.unsupportedFeature(String requestId, String message) +- : this(requestId, +- error: new RequestError( +- RequestErrorCode.UNSUPPORTED_FEATURE, message)); +- +- /** +- * Return a table representing the structure of the Json object that wi= ll be +- * sent to the client to represent this response. +- */ +- Map toJson() { +- Map jsonObject =3D {}; +- jsonObject[ID] =3D id; +- if (error !=3D null) { +- jsonObject[ERROR] =3D error.toJson(); +- } +- if (result !=3D null) { +- jsonObject[RESULT] =3D result; +- } +- return jsonObject; +- } +-} +diff --git a/pkg/analysis_server/lib/protocol/protocol_constants.dart b/pk= g/analysis_server/lib/protocol/protocol_constants.dart +deleted file mode 100644 +index 9ff059c1f58..00000000000 +--- a/pkg/analysis_server/lib/protocol/protocol_constants.dart ++++ /dev/null +@@ -1,258 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +-// +-// This file has been automatically generated. Please do not edit it man= ually. +-// To regenerate the file, use the script +-// "pkg/analysis_server/tool/spec/generate_files". +- +-const String ANALYSIS_NOTIFICATION_ANALYZED_FILES =3D 'analysis.analyzedF= iles'; +-const String ANALYSIS_NOTIFICATION_ANALYZED_FILES_DIRECTORIES =3D 'direct= ories'; +-const String ANALYSIS_NOTIFICATION_CLOSING_LABELS =3D 'analysis.closingLa= bels'; +-const String ANALYSIS_NOTIFICATION_CLOSING_LABELS_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_CLOSING_LABELS_LABELS =3D 'labels'; +-const String ANALYSIS_NOTIFICATION_ERRORS =3D 'analysis.errors'; +-const String ANALYSIS_NOTIFICATION_ERRORS_ERRORS =3D 'errors'; +-const String ANALYSIS_NOTIFICATION_ERRORS_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_FLUSH_RESULTS =3D 'analysis.flushResul= ts'; +-const String ANALYSIS_NOTIFICATION_FLUSH_RESULTS_FILES =3D 'files'; +-const String ANALYSIS_NOTIFICATION_FOLDING =3D 'analysis.folding'; +-const String ANALYSIS_NOTIFICATION_FOLDING_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_FOLDING_REGIONS =3D 'regions'; +-const String ANALYSIS_NOTIFICATION_HIGHLIGHTS =3D 'analysis.highlights'; +-const String ANALYSIS_NOTIFICATION_HIGHLIGHTS_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_HIGHLIGHTS_REGIONS =3D 'regions'; +-const String ANALYSIS_NOTIFICATION_IMPLEMENTED =3D 'analysis.implemented'; +-const String ANALYSIS_NOTIFICATION_IMPLEMENTED_CLASSES =3D 'classes'; +-const String ANALYSIS_NOTIFICATION_IMPLEMENTED_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_IMPLEMENTED_MEMBERS =3D 'members'; +-const String ANALYSIS_NOTIFICATION_INVALIDATE =3D 'analysis.invalidate'; +-const String ANALYSIS_NOTIFICATION_INVALIDATE_DELTA =3D 'delta'; +-const String ANALYSIS_NOTIFICATION_INVALIDATE_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_INVALIDATE_LENGTH =3D 'length'; +-const String ANALYSIS_NOTIFICATION_INVALIDATE_OFFSET =3D 'offset'; +-const String ANALYSIS_NOTIFICATION_NAVIGATION =3D 'analysis.navigation'; +-const String ANALYSIS_NOTIFICATION_NAVIGATION_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_NAVIGATION_FILES =3D 'files'; +-const String ANALYSIS_NOTIFICATION_NAVIGATION_REGIONS =3D 'regions'; +-const String ANALYSIS_NOTIFICATION_NAVIGATION_TARGETS =3D 'targets'; +-const String ANALYSIS_NOTIFICATION_OCCURRENCES =3D 'analysis.occurrences'; +-const String ANALYSIS_NOTIFICATION_OCCURRENCES_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_OCCURRENCES_OCCURRENCES =3D 'occurrenc= es'; +-const String ANALYSIS_NOTIFICATION_OUTLINE =3D 'analysis.outline'; +-const String ANALYSIS_NOTIFICATION_OUTLINE_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_OUTLINE_KIND =3D 'kind'; +-const String ANALYSIS_NOTIFICATION_OUTLINE_LIBRARY_NAME =3D 'libraryName'; +-const String ANALYSIS_NOTIFICATION_OUTLINE_OUTLINE =3D 'outline'; +-const String ANALYSIS_NOTIFICATION_OVERRIDES =3D 'analysis.overrides'; +-const String ANALYSIS_NOTIFICATION_OVERRIDES_FILE =3D 'file'; +-const String ANALYSIS_NOTIFICATION_OVERRIDES_OVERRIDES =3D 'overrides'; +-const String ANALYSIS_REQUEST_GET_ERRORS =3D 'analysis.getErrors'; +-const String ANALYSIS_REQUEST_GET_ERRORS_FILE =3D 'file'; +-const String ANALYSIS_REQUEST_GET_HOVER =3D 'analysis.getHover'; +-const String ANALYSIS_REQUEST_GET_HOVER_FILE =3D 'file'; +-const String ANALYSIS_REQUEST_GET_HOVER_OFFSET =3D 'offset'; +-const String ANALYSIS_REQUEST_GET_IMPORTED_ELEMENTS =3D +- 'analysis.getImportedElements'; +-const String ANALYSIS_REQUEST_GET_IMPORTED_ELEMENTS_FILE =3D 'file'; +-const String ANALYSIS_REQUEST_GET_IMPORTED_ELEMENTS_LENGTH =3D 'length'; +-const String ANALYSIS_REQUEST_GET_IMPORTED_ELEMENTS_OFFSET =3D 'offset'; +-const String ANALYSIS_REQUEST_GET_LIBRARY_DEPENDENCIES =3D +- 'analysis.getLibraryDependencies'; +-const String ANALYSIS_REQUEST_GET_NAVIGATION =3D 'analysis.getNavigation'; +-const String ANALYSIS_REQUEST_GET_NAVIGATION_FILE =3D 'file'; +-const String ANALYSIS_REQUEST_GET_NAVIGATION_LENGTH =3D 'length'; +-const String ANALYSIS_REQUEST_GET_NAVIGATION_OFFSET =3D 'offset'; +-const String ANALYSIS_REQUEST_GET_REACHABLE_SOURCES =3D +- 'analysis.getReachableSources'; +-const String ANALYSIS_REQUEST_GET_REACHABLE_SOURCES_FILE =3D 'file'; +-const String ANALYSIS_REQUEST_REANALYZE =3D 'analysis.reanalyze'; +-const String ANALYSIS_REQUEST_REANALYZE_ROOTS =3D 'roots'; +-const String ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS =3D 'analysis.setAnalysi= sRoots'; +-const String ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS_EXCLUDED =3D 'excluded'; +-const String ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS_INCLUDED =3D 'included'; +-const String ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS_PACKAGE_ROOTS =3D 'packa= geRoots'; +-const String ANALYSIS_REQUEST_SET_GENERAL_SUBSCRIPTIONS =3D +- 'analysis.setGeneralSubscriptions'; +-const String ANALYSIS_REQUEST_SET_GENERAL_SUBSCRIPTIONS_SUBSCRIPTIONS =3D +- 'subscriptions'; +-const String ANALYSIS_REQUEST_SET_PRIORITY_FILES =3D 'analysis.setPriorit= yFiles'; +-const String ANALYSIS_REQUEST_SET_PRIORITY_FILES_FILES =3D 'files'; +-const String ANALYSIS_REQUEST_SET_SUBSCRIPTIONS =3D 'analysis.setSubscrip= tions'; +-const String ANALYSIS_REQUEST_SET_SUBSCRIPTIONS_SUBSCRIPTIONS =3D 'subscr= iptions'; +-const String ANALYSIS_REQUEST_UPDATE_CONTENT =3D 'analysis.updateContent'; +-const String ANALYSIS_REQUEST_UPDATE_CONTENT_FILES =3D 'files'; +-const String ANALYSIS_REQUEST_UPDATE_OPTIONS =3D 'analysis.updateOptions'; +-const String ANALYSIS_REQUEST_UPDATE_OPTIONS_OPTIONS =3D 'options'; +-const String ANALYSIS_RESPONSE_GET_ERRORS_ERRORS =3D 'errors'; +-const String ANALYSIS_RESPONSE_GET_HOVER_HOVERS =3D 'hovers'; +-const String ANALYSIS_RESPONSE_GET_IMPORTED_ELEMENTS_ELEMENTS =3D 'elemen= ts'; +-const String ANALYSIS_RESPONSE_GET_LIBRARY_DEPENDENCIES_LIBRARIES =3D 'li= braries'; +-const String ANALYSIS_RESPONSE_GET_LIBRARY_DEPENDENCIES_PACKAGE_MAP =3D +- 'packageMap'; +-const String ANALYSIS_RESPONSE_GET_NAVIGATION_FILES =3D 'files'; +-const String ANALYSIS_RESPONSE_GET_NAVIGATION_REGIONS =3D 'regions'; +-const String ANALYSIS_RESPONSE_GET_NAVIGATION_TARGETS =3D 'targets'; +-const String ANALYSIS_RESPONSE_GET_REACHABLE_SOURCES_SOURCES =3D 'sources= '; +-const String ANALYTICS_REQUEST_ENABLE =3D 'analytics.enable'; +-const String ANALYTICS_REQUEST_ENABLE_VALUE =3D 'value'; +-const String ANALYTICS_REQUEST_IS_ENABLED =3D 'analytics.isEnabled'; +-const String ANALYTICS_REQUEST_SEND_EVENT =3D 'analytics.sendEvent'; +-const String ANALYTICS_REQUEST_SEND_EVENT_ACTION =3D 'action'; +-const String ANALYTICS_REQUEST_SEND_TIMING =3D 'analytics.sendTiming'; +-const String ANALYTICS_REQUEST_SEND_TIMING_EVENT =3D 'event'; +-const String ANALYTICS_REQUEST_SEND_TIMING_MILLIS =3D 'millis'; +-const String ANALYTICS_RESPONSE_IS_ENABLED_ENABLED =3D 'enabled'; +-const String COMPLETION_NOTIFICATION_RESULTS =3D 'completion.results'; +-const String COMPLETION_NOTIFICATION_RESULTS_ID =3D 'id'; +-const String COMPLETION_NOTIFICATION_RESULTS_IS_LAST =3D 'isLast'; +-const String COMPLETION_NOTIFICATION_RESULTS_REPLACEMENT_LENGTH =3D +- 'replacementLength'; +-const String COMPLETION_NOTIFICATION_RESULTS_REPLACEMENT_OFFSET =3D +- 'replacementOffset'; +-const String COMPLETION_NOTIFICATION_RESULTS_RESULTS =3D 'results'; +-const String COMPLETION_REQUEST_GET_SUGGESTIONS =3D 'completion.getSugges= tions'; +-const String COMPLETION_REQUEST_GET_SUGGESTIONS_FILE =3D 'file'; +-const String COMPLETION_REQUEST_GET_SUGGESTIONS_OFFSET =3D 'offset'; +-const String COMPLETION_RESPONSE_GET_SUGGESTIONS_ID =3D 'id'; +-const String DIAGNOSTIC_REQUEST_GET_DIAGNOSTICS =3D 'diagnostic.getDiagno= stics'; +-const String DIAGNOSTIC_REQUEST_GET_SERVER_PORT =3D 'diagnostic.getServer= Port'; +-const String DIAGNOSTIC_RESPONSE_GET_DIAGNOSTICS_CONTEXTS =3D 'contexts'; +-const String DIAGNOSTIC_RESPONSE_GET_SERVER_PORT_PORT =3D 'port'; +-const String EDIT_REQUEST_FORMAT =3D 'edit.format'; +-const String EDIT_REQUEST_FORMAT_FILE =3D 'file'; +-const String EDIT_REQUEST_FORMAT_LINE_LENGTH =3D 'lineLength'; +-const String EDIT_REQUEST_FORMAT_SELECTION_LENGTH =3D 'selectionLength'; +-const String EDIT_REQUEST_FORMAT_SELECTION_OFFSET =3D 'selectionOffset'; +-const String EDIT_REQUEST_GET_ASSISTS =3D 'edit.getAssists'; +-const String EDIT_REQUEST_GET_ASSISTS_FILE =3D 'file'; +-const String EDIT_REQUEST_GET_ASSISTS_LENGTH =3D 'length'; +-const String EDIT_REQUEST_GET_ASSISTS_OFFSET =3D 'offset'; +-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS =3D +- 'edit.getAvailableRefactorings'; +-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS_FILE =3D 'file'; +-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS_LENGTH =3D 'length'; +-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS_OFFSET =3D 'offset'; +-const String EDIT_REQUEST_GET_FIXES =3D 'edit.getFixes'; +-const String EDIT_REQUEST_GET_FIXES_FILE =3D 'file'; +-const String EDIT_REQUEST_GET_FIXES_OFFSET =3D 'offset'; +-const String EDIT_REQUEST_GET_POSTFIX_COMPLETION =3D 'edit.getPostfixComp= letion'; +-const String EDIT_REQUEST_GET_POSTFIX_COMPLETION_FILE =3D 'file'; +-const String EDIT_REQUEST_GET_POSTFIX_COMPLETION_KEY =3D 'key'; +-const String EDIT_REQUEST_GET_POSTFIX_COMPLETION_OFFSET =3D 'offset'; +-const String EDIT_REQUEST_GET_REFACTORING =3D 'edit.getRefactoring'; +-const String EDIT_REQUEST_GET_REFACTORING_FILE =3D 'file'; +-const String EDIT_REQUEST_GET_REFACTORING_KIND =3D 'kind'; +-const String EDIT_REQUEST_GET_REFACTORING_LENGTH =3D 'length'; +-const String EDIT_REQUEST_GET_REFACTORING_OFFSET =3D 'offset'; +-const String EDIT_REQUEST_GET_REFACTORING_OPTIONS =3D 'options'; +-const String EDIT_REQUEST_GET_REFACTORING_VALIDATE_ONLY =3D 'validateOnly= '; +-const String EDIT_REQUEST_GET_STATEMENT_COMPLETION =3D +- 'edit.getStatementCompletion'; +-const String EDIT_REQUEST_GET_STATEMENT_COMPLETION_FILE =3D 'file'; +-const String EDIT_REQUEST_GET_STATEMENT_COMPLETION_OFFSET =3D 'offset'; +-const String EDIT_REQUEST_IMPORT_ELEMENTS =3D 'edit.importElements'; +-const String EDIT_REQUEST_IMPORT_ELEMENTS_ELEMENTS =3D 'elements'; +-const String EDIT_REQUEST_IMPORT_ELEMENTS_FILE =3D 'file'; +-const String EDIT_REQUEST_IS_POSTFIX_COMPLETION_APPLICABLE =3D +- 'edit.isPostfixCompletionApplicable'; +-const String EDIT_REQUEST_IS_POSTFIX_COMPLETION_APPLICABLE_FILE =3D 'file= '; +-const String EDIT_REQUEST_IS_POSTFIX_COMPLETION_APPLICABLE_KEY =3D 'key'; +-const String EDIT_REQUEST_IS_POSTFIX_COMPLETION_APPLICABLE_OFFSET =3D 'of= fset'; +-const String EDIT_REQUEST_LIST_POSTFIX_COMPLETION_TEMPLATES =3D +- 'edit.listPostfixCompletionTemplates'; +-const String EDIT_REQUEST_ORGANIZE_DIRECTIVES =3D 'edit.organizeDirective= s'; +-const String EDIT_REQUEST_ORGANIZE_DIRECTIVES_FILE =3D 'file'; +-const String EDIT_REQUEST_SORT_MEMBERS =3D 'edit.sortMembers'; +-const String EDIT_REQUEST_SORT_MEMBERS_FILE =3D 'file'; +-const String EDIT_RESPONSE_FORMAT_EDITS =3D 'edits'; +-const String EDIT_RESPONSE_FORMAT_SELECTION_LENGTH =3D 'selectionLength'; +-const String EDIT_RESPONSE_FORMAT_SELECTION_OFFSET =3D 'selectionOffset'; +-const String EDIT_RESPONSE_GET_ASSISTS_ASSISTS =3D 'assists'; +-const String EDIT_RESPONSE_GET_AVAILABLE_REFACTORINGS_KINDS =3D 'kinds'; +-const String EDIT_RESPONSE_GET_FIXES_FIXES =3D 'fixes'; +-const String EDIT_RESPONSE_GET_POSTFIX_COMPLETION_CHANGE =3D 'change'; +-const String EDIT_RESPONSE_GET_REFACTORING_CHANGE =3D 'change'; +-const String EDIT_RESPONSE_GET_REFACTORING_FEEDBACK =3D 'feedback'; +-const String EDIT_RESPONSE_GET_REFACTORING_FINAL_PROBLEMS =3D 'finalProbl= ems'; +-const String EDIT_RESPONSE_GET_REFACTORING_INITIAL_PROBLEMS =3D 'initialP= roblems'; +-const String EDIT_RESPONSE_GET_REFACTORING_OPTIONS_PROBLEMS =3D 'optionsP= roblems'; +-const String EDIT_RESPONSE_GET_REFACTORING_POTENTIAL_EDITS =3D 'potential= Edits'; +-const String EDIT_RESPONSE_GET_STATEMENT_COMPLETION_CHANGE =3D 'change'; +-const String EDIT_RESPONSE_GET_STATEMENT_COMPLETION_WHITESPACE_ONLY =3D +- 'whitespaceOnly'; +-const String EDIT_RESPONSE_IMPORT_ELEMENTS_EDIT =3D 'edit'; +-const String EDIT_RESPONSE_IS_POSTFIX_COMPLETION_APPLICABLE_VALUE =3D 'va= lue'; +-const String EDIT_RESPONSE_LIST_POSTFIX_COMPLETION_TEMPLATES_TEMPLATES =3D +- 'templates'; +-const String EDIT_RESPONSE_ORGANIZE_DIRECTIVES_EDIT =3D 'edit'; +-const String EDIT_RESPONSE_SORT_MEMBERS_EDIT =3D 'edit'; +-const String EXECUTION_NOTIFICATION_LAUNCH_DATA =3D 'execution.launchData= '; +-const String EXECUTION_NOTIFICATION_LAUNCH_DATA_FILE =3D 'file'; +-const String EXECUTION_NOTIFICATION_LAUNCH_DATA_KIND =3D 'kind'; +-const String EXECUTION_NOTIFICATION_LAUNCH_DATA_REFERENCED_FILES =3D +- 'referencedFiles'; +-const String EXECUTION_REQUEST_CREATE_CONTEXT =3D 'execution.createContex= t'; +-const String EXECUTION_REQUEST_CREATE_CONTEXT_CONTEXT_ROOT =3D 'contextRo= ot'; +-const String EXECUTION_REQUEST_DELETE_CONTEXT =3D 'execution.deleteContex= t'; +-const String EXECUTION_REQUEST_DELETE_CONTEXT_ID =3D 'id'; +-const String EXECUTION_REQUEST_MAP_URI =3D 'execution.mapUri'; +-const String EXECUTION_REQUEST_MAP_URI_FILE =3D 'file'; +-const String EXECUTION_REQUEST_MAP_URI_ID =3D 'id'; +-const String EXECUTION_REQUEST_MAP_URI_URI =3D 'uri'; +-const String EXECUTION_REQUEST_SET_SUBSCRIPTIONS =3D 'execution.setSubscr= iptions'; +-const String EXECUTION_REQUEST_SET_SUBSCRIPTIONS_SUBSCRIPTIONS =3D +- 'subscriptions'; +-const String EXECUTION_RESPONSE_CREATE_CONTEXT_ID =3D 'id'; +-const String EXECUTION_RESPONSE_MAP_URI_FILE =3D 'file'; +-const String EXECUTION_RESPONSE_MAP_URI_URI =3D 'uri'; +-const String KYTHE_REQUEST_GET_KYTHE_ENTRIES =3D 'kythe.getKytheEntries'; +-const String KYTHE_REQUEST_GET_KYTHE_ENTRIES_FILE =3D 'file'; +-const String KYTHE_RESPONSE_GET_KYTHE_ENTRIES_ENTRIES =3D 'entries'; +-const String KYTHE_RESPONSE_GET_KYTHE_ENTRIES_FILES =3D 'files'; +-const String SEARCH_NOTIFICATION_RESULTS =3D 'search.results'; +-const String SEARCH_NOTIFICATION_RESULTS_ID =3D 'id'; +-const String SEARCH_NOTIFICATION_RESULTS_IS_LAST =3D 'isLast'; +-const String SEARCH_NOTIFICATION_RESULTS_RESULTS =3D 'results'; +-const String SEARCH_REQUEST_FIND_ELEMENT_REFERENCES =3D +- 'search.findElementReferences'; +-const String SEARCH_REQUEST_FIND_ELEMENT_REFERENCES_FILE =3D 'file'; +-const String SEARCH_REQUEST_FIND_ELEMENT_REFERENCES_INCLUDE_POTENTIAL =3D +- 'includePotential'; +-const String SEARCH_REQUEST_FIND_ELEMENT_REFERENCES_OFFSET =3D 'offset'; +-const String SEARCH_REQUEST_FIND_MEMBER_DECLARATIONS =3D +- 'search.findMemberDeclarations'; +-const String SEARCH_REQUEST_FIND_MEMBER_DECLARATIONS_NAME =3D 'name'; +-const String SEARCH_REQUEST_FIND_MEMBER_REFERENCES =3D +- 'search.findMemberReferences'; +-const String SEARCH_REQUEST_FIND_MEMBER_REFERENCES_NAME =3D 'name'; +-const String SEARCH_REQUEST_FIND_TOP_LEVEL_DECLARATIONS =3D +- 'search.findTopLevelDeclarations'; +-const String SEARCH_REQUEST_FIND_TOP_LEVEL_DECLARATIONS_PATTERN =3D 'patt= ern'; +-const String SEARCH_REQUEST_GET_TYPE_HIERARCHY =3D 'search.getTypeHierarc= hy'; +-const String SEARCH_REQUEST_GET_TYPE_HIERARCHY_FILE =3D 'file'; +-const String SEARCH_REQUEST_GET_TYPE_HIERARCHY_OFFSET =3D 'offset'; +-const String SEARCH_REQUEST_GET_TYPE_HIERARCHY_SUPER_ONLY =3D 'superOnly'; +-const String SEARCH_RESPONSE_FIND_ELEMENT_REFERENCES_ELEMENT =3D 'element= '; +-const String SEARCH_RESPONSE_FIND_ELEMENT_REFERENCES_ID =3D 'id'; +-const String SEARCH_RESPONSE_FIND_MEMBER_DECLARATIONS_ID =3D 'id'; +-const String SEARCH_RESPONSE_FIND_MEMBER_REFERENCES_ID =3D 'id'; +-const String SEARCH_RESPONSE_FIND_TOP_LEVEL_DECLARATIONS_ID =3D 'id'; +-const String SEARCH_RESPONSE_GET_TYPE_HIERARCHY_HIERARCHY_ITEMS =3D +- 'hierarchyItems'; +-const String SERVER_NOTIFICATION_CONNECTED =3D 'server.connected'; +-const String SERVER_NOTIFICATION_CONNECTED_PID =3D 'pid'; +-const String SERVER_NOTIFICATION_CONNECTED_SESSION_ID =3D 'sessionId'; +-const String SERVER_NOTIFICATION_CONNECTED_VERSION =3D 'version'; +-const String SERVER_NOTIFICATION_ERROR =3D 'server.error'; +-const String SERVER_NOTIFICATION_ERROR_IS_FATAL =3D 'isFatal'; +-const String SERVER_NOTIFICATION_ERROR_MESSAGE =3D 'message'; +-const String SERVER_NOTIFICATION_ERROR_STACK_TRACE =3D 'stackTrace'; +-const String SERVER_NOTIFICATION_STATUS =3D 'server.status'; +-const String SERVER_NOTIFICATION_STATUS_ANALYSIS =3D 'analysis'; +-const String SERVER_NOTIFICATION_STATUS_PUB =3D 'pub'; +-const String SERVER_REQUEST_GET_VERSION =3D 'server.getVersion'; +-const String SERVER_REQUEST_SET_SUBSCRIPTIONS =3D 'server.setSubscription= s'; +-const String SERVER_REQUEST_SET_SUBSCRIPTIONS_SUBSCRIPTIONS =3D 'subscrip= tions'; +-const String SERVER_REQUEST_SHUTDOWN =3D 'server.shutdown'; +-const String SERVER_RESPONSE_GET_VERSION_VERSION =3D 'version'; +diff --git a/pkg/analysis_server/lib/protocol/protocol_generated.dart b/pk= g/analysis_server/lib/protocol/protocol_generated.dart +deleted file mode 100644 +index 20400573c49..00000000000 +--- a/pkg/analysis_server/lib/protocol/protocol_generated.dart ++++ /dev/null +@@ -1,15802 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +-// +-// This file has been automatically generated. Please do not edit it man= ually. +-// To regenerate the file, use the script +-// "pkg/analysis_server/tool/spec/generate_files". +- +-import 'dart:convert' hide JsonDecoder; +- +-import 'package:analyzer/src/generated/utilities_general.dart'; +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * analysis.analyzedFiles params +- * +- * { +- * "directories": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisAnalyzedFilesParams implements HasToJson { +- List _directories; +- +- /** +- * A list of the paths of the files that are being analyzed. +- */ +- List get directories =3D> _directories; +- +- /** +- * A list of the paths of the files that are being analyzed. +- */ +- void set directories(List value) { +- assert(value !=3D null); +- this._directories =3D value; +- } +- +- AnalysisAnalyzedFilesParams(List directories) { +- this.directories =3D directories; +- } +- +- factory AnalysisAnalyzedFilesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List directories; +- if (json.containsKey("directories")) { +- directories =3D jsonDecoder.decodeList(jsonPath + ".directories", +- json["directories"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "directories"); +- } +- return new AnalysisAnalyzedFilesParams(directories); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.analyzedFiles params", json); +- } +- } +- +- factory AnalysisAnalyzedFilesParams.fromNotification( +- Notification notification) { +- return new AnalysisAnalyzedFilesParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["directories"] =3D directories; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.analyzedFiles", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisAnalyzedFilesParams) { +- return listEqual( +- directories, other.directories, (String a, String b) =3D> a =3D= =3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, directories.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.closingLabels params +- * +- * { +- * "file": FilePath +- * "labels": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisClosingLabelsParams implements HasToJson { +- String _file; +- +- List _labels; +- +- /** +- * The file the closing labels relate to. +- */ +- String get file =3D> _file; +- +- /** +- * The file the closing labels relate to. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * Closing labels relevant to the file. Each item represents a useful l= abel +- * associated with some range with may be useful to display to the user +- * within the editor at the end of the range to indicate what construct= is +- * closed at that location. Closing labels include constructor/method c= alls +- * and List arguments that span multiple lines. Note that the ranges th= at are +- * returned can overlap each other because they may be associated with +- * constructs that can be nested. +- */ +- List get labels =3D> _labels; +- +- /** +- * Closing labels relevant to the file. Each item represents a useful l= abel +- * associated with some range with may be useful to display to the user +- * within the editor at the end of the range to indicate what construct= is +- * closed at that location. Closing labels include constructor/method c= alls +- * and List arguments that span multiple lines. Note that the ranges th= at are +- * returned can overlap each other because they may be associated with +- * constructs that can be nested. +- */ +- void set labels(List value) { +- assert(value !=3D null); +- this._labels =3D value; +- } +- +- AnalysisClosingLabelsParams(String file, List labels) { +- this.file =3D file; +- this.labels =3D labels; +- } +- +- factory AnalysisClosingLabelsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List labels; +- if (json.containsKey("labels")) { +- labels =3D jsonDecoder.decodeList( +- jsonPath + ".labels", +- json["labels"], +- (String jsonPath, Object json) =3D> +- new ClosingLabel.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "labels"); +- } +- return new AnalysisClosingLabelsParams(file, labels); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.closingLabels params", json); +- } +- } +- +- factory AnalysisClosingLabelsParams.fromNotification( +- Notification notification) { +- return new AnalysisClosingLabelsParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["labels"] =3D +- labels.map((ClosingLabel value) =3D> value.toJson()).toList(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.closingLabels", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisClosingLabelsParams) { +- return file =3D=3D other.file && +- listEqual( +- labels, other.labels, (ClosingLabel a, ClosingLabel b) =3D>= a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, labels.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * AnalysisErrorFixes +- * +- * { +- * "error": AnalysisError +- * "fixes": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisErrorFixes implements HasToJson { +- AnalysisError _error; +- +- List _fixes; +- +- /** +- * The error with which the fixes are associated. +- */ +- AnalysisError get error =3D> _error; +- +- /** +- * The error with which the fixes are associated. +- */ +- void set error(AnalysisError value) { +- assert(value !=3D null); +- this._error =3D value; +- } +- +- /** +- * The fixes associated with the error. +- */ +- List get fixes =3D> _fixes; +- +- /** +- * The fixes associated with the error. +- */ +- void set fixes(List value) { +- assert(value !=3D null); +- this._fixes =3D value; +- } +- +- AnalysisErrorFixes(AnalysisError error, {List fixes}) { +- this.error =3D error; +- if (fixes =3D=3D null) { +- this.fixes =3D []; +- } else { +- this.fixes =3D fixes; +- } +- } +- +- factory AnalysisErrorFixes.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- AnalysisError error; +- if (json.containsKey("error")) { +- error =3D new AnalysisError.fromJson( +- jsonDecoder, jsonPath + ".error", json["error"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "error"); +- } +- List fixes; +- if (json.containsKey("fixes")) { +- fixes =3D jsonDecoder.decodeList( +- jsonPath + ".fixes", +- json["fixes"], +- (String jsonPath, Object json) =3D> +- new SourceChange.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "fixes"); +- } +- return new AnalysisErrorFixes(error, fixes: fixes); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "AnalysisErrorFixes", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["error"] =3D error.toJson(); +- result["fixes"] =3D +- fixes.map((SourceChange value) =3D> value.toJson()).toList(); +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisErrorFixes) { +- return error =3D=3D other.error && +- listEqual( +- fixes, other.fixes, (SourceChange a, SourceChange b) =3D> a= =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, error.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, fixes.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.errors params +- * +- * { +- * "file": FilePath +- * "errors": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisErrorsParams implements HasToJson { +- String _file; +- +- List _errors; +- +- /** +- * The file containing the errors. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the errors. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The errors contained in the file. +- */ +- List get errors =3D> _errors; +- +- /** +- * The errors contained in the file. +- */ +- void set errors(List value) { +- assert(value !=3D null); +- this._errors =3D value; +- } +- +- AnalysisErrorsParams(String file, List errors) { +- this.file =3D file; +- this.errors =3D errors; +- } +- +- factory AnalysisErrorsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List errors; +- if (json.containsKey("errors")) { +- errors =3D jsonDecoder.decodeList( +- jsonPath + ".errors", +- json["errors"], +- (String jsonPath, Object json) =3D> +- new AnalysisError.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "errors"); +- } +- return new AnalysisErrorsParams(file, errors); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.errors params", json= ); +- } +- } +- +- factory AnalysisErrorsParams.fromNotification(Notification notification= ) { +- return new AnalysisErrorsParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["errors"] =3D +- errors.map((AnalysisError value) =3D> value.toJson()).toList(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.errors", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisErrorsParams) { +- return file =3D=3D other.file && +- listEqual(errors, other.errors, +- (AnalysisError a, AnalysisError b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, errors.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.flushResults params +- * +- * { +- * "files": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisFlushResultsParams implements HasToJson { +- List _files; +- +- /** +- * The files that are no longer being analyzed. +- */ +- List get files =3D> _files; +- +- /** +- * The files that are no longer being analyzed. +- */ +- void set files(List value) { +- assert(value !=3D null); +- this._files =3D value; +- } +- +- AnalysisFlushResultsParams(List files) { +- this.files =3D files; +- } +- +- factory AnalysisFlushResultsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List files; +- if (json.containsKey("files")) { +- files =3D jsonDecoder.decodeList( +- jsonPath + ".files", json["files"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "files"); +- } +- return new AnalysisFlushResultsParams(files); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.flushResults params", json); +- } +- } +- +- factory AnalysisFlushResultsParams.fromNotification( +- Notification notification) { +- return new AnalysisFlushResultsParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["files"] =3D files; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.flushResults", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisFlushResultsParams) { +- return listEqual(files, other.files, (String a, String b) =3D> a = =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, files.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.folding params +- * +- * { +- * "file": FilePath +- * "regions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisFoldingParams implements HasToJson { +- String _file; +- +- List _regions; +- +- /** +- * The file containing the folding regions. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the folding regions. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The folding regions contained in the file. +- */ +- List get regions =3D> _regions; +- +- /** +- * The folding regions contained in the file. +- */ +- void set regions(List value) { +- assert(value !=3D null); +- this._regions =3D value; +- } +- +- AnalysisFoldingParams(String file, List regions) { +- this.file =3D file; +- this.regions =3D regions; +- } +- +- factory AnalysisFoldingParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List regions; +- if (json.containsKey("regions")) { +- regions =3D jsonDecoder.decodeList( +- jsonPath + ".regions", +- json["regions"], +- (String jsonPath, Object json) =3D> +- new FoldingRegion.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "regions"); +- } +- return new AnalysisFoldingParams(file, regions); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.folding params", jso= n); +- } +- } +- +- factory AnalysisFoldingParams.fromNotification(Notification notificatio= n) { +- return new AnalysisFoldingParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["regions"] =3D +- regions.map((FoldingRegion value) =3D> value.toJson()).toList(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.folding", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisFoldingParams) { +- return file =3D=3D other.file && +- listEqual(regions, other.regions, +- (FoldingRegion a, FoldingRegion b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, regions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getErrors params +- * +- * { +- * "file": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetErrorsParams implements RequestParams { +- String _file; +- +- /** +- * The file for which errors are being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file for which errors are being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- AnalysisGetErrorsParams(String file) { +- this.file =3D file; +- } +- +- factory AnalysisGetErrorsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- return new AnalysisGetErrorsParams(file); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.getErrors params", j= son); +- } +- } +- +- factory AnalysisGetErrorsParams.fromRequest(Request request) { +- return new AnalysisGetErrorsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.getErrors", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetErrorsParams) { +- return file =3D=3D other.file; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getErrors result +- * +- * { +- * "errors": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetErrorsResult implements ResponseResult { +- List _errors; +- +- /** +- * The errors associated with the file. +- */ +- List get errors =3D> _errors; +- +- /** +- * The errors associated with the file. +- */ +- void set errors(List value) { +- assert(value !=3D null); +- this._errors =3D value; +- } +- +- AnalysisGetErrorsResult(List errors) { +- this.errors =3D errors; +- } +- +- factory AnalysisGetErrorsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List errors; +- if (json.containsKey("errors")) { +- errors =3D jsonDecoder.decodeList( +- jsonPath + ".errors", +- json["errors"], +- (String jsonPath, Object json) =3D> +- new AnalysisError.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "errors"); +- } +- return new AnalysisGetErrorsResult(errors); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.getErrors result", j= son); +- } +- } +- +- factory AnalysisGetErrorsResult.fromResponse(Response response) { +- return new AnalysisGetErrorsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["errors"] =3D +- errors.map((AnalysisError value) =3D> value.toJson()).toList(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetErrorsResult) { +- return listEqual( +- errors, other.errors, (AnalysisError a, AnalysisError b) =3D> a= =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, errors.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getHover params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetHoverParams implements RequestParams { +- String _file; +- +- int _offset; +- +- /** +- * The file in which hover information is being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file in which hover information is being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset for which hover information is being requested. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset for which hover information is being requested. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- AnalysisGetHoverParams(String file, int offset) { +- this.file =3D file; +- this.offset =3D offset; +- } +- +- factory AnalysisGetHoverParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- return new AnalysisGetHoverParams(file, offset); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.getHover params", js= on); +- } +- } +- +- factory AnalysisGetHoverParams.fromRequest(Request request) { +- return new AnalysisGetHoverParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.getHover", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetHoverParams) { +- return file =3D=3D other.file && offset =3D=3D other.offset; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getHover result +- * +- * { +- * "hovers": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetHoverResult implements ResponseResult { +- List _hovers; +- +- /** +- * The hover information associated with the location. The list will be= empty +- * if no information could be determined for the location. The list can +- * contain multiple items if the file is being analyzed in multiple con= texts +- * in conflicting ways (such as a part that is included in multiple +- * libraries). +- */ +- List get hovers =3D> _hovers; +- +- /** +- * The hover information associated with the location. The list will be= empty +- * if no information could be determined for the location. The list can +- * contain multiple items if the file is being analyzed in multiple con= texts +- * in conflicting ways (such as a part that is included in multiple +- * libraries). +- */ +- void set hovers(List value) { +- assert(value !=3D null); +- this._hovers =3D value; +- } +- +- AnalysisGetHoverResult(List hovers) { +- this.hovers =3D hovers; +- } +- +- factory AnalysisGetHoverResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List hovers; +- if (json.containsKey("hovers")) { +- hovers =3D jsonDecoder.decodeList( +- jsonPath + ".hovers", +- json["hovers"], +- (String jsonPath, Object json) =3D> +- new HoverInformation.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "hovers"); +- } +- return new AnalysisGetHoverResult(hovers); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.getHover result", js= on); +- } +- } +- +- factory AnalysisGetHoverResult.fromResponse(Response response) { +- return new AnalysisGetHoverResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["hovers"] =3D +- hovers.map((HoverInformation value) =3D> value.toJson()).toList(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetHoverResult) { +- return listEqual(hovers, other.hovers, +- (HoverInformation a, HoverInformation b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, hovers.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getImportedElements params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetImportedElementsParams implements RequestParams { +- String _file; +- +- int _offset; +- +- int _length; +- +- /** +- * The file in which import information is being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file in which import information is being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the region for which import information is being reque= sted. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the region for which import information is being reque= sted. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the region for which import information is being reque= sted. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the region for which import information is being reque= sted. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- AnalysisGetImportedElementsParams(String file, int offset, int length) { +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- factory AnalysisGetImportedElementsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- return new AnalysisGetImportedElementsParams(file, offset, length); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getImportedElements params", json); +- } +- } +- +- factory AnalysisGetImportedElementsParams.fromRequest(Request request) { +- return new AnalysisGetImportedElementsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["length"] =3D length; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.getImportedElements", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetImportedElementsParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- length =3D=3D other.length; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getImportedElements result +- * +- * { +- * "elements": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetImportedElementsResult implements ResponseResult { +- List _elements; +- +- /** +- * The information about the elements that are referenced in the specif= ied +- * region of the specified file that come from imported libraries. +- */ +- List get elements =3D> _elements; +- +- /** +- * The information about the elements that are referenced in the specif= ied +- * region of the specified file that come from imported libraries. +- */ +- void set elements(List value) { +- assert(value !=3D null); +- this._elements =3D value; +- } +- +- AnalysisGetImportedElementsResult(List elements) { +- this.elements =3D elements; +- } +- +- factory AnalysisGetImportedElementsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List elements; +- if (json.containsKey("elements")) { +- elements =3D jsonDecoder.decodeList( +- jsonPath + ".elements", +- json["elements"], +- (String jsonPath, Object json) =3D> +- new ImportedElements.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "elements"); +- } +- return new AnalysisGetImportedElementsResult(elements); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getImportedElements result", json); +- } +- } +- +- factory AnalysisGetImportedElementsResult.fromResponse(Response respons= e) { +- return new AnalysisGetImportedElementsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["elements"] =3D +- elements.map((ImportedElements value) =3D> value.toJson()).toList= (); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetImportedElementsResult) { +- return listEqual(elements, other.elements, +- (ImportedElements a, ImportedElements b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, elements.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getLibraryDependencies params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetLibraryDependenciesParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.getLibraryDependencies", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetLibraryDependenciesParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 246577680; +- } +-} +- +-/** +- * analysis.getLibraryDependencies result +- * +- * { +- * "libraries": List +- * "packageMap": Map>> +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetLibraryDependenciesResult implements ResponseResult { +- List _libraries; +- +- Map>> _packageMap; +- +- /** +- * A list of the paths of library elements referenced by files in exist= ing +- * analysis roots. +- */ +- List get libraries =3D> _libraries; +- +- /** +- * A list of the paths of library elements referenced by files in exist= ing +- * analysis roots. +- */ +- void set libraries(List value) { +- assert(value !=3D null); +- this._libraries =3D value; +- } +- +- /** +- * A mapping from context source roots to package maps which map package +- * names to source directories for use in client-side package URI resol= ution. +- */ +- Map>> get packageMap =3D> _packageMap; +- +- /** +- * A mapping from context source roots to package maps which map package +- * names to source directories for use in client-side package URI resol= ution. +- */ +- void set packageMap(Map>> value) { +- assert(value !=3D null); +- this._packageMap =3D value; +- } +- +- AnalysisGetLibraryDependenciesResult(List libraries, +- Map>> packageMap) { +- this.libraries =3D libraries; +- this.packageMap =3D packageMap; +- } +- +- factory AnalysisGetLibraryDependenciesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List libraries; +- if (json.containsKey("libraries")) { +- libraries =3D jsonDecoder.decodeList(jsonPath + ".libraries", +- json["libraries"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "libraries"); +- } +- Map>> packageMap; +- if (json.containsKey("packageMap")) { +- packageMap =3D jsonDecoder.decodeMap( +- jsonPath + ".packageMap", json["packageMap"], +- valueDecoder: (String jsonPath, Object json) =3D> +- jsonDecoder.decodeMap(jsonPath, json, +- valueDecoder: (String jsonPath, Object json) =3D> jso= nDecoder +- .decodeList(jsonPath, json, jsonDecoder.decodeStr= ing))); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "packageMap"); +- } +- return new AnalysisGetLibraryDependenciesResult(libraries, packageM= ap); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getLibraryDependencies result", json); +- } +- } +- +- factory AnalysisGetLibraryDependenciesResult.fromResponse(Response resp= onse) { +- return new AnalysisGetLibraryDependenciesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["libraries"] =3D libraries; +- result["packageMap"] =3D packageMap; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetLibraryDependenciesResult) { +- return listEqual( +- libraries, other.libraries, (String a, String b) =3D> a =3D= =3D b) && +- mapEqual( +- packageMap, +- other.packageMap, +- (Map> a, Map> b) = =3D> +- mapEqual( +- a, +- b, +- (List a, List b) =3D> +- listEqual(a, b, (String a, String b) =3D> a =3D= =3D b))); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, libraries.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, packageMap.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getNavigation params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetNavigationParams implements RequestParams { +- String _file; +- +- int _offset; +- +- int _length; +- +- /** +- * The file in which navigation information is being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file in which navigation information is being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the region for which navigation information is being +- * requested. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the region for which navigation information is being +- * requested. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the region for which navigation information is being +- * requested. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the region for which navigation information is being +- * requested. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- AnalysisGetNavigationParams(String file, int offset, int length) { +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- factory AnalysisGetNavigationParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- return new AnalysisGetNavigationParams(file, offset, length); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getNavigation params", json); +- } +- } +- +- factory AnalysisGetNavigationParams.fromRequest(Request request) { +- return new AnalysisGetNavigationParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["length"] =3D length; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.getNavigation", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetNavigationParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- length =3D=3D other.length; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getNavigation result +- * +- * { +- * "files": List +- * "targets": List +- * "regions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetNavigationResult implements ResponseResult { +- List _files; +- +- List _targets; +- +- List _regions; +- +- /** +- * A list of the paths of files that are referenced by the navigation +- * targets. +- */ +- List get files =3D> _files; +- +- /** +- * A list of the paths of files that are referenced by the navigation +- * targets. +- */ +- void set files(List value) { +- assert(value !=3D null); +- this._files =3D value; +- } +- +- /** +- * A list of the navigation targets that are referenced by the navigati= on +- * regions. +- */ +- List get targets =3D> _targets; +- +- /** +- * A list of the navigation targets that are referenced by the navigati= on +- * regions. +- */ +- void set targets(List value) { +- assert(value !=3D null); +- this._targets =3D value; +- } +- +- /** +- * A list of the navigation regions within the requested region of the = file. +- */ +- List get regions =3D> _regions; +- +- /** +- * A list of the navigation regions within the requested region of the = file. +- */ +- void set regions(List value) { +- assert(value !=3D null); +- this._regions =3D value; +- } +- +- AnalysisGetNavigationResult(List files, +- List targets, List regions) { +- this.files =3D files; +- this.targets =3D targets; +- this.regions =3D regions; +- } +- +- factory AnalysisGetNavigationResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List files; +- if (json.containsKey("files")) { +- files =3D jsonDecoder.decodeList( +- jsonPath + ".files", json["files"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "files"); +- } +- List targets; +- if (json.containsKey("targets")) { +- targets =3D jsonDecoder.decodeList( +- jsonPath + ".targets", +- json["targets"], +- (String jsonPath, Object json) =3D> +- new NavigationTarget.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "targets"); +- } +- List regions; +- if (json.containsKey("regions")) { +- regions =3D jsonDecoder.decodeList( +- jsonPath + ".regions", +- json["regions"], +- (String jsonPath, Object json) =3D> +- new NavigationRegion.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "regions"); +- } +- return new AnalysisGetNavigationResult(files, targets, regions); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getNavigation result", json); +- } +- } +- +- factory AnalysisGetNavigationResult.fromResponse(Response response) { +- return new AnalysisGetNavigationResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["files"] =3D files; +- result["targets"] =3D +- targets.map((NavigationTarget value) =3D> value.toJson()).toList(= ); +- result["regions"] =3D +- regions.map((NavigationRegion value) =3D> value.toJson()).toList(= ); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetNavigationResult) { +- return listEqual(files, other.files, (String a, String b) =3D> a = =3D=3D b) && +- listEqual(targets, other.targets, +- (NavigationTarget a, NavigationTarget b) =3D> a =3D=3D b) && +- listEqual(regions, other.regions, +- (NavigationRegion a, NavigationRegion b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, files.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, targets.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, regions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getReachableSources params +- * +- * { +- * "file": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetReachableSourcesParams implements RequestParams { +- String _file; +- +- /** +- * The file for which reachable source information is being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file for which reachable source information is being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- AnalysisGetReachableSourcesParams(String file) { +- this.file =3D file; +- } +- +- factory AnalysisGetReachableSourcesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- return new AnalysisGetReachableSourcesParams(file); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getReachableSources params", json); +- } +- } +- +- factory AnalysisGetReachableSourcesParams.fromRequest(Request request) { +- return new AnalysisGetReachableSourcesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.getReachableSources", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetReachableSourcesParams) { +- return file =3D=3D other.file; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.getReachableSources result +- * +- * { +- * "sources": Map> +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisGetReachableSourcesResult implements ResponseResult { +- Map> _sources; +- +- /** +- * A mapping from source URIs to directly reachable source URIs. For ex= ample, +- * a file "foo.dart" that imports "bar.dart" would have the correspondi= ng +- * mapping { "file:///foo.dart" : ["file:///bar.dart"] }. If "bar.dart"= has +- * further imports (or exports) there will be a mapping from the URI +- * "file:///bar.dart" to them. To check if a specific URI is reachable = from a +- * given file, clients can check for its presence in the resulting key = set. +- */ +- Map> get sources =3D> _sources; +- +- /** +- * A mapping from source URIs to directly reachable source URIs. For ex= ample, +- * a file "foo.dart" that imports "bar.dart" would have the correspondi= ng +- * mapping { "file:///foo.dart" : ["file:///bar.dart"] }. If "bar.dart"= has +- * further imports (or exports) there will be a mapping from the URI +- * "file:///bar.dart" to them. To check if a specific URI is reachable = from a +- * given file, clients can check for its presence in the resulting key = set. +- */ +- void set sources(Map> value) { +- assert(value !=3D null); +- this._sources =3D value; +- } +- +- AnalysisGetReachableSourcesResult(Map> sources) { +- this.sources =3D sources; +- } +- +- factory AnalysisGetReachableSourcesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- Map> sources; +- if (json.containsKey("sources")) { +- sources =3D jsonDecoder.decodeMap(jsonPath + ".sources", json["so= urces"], +- valueDecoder: (String jsonPath, Object json) =3D> jsonDecoder +- .decodeList(jsonPath, json, jsonDecoder.decodeString)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "sources"); +- } +- return new AnalysisGetReachableSourcesResult(sources); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.getReachableSources result", json); +- } +- } +- +- factory AnalysisGetReachableSourcesResult.fromResponse(Response respons= e) { +- return new AnalysisGetReachableSourcesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["sources"] =3D sources; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisGetReachableSourcesResult) { +- return mapEqual( +- sources, +- other.sources, +- (List a, List b) =3D> +- listEqual(a, b, (String a, String b) =3D> a =3D=3D b)); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, sources.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.highlights params +- * +- * { +- * "file": FilePath +- * "regions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisHighlightsParams implements HasToJson { +- String _file; +- +- List _regions; +- +- /** +- * The file containing the highlight regions. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the highlight regions. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The highlight regions contained in the file. Each highlight region +- * represents a particular syntactic or semantic meaning associated wit= h some +- * range. Note that the highlight regions that are returned can overlap= other +- * highlight regions if there is more than one meaning associated with a +- * particular region. +- */ +- List get regions =3D> _regions; +- +- /** +- * The highlight regions contained in the file. Each highlight region +- * represents a particular syntactic or semantic meaning associated wit= h some +- * range. Note that the highlight regions that are returned can overlap= other +- * highlight regions if there is more than one meaning associated with a +- * particular region. +- */ +- void set regions(List value) { +- assert(value !=3D null); +- this._regions =3D value; +- } +- +- AnalysisHighlightsParams(String file, List regions) { +- this.file =3D file; +- this.regions =3D regions; +- } +- +- factory AnalysisHighlightsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List regions; +- if (json.containsKey("regions")) { +- regions =3D jsonDecoder.decodeList( +- jsonPath + ".regions", +- json["regions"], +- (String jsonPath, Object json) =3D> +- new HighlightRegion.fromJson(jsonDecoder, jsonPath, json)= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "regions"); +- } +- return new AnalysisHighlightsParams(file, regions); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.highlights params", = json); +- } +- } +- +- factory AnalysisHighlightsParams.fromNotification(Notification notifica= tion) { +- return new AnalysisHighlightsParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["regions"] =3D +- regions.map((HighlightRegion value) =3D> value.toJson()).toList(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.highlights", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisHighlightsParams) { +- return file =3D=3D other.file && +- listEqual(regions, other.regions, +- (HighlightRegion a, HighlightRegion b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, regions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.implemented params +- * +- * { +- * "file": FilePath +- * "classes": List +- * "members": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisImplementedParams implements HasToJson { +- String _file; +- +- List _classes; +- +- List _members; +- +- /** +- * The file with which the implementations are associated. +- */ +- String get file =3D> _file; +- +- /** +- * The file with which the implementations are associated. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The classes defined in the file that are implemented or extended. +- */ +- List get classes =3D> _classes; +- +- /** +- * The classes defined in the file that are implemented or extended. +- */ +- void set classes(List value) { +- assert(value !=3D null); +- this._classes =3D value; +- } +- +- /** +- * The member defined in the file that are implemented or overridden. +- */ +- List get members =3D> _members; +- +- /** +- * The member defined in the file that are implemented or overridden. +- */ +- void set members(List value) { +- assert(value !=3D null); +- this._members =3D value; +- } +- +- AnalysisImplementedParams(String file, List classes, +- List members) { +- this.file =3D file; +- this.classes =3D classes; +- this.members =3D members; +- } +- +- factory AnalysisImplementedParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List classes; +- if (json.containsKey("classes")) { +- classes =3D jsonDecoder.decodeList( +- jsonPath + ".classes", +- json["classes"], +- (String jsonPath, Object json) =3D> +- new ImplementedClass.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "classes"); +- } +- List members; +- if (json.containsKey("members")) { +- members =3D jsonDecoder.decodeList( +- jsonPath + ".members", +- json["members"], +- (String jsonPath, Object json) =3D> +- new ImplementedMember.fromJson(jsonDecoder, jsonPath, jso= n)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "members"); +- } +- return new AnalysisImplementedParams(file, classes, members); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.implemented params",= json); +- } +- } +- +- factory AnalysisImplementedParams.fromNotification( +- Notification notification) { +- return new AnalysisImplementedParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["classes"] =3D +- classes.map((ImplementedClass value) =3D> value.toJson()).toList(= ); +- result["members"] =3D +- members.map((ImplementedMember value) =3D> value.toJson()).toList= (); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.implemented", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisImplementedParams) { +- return file =3D=3D other.file && +- listEqual(classes, other.classes, +- (ImplementedClass a, ImplementedClass b) =3D> a =3D=3D b) && +- listEqual(members, other.members, +- (ImplementedMember a, ImplementedMember b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, classes.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, members.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.invalidate params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * "delta": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisInvalidateParams implements HasToJson { +- String _file; +- +- int _offset; +- +- int _length; +- +- int _delta; +- +- /** +- * The file whose information has been invalidated. +- */ +- String get file =3D> _file; +- +- /** +- * The file whose information has been invalidated. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the invalidated region. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the invalidated region. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the invalidated region. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the invalidated region. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * The delta to be applied to the offsets in information that follows t= he +- * invalidated region in order to update it so that it doesn't need to = be +- * re-requested. +- */ +- int get delta =3D> _delta; +- +- /** +- * The delta to be applied to the offsets in information that follows t= he +- * invalidated region in order to update it so that it doesn't need to = be +- * re-requested. +- */ +- void set delta(int value) { +- assert(value !=3D null); +- this._delta =3D value; +- } +- +- AnalysisInvalidateParams(String file, int offset, int length, int delta= ) { +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- this.delta =3D delta; +- } +- +- factory AnalysisInvalidateParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- int delta; +- if (json.containsKey("delta")) { +- delta =3D jsonDecoder.decodeInt(jsonPath + ".delta", json["delta"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "delta"); +- } +- return new AnalysisInvalidateParams(file, offset, length, delta); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.invalidate params", = json); +- } +- } +- +- factory AnalysisInvalidateParams.fromNotification(Notification notifica= tion) { +- return new AnalysisInvalidateParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["length"] =3D length; +- result["delta"] =3D delta; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.invalidate", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisInvalidateParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- length =3D=3D other.length && +- delta =3D=3D other.delta; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, delta.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.navigation params +- * +- * { +- * "file": FilePath +- * "regions": List +- * "targets": List +- * "files": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisNavigationParams implements HasToJson { +- String _file; +- +- List _regions; +- +- List _targets; +- +- List _files; +- +- /** +- * The file containing the navigation regions. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the navigation regions. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The navigation regions contained in the file. The regions are sorted= by +- * their offsets. Each navigation region represents a list of targets +- * associated with some range. The lists will usually contain a single +- * target, but can contain more in the case of a part that is included = in +- * multiple libraries or in Dart code that is compiled against multiple +- * versions of a package. Note that the navigation regions that are ret= urned +- * do not overlap other navigation regions. +- */ +- List get regions =3D> _regions; +- +- /** +- * The navigation regions contained in the file. The regions are sorted= by +- * their offsets. Each navigation region represents a list of targets +- * associated with some range. The lists will usually contain a single +- * target, but can contain more in the case of a part that is included = in +- * multiple libraries or in Dart code that is compiled against multiple +- * versions of a package. Note that the navigation regions that are ret= urned +- * do not overlap other navigation regions. +- */ +- void set regions(List value) { +- assert(value !=3D null); +- this._regions =3D value; +- } +- +- /** +- * The navigation targets referenced in the file. They are referenced by +- * NavigationRegions by their index in this array. +- */ +- List get targets =3D> _targets; +- +- /** +- * The navigation targets referenced in the file. They are referenced by +- * NavigationRegions by their index in this array. +- */ +- void set targets(List value) { +- assert(value !=3D null); +- this._targets =3D value; +- } +- +- /** +- * The files containing navigation targets referenced in the file. They= are +- * referenced by NavigationTargets by their index in this array. +- */ +- List get files =3D> _files; +- +- /** +- * The files containing navigation targets referenced in the file. They= are +- * referenced by NavigationTargets by their index in this array. +- */ +- void set files(List value) { +- assert(value !=3D null); +- this._files =3D value; +- } +- +- AnalysisNavigationParams(String file, List regions, +- List targets, List files) { +- this.file =3D file; +- this.regions =3D regions; +- this.targets =3D targets; +- this.files =3D files; +- } +- +- factory AnalysisNavigationParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List regions; +- if (json.containsKey("regions")) { +- regions =3D jsonDecoder.decodeList( +- jsonPath + ".regions", +- json["regions"], +- (String jsonPath, Object json) =3D> +- new NavigationRegion.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "regions"); +- } +- List targets; +- if (json.containsKey("targets")) { +- targets =3D jsonDecoder.decodeList( +- jsonPath + ".targets", +- json["targets"], +- (String jsonPath, Object json) =3D> +- new NavigationTarget.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "targets"); +- } +- List files; +- if (json.containsKey("files")) { +- files =3D jsonDecoder.decodeList( +- jsonPath + ".files", json["files"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "files"); +- } +- return new AnalysisNavigationParams(file, regions, targets, files); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.navigation params", = json); +- } +- } +- +- factory AnalysisNavigationParams.fromNotification(Notification notifica= tion) { +- return new AnalysisNavigationParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["regions"] =3D +- regions.map((NavigationRegion value) =3D> value.toJson()).toList(= ); +- result["targets"] =3D +- targets.map((NavigationTarget value) =3D> value.toJson()).toList(= ); +- result["files"] =3D files; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.navigation", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisNavigationParams) { +- return file =3D=3D other.file && +- listEqual(regions, other.regions, +- (NavigationRegion a, NavigationRegion b) =3D> a =3D=3D b) && +- listEqual(targets, other.targets, +- (NavigationTarget a, NavigationTarget b) =3D> a =3D=3D b) && +- listEqual(files, other.files, (String a, String b) =3D> a =3D= =3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, regions.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, targets.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, files.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.occurrences params +- * +- * { +- * "file": FilePath +- * "occurrences": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisOccurrencesParams implements HasToJson { +- String _file; +- +- List _occurrences; +- +- /** +- * The file in which the references occur. +- */ +- String get file =3D> _file; +- +- /** +- * The file in which the references occur. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The occurrences of references to elements within the file. +- */ +- List get occurrences =3D> _occurrences; +- +- /** +- * The occurrences of references to elements within the file. +- */ +- void set occurrences(List value) { +- assert(value !=3D null); +- this._occurrences =3D value; +- } +- +- AnalysisOccurrencesParams(String file, List occurrences) { +- this.file =3D file; +- this.occurrences =3D occurrences; +- } +- +- factory AnalysisOccurrencesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List occurrences; +- if (json.containsKey("occurrences")) { +- occurrences =3D jsonDecoder.decodeList( +- jsonPath + ".occurrences", +- json["occurrences"], +- (String jsonPath, Object json) =3D> +- new Occurrences.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "occurrences"); +- } +- return new AnalysisOccurrencesParams(file, occurrences); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.occurrences params",= json); +- } +- } +- +- factory AnalysisOccurrencesParams.fromNotification( +- Notification notification) { +- return new AnalysisOccurrencesParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["occurrences"] =3D +- occurrences.map((Occurrences value) =3D> value.toJson()).toList(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.occurrences", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisOccurrencesParams) { +- return file =3D=3D other.file && +- listEqual(occurrences, other.occurrences, +- (Occurrences a, Occurrences b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, occurrences.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * AnalysisOptions +- * +- * { +- * "enableAsync": optional bool +- * "enableDeferredLoading": optional bool +- * "enableEnums": optional bool +- * "enableNullAwareOperators": optional bool +- * "enableSuperMixins": optional bool +- * "generateDart2jsHints": optional bool +- * "generateHints": optional bool +- * "generateLints": optional bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisOptions implements HasToJson { +- bool _enableAsync; +- +- bool _enableDeferredLoading; +- +- bool _enableEnums; +- +- bool _enableNullAwareOperators; +- +- bool _enableSuperMixins; +- +- bool _generateDart2jsHints; +- +- bool _generateHints; +- +- bool _generateLints; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed async fe= ature. +- */ +- bool get enableAsync =3D> _enableAsync; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed async fe= ature. +- */ +- void set enableAsync(bool value) { +- this._enableAsync =3D value; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed deferred +- * loading feature. +- */ +- bool get enableDeferredLoading =3D> _enableDeferredLoading; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed deferred +- * loading feature. +- */ +- void set enableDeferredLoading(bool value) { +- this._enableDeferredLoading =3D value; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed enum fea= ture. +- */ +- bool get enableEnums =3D> _enableEnums; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed enum fea= ture. +- */ +- void set enableEnums(bool value) { +- this._enableEnums =3D value; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed "null aw= are +- * operators" feature. +- */ +- bool get enableNullAwareOperators =3D> _enableNullAwareOperators; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed "null aw= are +- * operators" feature. +- */ +- void set enableNullAwareOperators(bool value) { +- this._enableNullAwareOperators =3D value; +- } +- +- /** +- * True if the client wants to enable support for the proposed "less +- * restricted mixins" proposal (DEP 34). +- */ +- bool get enableSuperMixins =3D> _enableSuperMixins; +- +- /** +- * True if the client wants to enable support for the proposed "less +- * restricted mixins" proposal (DEP 34). +- */ +- void set enableSuperMixins(bool value) { +- this._enableSuperMixins =3D value; +- } +- +- /** +- * True if hints that are specific to dart2js should be generated. This +- * option is ignored if generateHints is false. +- */ +- bool get generateDart2jsHints =3D> _generateDart2jsHints; +- +- /** +- * True if hints that are specific to dart2js should be generated. This +- * option is ignored if generateHints is false. +- */ +- void set generateDart2jsHints(bool value) { +- this._generateDart2jsHints =3D value; +- } +- +- /** +- * True if hints should be generated as part of generating errors and +- * warnings. +- */ +- bool get generateHints =3D> _generateHints; +- +- /** +- * True if hints should be generated as part of generating errors and +- * warnings. +- */ +- void set generateHints(bool value) { +- this._generateHints =3D value; +- } +- +- /** +- * True if lints should be generated as part of generating errors and +- * warnings. +- */ +- bool get generateLints =3D> _generateLints; +- +- /** +- * True if lints should be generated as part of generating errors and +- * warnings. +- */ +- void set generateLints(bool value) { +- this._generateLints =3D value; +- } +- +- AnalysisOptions( +- {bool enableAsync, +- bool enableDeferredLoading, +- bool enableEnums, +- bool enableNullAwareOperators, +- bool enableSuperMixins, +- bool generateDart2jsHints, +- bool generateHints, +- bool generateLints}) { +- this.enableAsync =3D enableAsync; +- this.enableDeferredLoading =3D enableDeferredLoading; +- this.enableEnums =3D enableEnums; +- this.enableNullAwareOperators =3D enableNullAwareOperators; +- this.enableSuperMixins =3D enableSuperMixins; +- this.generateDart2jsHints =3D generateDart2jsHints; +- this.generateHints =3D generateHints; +- this.generateLints =3D generateLints; +- } +- +- factory AnalysisOptions.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool enableAsync; +- if (json.containsKey("enableAsync")) { +- enableAsync =3D jsonDecoder.decodeBool( +- jsonPath + ".enableAsync", json["enableAsync"]); +- } +- bool enableDeferredLoading; +- if (json.containsKey("enableDeferredLoading")) { +- enableDeferredLoading =3D jsonDecoder.decodeBool( +- jsonPath + ".enableDeferredLoading", json["enableDeferredLoad= ing"]); +- } +- bool enableEnums; +- if (json.containsKey("enableEnums")) { +- enableEnums =3D jsonDecoder.decodeBool( +- jsonPath + ".enableEnums", json["enableEnums"]); +- } +- bool enableNullAwareOperators; +- if (json.containsKey("enableNullAwareOperators")) { +- enableNullAwareOperators =3D jsonDecoder.decodeBool( +- jsonPath + ".enableNullAwareOperators", +- json["enableNullAwareOperators"]); +- } +- bool enableSuperMixins; +- if (json.containsKey("enableSuperMixins")) { +- enableSuperMixins =3D jsonDecoder.decodeBool( +- jsonPath + ".enableSuperMixins", json["enableSuperMixins"]); +- } +- bool generateDart2jsHints; +- if (json.containsKey("generateDart2jsHints")) { +- generateDart2jsHints =3D jsonDecoder.decodeBool( +- jsonPath + ".generateDart2jsHints", json["generateDart2jsHint= s"]); +- } +- bool generateHints; +- if (json.containsKey("generateHints")) { +- generateHints =3D jsonDecoder.decodeBool( +- jsonPath + ".generateHints", json["generateHints"]); +- } +- bool generateLints; +- if (json.containsKey("generateLints")) { +- generateLints =3D jsonDecoder.decodeBool( +- jsonPath + ".generateLints", json["generateLints"]); +- } +- return new AnalysisOptions( +- enableAsync: enableAsync, +- enableDeferredLoading: enableDeferredLoading, +- enableEnums: enableEnums, +- enableNullAwareOperators: enableNullAwareOperators, +- enableSuperMixins: enableSuperMixins, +- generateDart2jsHints: generateDart2jsHints, +- generateHints: generateHints, +- generateLints: generateLints); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "AnalysisOptions", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (enableAsync !=3D null) { +- result["enableAsync"] =3D enableAsync; +- } +- if (enableDeferredLoading !=3D null) { +- result["enableDeferredLoading"] =3D enableDeferredLoading; +- } +- if (enableEnums !=3D null) { +- result["enableEnums"] =3D enableEnums; +- } +- if (enableNullAwareOperators !=3D null) { +- result["enableNullAwareOperators"] =3D enableNullAwareOperators; +- } +- if (enableSuperMixins !=3D null) { +- result["enableSuperMixins"] =3D enableSuperMixins; +- } +- if (generateDart2jsHints !=3D null) { +- result["generateDart2jsHints"] =3D generateDart2jsHints; +- } +- if (generateHints !=3D null) { +- result["generateHints"] =3D generateHints; +- } +- if (generateLints !=3D null) { +- result["generateLints"] =3D generateLints; +- } +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisOptions) { +- return enableAsync =3D=3D other.enableAsync && +- enableDeferredLoading =3D=3D other.enableDeferredLoading && +- enableEnums =3D=3D other.enableEnums && +- enableNullAwareOperators =3D=3D other.enableNullAwareOperators = && +- enableSuperMixins =3D=3D other.enableSuperMixins && +- generateDart2jsHints =3D=3D other.generateDart2jsHints && +- generateHints =3D=3D other.generateHints && +- generateLints =3D=3D other.generateLints; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, enableAsync.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, enableDeferredLoading.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, enableEnums.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, enableNullAwareOperators.hashCo= de); +- hash =3D JenkinsSmiHash.combine(hash, enableSuperMixins.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, generateDart2jsHints.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, generateHints.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, generateLints.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.outline params +- * +- * { +- * "file": FilePath +- * "kind": FileKind +- * "libraryName": optional String +- * "outline": Outline +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisOutlineParams implements HasToJson { +- String _file; +- +- FileKind _kind; +- +- String _libraryName; +- +- Outline _outline; +- +- /** +- * The file with which the outline is associated. +- */ +- String get file =3D> _file; +- +- /** +- * The file with which the outline is associated. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The kind of the file. +- */ +- FileKind get kind =3D> _kind; +- +- /** +- * The kind of the file. +- */ +- void set kind(FileKind value) { +- assert(value !=3D null); +- this._kind =3D value; +- } +- +- /** +- * The name of the library defined by the file using a "library" direct= ive, +- * or referenced by a "part of" directive. If both "library" and "part = of" +- * directives are present, then the "library" directive takes precedenc= e. +- * This field will be omitted if the file has neither "library" nor "pa= rt of" +- * directives. +- */ +- String get libraryName =3D> _libraryName; +- +- /** +- * The name of the library defined by the file using a "library" direct= ive, +- * or referenced by a "part of" directive. If both "library" and "part = of" +- * directives are present, then the "library" directive takes precedenc= e. +- * This field will be omitted if the file has neither "library" nor "pa= rt of" +- * directives. +- */ +- void set libraryName(String value) { +- this._libraryName =3D value; +- } +- +- /** +- * The outline associated with the file. +- */ +- Outline get outline =3D> _outline; +- +- /** +- * The outline associated with the file. +- */ +- void set outline(Outline value) { +- assert(value !=3D null); +- this._outline =3D value; +- } +- +- AnalysisOutlineParams(String file, FileKind kind, Outline outline, +- {String libraryName}) { +- this.file =3D file; +- this.kind =3D kind; +- this.libraryName =3D libraryName; +- this.outline =3D outline; +- } +- +- factory AnalysisOutlineParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- FileKind kind; +- if (json.containsKey("kind")) { +- kind =3D new FileKind.fromJson( +- jsonDecoder, jsonPath + ".kind", json["kind"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "kind"); +- } +- String libraryName; +- if (json.containsKey("libraryName")) { +- libraryName =3D jsonDecoder.decodeString( +- jsonPath + ".libraryName", json["libraryName"]); +- } +- Outline outline; +- if (json.containsKey("outline")) { +- outline =3D new Outline.fromJson( +- jsonDecoder, jsonPath + ".outline", json["outline"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "outline"); +- } +- return new AnalysisOutlineParams(file, kind, outline, +- libraryName: libraryName); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.outline params", jso= n); +- } +- } +- +- factory AnalysisOutlineParams.fromNotification(Notification notificatio= n) { +- return new AnalysisOutlineParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["kind"] =3D kind.toJson(); +- if (libraryName !=3D null) { +- result["libraryName"] =3D libraryName; +- } +- result["outline"] =3D outline.toJson(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.outline", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisOutlineParams) { +- return file =3D=3D other.file && +- kind =3D=3D other.kind && +- libraryName =3D=3D other.libraryName && +- outline =3D=3D other.outline; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, kind.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, libraryName.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, outline.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.overrides params +- * +- * { +- * "file": FilePath +- * "overrides": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisOverridesParams implements HasToJson { +- String _file; +- +- List _overrides; +- +- /** +- * The file with which the overrides are associated. +- */ +- String get file =3D> _file; +- +- /** +- * The file with which the overrides are associated. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The overrides associated with the file. +- */ +- List get overrides =3D> _overrides; +- +- /** +- * The overrides associated with the file. +- */ +- void set overrides(List value) { +- assert(value !=3D null); +- this._overrides =3D value; +- } +- +- AnalysisOverridesParams(String file, List overrides) { +- this.file =3D file; +- this.overrides =3D overrides; +- } +- +- factory AnalysisOverridesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List overrides; +- if (json.containsKey("overrides")) { +- overrides =3D jsonDecoder.decodeList( +- jsonPath + ".overrides", +- json["overrides"], +- (String jsonPath, Object json) =3D> +- new Override.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "overrides"); +- } +- return new AnalysisOverridesParams(file, overrides); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.overrides params", j= son); +- } +- } +- +- factory AnalysisOverridesParams.fromNotification(Notification notificat= ion) { +- return new AnalysisOverridesParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["overrides"] =3D +- overrides.map((Override value) =3D> value.toJson()).toList(); +- return result; +- } +- +- Notification toNotification() { +- return new Notification("analysis.overrides", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisOverridesParams) { +- return file =3D=3D other.file && +- listEqual( +- overrides, other.overrides, (Override a, Override b) =3D> a= =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, overrides.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.reanalyze params +- * +- * { +- * "roots": optional List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisReanalyzeParams implements RequestParams { +- List _roots; +- +- /** +- * A list of the analysis roots that are to be re-analyzed. +- */ +- List get roots =3D> _roots; +- +- /** +- * A list of the analysis roots that are to be re-analyzed. +- */ +- void set roots(List value) { +- this._roots =3D value; +- } +- +- AnalysisReanalyzeParams({List roots}) { +- this.roots =3D roots; +- } +- +- factory AnalysisReanalyzeParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List roots; +- if (json.containsKey("roots")) { +- roots =3D jsonDecoder.decodeList( +- jsonPath + ".roots", json["roots"], jsonDecoder.decodeString); +- } +- return new AnalysisReanalyzeParams(roots: roots); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analysis.reanalyze params", j= son); +- } +- } +- +- factory AnalysisReanalyzeParams.fromRequest(Request request) { +- return new AnalysisReanalyzeParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (roots !=3D null) { +- result["roots"] =3D roots; +- } +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.reanalyze", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisReanalyzeParams) { +- return listEqual(roots, other.roots, (String a, String b) =3D> a = =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, roots.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.reanalyze result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisReanalyzeResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisReanalyzeResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 846803925; +- } +-} +- +-/** +- * AnalysisService +- * +- * enum { +- * CLOSING_LABELS +- * FOLDING +- * HIGHLIGHTS +- * IMPLEMENTED +- * INVALIDATE +- * NAVIGATION +- * OCCURRENCES +- * OUTLINE +- * OVERRIDES +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisService implements Enum { +- static const AnalysisService CLOSING_LABELS =3D +- const AnalysisService._("CLOSING_LABELS"); +- +- static const AnalysisService FOLDING =3D const AnalysisService._("FOLDI= NG"); +- +- static const AnalysisService HIGHLIGHTS =3D +- const AnalysisService._("HIGHLIGHTS"); +- +- static const AnalysisService IMPLEMENTED =3D +- const AnalysisService._("IMPLEMENTED"); +- +- /** +- * This service is not currently implemented and will become a +- * GeneralAnalysisService in a future release. +- */ +- static const AnalysisService INVALIDATE =3D +- const AnalysisService._("INVALIDATE"); +- +- static const AnalysisService NAVIGATION =3D +- const AnalysisService._("NAVIGATION"); +- +- static const AnalysisService OCCURRENCES =3D +- const AnalysisService._("OCCURRENCES"); +- +- static const AnalysisService OUTLINE =3D const AnalysisService._("OUTLI= NE"); +- +- static const AnalysisService OVERRIDES =3D const AnalysisService._("OVE= RRIDES"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [ +- CLOSING_LABELS, +- FOLDING, +- HIGHLIGHTS, +- IMPLEMENTED, +- INVALIDATE, +- NAVIGATION, +- OCCURRENCES, +- OUTLINE, +- OVERRIDES +- ]; +- +- @override +- final String name; +- +- const AnalysisService._(this.name); +- +- factory AnalysisService(String name) { +- switch (name) { +- case "CLOSING_LABELS": +- return CLOSING_LABELS; +- case "FOLDING": +- return FOLDING; +- case "HIGHLIGHTS": +- return HIGHLIGHTS; +- case "IMPLEMENTED": +- return IMPLEMENTED; +- case "INVALIDATE": +- return INVALIDATE; +- case "NAVIGATION": +- return NAVIGATION; +- case "OCCURRENCES": +- return OCCURRENCES; +- case "OUTLINE": +- return OUTLINE; +- case "OVERRIDES": +- return OVERRIDES; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory AnalysisService.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new AnalysisService(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "AnalysisService", json); +- } +- +- @override +- String toString() =3D> "AnalysisService.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * analysis.setAnalysisRoots params +- * +- * { +- * "included": List +- * "excluded": List +- * "packageRoots": optional Map +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetAnalysisRootsParams implements RequestParams { +- List _included; +- +- List _excluded; +- +- Map _packageRoots; +- +- /** +- * A list of the files and directories that should be analyzed. +- */ +- List get included =3D> _included; +- +- /** +- * A list of the files and directories that should be analyzed. +- */ +- void set included(List value) { +- assert(value !=3D null); +- this._included =3D value; +- } +- +- /** +- * A list of the files and directories within the included directories = that +- * should not be analyzed. +- */ +- List get excluded =3D> _excluded; +- +- /** +- * A list of the files and directories within the included directories = that +- * should not be analyzed. +- */ +- void set excluded(List value) { +- assert(value !=3D null); +- this._excluded =3D value; +- } +- +- /** +- * A mapping from source directories to package roots that should overr= ide +- * the normal package: URI resolution mechanism. +- * +- * If a package root is a directory, then the analyzer will behave as t= hough +- * the associated source directory in the map contains a special pubspe= c.yaml +- * file which resolves any package: URI to the corresponding path withi= n that +- * package root directory. The effect is the same as specifying the pac= kage +- * root directory as a "--package_root" parameter to the Dart VM when +- * executing any Dart file inside the source directory. +- * +- * If a package root is a file, then the analyzer will behave as though= that +- * file is a ".packages" file in the source directory. The effect is th= e same +- * as specifying the file as a "--packages" parameter to the Dart VM wh= en +- * executing any Dart file inside the source directory. +- * +- * Files in any directories that are not overridden by this mapping have +- * their package: URI's resolved using the normal pubspec.yaml mechanis= m. If +- * this field is absent, or the empty map is specified, that indicates = that +- * the normal pubspec.yaml mechanism should always be used. +- */ +- Map get packageRoots =3D> _packageRoots; +- +- /** +- * A mapping from source directories to package roots that should overr= ide +- * the normal package: URI resolution mechanism. +- * +- * If a package root is a directory, then the analyzer will behave as t= hough +- * the associated source directory in the map contains a special pubspe= c.yaml +- * file which resolves any package: URI to the corresponding path withi= n that +- * package root directory. The effect is the same as specifying the pac= kage +- * root directory as a "--package_root" parameter to the Dart VM when +- * executing any Dart file inside the source directory. +- * +- * If a package root is a file, then the analyzer will behave as though= that +- * file is a ".packages" file in the source directory. The effect is th= e same +- * as specifying the file as a "--packages" parameter to the Dart VM wh= en +- * executing any Dart file inside the source directory. +- * +- * Files in any directories that are not overridden by this mapping have +- * their package: URI's resolved using the normal pubspec.yaml mechanis= m. If +- * this field is absent, or the empty map is specified, that indicates = that +- * the normal pubspec.yaml mechanism should always be used. +- */ +- void set packageRoots(Map value) { +- this._packageRoots =3D value; +- } +- +- AnalysisSetAnalysisRootsParams(List included, List excl= uded, +- {Map packageRoots}) { +- this.included =3D included; +- this.excluded =3D excluded; +- this.packageRoots =3D packageRoots; +- } +- +- factory AnalysisSetAnalysisRootsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List included; +- if (json.containsKey("included")) { +- included =3D jsonDecoder.decodeList( +- jsonPath + ".included", json["included"], jsonDecoder.decodeS= tring); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "included"); +- } +- List excluded; +- if (json.containsKey("excluded")) { +- excluded =3D jsonDecoder.decodeList( +- jsonPath + ".excluded", json["excluded"], jsonDecoder.decodeS= tring); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "excluded"); +- } +- Map packageRoots; +- if (json.containsKey("packageRoots")) { +- packageRoots =3D jsonDecoder.decodeMap( +- jsonPath + ".packageRoots", json["packageRoots"], +- valueDecoder: jsonDecoder.decodeString); +- } +- return new AnalysisSetAnalysisRootsParams(included, excluded, +- packageRoots: packageRoots); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.setAnalysisRoots params", json); +- } +- } +- +- factory AnalysisSetAnalysisRootsParams.fromRequest(Request request) { +- return new AnalysisSetAnalysisRootsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["included"] =3D included; +- result["excluded"] =3D excluded; +- if (packageRoots !=3D null) { +- result["packageRoots"] =3D packageRoots; +- } +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.setAnalysisRoots", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetAnalysisRootsParams) { +- return listEqual( +- included, other.included, (String a, String b) =3D> a =3D= =3D b) && +- listEqual(excluded, other.excluded, (String a, String b) =3D> a= =3D=3D b) && +- mapEqual( +- packageRoots, other.packageRoots, (String a, String b) =3D>= a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, included.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, excluded.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, packageRoots.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.setAnalysisRoots result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetAnalysisRootsResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetAnalysisRootsResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 866004753; +- } +-} +- +-/** +- * analysis.setGeneralSubscriptions params +- * +- * { +- * "subscriptions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetGeneralSubscriptionsParams implements RequestParams { +- List _subscriptions; +- +- /** +- * A list of the services being subscribed to. +- */ +- List get subscriptions =3D> _subscriptions; +- +- /** +- * A list of the services being subscribed to. +- */ +- void set subscriptions(List value) { +- assert(value !=3D null); +- this._subscriptions =3D value; +- } +- +- AnalysisSetGeneralSubscriptionsParams( +- List subscriptions) { +- this.subscriptions =3D subscriptions; +- } +- +- factory AnalysisSetGeneralSubscriptionsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List subscriptions; +- if (json.containsKey("subscriptions")) { +- subscriptions =3D jsonDecoder.decodeList( +- jsonPath + ".subscriptions", +- json["subscriptions"], +- (String jsonPath, Object json) =3D> +- new GeneralAnalysisService.fromJson( +- jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "subscriptions"); +- } +- return new AnalysisSetGeneralSubscriptionsParams(subscriptions); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.setGeneralSubscriptions params", json); +- } +- } +- +- factory AnalysisSetGeneralSubscriptionsParams.fromRequest(Request reque= st) { +- return new AnalysisSetGeneralSubscriptionsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["subscriptions"] =3D subscriptions +- .map((GeneralAnalysisService value) =3D> value.toJson()) +- .toList(); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.setGeneralSubscriptions", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetGeneralSubscriptionsParams) { +- return listEqual(subscriptions, other.subscriptions, +- (GeneralAnalysisService a, GeneralAnalysisService b) =3D> a =3D= =3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, subscriptions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.setGeneralSubscriptions result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetGeneralSubscriptionsResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetGeneralSubscriptionsResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 386759562; +- } +-} +- +-/** +- * analysis.setPriorityFiles params +- * +- * { +- * "files": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetPriorityFilesParams implements RequestParams { +- List _files; +- +- /** +- * The files that are to be a priority for analysis. +- */ +- List get files =3D> _files; +- +- /** +- * The files that are to be a priority for analysis. +- */ +- void set files(List value) { +- assert(value !=3D null); +- this._files =3D value; +- } +- +- AnalysisSetPriorityFilesParams(List files) { +- this.files =3D files; +- } +- +- factory AnalysisSetPriorityFilesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List files; +- if (json.containsKey("files")) { +- files =3D jsonDecoder.decodeList( +- jsonPath + ".files", json["files"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "files"); +- } +- return new AnalysisSetPriorityFilesParams(files); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.setPriorityFiles params", json); +- } +- } +- +- factory AnalysisSetPriorityFilesParams.fromRequest(Request request) { +- return new AnalysisSetPriorityFilesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["files"] =3D files; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.setPriorityFiles", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetPriorityFilesParams) { +- return listEqual(files, other.files, (String a, String b) =3D> a = =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, files.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.setPriorityFiles result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetPriorityFilesResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetPriorityFilesResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 330050055; +- } +-} +- +-/** +- * analysis.setSubscriptions params +- * +- * { +- * "subscriptions": Map> +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetSubscriptionsParams implements RequestParams { +- Map> _subscriptions; +- +- /** +- * A table mapping services to a list of the files being subscribed to = the +- * service. +- */ +- Map> get subscriptions =3D> _subscription= s; +- +- /** +- * A table mapping services to a list of the files being subscribed to = the +- * service. +- */ +- void set subscriptions(Map> value) { +- assert(value !=3D null); +- this._subscriptions =3D value; +- } +- +- AnalysisSetSubscriptionsParams( +- Map> subscriptions) { +- this.subscriptions =3D subscriptions; +- } +- +- factory AnalysisSetSubscriptionsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- Map> subscriptions; +- if (json.containsKey("subscriptions")) { +- subscriptions =3D jsonDecoder.decodeMap( +- jsonPath + ".subscriptions", json["subscriptions"], +- keyDecoder: (String jsonPath, Object json) =3D> +- new AnalysisService.fromJson(jsonDecoder, jsonPath, json), +- valueDecoder: (String jsonPath, Object json) =3D> jsonDecoder +- .decodeList(jsonPath, json, jsonDecoder.decodeString)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "subscriptions"); +- } +- return new AnalysisSetSubscriptionsParams(subscriptions); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.setSubscriptions params", json); +- } +- } +- +- factory AnalysisSetSubscriptionsParams.fromRequest(Request request) { +- return new AnalysisSetSubscriptionsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["subscriptions"] =3D mapMap(subscriptions, +- keyCallback: (AnalysisService value) =3D> value.toJson()); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.setSubscriptions", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetSubscriptionsParams) { +- return mapEqual( +- subscriptions, +- other.subscriptions, +- (List a, List b) =3D> +- listEqual(a, b, (String a, String b) =3D> a =3D=3D b)); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, subscriptions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.setSubscriptions result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisSetSubscriptionsResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisSetSubscriptionsResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 218088493; +- } +-} +- +-/** +- * AnalysisStatus +- * +- * { +- * "isAnalyzing": bool +- * "analysisTarget": optional String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisStatus implements HasToJson { +- bool _isAnalyzing; +- +- String _analysisTarget; +- +- /** +- * True if analysis is currently being performed. +- */ +- bool get isAnalyzing =3D> _isAnalyzing; +- +- /** +- * True if analysis is currently being performed. +- */ +- void set isAnalyzing(bool value) { +- assert(value !=3D null); +- this._isAnalyzing =3D value; +- } +- +- /** +- * The name of the current target of analysis. This field is omitted if +- * analyzing is false. +- */ +- String get analysisTarget =3D> _analysisTarget; +- +- /** +- * The name of the current target of analysis. This field is omitted if +- * analyzing is false. +- */ +- void set analysisTarget(String value) { +- this._analysisTarget =3D value; +- } +- +- AnalysisStatus(bool isAnalyzing, {String analysisTarget}) { +- this.isAnalyzing =3D isAnalyzing; +- this.analysisTarget =3D analysisTarget; +- } +- +- factory AnalysisStatus.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool isAnalyzing; +- if (json.containsKey("isAnalyzing")) { +- isAnalyzing =3D jsonDecoder.decodeBool( +- jsonPath + ".isAnalyzing", json["isAnalyzing"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isAnalyzing"); +- } +- String analysisTarget; +- if (json.containsKey("analysisTarget")) { +- analysisTarget =3D jsonDecoder.decodeString( +- jsonPath + ".analysisTarget", json["analysisTarget"]); +- } +- return new AnalysisStatus(isAnalyzing, analysisTarget: analysisTarg= et); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "AnalysisStatus", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["isAnalyzing"] =3D isAnalyzing; +- if (analysisTarget !=3D null) { +- result["analysisTarget"] =3D analysisTarget; +- } +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisStatus) { +- return isAnalyzing =3D=3D other.isAnalyzing && +- analysisTarget =3D=3D other.analysisTarget; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, isAnalyzing.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, analysisTarget.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.updateContent params +- * +- * { +- * "files": Map +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisUpdateContentParams implements RequestParams { +- Map _files; +- +- /** +- * A table mapping the files whose content has changed to a description= of +- * the content change. +- */ +- Map get files =3D> _files; +- +- /** +- * A table mapping the files whose content has changed to a description= of +- * the content change. +- */ +- void set files(Map value) { +- assert(value !=3D null); +- this._files =3D value; +- } +- +- AnalysisUpdateContentParams(Map files) { +- this.files =3D files; +- } +- +- factory AnalysisUpdateContentParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- Map files; +- if (json.containsKey("files")) { +- files =3D jsonDecoder.decodeMap(jsonPath + ".files", json["files"= ], +- valueDecoder: (String jsonPath, Object json) =3D> +- jsonDecoder.decodeUnion(jsonPath, json, "type", { +- "add": (String jsonPath, Object json) =3D> +- new AddContentOverlay.fromJson( +- jsonDecoder, jsonPath, json), +- "change": (String jsonPath, Object json) =3D> +- new ChangeContentOverlay.fromJson( +- jsonDecoder, jsonPath, json), +- "remove": (String jsonPath, Object json) =3D> +- new RemoveContentOverlay.fromJson( +- jsonDecoder, jsonPath, json) +- })); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "files"); +- } +- return new AnalysisUpdateContentParams(files); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.updateContent params", json); +- } +- } +- +- factory AnalysisUpdateContentParams.fromRequest(Request request) { +- return new AnalysisUpdateContentParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["files"] =3D +- mapMap(files, valueCallback: (dynamic value) =3D> value.toJson()); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.updateContent", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisUpdateContentParams) { +- return mapEqual(files, other.files, (dynamic a, dynamic b) =3D> a = =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, files.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.updateContent result +- * +- * { +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisUpdateContentResult implements ResponseResult { +- AnalysisUpdateContentResult(); +- +- factory AnalysisUpdateContentResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- return new AnalysisUpdateContentResult(); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.updateContent result", json); +- } +- } +- +- factory AnalysisUpdateContentResult.fromResponse(Response response) { +- return new AnalysisUpdateContentResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisUpdateContentResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.updateOptions params +- * +- * { +- * "options": AnalysisOptions +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisUpdateOptionsParams implements RequestParams { +- AnalysisOptions _options; +- +- /** +- * The options that are to be used to control analysis. +- */ +- AnalysisOptions get options =3D> _options; +- +- /** +- * The options that are to be used to control analysis. +- */ +- void set options(AnalysisOptions value) { +- assert(value !=3D null); +- this._options =3D value; +- } +- +- AnalysisUpdateOptionsParams(AnalysisOptions options) { +- this.options =3D options; +- } +- +- factory AnalysisUpdateOptionsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- AnalysisOptions options; +- if (json.containsKey("options")) { +- options =3D new AnalysisOptions.fromJson( +- jsonDecoder, jsonPath + ".options", json["options"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "options"); +- } +- return new AnalysisUpdateOptionsParams(options); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "analysis.updateOptions params", json); +- } +- } +- +- factory AnalysisUpdateOptionsParams.fromRequest(Request request) { +- return new AnalysisUpdateOptionsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["options"] =3D options.toJson(); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analysis.updateOptions", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisUpdateOptionsParams) { +- return options =3D=3D other.options; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, options.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analysis.updateOptions result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalysisUpdateOptionsResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalysisUpdateOptionsResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 179689467; +- } +-} +- +-/** +- * analytics.enable params +- * +- * { +- * "value": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsEnableParams implements RequestParams { +- bool _value; +- +- /** +- * Enable or disable analytics. +- */ +- bool get value =3D> _value; +- +- /** +- * Enable or disable analytics. +- */ +- void set value(bool value) { +- assert(value !=3D null); +- this._value =3D value; +- } +- +- AnalyticsEnableParams(bool value) { +- this.value =3D value; +- } +- +- factory AnalyticsEnableParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool value; +- if (json.containsKey("value")) { +- value =3D jsonDecoder.decodeBool(jsonPath + ".value", json["value= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "value"); +- } +- return new AnalyticsEnableParams(value); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analytics.enable params", jso= n); +- } +- } +- +- factory AnalyticsEnableParams.fromRequest(Request request) { +- return new AnalyticsEnableParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["value"] =3D value; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analytics.enable", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsEnableParams) { +- return value =3D=3D other.value; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, value.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analytics.enable result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsEnableResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsEnableResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 237990792; +- } +-} +- +-/** +- * analytics.isEnabled params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsIsEnabledParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analytics.isEnabled", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsIsEnabledParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 57215544; +- } +-} +- +-/** +- * analytics.isEnabled result +- * +- * { +- * "enabled": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsIsEnabledResult implements ResponseResult { +- bool _enabled; +- +- /** +- * Whether sending analytics is enabled or not. +- */ +- bool get enabled =3D> _enabled; +- +- /** +- * Whether sending analytics is enabled or not. +- */ +- void set enabled(bool value) { +- assert(value !=3D null); +- this._enabled =3D value; +- } +- +- AnalyticsIsEnabledResult(bool enabled) { +- this.enabled =3D enabled; +- } +- +- factory AnalyticsIsEnabledResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool enabled; +- if (json.containsKey("enabled")) { +- enabled =3D +- jsonDecoder.decodeBool(jsonPath + ".enabled", json["enabled"]= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "enabled"); +- } +- return new AnalyticsIsEnabledResult(enabled); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analytics.isEnabled result", = json); +- } +- } +- +- factory AnalyticsIsEnabledResult.fromResponse(Response response) { +- return new AnalyticsIsEnabledResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["enabled"] =3D enabled; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsIsEnabledResult) { +- return enabled =3D=3D other.enabled; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, enabled.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analytics.sendEvent params +- * +- * { +- * "action": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsSendEventParams implements RequestParams { +- String _action; +- +- /** +- * The value used to indicate which action was performed. +- */ +- String get action =3D> _action; +- +- /** +- * The value used to indicate which action was performed. +- */ +- void set action(String value) { +- assert(value !=3D null); +- this._action =3D value; +- } +- +- AnalyticsSendEventParams(String action) { +- this.action =3D action; +- } +- +- factory AnalyticsSendEventParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String action; +- if (json.containsKey("action")) { +- action =3D jsonDecoder.decodeString(jsonPath + ".action", json["a= ction"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "action"); +- } +- return new AnalyticsSendEventParams(action); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analytics.sendEvent params", = json); +- } +- } +- +- factory AnalyticsSendEventParams.fromRequest(Request request) { +- return new AnalyticsSendEventParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["action"] =3D action; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analytics.sendEvent", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsSendEventParams) { +- return action =3D=3D other.action; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, action.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analytics.sendEvent result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsSendEventResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsSendEventResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 227063188; +- } +-} +- +-/** +- * analytics.sendTiming params +- * +- * { +- * "event": String +- * "millis": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsSendTimingParams implements RequestParams { +- String _event; +- +- int _millis; +- +- /** +- * The name of the event. +- */ +- String get event =3D> _event; +- +- /** +- * The name of the event. +- */ +- void set event(String value) { +- assert(value !=3D null); +- this._event =3D value; +- } +- +- /** +- * The duration of the event in milliseconds. +- */ +- int get millis =3D> _millis; +- +- /** +- * The duration of the event in milliseconds. +- */ +- void set millis(int value) { +- assert(value !=3D null); +- this._millis =3D value; +- } +- +- AnalyticsSendTimingParams(String event, int millis) { +- this.event =3D event; +- this.millis =3D millis; +- } +- +- factory AnalyticsSendTimingParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String event; +- if (json.containsKey("event")) { +- event =3D jsonDecoder.decodeString(jsonPath + ".event", json["eve= nt"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "event"); +- } +- int millis; +- if (json.containsKey("millis")) { +- millis =3D jsonDecoder.decodeInt(jsonPath + ".millis", json["mill= is"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "millis"); +- } +- return new AnalyticsSendTimingParams(event, millis); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "analytics.sendTiming params",= json); +- } +- } +- +- factory AnalyticsSendTimingParams.fromRequest(Request request) { +- return new AnalyticsSendTimingParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["event"] =3D event; +- result["millis"] =3D millis; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "analytics.sendTiming", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsSendTimingParams) { +- return event =3D=3D other.event && millis =3D=3D other.millis; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, event.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, millis.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * analytics.sendTiming result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class AnalyticsSendTimingResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is AnalyticsSendTimingResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 875010924; +- } +-} +- +-/** +- * ClosingLabel +- * +- * { +- * "offset": int +- * "length": int +- * "label": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ClosingLabel implements HasToJson { +- int _offset; +- +- int _length; +- +- String _label; +- +- /** +- * The offset of the construct being labelled. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the construct being labelled. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the whole construct to be labelled. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the whole construct to be labelled. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * The label associated with this range that should be displayed to the= user. +- */ +- String get label =3D> _label; +- +- /** +- * The label associated with this range that should be displayed to the= user. +- */ +- void set label(String value) { +- assert(value !=3D null); +- this._label =3D value; +- } +- +- ClosingLabel(int offset, int length, String label) { +- this.offset =3D offset; +- this.length =3D length; +- this.label =3D label; +- } +- +- factory ClosingLabel.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- String label; +- if (json.containsKey("label")) { +- label =3D jsonDecoder.decodeString(jsonPath + ".label", json["lab= el"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "label"); +- } +- return new ClosingLabel(offset, length, label); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "ClosingLabel", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- result["label"] =3D label; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ClosingLabel) { +- return offset =3D=3D other.offset && +- length =3D=3D other.length && +- label =3D=3D other.label; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, label.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * completion.getSuggestions params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class CompletionGetSuggestionsParams implements RequestParams { +- String _file; +- +- int _offset; +- +- /** +- * The file containing the point at which suggestions are to be made. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the point at which suggestions are to be made. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset within the file at which suggestions are to be made. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset within the file at which suggestions are to be made. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- CompletionGetSuggestionsParams(String file, int offset) { +- this.file =3D file; +- this.offset =3D offset; +- } +- +- factory CompletionGetSuggestionsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- return new CompletionGetSuggestionsParams(file, offset); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "completion.getSuggestions params", json); +- } +- } +- +- factory CompletionGetSuggestionsParams.fromRequest(Request request) { +- return new CompletionGetSuggestionsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "completion.getSuggestions", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is CompletionGetSuggestionsParams) { +- return file =3D=3D other.file && offset =3D=3D other.offset; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * completion.getSuggestions result +- * +- * { +- * "id": CompletionId +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class CompletionGetSuggestionsResult implements ResponseResult { +- String _id; +- +- /** +- * The identifier used to associate results with this completion reques= t. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier used to associate results with this completion reques= t. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- CompletionGetSuggestionsResult(String id) { +- this.id =3D id; +- } +- +- factory CompletionGetSuggestionsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- return new CompletionGetSuggestionsResult(id); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "completion.getSuggestions result", json); +- } +- } +- +- factory CompletionGetSuggestionsResult.fromResponse(Response response) { +- return new CompletionGetSuggestionsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is CompletionGetSuggestionsResult) { +- return id =3D=3D other.id; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * completion.results params +- * +- * { +- * "id": CompletionId +- * "replacementOffset": int +- * "replacementLength": int +- * "results": List +- * "isLast": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class CompletionResultsParams implements HasToJson { +- String _id; +- +- int _replacementOffset; +- +- int _replacementLength; +- +- List _results; +- +- bool _isLast; +- +- /** +- * The id associated with the completion. +- */ +- String get id =3D> _id; +- +- /** +- * The id associated with the completion. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- /** +- * The offset of the start of the text to be replaced. This will be dif= ferent +- * than the offset used to request the completion suggestions if there = was a +- * portion of an identifier before the original offset. In particular, = the +- * replacementOffset will be the offset of the beginning of said identi= fier. +- */ +- int get replacementOffset =3D> _replacementOffset; +- +- /** +- * The offset of the start of the text to be replaced. This will be dif= ferent +- * than the offset used to request the completion suggestions if there = was a +- * portion of an identifier before the original offset. In particular, = the +- * replacementOffset will be the offset of the beginning of said identi= fier. +- */ +- void set replacementOffset(int value) { +- assert(value !=3D null); +- this._replacementOffset =3D value; +- } +- +- /** +- * The length of the text to be replaced if the remainder of the identi= fier +- * containing the cursor is to be replaced when the suggestion is appli= ed +- * (that is, the number of characters in the existing identifier). +- */ +- int get replacementLength =3D> _replacementLength; +- +- /** +- * The length of the text to be replaced if the remainder of the identi= fier +- * containing the cursor is to be replaced when the suggestion is appli= ed +- * (that is, the number of characters in the existing identifier). +- */ +- void set replacementLength(int value) { +- assert(value !=3D null); +- this._replacementLength =3D value; +- } +- +- /** +- * The completion suggestions being reported. The notification contains= all +- * possible completions at the requested cursor position, even those th= at do +- * not match the characters the user has already typed. This allows the +- * client to respond to further keystrokes from the user without having= to +- * make additional requests. +- */ +- List get results =3D> _results; +- +- /** +- * The completion suggestions being reported. The notification contains= all +- * possible completions at the requested cursor position, even those th= at do +- * not match the characters the user has already typed. This allows the +- * client to respond to further keystrokes from the user without having= to +- * make additional requests. +- */ +- void set results(List value) { +- assert(value !=3D null); +- this._results =3D value; +- } +- +- /** +- * True if this is that last set of results that will be returned for t= he +- * indicated completion. +- */ +- bool get isLast =3D> _isLast; +- +- /** +- * True if this is that last set of results that will be returned for t= he +- * indicated completion. +- */ +- void set isLast(bool value) { +- assert(value !=3D null); +- this._isLast =3D value; +- } +- +- CompletionResultsParams(String id, int replacementOffset, +- int replacementLength, List results, bool isL= ast) { +- this.id =3D id; +- this.replacementOffset =3D replacementOffset; +- this.replacementLength =3D replacementLength; +- this.results =3D results; +- this.isLast =3D isLast; +- } +- +- factory CompletionResultsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- int replacementOffset; +- if (json.containsKey("replacementOffset")) { +- replacementOffset =3D jsonDecoder.decodeInt( +- jsonPath + ".replacementOffset", json["replacementOffset"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "replacementOffset"); +- } +- int replacementLength; +- if (json.containsKey("replacementLength")) { +- replacementLength =3D jsonDecoder.decodeInt( +- jsonPath + ".replacementLength", json["replacementLength"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "replacementLength"); +- } +- List results; +- if (json.containsKey("results")) { +- results =3D jsonDecoder.decodeList( +- jsonPath + ".results", +- json["results"], +- (String jsonPath, Object json) =3D> +- new CompletionSuggestion.fromJson(jsonDecoder, jsonPath, = json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "results"); +- } +- bool isLast; +- if (json.containsKey("isLast")) { +- isLast =3D jsonDecoder.decodeBool(jsonPath + ".isLast", json["isL= ast"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isLast"); +- } +- return new CompletionResultsParams( +- id, replacementOffset, replacementLength, results, isLast); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "completion.results params", j= son); +- } +- } +- +- factory CompletionResultsParams.fromNotification(Notification notificat= ion) { +- return new CompletionResultsParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- result["replacementOffset"] =3D replacementOffset; +- result["replacementLength"] =3D replacementLength; +- result["results"] =3D +- results.map((CompletionSuggestion value) =3D> value.toJson()).toL= ist(); +- result["isLast"] =3D isLast; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("completion.results", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is CompletionResultsParams) { +- return id =3D=3D other.id && +- replacementOffset =3D=3D other.replacementOffset && +- replacementLength =3D=3D other.replacementLength && +- listEqual(results, other.results, +- (CompletionSuggestion a, CompletionSuggestion b) =3D> a =3D= =3D b) && +- isLast =3D=3D other.isLast; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, replacementOffset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, replacementLength.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, results.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, isLast.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ContextData +- * +- * { +- * "name": String +- * "explicitFileCount": int +- * "implicitFileCount": int +- * "workItemQueueLength": int +- * "cacheEntryExceptions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ContextData implements HasToJson { +- String _name; +- +- int _explicitFileCount; +- +- int _implicitFileCount; +- +- int _workItemQueueLength; +- +- List _cacheEntryExceptions; +- +- /** +- * The name of the context. +- */ +- String get name =3D> _name; +- +- /** +- * The name of the context. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- /** +- * Explicitly analyzed files. +- */ +- int get explicitFileCount =3D> _explicitFileCount; +- +- /** +- * Explicitly analyzed files. +- */ +- void set explicitFileCount(int value) { +- assert(value !=3D null); +- this._explicitFileCount =3D value; +- } +- +- /** +- * Implicitly analyzed files. +- */ +- int get implicitFileCount =3D> _implicitFileCount; +- +- /** +- * Implicitly analyzed files. +- */ +- void set implicitFileCount(int value) { +- assert(value !=3D null); +- this._implicitFileCount =3D value; +- } +- +- /** +- * The number of work items in the queue. +- */ +- int get workItemQueueLength =3D> _workItemQueueLength; +- +- /** +- * The number of work items in the queue. +- */ +- void set workItemQueueLength(int value) { +- assert(value !=3D null); +- this._workItemQueueLength =3D value; +- } +- +- /** +- * Exceptions associated with cache entries. +- */ +- List get cacheEntryExceptions =3D> _cacheEntryExceptions; +- +- /** +- * Exceptions associated with cache entries. +- */ +- void set cacheEntryExceptions(List value) { +- assert(value !=3D null); +- this._cacheEntryExceptions =3D value; +- } +- +- ContextData(String name, int explicitFileCount, int implicitFileCount, +- int workItemQueueLength, List cacheEntryExceptions) { +- this.name =3D name; +- this.explicitFileCount =3D explicitFileCount; +- this.implicitFileCount =3D implicitFileCount; +- this.workItemQueueLength =3D workItemQueueLength; +- this.cacheEntryExceptions =3D cacheEntryExceptions; +- } +- +- factory ContextData.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- int explicitFileCount; +- if (json.containsKey("explicitFileCount")) { +- explicitFileCount =3D jsonDecoder.decodeInt( +- jsonPath + ".explicitFileCount", json["explicitFileCount"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "explicitFileCount"); +- } +- int implicitFileCount; +- if (json.containsKey("implicitFileCount")) { +- implicitFileCount =3D jsonDecoder.decodeInt( +- jsonPath + ".implicitFileCount", json["implicitFileCount"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "implicitFileCount"); +- } +- int workItemQueueLength; +- if (json.containsKey("workItemQueueLength")) { +- workItemQueueLength =3D jsonDecoder.decodeInt( +- jsonPath + ".workItemQueueLength", json["workItemQueueLength"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "workItemQueueLength"); +- } +- List cacheEntryExceptions; +- if (json.containsKey("cacheEntryExceptions")) { +- cacheEntryExceptions =3D jsonDecoder.decodeList( +- jsonPath + ".cacheEntryExceptions", +- json["cacheEntryExceptions"], +- jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "cacheEntryExceptions"); +- } +- return new ContextData(name, explicitFileCount, implicitFileCount, +- workItemQueueLength, cacheEntryExceptions); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "ContextData", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["name"] =3D name; +- result["explicitFileCount"] =3D explicitFileCount; +- result["implicitFileCount"] =3D implicitFileCount; +- result["workItemQueueLength"] =3D workItemQueueLength; +- result["cacheEntryExceptions"] =3D cacheEntryExceptions; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ContextData) { +- return name =3D=3D other.name && +- explicitFileCount =3D=3D other.explicitFileCount && +- implicitFileCount =3D=3D other.implicitFileCount && +- workItemQueueLength =3D=3D other.workItemQueueLength && +- listEqual(cacheEntryExceptions, other.cacheEntryExceptions, +- (String a, String b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, explicitFileCount.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, implicitFileCount.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, workItemQueueLength.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, cacheEntryExceptions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * convertGetterToMethod feedback +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ConvertGetterToMethodFeedback extends RefactoringFeedback +- implements HasToJson { +- @override +- bool operator =3D=3D(other) { +- if (other is ConvertGetterToMethodFeedback) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 616032599; +- } +-} +- +-/** +- * convertGetterToMethod options +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ConvertGetterToMethodOptions extends RefactoringOptions +- implements HasToJson { +- @override +- bool operator =3D=3D(other) { +- if (other is ConvertGetterToMethodOptions) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 488848400; +- } +-} +- +-/** +- * convertMethodToGetter feedback +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ConvertMethodToGetterFeedback extends RefactoringFeedback +- implements HasToJson { +- @override +- bool operator =3D=3D(other) { +- if (other is ConvertMethodToGetterFeedback) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 165291526; +- } +-} +- +-/** +- * convertMethodToGetter options +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ConvertMethodToGetterOptions extends RefactoringOptions +- implements HasToJson { +- @override +- bool operator =3D=3D(other) { +- if (other is ConvertMethodToGetterOptions) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 27952290; +- } +-} +- +-/** +- * diagnostic.getDiagnostics params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class DiagnosticGetDiagnosticsParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "diagnostic.getDiagnostics", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is DiagnosticGetDiagnosticsParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 587526202; +- } +-} +- +-/** +- * diagnostic.getDiagnostics result +- * +- * { +- * "contexts": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class DiagnosticGetDiagnosticsResult implements ResponseResult { +- List _contexts; +- +- /** +- * The list of analysis contexts. +- */ +- List get contexts =3D> _contexts; +- +- /** +- * The list of analysis contexts. +- */ +- void set contexts(List value) { +- assert(value !=3D null); +- this._contexts =3D value; +- } +- +- DiagnosticGetDiagnosticsResult(List contexts) { +- this.contexts =3D contexts; +- } +- +- factory DiagnosticGetDiagnosticsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List contexts; +- if (json.containsKey("contexts")) { +- contexts =3D jsonDecoder.decodeList( +- jsonPath + ".contexts", +- json["contexts"], +- (String jsonPath, Object json) =3D> +- new ContextData.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "contexts"); +- } +- return new DiagnosticGetDiagnosticsResult(contexts); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "diagnostic.getDiagnostics result", json); +- } +- } +- +- factory DiagnosticGetDiagnosticsResult.fromResponse(Response response) { +- return new DiagnosticGetDiagnosticsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["contexts"] =3D +- contexts.map((ContextData value) =3D> value.toJson()).toList(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is DiagnosticGetDiagnosticsResult) { +- return listEqual( +- contexts, other.contexts, (ContextData a, ContextData b) =3D> a= =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, contexts.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * diagnostic.getServerPort params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class DiagnosticGetServerPortParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "diagnostic.getServerPort", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is DiagnosticGetServerPortParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 367508704; +- } +-} +- +-/** +- * diagnostic.getServerPort result +- * +- * { +- * "port": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class DiagnosticGetServerPortResult implements ResponseResult { +- int _port; +- +- /** +- * The diagnostic server port. +- */ +- int get port =3D> _port; +- +- /** +- * The diagnostic server port. +- */ +- void set port(int value) { +- assert(value !=3D null); +- this._port =3D value; +- } +- +- DiagnosticGetServerPortResult(int port) { +- this.port =3D port; +- } +- +- factory DiagnosticGetServerPortResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int port; +- if (json.containsKey("port")) { +- port =3D jsonDecoder.decodeInt(jsonPath + ".port", json["port"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "port"); +- } +- return new DiagnosticGetServerPortResult(port); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "diagnostic.getServerPort result", json); +- } +- } +- +- factory DiagnosticGetServerPortResult.fromResponse(Response response) { +- return new DiagnosticGetServerPortResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["port"] =3D port; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is DiagnosticGetServerPortResult) { +- return port =3D=3D other.port; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, port.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.format params +- * +- * { +- * "file": FilePath +- * "selectionOffset": int +- * "selectionLength": int +- * "lineLength": optional int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditFormatParams implements RequestParams { +- String _file; +- +- int _selectionOffset; +- +- int _selectionLength; +- +- int _lineLength; +- +- /** +- * The file containing the code to be formatted. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the code to be formatted. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the current selection in the file. +- */ +- int get selectionOffset =3D> _selectionOffset; +- +- /** +- * The offset of the current selection in the file. +- */ +- void set selectionOffset(int value) { +- assert(value !=3D null); +- this._selectionOffset =3D value; +- } +- +- /** +- * The length of the current selection in the file. +- */ +- int get selectionLength =3D> _selectionLength; +- +- /** +- * The length of the current selection in the file. +- */ +- void set selectionLength(int value) { +- assert(value !=3D null); +- this._selectionLength =3D value; +- } +- +- /** +- * The line length to be used by the formatter. +- */ +- int get lineLength =3D> _lineLength; +- +- /** +- * The line length to be used by the formatter. +- */ +- void set lineLength(int value) { +- this._lineLength =3D value; +- } +- +- EditFormatParams(String file, int selectionOffset, int selectionLength, +- {int lineLength}) { +- this.file =3D file; +- this.selectionOffset =3D selectionOffset; +- this.selectionLength =3D selectionLength; +- this.lineLength =3D lineLength; +- } +- +- factory EditFormatParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int selectionOffset; +- if (json.containsKey("selectionOffset")) { +- selectionOffset =3D jsonDecoder.decodeInt( +- jsonPath + ".selectionOffset", json["selectionOffset"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "selectionOffset"); +- } +- int selectionLength; +- if (json.containsKey("selectionLength")) { +- selectionLength =3D jsonDecoder.decodeInt( +- jsonPath + ".selectionLength", json["selectionLength"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "selectionLength"); +- } +- int lineLength; +- if (json.containsKey("lineLength")) { +- lineLength =3D +- jsonDecoder.decodeInt(jsonPath + ".lineLength", json["lineLen= gth"]); +- } +- return new EditFormatParams(file, selectionOffset, selectionLength, +- lineLength: lineLength); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.format params", json); +- } +- } +- +- factory EditFormatParams.fromRequest(Request request) { +- return new EditFormatParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["selectionOffset"] =3D selectionOffset; +- result["selectionLength"] =3D selectionLength; +- if (lineLength !=3D null) { +- result["lineLength"] =3D lineLength; +- } +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.format", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditFormatParams) { +- return file =3D=3D other.file && +- selectionOffset =3D=3D other.selectionOffset && +- selectionLength =3D=3D other.selectionLength && +- lineLength =3D=3D other.lineLength; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, selectionOffset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, selectionLength.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, lineLength.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.format result +- * +- * { +- * "edits": List +- * "selectionOffset": int +- * "selectionLength": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditFormatResult implements ResponseResult { +- List _edits; +- +- int _selectionOffset; +- +- int _selectionLength; +- +- /** +- * The edit(s) to be applied in order to format the code. The list will= be +- * empty if the code was already formatted (there are no changes). +- */ +- List get edits =3D> _edits; +- +- /** +- * The edit(s) to be applied in order to format the code. The list will= be +- * empty if the code was already formatted (there are no changes). +- */ +- void set edits(List value) { +- assert(value !=3D null); +- this._edits =3D value; +- } +- +- /** +- * The offset of the selection after formatting the code. +- */ +- int get selectionOffset =3D> _selectionOffset; +- +- /** +- * The offset of the selection after formatting the code. +- */ +- void set selectionOffset(int value) { +- assert(value !=3D null); +- this._selectionOffset =3D value; +- } +- +- /** +- * The length of the selection after formatting the code. +- */ +- int get selectionLength =3D> _selectionLength; +- +- /** +- * The length of the selection after formatting the code. +- */ +- void set selectionLength(int value) { +- assert(value !=3D null); +- this._selectionLength =3D value; +- } +- +- EditFormatResult( +- List edits, int selectionOffset, int selectionLength) { +- this.edits =3D edits; +- this.selectionOffset =3D selectionOffset; +- this.selectionLength =3D selectionLength; +- } +- +- factory EditFormatResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List edits; +- if (json.containsKey("edits")) { +- edits =3D jsonDecoder.decodeList( +- jsonPath + ".edits", +- json["edits"], +- (String jsonPath, Object json) =3D> +- new SourceEdit.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edits"); +- } +- int selectionOffset; +- if (json.containsKey("selectionOffset")) { +- selectionOffset =3D jsonDecoder.decodeInt( +- jsonPath + ".selectionOffset", json["selectionOffset"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "selectionOffset"); +- } +- int selectionLength; +- if (json.containsKey("selectionLength")) { +- selectionLength =3D jsonDecoder.decodeInt( +- jsonPath + ".selectionLength", json["selectionLength"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "selectionLength"); +- } +- return new EditFormatResult(edits, selectionOffset, selectionLength= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.format result", json); +- } +- } +- +- factory EditFormatResult.fromResponse(Response response) { +- return new EditFormatResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["edits"] =3D edits.map((SourceEdit value) =3D> value.toJson())= .toList(); +- result["selectionOffset"] =3D selectionOffset; +- result["selectionLength"] =3D selectionLength; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditFormatResult) { +- return listEqual( +- edits, other.edits, (SourceEdit a, SourceEdit b) =3D> a =3D= =3D b) && +- selectionOffset =3D=3D other.selectionOffset && +- selectionLength =3D=3D other.selectionLength; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, edits.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, selectionOffset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, selectionLength.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getAssists params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetAssistsParams implements RequestParams { +- String _file; +- +- int _offset; +- +- int _length; +- +- /** +- * The file containing the code for which assists are being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the code for which assists are being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the code for which assists are being requested. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the code for which assists are being requested. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the code for which assists are being requested. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the code for which assists are being requested. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- EditGetAssistsParams(String file, int offset, int length) { +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- factory EditGetAssistsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- return new EditGetAssistsParams(file, offset, length); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.getAssists params", json= ); +- } +- } +- +- factory EditGetAssistsParams.fromRequest(Request request) { +- return new EditGetAssistsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["length"] =3D length; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.getAssists", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetAssistsParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- length =3D=3D other.length; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getAssists result +- * +- * { +- * "assists": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetAssistsResult implements ResponseResult { +- List _assists; +- +- /** +- * The assists that are available at the given location. +- */ +- List get assists =3D> _assists; +- +- /** +- * The assists that are available at the given location. +- */ +- void set assists(List value) { +- assert(value !=3D null); +- this._assists =3D value; +- } +- +- EditGetAssistsResult(List assists) { +- this.assists =3D assists; +- } +- +- factory EditGetAssistsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List assists; +- if (json.containsKey("assists")) { +- assists =3D jsonDecoder.decodeList( +- jsonPath + ".assists", +- json["assists"], +- (String jsonPath, Object json) =3D> +- new SourceChange.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "assists"); +- } +- return new EditGetAssistsResult(assists); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.getAssists result", json= ); +- } +- } +- +- factory EditGetAssistsResult.fromResponse(Response response) { +- return new EditGetAssistsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["assists"] =3D +- assists.map((SourceChange value) =3D> value.toJson()).toList(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetAssistsResult) { +- return listEqual( +- assists, other.assists, (SourceChange a, SourceChange b) =3D> a= =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, assists.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getAvailableRefactorings params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetAvailableRefactoringsParams implements RequestParams { +- String _file; +- +- int _offset; +- +- int _length; +- +- /** +- * The file containing the code on which the refactoring would be based. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the code on which the refactoring would be based. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the code on which the refactoring would be based. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the code on which the refactoring would be based. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the code on which the refactoring would be based. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the code on which the refactoring would be based. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- EditGetAvailableRefactoringsParams(String file, int offset, int length)= { +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- factory EditGetAvailableRefactoringsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- return new EditGetAvailableRefactoringsParams(file, offset, length); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.getAvailableRefactorings params", json); +- } +- } +- +- factory EditGetAvailableRefactoringsParams.fromRequest(Request request)= { +- return new EditGetAvailableRefactoringsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["length"] =3D length; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.getAvailableRefactorings", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetAvailableRefactoringsParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- length =3D=3D other.length; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getAvailableRefactorings result +- * +- * { +- * "kinds": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetAvailableRefactoringsResult implements ResponseResult { +- List _kinds; +- +- /** +- * The kinds of refactorings that are valid for the given selection. +- */ +- List get kinds =3D> _kinds; +- +- /** +- * The kinds of refactorings that are valid for the given selection. +- */ +- void set kinds(List value) { +- assert(value !=3D null); +- this._kinds =3D value; +- } +- +- EditGetAvailableRefactoringsResult(List kinds) { +- this.kinds =3D kinds; +- } +- +- factory EditGetAvailableRefactoringsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List kinds; +- if (json.containsKey("kinds")) { +- kinds =3D jsonDecoder.decodeList( +- jsonPath + ".kinds", +- json["kinds"], +- (String jsonPath, Object json) =3D> +- new RefactoringKind.fromJson(jsonDecoder, jsonPath, json)= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "kinds"); +- } +- return new EditGetAvailableRefactoringsResult(kinds); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.getAvailableRefactorings result", json); +- } +- } +- +- factory EditGetAvailableRefactoringsResult.fromResponse(Response respon= se) { +- return new EditGetAvailableRefactoringsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["kinds"] =3D +- kinds.map((RefactoringKind value) =3D> value.toJson()).toList(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetAvailableRefactoringsResult) { +- return listEqual( +- kinds, other.kinds, (RefactoringKind a, RefactoringKind b) =3D>= a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, kinds.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getFixes params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetFixesParams implements RequestParams { +- String _file; +- +- int _offset; +- +- /** +- * The file containing the errors for which fixes are being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the errors for which fixes are being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset used to select the errors for which fixes will be returne= d. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset used to select the errors for which fixes will be returne= d. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- EditGetFixesParams(String file, int offset) { +- this.file =3D file; +- this.offset =3D offset; +- } +- +- factory EditGetFixesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- return new EditGetFixesParams(file, offset); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.getFixes params", json); +- } +- } +- +- factory EditGetFixesParams.fromRequest(Request request) { +- return new EditGetFixesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.getFixes", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetFixesParams) { +- return file =3D=3D other.file && offset =3D=3D other.offset; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getFixes result +- * +- * { +- * "fixes": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetFixesResult implements ResponseResult { +- List _fixes; +- +- /** +- * The fixes that are available for the errors at the given offset. +- */ +- List get fixes =3D> _fixes; +- +- /** +- * The fixes that are available for the errors at the given offset. +- */ +- void set fixes(List value) { +- assert(value !=3D null); +- this._fixes =3D value; +- } +- +- EditGetFixesResult(List fixes) { +- this.fixes =3D fixes; +- } +- +- factory EditGetFixesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List fixes; +- if (json.containsKey("fixes")) { +- fixes =3D jsonDecoder.decodeList( +- jsonPath + ".fixes", +- json["fixes"], +- (String jsonPath, Object json) =3D> +- new AnalysisErrorFixes.fromJson(jsonDecoder, jsonPath, js= on)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "fixes"); +- } +- return new EditGetFixesResult(fixes); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.getFixes result", json); +- } +- } +- +- factory EditGetFixesResult.fromResponse(Response response) { +- return new EditGetFixesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["fixes"] =3D +- fixes.map((AnalysisErrorFixes value) =3D> value.toJson()).toList(= ); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetFixesResult) { +- return listEqual(fixes, other.fixes, +- (AnalysisErrorFixes a, AnalysisErrorFixes b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, fixes.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getPostfixCompletion params +- * +- * { +- * "file": FilePath +- * "key": String +- * "offset": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetPostfixCompletionParams implements RequestParams { +- String _file; +- +- String _key; +- +- int _offset; +- +- /** +- * The file containing the postfix template to be expanded. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the postfix template to be expanded. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The unique name that identifies the template in use. +- */ +- String get key =3D> _key; +- +- /** +- * The unique name that identifies the template in use. +- */ +- void set key(String value) { +- assert(value !=3D null); +- this._key =3D value; +- } +- +- /** +- * The offset used to identify the code to which the template will be +- * applied. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset used to identify the code to which the template will be +- * applied. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- EditGetPostfixCompletionParams(String file, String key, int offset) { +- this.file =3D file; +- this.key =3D key; +- this.offset =3D offset; +- } +- +- factory EditGetPostfixCompletionParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- String key; +- if (json.containsKey("key")) { +- key =3D jsonDecoder.decodeString(jsonPath + ".key", json["key"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "key"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- return new EditGetPostfixCompletionParams(file, key, offset); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.getPostfixCompletion params", json); +- } +- } +- +- factory EditGetPostfixCompletionParams.fromRequest(Request request) { +- return new EditGetPostfixCompletionParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["key"] =3D key; +- result["offset"] =3D offset; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.getPostfixCompletion", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetPostfixCompletionParams) { +- return file =3D=3D other.file && key =3D=3D other.key && offset =3D= =3D other.offset; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, key.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getPostfixCompletion result +- * +- * { +- * "change": SourceChange +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetPostfixCompletionResult implements ResponseResult { +- SourceChange _change; +- +- /** +- * The change to be applied in order to complete the statement. +- */ +- SourceChange get change =3D> _change; +- +- /** +- * The change to be applied in order to complete the statement. +- */ +- void set change(SourceChange value) { +- assert(value !=3D null); +- this._change =3D value; +- } +- +- EditGetPostfixCompletionResult(SourceChange change) { +- this.change =3D change; +- } +- +- factory EditGetPostfixCompletionResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- SourceChange change; +- if (json.containsKey("change")) { +- change =3D new SourceChange.fromJson( +- jsonDecoder, jsonPath + ".change", json["change"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "change"); +- } +- return new EditGetPostfixCompletionResult(change); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.getPostfixCompletion result", json); +- } +- } +- +- factory EditGetPostfixCompletionResult.fromResponse(Response response) { +- return new EditGetPostfixCompletionResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["change"] =3D change.toJson(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetPostfixCompletionResult) { +- return change =3D=3D other.change; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, change.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getRefactoring params +- * +- * { +- * "kind": RefactoringKind +- * "file": FilePath +- * "offset": int +- * "length": int +- * "validateOnly": bool +- * "options": optional RefactoringOptions +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetRefactoringParams implements RequestParams { +- RefactoringKind _kind; +- +- String _file; +- +- int _offset; +- +- int _length; +- +- bool _validateOnly; +- +- RefactoringOptions _options; +- +- /** +- * The kind of refactoring to be performed. +- */ +- RefactoringKind get kind =3D> _kind; +- +- /** +- * The kind of refactoring to be performed. +- */ +- void set kind(RefactoringKind value) { +- assert(value !=3D null); +- this._kind =3D value; +- } +- +- /** +- * The file containing the code involved in the refactoring. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the code involved in the refactoring. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the region involved in the refactoring. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the region involved in the refactoring. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the region involved in the refactoring. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the region involved in the refactoring. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * True if the client is only requesting that the values of the options= be +- * validated and no change be generated. +- */ +- bool get validateOnly =3D> _validateOnly; +- +- /** +- * True if the client is only requesting that the values of the options= be +- * validated and no change be generated. +- */ +- void set validateOnly(bool value) { +- assert(value !=3D null); +- this._validateOnly =3D value; +- } +- +- /** +- * Data used to provide values provided by the user. The structure of t= he +- * data is dependent on the kind of refactoring being performed. The da= ta +- * that is expected is documented in the section titled Refactorings, l= abeled +- * as "Options". This field can be omitted if the refactoring does not +- * require any options or if the values of those options are not known. +- */ +- RefactoringOptions get options =3D> _options; +- +- /** +- * Data used to provide values provided by the user. The structure of t= he +- * data is dependent on the kind of refactoring being performed. The da= ta +- * that is expected is documented in the section titled Refactorings, l= abeled +- * as "Options". This field can be omitted if the refactoring does not +- * require any options or if the values of those options are not known. +- */ +- void set options(RefactoringOptions value) { +- this._options =3D value; +- } +- +- EditGetRefactoringParams(RefactoringKind kind, String file, int offset, +- int length, bool validateOnly, +- {RefactoringOptions options}) { +- this.kind =3D kind; +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- this.validateOnly =3D validateOnly; +- this.options =3D options; +- } +- +- factory EditGetRefactoringParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- RefactoringKind kind; +- if (json.containsKey("kind")) { +- kind =3D new RefactoringKind.fromJson( +- jsonDecoder, jsonPath + ".kind", json["kind"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "kind"); +- } +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- bool validateOnly; +- if (json.containsKey("validateOnly")) { +- validateOnly =3D jsonDecoder.decodeBool( +- jsonPath + ".validateOnly", json["validateOnly"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "validateOnly"); +- } +- RefactoringOptions options; +- if (json.containsKey("options")) { +- options =3D new RefactoringOptions.fromJson( +- jsonDecoder, jsonPath + ".options", json["options"], kind); +- } +- return new EditGetRefactoringParams( +- kind, file, offset, length, validateOnly, +- options: options); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.getRefactoring params", = json); +- } +- } +- +- factory EditGetRefactoringParams.fromRequest(Request request) { +- var params =3D new EditGetRefactoringParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- REQUEST_ID_REFACTORING_KINDS[request.id] =3D params.kind; +- return params; +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["kind"] =3D kind.toJson(); +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["length"] =3D length; +- result["validateOnly"] =3D validateOnly; +- if (options !=3D null) { +- result["options"] =3D options.toJson(); +- } +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.getRefactoring", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetRefactoringParams) { +- return kind =3D=3D other.kind && +- file =3D=3D other.file && +- offset =3D=3D other.offset && +- length =3D=3D other.length && +- validateOnly =3D=3D other.validateOnly && +- options =3D=3D other.options; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, kind.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, validateOnly.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, options.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getRefactoring result +- * +- * { +- * "initialProblems": List +- * "optionsProblems": List +- * "finalProblems": List +- * "feedback": optional RefactoringFeedback +- * "change": optional SourceChange +- * "potentialEdits": optional List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetRefactoringResult implements ResponseResult { +- List _initialProblems; +- +- List _optionsProblems; +- +- List _finalProblems; +- +- RefactoringFeedback _feedback; +- +- SourceChange _change; +- +- List _potentialEdits; +- +- /** +- * The initial status of the refactoring, i.e. problems related to the +- * context in which the refactoring is requested. The array will be emp= ty if +- * there are no known problems. +- */ +- List get initialProblems =3D> _initialProblems; +- +- /** +- * The initial status of the refactoring, i.e. problems related to the +- * context in which the refactoring is requested. The array will be emp= ty if +- * there are no known problems. +- */ +- void set initialProblems(List value) { +- assert(value !=3D null); +- this._initialProblems =3D value; +- } +- +- /** +- * The options validation status, i.e. problems in the given options, s= uch as +- * light-weight validation of a new name, flags compatibility, etc. The= array +- * will be empty if there are no known problems. +- */ +- List get optionsProblems =3D> _optionsProblems; +- +- /** +- * The options validation status, i.e. problems in the given options, s= uch as +- * light-weight validation of a new name, flags compatibility, etc. The= array +- * will be empty if there are no known problems. +- */ +- void set optionsProblems(List value) { +- assert(value !=3D null); +- this._optionsProblems =3D value; +- } +- +- /** +- * The final status of the refactoring, i.e. problems identified in the +- * result of a full, potentially expensive validation and / or change +- * creation. The array will be empty if there are no known problems. +- */ +- List get finalProblems =3D> _finalProblems; +- +- /** +- * The final status of the refactoring, i.e. problems identified in the +- * result of a full, potentially expensive validation and / or change +- * creation. The array will be empty if there are no known problems. +- */ +- void set finalProblems(List value) { +- assert(value !=3D null); +- this._finalProblems =3D value; +- } +- +- /** +- * Data used to provide feedback to the user. The structure of the data= is +- * dependent on the kind of refactoring being created. The data that is +- * returned is documented in the section titled Refactorings, labeled as +- * "Feedback". +- */ +- RefactoringFeedback get feedback =3D> _feedback; +- +- /** +- * Data used to provide feedback to the user. The structure of the data= is +- * dependent on the kind of refactoring being created. The data that is +- * returned is documented in the section titled Refactorings, labeled as +- * "Feedback". +- */ +- void set feedback(RefactoringFeedback value) { +- this._feedback =3D value; +- } +- +- /** +- * The changes that are to be applied to affect the refactoring. This f= ield +- * will be omitted if there are problems that prevent a set of changes = from +- * being computed, such as having no options specified for a refactorin= g that +- * requires them, or if only validation was requested. +- */ +- SourceChange get change =3D> _change; +- +- /** +- * The changes that are to be applied to affect the refactoring. This f= ield +- * will be omitted if there are problems that prevent a set of changes = from +- * being computed, such as having no options specified for a refactorin= g that +- * requires them, or if only validation was requested. +- */ +- void set change(SourceChange value) { +- this._change =3D value; +- } +- +- /** +- * The ids of source edits that are not known to be valid. An edit is n= ot +- * known to be valid if there was insufficient type information for the +- * server to be able to determine whether or not the code needs to be +- * modified, such as when a member is being renamed and there is a refe= rence +- * to a member from an unknown type. This field will be omitted if the = change +- * field is omitted or if there are no potential edits for the refactor= ing. +- */ +- List get potentialEdits =3D> _potentialEdits; +- +- /** +- * The ids of source edits that are not known to be valid. An edit is n= ot +- * known to be valid if there was insufficient type information for the +- * server to be able to determine whether or not the code needs to be +- * modified, such as when a member is being renamed and there is a refe= rence +- * to a member from an unknown type. This field will be omitted if the = change +- * field is omitted or if there are no potential edits for the refactor= ing. +- */ +- void set potentialEdits(List value) { +- this._potentialEdits =3D value; +- } +- +- EditGetRefactoringResult( +- List initialProblems, +- List optionsProblems, +- List finalProblems, +- {RefactoringFeedback feedback, +- SourceChange change, +- List potentialEdits}) { +- this.initialProblems =3D initialProblems; +- this.optionsProblems =3D optionsProblems; +- this.finalProblems =3D finalProblems; +- this.feedback =3D feedback; +- this.change =3D change; +- this.potentialEdits =3D potentialEdits; +- } +- +- factory EditGetRefactoringResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List initialProblems; +- if (json.containsKey("initialProblems")) { +- initialProblems =3D jsonDecoder.decodeList( +- jsonPath + ".initialProblems", +- json["initialProblems"], +- (String jsonPath, Object json) =3D> +- new RefactoringProblem.fromJson(jsonDecoder, jsonPath, js= on)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "initialProblems"); +- } +- List optionsProblems; +- if (json.containsKey("optionsProblems")) { +- optionsProblems =3D jsonDecoder.decodeList( +- jsonPath + ".optionsProblems", +- json["optionsProblems"], +- (String jsonPath, Object json) =3D> +- new RefactoringProblem.fromJson(jsonDecoder, jsonPath, js= on)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "optionsProblems"); +- } +- List finalProblems; +- if (json.containsKey("finalProblems")) { +- finalProblems =3D jsonDecoder.decodeList( +- jsonPath + ".finalProblems", +- json["finalProblems"], +- (String jsonPath, Object json) =3D> +- new RefactoringProblem.fromJson(jsonDecoder, jsonPath, js= on)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "finalProblems"); +- } +- RefactoringFeedback feedback; +- if (json.containsKey("feedback")) { +- feedback =3D new RefactoringFeedback.fromJson( +- jsonDecoder, jsonPath + ".feedback", json["feedback"], json); +- } +- SourceChange change; +- if (json.containsKey("change")) { +- change =3D new SourceChange.fromJson( +- jsonDecoder, jsonPath + ".change", json["change"]); +- } +- List potentialEdits; +- if (json.containsKey("potentialEdits")) { +- potentialEdits =3D jsonDecoder.decodeList(jsonPath + ".potentialE= dits", +- json["potentialEdits"], jsonDecoder.decodeString); +- } +- return new EditGetRefactoringResult( +- initialProblems, optionsProblems, finalProblems, +- feedback: feedback, change: change, potentialEdits: potentialEd= its); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.getRefactoring result", = json); +- } +- } +- +- factory EditGetRefactoringResult.fromResponse(Response response) { +- return new EditGetRefactoringResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["initialProblems"] =3D initialProblems +- .map((RefactoringProblem value) =3D> value.toJson()) +- .toList(); +- result["optionsProblems"] =3D optionsProblems +- .map((RefactoringProblem value) =3D> value.toJson()) +- .toList(); +- result["finalProblems"] =3D finalProblems +- .map((RefactoringProblem value) =3D> value.toJson()) +- .toList(); +- if (feedback !=3D null) { +- result["feedback"] =3D feedback.toJson(); +- } +- if (change !=3D null) { +- result["change"] =3D change.toJson(); +- } +- if (potentialEdits !=3D null) { +- result["potentialEdits"] =3D potentialEdits; +- } +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetRefactoringResult) { +- return listEqual(initialProblems, other.initialProblems, +- (RefactoringProblem a, RefactoringProblem b) =3D> a =3D=3D = b) && +- listEqual(optionsProblems, other.optionsProblems, +- (RefactoringProblem a, RefactoringProblem b) =3D> a =3D=3D = b) && +- listEqual(finalProblems, other.finalProblems, +- (RefactoringProblem a, RefactoringProblem b) =3D> a =3D=3D = b) && +- feedback =3D=3D other.feedback && +- change =3D=3D other.change && +- listEqual(potentialEdits, other.potentialEdits, +- (String a, String b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, initialProblems.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, optionsProblems.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, finalProblems.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, feedback.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, change.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, potentialEdits.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getStatementCompletion params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetStatementCompletionParams implements RequestParams { +- String _file; +- +- int _offset; +- +- /** +- * The file containing the statement to be completed. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the statement to be completed. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset used to identify the statement to be completed. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset used to identify the statement to be completed. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- EditGetStatementCompletionParams(String file, int offset) { +- this.file =3D file; +- this.offset =3D offset; +- } +- +- factory EditGetStatementCompletionParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- return new EditGetStatementCompletionParams(file, offset); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.getStatementCompletion params", json); +- } +- } +- +- factory EditGetStatementCompletionParams.fromRequest(Request request) { +- return new EditGetStatementCompletionParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.getStatementCompletion", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetStatementCompletionParams) { +- return file =3D=3D other.file && offset =3D=3D other.offset; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.getStatementCompletion result +- * +- * { +- * "change": SourceChange +- * "whitespaceOnly": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditGetStatementCompletionResult implements ResponseResult { +- SourceChange _change; +- +- bool _whitespaceOnly; +- +- /** +- * The change to be applied in order to complete the statement. +- */ +- SourceChange get change =3D> _change; +- +- /** +- * The change to be applied in order to complete the statement. +- */ +- void set change(SourceChange value) { +- assert(value !=3D null); +- this._change =3D value; +- } +- +- /** +- * Will be true if the change contains nothing but whitespace character= s, or +- * is empty. +- */ +- bool get whitespaceOnly =3D> _whitespaceOnly; +- +- /** +- * Will be true if the change contains nothing but whitespace character= s, or +- * is empty. +- */ +- void set whitespaceOnly(bool value) { +- assert(value !=3D null); +- this._whitespaceOnly =3D value; +- } +- +- EditGetStatementCompletionResult(SourceChange change, bool whitespaceOn= ly) { +- this.change =3D change; +- this.whitespaceOnly =3D whitespaceOnly; +- } +- +- factory EditGetStatementCompletionResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- SourceChange change; +- if (json.containsKey("change")) { +- change =3D new SourceChange.fromJson( +- jsonDecoder, jsonPath + ".change", json["change"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "change"); +- } +- bool whitespaceOnly; +- if (json.containsKey("whitespaceOnly")) { +- whitespaceOnly =3D jsonDecoder.decodeBool( +- jsonPath + ".whitespaceOnly", json["whitespaceOnly"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "whitespaceOnly"); +- } +- return new EditGetStatementCompletionResult(change, whitespaceOnly); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.getStatementCompletion result", json); +- } +- } +- +- factory EditGetStatementCompletionResult.fromResponse(Response response= ) { +- return new EditGetStatementCompletionResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["change"] =3D change.toJson(); +- result["whitespaceOnly"] =3D whitespaceOnly; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditGetStatementCompletionResult) { +- return change =3D=3D other.change && whitespaceOnly =3D=3D other.wh= itespaceOnly; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, change.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, whitespaceOnly.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.importElements params +- * +- * { +- * "file": FilePath +- * "elements": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditImportElementsParams implements RequestParams { +- String _file; +- +- List _elements; +- +- /** +- * The file in which the specified elements are to be made accessible. +- */ +- String get file =3D> _file; +- +- /** +- * The file in which the specified elements are to be made accessible. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The elements to be made accessible in the specified file. +- */ +- List get elements =3D> _elements; +- +- /** +- * The elements to be made accessible in the specified file. +- */ +- void set elements(List value) { +- assert(value !=3D null); +- this._elements =3D value; +- } +- +- EditImportElementsParams(String file, List elements) { +- this.file =3D file; +- this.elements =3D elements; +- } +- +- factory EditImportElementsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- List elements; +- if (json.containsKey("elements")) { +- elements =3D jsonDecoder.decodeList( +- jsonPath + ".elements", +- json["elements"], +- (String jsonPath, Object json) =3D> +- new ImportedElements.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "elements"); +- } +- return new EditImportElementsParams(file, elements); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.importElements params", = json); +- } +- } +- +- factory EditImportElementsParams.fromRequest(Request request) { +- return new EditImportElementsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["elements"] =3D +- elements.map((ImportedElements value) =3D> value.toJson()).toList= (); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.importElements", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditImportElementsParams) { +- return file =3D=3D other.file && +- listEqual(elements, other.elements, +- (ImportedElements a, ImportedElements b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, elements.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.importElements result +- * +- * { +- * "edit": SourceFileEdit +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditImportElementsResult implements ResponseResult { +- SourceFileEdit _edit; +- +- /** +- * The edits to be applied in order to make the specified elements +- * accessible. The file to be edited will be the defining compilation u= nit of +- * the library containing the file specified in the request, which can = be +- * different than the file specified in the request if the specified fi= le is +- * a part file. +- */ +- SourceFileEdit get edit =3D> _edit; +- +- /** +- * The edits to be applied in order to make the specified elements +- * accessible. The file to be edited will be the defining compilation u= nit of +- * the library containing the file specified in the request, which can = be +- * different than the file specified in the request if the specified fi= le is +- * a part file. +- */ +- void set edit(SourceFileEdit value) { +- assert(value !=3D null); +- this._edit =3D value; +- } +- +- EditImportElementsResult(SourceFileEdit edit) { +- this.edit =3D edit; +- } +- +- factory EditImportElementsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- SourceFileEdit edit; +- if (json.containsKey("edit")) { +- edit =3D new SourceFileEdit.fromJson( +- jsonDecoder, jsonPath + ".edit", json["edit"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit"); +- } +- return new EditImportElementsResult(edit); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.importElements result", = json); +- } +- } +- +- factory EditImportElementsResult.fromResponse(Response response) { +- return new EditImportElementsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["edit"] =3D edit.toJson(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditImportElementsResult) { +- return edit =3D=3D other.edit; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, edit.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.isPostfixCompletionApplicable params +- * +- * { +- * "file": FilePath +- * "key": String +- * "offset": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditIsPostfixCompletionApplicableParams implements RequestParams { +- String _file; +- +- String _key; +- +- int _offset; +- +- /** +- * The file containing the postfix template to be expanded. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the postfix template to be expanded. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The unique name that identifies the template in use. +- */ +- String get key =3D> _key; +- +- /** +- * The unique name that identifies the template in use. +- */ +- void set key(String value) { +- assert(value !=3D null); +- this._key =3D value; +- } +- +- /** +- * The offset used to identify the code to which the template will be +- * applied. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset used to identify the code to which the template will be +- * applied. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- EditIsPostfixCompletionApplicableParams(String file, String key, int of= fset) { +- this.file =3D file; +- this.key =3D key; +- this.offset =3D offset; +- } +- +- factory EditIsPostfixCompletionApplicableParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- String key; +- if (json.containsKey("key")) { +- key =3D jsonDecoder.decodeString(jsonPath + ".key", json["key"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "key"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- return new EditIsPostfixCompletionApplicableParams(file, key, offse= t); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.isPostfixCompletionApplicable params", json); +- } +- } +- +- factory EditIsPostfixCompletionApplicableParams.fromRequest(Request req= uest) { +- return new EditIsPostfixCompletionApplicableParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["key"] =3D key; +- result["offset"] =3D offset; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.isPostfixCompletionApplicable", toJson()= ); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditIsPostfixCompletionApplicableParams) { +- return file =3D=3D other.file && key =3D=3D other.key && offset =3D= =3D other.offset; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, key.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.isPostfixCompletionApplicable result +- * +- * { +- * "value": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditIsPostfixCompletionApplicableResult implements ResponseResult { +- bool _value; +- +- /** +- * True if the template can be expanded at the given location. +- */ +- bool get value =3D> _value; +- +- /** +- * True if the template can be expanded at the given location. +- */ +- void set value(bool value) { +- assert(value !=3D null); +- this._value =3D value; +- } +- +- EditIsPostfixCompletionApplicableResult(bool value) { +- this.value =3D value; +- } +- +- factory EditIsPostfixCompletionApplicableResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool value; +- if (json.containsKey("value")) { +- value =3D jsonDecoder.decodeBool(jsonPath + ".value", json["value= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "value"); +- } +- return new EditIsPostfixCompletionApplicableResult(value); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.isPostfixCompletionApplicable result", json); +- } +- } +- +- factory EditIsPostfixCompletionApplicableResult.fromResponse( +- Response response) { +- return new EditIsPostfixCompletionApplicableResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["value"] =3D value; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditIsPostfixCompletionApplicableResult) { +- return value =3D=3D other.value; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, value.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.listPostfixCompletionTemplates params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditListPostfixCompletionTemplatesParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.listPostfixCompletionTemplates", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditListPostfixCompletionTemplatesParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 690713107; +- } +-} +- +-/** +- * edit.listPostfixCompletionTemplates result +- * +- * { +- * "templates": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditListPostfixCompletionTemplatesResult implements ResponseResult { +- List _templates; +- +- /** +- * The list of available templates. +- */ +- List get templates =3D> _templates; +- +- /** +- * The list of available templates. +- */ +- void set templates(List value) { +- assert(value !=3D null); +- this._templates =3D value; +- } +- +- EditListPostfixCompletionTemplatesResult( +- List templates) { +- this.templates =3D templates; +- } +- +- factory EditListPostfixCompletionTemplatesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List templates; +- if (json.containsKey("templates")) { +- templates =3D jsonDecoder.decodeList( +- jsonPath + ".templates", +- json["templates"], +- (String jsonPath, Object json) =3D> +- new PostfixTemplateDescriptor.fromJson( +- jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "templates"); +- } +- return new EditListPostfixCompletionTemplatesResult(templates); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.listPostfixCompletionTemplates result", json); +- } +- } +- +- factory EditListPostfixCompletionTemplatesResult.fromResponse( +- Response response) { +- return new EditListPostfixCompletionTemplatesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["templates"] =3D templates +- .map((PostfixTemplateDescriptor value) =3D> value.toJson()) +- .toList(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditListPostfixCompletionTemplatesResult) { +- return listEqual(templates, other.templates, +- (PostfixTemplateDescriptor a, PostfixTemplateDescriptor b) =3D>= a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, templates.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.organizeDirectives params +- * +- * { +- * "file": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditOrganizeDirectivesParams implements RequestParams { +- String _file; +- +- /** +- * The Dart file to organize directives in. +- */ +- String get file =3D> _file; +- +- /** +- * The Dart file to organize directives in. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- EditOrganizeDirectivesParams(String file) { +- this.file =3D file; +- } +- +- factory EditOrganizeDirectivesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- return new EditOrganizeDirectivesParams(file); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.organizeDirectives params", json); +- } +- } +- +- factory EditOrganizeDirectivesParams.fromRequest(Request request) { +- return new EditOrganizeDirectivesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.organizeDirectives", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditOrganizeDirectivesParams) { +- return file =3D=3D other.file; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.organizeDirectives result +- * +- * { +- * "edit": SourceFileEdit +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditOrganizeDirectivesResult implements ResponseResult { +- SourceFileEdit _edit; +- +- /** +- * The file edit that is to be applied to the given file to effect the +- * organizing. +- */ +- SourceFileEdit get edit =3D> _edit; +- +- /** +- * The file edit that is to be applied to the given file to effect the +- * organizing. +- */ +- void set edit(SourceFileEdit value) { +- assert(value !=3D null); +- this._edit =3D value; +- } +- +- EditOrganizeDirectivesResult(SourceFileEdit edit) { +- this.edit =3D edit; +- } +- +- factory EditOrganizeDirectivesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- SourceFileEdit edit; +- if (json.containsKey("edit")) { +- edit =3D new SourceFileEdit.fromJson( +- jsonDecoder, jsonPath + ".edit", json["edit"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit"); +- } +- return new EditOrganizeDirectivesResult(edit); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "edit.organizeDirectives result", json); +- } +- } +- +- factory EditOrganizeDirectivesResult.fromResponse(Response response) { +- return new EditOrganizeDirectivesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["edit"] =3D edit.toJson(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditOrganizeDirectivesResult) { +- return edit =3D=3D other.edit; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, edit.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.sortMembers params +- * +- * { +- * "file": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditSortMembersParams implements RequestParams { +- String _file; +- +- /** +- * The Dart file to sort. +- */ +- String get file =3D> _file; +- +- /** +- * The Dart file to sort. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- EditSortMembersParams(String file) { +- this.file =3D file; +- } +- +- factory EditSortMembersParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- return new EditSortMembersParams(file); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.sortMembers params", jso= n); +- } +- } +- +- factory EditSortMembersParams.fromRequest(Request request) { +- return new EditSortMembersParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "edit.sortMembers", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditSortMembersParams) { +- return file =3D=3D other.file; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * edit.sortMembers result +- * +- * { +- * "edit": SourceFileEdit +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class EditSortMembersResult implements ResponseResult { +- SourceFileEdit _edit; +- +- /** +- * The file edit that is to be applied to the given file to effect the +- * sorting. +- */ +- SourceFileEdit get edit =3D> _edit; +- +- /** +- * The file edit that is to be applied to the given file to effect the +- * sorting. +- */ +- void set edit(SourceFileEdit value) { +- assert(value !=3D null); +- this._edit =3D value; +- } +- +- EditSortMembersResult(SourceFileEdit edit) { +- this.edit =3D edit; +- } +- +- factory EditSortMembersResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- SourceFileEdit edit; +- if (json.containsKey("edit")) { +- edit =3D new SourceFileEdit.fromJson( +- jsonDecoder, jsonPath + ".edit", json["edit"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit"); +- } +- return new EditSortMembersResult(edit); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "edit.sortMembers result", jso= n); +- } +- } +- +- factory EditSortMembersResult.fromResponse(Response response) { +- return new EditSortMembersResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["edit"] =3D edit.toJson(); +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is EditSortMembersResult) { +- return edit =3D=3D other.edit; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, edit.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ExecutableFile +- * +- * { +- * "file": FilePath +- * "kind": ExecutableKind +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutableFile implements HasToJson { +- String _file; +- +- ExecutableKind _kind; +- +- /** +- * The path of the executable file. +- */ +- String get file =3D> _file; +- +- /** +- * The path of the executable file. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The kind of the executable file. +- */ +- ExecutableKind get kind =3D> _kind; +- +- /** +- * The kind of the executable file. +- */ +- void set kind(ExecutableKind value) { +- assert(value !=3D null); +- this._kind =3D value; +- } +- +- ExecutableFile(String file, ExecutableKind kind) { +- this.file =3D file; +- this.kind =3D kind; +- } +- +- factory ExecutableFile.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- ExecutableKind kind; +- if (json.containsKey("kind")) { +- kind =3D new ExecutableKind.fromJson( +- jsonDecoder, jsonPath + ".kind", json["kind"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "kind"); +- } +- return new ExecutableFile(file, kind); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "ExecutableFile", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["kind"] =3D kind.toJson(); +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutableFile) { +- return file =3D=3D other.file && kind =3D=3D other.kind; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, kind.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ExecutableKind +- * +- * enum { +- * CLIENT +- * EITHER +- * NOT_EXECUTABLE +- * SERVER +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutableKind implements Enum { +- static const ExecutableKind CLIENT =3D const ExecutableKind._("CLIENT"); +- +- static const ExecutableKind EITHER =3D const ExecutableKind._("EITHER"); +- +- static const ExecutableKind NOT_EXECUTABLE =3D +- const ExecutableKind._("NOT_EXECUTABLE"); +- +- static const ExecutableKind SERVER =3D const ExecutableKind._("SERVER"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [ +- CLIENT, +- EITHER, +- NOT_EXECUTABLE, +- SERVER +- ]; +- +- @override +- final String name; +- +- const ExecutableKind._(this.name); +- +- factory ExecutableKind(String name) { +- switch (name) { +- case "CLIENT": +- return CLIENT; +- case "EITHER": +- return EITHER; +- case "NOT_EXECUTABLE": +- return NOT_EXECUTABLE; +- case "SERVER": +- return SERVER; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory ExecutableKind.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new ExecutableKind(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "ExecutableKind", json); +- } +- +- @override +- String toString() =3D> "ExecutableKind.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * execution.createContext params +- * +- * { +- * "contextRoot": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionCreateContextParams implements RequestParams { +- String _contextRoot; +- +- /** +- * The path of the Dart or HTML file that will be launched, or the path= of +- * the directory containing the file. +- */ +- String get contextRoot =3D> _contextRoot; +- +- /** +- * The path of the Dart or HTML file that will be launched, or the path= of +- * the directory containing the file. +- */ +- void set contextRoot(String value) { +- assert(value !=3D null); +- this._contextRoot =3D value; +- } +- +- ExecutionCreateContextParams(String contextRoot) { +- this.contextRoot =3D contextRoot; +- } +- +- factory ExecutionCreateContextParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String contextRoot; +- if (json.containsKey("contextRoot")) { +- contextRoot =3D jsonDecoder.decodeString( +- jsonPath + ".contextRoot", json["contextRoot"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "contextRoot"); +- } +- return new ExecutionCreateContextParams(contextRoot); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "execution.createContext params", json); +- } +- } +- +- factory ExecutionCreateContextParams.fromRequest(Request request) { +- return new ExecutionCreateContextParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["contextRoot"] =3D contextRoot; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "execution.createContext", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionCreateContextParams) { +- return contextRoot =3D=3D other.contextRoot; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, contextRoot.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * execution.createContext result +- * +- * { +- * "id": ExecutionContextId +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionCreateContextResult implements ResponseResult { +- String _id; +- +- /** +- * The identifier used to refer to the execution context that was creat= ed. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier used to refer to the execution context that was creat= ed. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- ExecutionCreateContextResult(String id) { +- this.id =3D id; +- } +- +- factory ExecutionCreateContextResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- return new ExecutionCreateContextResult(id); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "execution.createContext result", json); +- } +- } +- +- factory ExecutionCreateContextResult.fromResponse(Response response) { +- return new ExecutionCreateContextResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionCreateContextResult) { +- return id =3D=3D other.id; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * execution.deleteContext params +- * +- * { +- * "id": ExecutionContextId +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionDeleteContextParams implements RequestParams { +- String _id; +- +- /** +- * The identifier of the execution context that is to be deleted. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier of the execution context that is to be deleted. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- ExecutionDeleteContextParams(String id) { +- this.id =3D id; +- } +- +- factory ExecutionDeleteContextParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- return new ExecutionDeleteContextParams(id); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "execution.deleteContext params", json); +- } +- } +- +- factory ExecutionDeleteContextParams.fromRequest(Request request) { +- return new ExecutionDeleteContextParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "execution.deleteContext", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionDeleteContextParams) { +- return id =3D=3D other.id; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * execution.deleteContext result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionDeleteContextResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionDeleteContextResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 479954425; +- } +-} +- +-/** +- * execution.launchData params +- * +- * { +- * "file": FilePath +- * "kind": optional ExecutableKind +- * "referencedFiles": optional List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionLaunchDataParams implements HasToJson { +- String _file; +- +- ExecutableKind _kind; +- +- List _referencedFiles; +- +- /** +- * The file for which launch data is being provided. This will either b= e a +- * Dart library or an HTML file. +- */ +- String get file =3D> _file; +- +- /** +- * The file for which launch data is being provided. This will either b= e a +- * Dart library or an HTML file. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The kind of the executable file. This field is omitted if the file i= s not +- * a Dart file. +- */ +- ExecutableKind get kind =3D> _kind; +- +- /** +- * The kind of the executable file. This field is omitted if the file i= s not +- * a Dart file. +- */ +- void set kind(ExecutableKind value) { +- this._kind =3D value; +- } +- +- /** +- * A list of the Dart files that are referenced by the file. This field= is +- * omitted if the file is not an HTML file. +- */ +- List get referencedFiles =3D> _referencedFiles; +- +- /** +- * A list of the Dart files that are referenced by the file. This field= is +- * omitted if the file is not an HTML file. +- */ +- void set referencedFiles(List value) { +- this._referencedFiles =3D value; +- } +- +- ExecutionLaunchDataParams(String file, +- {ExecutableKind kind, List referencedFiles}) { +- this.file =3D file; +- this.kind =3D kind; +- this.referencedFiles =3D referencedFiles; +- } +- +- factory ExecutionLaunchDataParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- ExecutableKind kind; +- if (json.containsKey("kind")) { +- kind =3D new ExecutableKind.fromJson( +- jsonDecoder, jsonPath + ".kind", json["kind"]); +- } +- List referencedFiles; +- if (json.containsKey("referencedFiles")) { +- referencedFiles =3D jsonDecoder.decodeList(jsonPath + ".reference= dFiles", +- json["referencedFiles"], jsonDecoder.decodeString); +- } +- return new ExecutionLaunchDataParams(file, +- kind: kind, referencedFiles: referencedFiles); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "execution.launchData params",= json); +- } +- } +- +- factory ExecutionLaunchDataParams.fromNotification( +- Notification notification) { +- return new ExecutionLaunchDataParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- if (kind !=3D null) { +- result["kind"] =3D kind.toJson(); +- } +- if (referencedFiles !=3D null) { +- result["referencedFiles"] =3D referencedFiles; +- } +- return result; +- } +- +- Notification toNotification() { +- return new Notification("execution.launchData", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionLaunchDataParams) { +- return file =3D=3D other.file && +- kind =3D=3D other.kind && +- listEqual(referencedFiles, other.referencedFiles, +- (String a, String b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, kind.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, referencedFiles.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * execution.mapUri params +- * +- * { +- * "id": ExecutionContextId +- * "file": optional FilePath +- * "uri": optional String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionMapUriParams implements RequestParams { +- String _id; +- +- String _file; +- +- String _uri; +- +- /** +- * The identifier of the execution context in which the URI is to be ma= pped. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier of the execution context in which the URI is to be ma= pped. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- /** +- * The path of the file to be mapped into a URI. +- */ +- String get file =3D> _file; +- +- /** +- * The path of the file to be mapped into a URI. +- */ +- void set file(String value) { +- this._file =3D value; +- } +- +- /** +- * The URI to be mapped into a file path. +- */ +- String get uri =3D> _uri; +- +- /** +- * The URI to be mapped into a file path. +- */ +- void set uri(String value) { +- this._uri =3D value; +- } +- +- ExecutionMapUriParams(String id, {String file, String uri}) { +- this.id =3D id; +- this.file =3D file; +- this.uri =3D uri; +- } +- +- factory ExecutionMapUriParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } +- String uri; +- if (json.containsKey("uri")) { +- uri =3D jsonDecoder.decodeString(jsonPath + ".uri", json["uri"]); +- } +- return new ExecutionMapUriParams(id, file: file, uri: uri); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "execution.mapUri params", jso= n); +- } +- } +- +- factory ExecutionMapUriParams.fromRequest(Request request) { +- return new ExecutionMapUriParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- if (file !=3D null) { +- result["file"] =3D file; +- } +- if (uri !=3D null) { +- result["uri"] =3D uri; +- } +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "execution.mapUri", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionMapUriParams) { +- return id =3D=3D other.id && file =3D=3D other.file && uri =3D=3D o= ther.uri; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, uri.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * execution.mapUri result +- * +- * { +- * "file": optional FilePath +- * "uri": optional String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionMapUriResult implements ResponseResult { +- String _file; +- +- String _uri; +- +- /** +- * The file to which the URI was mapped. This field is omitted if the u= ri +- * field was not given in the request. +- */ +- String get file =3D> _file; +- +- /** +- * The file to which the URI was mapped. This field is omitted if the u= ri +- * field was not given in the request. +- */ +- void set file(String value) { +- this._file =3D value; +- } +- +- /** +- * The URI to which the file path was mapped. This field is omitted if = the +- * file field was not given in the request. +- */ +- String get uri =3D> _uri; +- +- /** +- * The URI to which the file path was mapped. This field is omitted if = the +- * file field was not given in the request. +- */ +- void set uri(String value) { +- this._uri =3D value; +- } +- +- ExecutionMapUriResult({String file, String uri}) { +- this.file =3D file; +- this.uri =3D uri; +- } +- +- factory ExecutionMapUriResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } +- String uri; +- if (json.containsKey("uri")) { +- uri =3D jsonDecoder.decodeString(jsonPath + ".uri", json["uri"]); +- } +- return new ExecutionMapUriResult(file: file, uri: uri); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "execution.mapUri result", jso= n); +- } +- } +- +- factory ExecutionMapUriResult.fromResponse(Response response) { +- return new ExecutionMapUriResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (file !=3D null) { +- result["file"] =3D file; +- } +- if (uri !=3D null) { +- result["uri"] =3D uri; +- } +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionMapUriResult) { +- return file =3D=3D other.file && uri =3D=3D other.uri; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, uri.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ExecutionService +- * +- * enum { +- * LAUNCH_DATA +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionService implements Enum { +- static const ExecutionService LAUNCH_DATA =3D +- const ExecutionService._("LAUNCH_DATA"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [ +- LAUNCH_DATA +- ]; +- +- @override +- final String name; +- +- const ExecutionService._(this.name); +- +- factory ExecutionService(String name) { +- switch (name) { +- case "LAUNCH_DATA": +- return LAUNCH_DATA; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory ExecutionService.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new ExecutionService(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "ExecutionService", json); +- } +- +- @override +- String toString() =3D> "ExecutionService.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * execution.setSubscriptions params +- * +- * { +- * "subscriptions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionSetSubscriptionsParams implements RequestParams { +- List _subscriptions; +- +- /** +- * A list of the services being subscribed to. +- */ +- List get subscriptions =3D> _subscriptions; +- +- /** +- * A list of the services being subscribed to. +- */ +- void set subscriptions(List value) { +- assert(value !=3D null); +- this._subscriptions =3D value; +- } +- +- ExecutionSetSubscriptionsParams(List subscriptions) { +- this.subscriptions =3D subscriptions; +- } +- +- factory ExecutionSetSubscriptionsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List subscriptions; +- if (json.containsKey("subscriptions")) { +- subscriptions =3D jsonDecoder.decodeList( +- jsonPath + ".subscriptions", +- json["subscriptions"], +- (String jsonPath, Object json) =3D> +- new ExecutionService.fromJson(jsonDecoder, jsonPath, json= )); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "subscriptions"); +- } +- return new ExecutionSetSubscriptionsParams(subscriptions); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "execution.setSubscriptions params", json); +- } +- } +- +- factory ExecutionSetSubscriptionsParams.fromRequest(Request request) { +- return new ExecutionSetSubscriptionsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["subscriptions"] =3D +- subscriptions.map((ExecutionService value) =3D> value.toJson()).t= oList(); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "execution.setSubscriptions", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionSetSubscriptionsParams) { +- return listEqual(subscriptions, other.subscriptions, +- (ExecutionService a, ExecutionService b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, subscriptions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * execution.setSubscriptions result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExecutionSetSubscriptionsResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExecutionSetSubscriptionsResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 287678780; +- } +-} +- +-/** +- * extractLocalVariable feedback +- * +- * { +- * "coveringExpressionOffsets": optional List +- * "coveringExpressionLengths": optional List +- * "names": List +- * "offsets": List +- * "lengths": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExtractLocalVariableFeedback extends RefactoringFeedback { +- List _coveringExpressionOffsets; +- +- List _coveringExpressionLengths; +- +- List _names; +- +- List _offsets; +- +- List _lengths; +- +- /** +- * The offsets of the expressions that cover the specified selection, f= rom +- * the down most to the up most. +- */ +- List get coveringExpressionOffsets =3D> _coveringExpressionOffsets; +- +- /** +- * The offsets of the expressions that cover the specified selection, f= rom +- * the down most to the up most. +- */ +- void set coveringExpressionOffsets(List value) { +- this._coveringExpressionOffsets =3D value; +- } +- +- /** +- * The lengths of the expressions that cover the specified selection, f= rom +- * the down most to the up most. +- */ +- List get coveringExpressionLengths =3D> _coveringExpressionLengths; +- +- /** +- * The lengths of the expressions that cover the specified selection, f= rom +- * the down most to the up most. +- */ +- void set coveringExpressionLengths(List value) { +- this._coveringExpressionLengths =3D value; +- } +- +- /** +- * The proposed names for the local variable. +- */ +- List get names =3D> _names; +- +- /** +- * The proposed names for the local variable. +- */ +- void set names(List value) { +- assert(value !=3D null); +- this._names =3D value; +- } +- +- /** +- * The offsets of the expressions that would be replaced by a reference= to +- * the variable. +- */ +- List get offsets =3D> _offsets; +- +- /** +- * The offsets of the expressions that would be replaced by a reference= to +- * the variable. +- */ +- void set offsets(List value) { +- assert(value !=3D null); +- this._offsets =3D value; +- } +- +- /** +- * The lengths of the expressions that would be replaced by a reference= to +- * the variable. The lengths correspond to the offsets. In other words,= for a +- * given expression, if the offset of that expression is offsets[i], th= en the +- * length of that expression is lengths[i]. +- */ +- List get lengths =3D> _lengths; +- +- /** +- * The lengths of the expressions that would be replaced by a reference= to +- * the variable. The lengths correspond to the offsets. In other words,= for a +- * given expression, if the offset of that expression is offsets[i], th= en the +- * length of that expression is lengths[i]. +- */ +- void set lengths(List value) { +- assert(value !=3D null); +- this._lengths =3D value; +- } +- +- ExtractLocalVariableFeedback( +- List names, List offsets, List lengths, +- {List coveringExpressionOffsets, +- List coveringExpressionLengths}) { +- this.coveringExpressionOffsets =3D coveringExpressionOffsets; +- this.coveringExpressionLengths =3D coveringExpressionLengths; +- this.names =3D names; +- this.offsets =3D offsets; +- this.lengths =3D lengths; +- } +- +- factory ExtractLocalVariableFeedback.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List coveringExpressionOffsets; +- if (json.containsKey("coveringExpressionOffsets")) { +- coveringExpressionOffsets =3D jsonDecoder.decodeList( +- jsonPath + ".coveringExpressionOffsets", +- json["coveringExpressionOffsets"], +- jsonDecoder.decodeInt); +- } +- List coveringExpressionLengths; +- if (json.containsKey("coveringExpressionLengths")) { +- coveringExpressionLengths =3D jsonDecoder.decodeList( +- jsonPath + ".coveringExpressionLengths", +- json["coveringExpressionLengths"], +- jsonDecoder.decodeInt); +- } +- List names; +- if (json.containsKey("names")) { +- names =3D jsonDecoder.decodeList( +- jsonPath + ".names", json["names"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "names"); +- } +- List offsets; +- if (json.containsKey("offsets")) { +- offsets =3D jsonDecoder.decodeList( +- jsonPath + ".offsets", json["offsets"], jsonDecoder.decodeInt= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offsets"); +- } +- List lengths; +- if (json.containsKey("lengths")) { +- lengths =3D jsonDecoder.decodeList( +- jsonPath + ".lengths", json["lengths"], jsonDecoder.decodeInt= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "lengths"); +- } +- return new ExtractLocalVariableFeedback(names, offsets, lengths, +- coveringExpressionOffsets: coveringExpressionOffsets, +- coveringExpressionLengths: coveringExpressionLengths); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "extractLocalVariable feedback", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (coveringExpressionOffsets !=3D null) { +- result["coveringExpressionOffsets"] =3D coveringExpressionOffsets; +- } +- if (coveringExpressionLengths !=3D null) { +- result["coveringExpressionLengths"] =3D coveringExpressionLengths; +- } +- result["names"] =3D names; +- result["offsets"] =3D offsets; +- result["lengths"] =3D lengths; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExtractLocalVariableFeedback) { +- return listEqual(coveringExpressionOffsets, +- other.coveringExpressionOffsets, (int a, int b) =3D> a =3D= =3D b) && +- listEqual(coveringExpressionLengths, other.coveringExpressionLe= ngths, +- (int a, int b) =3D> a =3D=3D b) && +- listEqual(names, other.names, (String a, String b) =3D> a =3D= =3D b) && +- listEqual(offsets, other.offsets, (int a, int b) =3D> a =3D=3D = b) && +- listEqual(lengths, other.lengths, (int a, int b) =3D> a =3D=3D = b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, coveringExpressionOffsets.hashC= ode); +- hash =3D JenkinsSmiHash.combine(hash, coveringExpressionLengths.hashC= ode); +- hash =3D JenkinsSmiHash.combine(hash, names.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offsets.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, lengths.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * extractLocalVariable options +- * +- * { +- * "name": String +- * "extractAll": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExtractLocalVariableOptions extends RefactoringOptions { +- String _name; +- +- bool _extractAll; +- +- /** +- * The name that the local variable should be given. +- */ +- String get name =3D> _name; +- +- /** +- * The name that the local variable should be given. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- /** +- * True if all occurrences of the expression within the scope in which = the +- * variable will be defined should be replaced by a reference to the lo= cal +- * variable. The expression used to initiate the refactoring will alway= s be +- * replaced. +- */ +- bool get extractAll =3D> _extractAll; +- +- /** +- * True if all occurrences of the expression within the scope in which = the +- * variable will be defined should be replaced by a reference to the lo= cal +- * variable. The expression used to initiate the refactoring will alway= s be +- * replaced. +- */ +- void set extractAll(bool value) { +- assert(value !=3D null); +- this._extractAll =3D value; +- } +- +- ExtractLocalVariableOptions(String name, bool extractAll) { +- this.name =3D name; +- this.extractAll =3D extractAll; +- } +- +- factory ExtractLocalVariableOptions.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- bool extractAll; +- if (json.containsKey("extractAll")) { +- extractAll =3D jsonDecoder.decodeBool( +- jsonPath + ".extractAll", json["extractAll"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "extractAll"); +- } +- return new ExtractLocalVariableOptions(name, extractAll); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "extractLocalVariable options", json); +- } +- } +- +- factory ExtractLocalVariableOptions.fromRefactoringParams( +- EditGetRefactoringParams refactoringParams, Request request) { +- return new ExtractLocalVariableOptions.fromJson( +- new RequestDecoder(request), "options", refactoringParams.options= ); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["name"] =3D name; +- result["extractAll"] =3D extractAll; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExtractLocalVariableOptions) { +- return name =3D=3D other.name && extractAll =3D=3D other.extractAll; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, extractAll.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * extractMethod feedback +- * +- * { +- * "offset": int +- * "length": int +- * "returnType": String +- * "names": List +- * "canCreateGetter": bool +- * "parameters": List +- * "offsets": List +- * "lengths": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExtractMethodFeedback extends RefactoringFeedback { +- int _offset; +- +- int _length; +- +- String _returnType; +- +- List _names; +- +- bool _canCreateGetter; +- +- List _parameters; +- +- List _offsets; +- +- List _lengths; +- +- /** +- * The offset to the beginning of the expression or statements that wil= l be +- * extracted. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset to the beginning of the expression or statements that wil= l be +- * extracted. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the expression or statements that will be extracted. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the expression or statements that will be extracted. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * The proposed return type for the method. If the returned element doe= s not +- * have a declared return type, this field will contain an empty string. +- */ +- String get returnType =3D> _returnType; +- +- /** +- * The proposed return type for the method. If the returned element doe= s not +- * have a declared return type, this field will contain an empty string. +- */ +- void set returnType(String value) { +- assert(value !=3D null); +- this._returnType =3D value; +- } +- +- /** +- * The proposed names for the method. +- */ +- List get names =3D> _names; +- +- /** +- * The proposed names for the method. +- */ +- void set names(List value) { +- assert(value !=3D null); +- this._names =3D value; +- } +- +- /** +- * True if a getter could be created rather than a method. +- */ +- bool get canCreateGetter =3D> _canCreateGetter; +- +- /** +- * True if a getter could be created rather than a method. +- */ +- void set canCreateGetter(bool value) { +- assert(value !=3D null); +- this._canCreateGetter =3D value; +- } +- +- /** +- * The proposed parameters for the method. +- */ +- List get parameters =3D> _parameters; +- +- /** +- * The proposed parameters for the method. +- */ +- void set parameters(List value) { +- assert(value !=3D null); +- this._parameters =3D value; +- } +- +- /** +- * The offsets of the expressions or statements that would be replaced = by an +- * invocation of the method. +- */ +- List get offsets =3D> _offsets; +- +- /** +- * The offsets of the expressions or statements that would be replaced = by an +- * invocation of the method. +- */ +- void set offsets(List value) { +- assert(value !=3D null); +- this._offsets =3D value; +- } +- +- /** +- * The lengths of the expressions or statements that would be replaced = by an +- * invocation of the method. The lengths correspond to the offsets. In = other +- * words, for a given expression (or block of statements), if the offse= t of +- * that expression is offsets[i], then the length of that expression is +- * lengths[i]. +- */ +- List get lengths =3D> _lengths; +- +- /** +- * The lengths of the expressions or statements that would be replaced = by an +- * invocation of the method. The lengths correspond to the offsets. In = other +- * words, for a given expression (or block of statements), if the offse= t of +- * that expression is offsets[i], then the length of that expression is +- * lengths[i]. +- */ +- void set lengths(List value) { +- assert(value !=3D null); +- this._lengths =3D value; +- } +- +- ExtractMethodFeedback( +- int offset, +- int length, +- String returnType, +- List names, +- bool canCreateGetter, +- List parameters, +- List offsets, +- List lengths) { +- this.offset =3D offset; +- this.length =3D length; +- this.returnType =3D returnType; +- this.names =3D names; +- this.canCreateGetter =3D canCreateGetter; +- this.parameters =3D parameters; +- this.offsets =3D offsets; +- this.lengths =3D lengths; +- } +- +- factory ExtractMethodFeedback.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- String returnType; +- if (json.containsKey("returnType")) { +- returnType =3D jsonDecoder.decodeString( +- jsonPath + ".returnType", json["returnType"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "returnType"); +- } +- List names; +- if (json.containsKey("names")) { +- names =3D jsonDecoder.decodeList( +- jsonPath + ".names", json["names"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "names"); +- } +- bool canCreateGetter; +- if (json.containsKey("canCreateGetter")) { +- canCreateGetter =3D jsonDecoder.decodeBool( +- jsonPath + ".canCreateGetter", json["canCreateGetter"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "canCreateGetter"); +- } +- List parameters; +- if (json.containsKey("parameters")) { +- parameters =3D jsonDecoder.decodeList( +- jsonPath + ".parameters", +- json["parameters"], +- (String jsonPath, Object json) =3D> +- new RefactoringMethodParameter.fromJson( +- jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "parameters"); +- } +- List offsets; +- if (json.containsKey("offsets")) { +- offsets =3D jsonDecoder.decodeList( +- jsonPath + ".offsets", json["offsets"], jsonDecoder.decodeInt= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offsets"); +- } +- List lengths; +- if (json.containsKey("lengths")) { +- lengths =3D jsonDecoder.decodeList( +- jsonPath + ".lengths", json["lengths"], jsonDecoder.decodeInt= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "lengths"); +- } +- return new ExtractMethodFeedback(offset, length, returnType, names, +- canCreateGetter, parameters, offsets, lengths); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "extractMethod feedback", json= ); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- result["returnType"] =3D returnType; +- result["names"] =3D names; +- result["canCreateGetter"] =3D canCreateGetter; +- result["parameters"] =3D parameters +- .map((RefactoringMethodParameter value) =3D> value.toJson()) +- .toList(); +- result["offsets"] =3D offsets; +- result["lengths"] =3D lengths; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExtractMethodFeedback) { +- return offset =3D=3D other.offset && +- length =3D=3D other.length && +- returnType =3D=3D other.returnType && +- listEqual(names, other.names, (String a, String b) =3D> a =3D= =3D b) && +- canCreateGetter =3D=3D other.canCreateGetter && +- listEqual( +- parameters, +- other.parameters, +- (RefactoringMethodParameter a, RefactoringMethodParameter b= ) =3D> +- a =3D=3D b) && +- listEqual(offsets, other.offsets, (int a, int b) =3D> a =3D=3D = b) && +- listEqual(lengths, other.lengths, (int a, int b) =3D> a =3D=3D = b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, returnType.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, names.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, canCreateGetter.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, parameters.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offsets.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, lengths.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * extractMethod options +- * +- * { +- * "returnType": String +- * "createGetter": bool +- * "name": String +- * "parameters": List +- * "extractAll": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ExtractMethodOptions extends RefactoringOptions { +- String _returnType; +- +- bool _createGetter; +- +- String _name; +- +- List _parameters; +- +- bool _extractAll; +- +- /** +- * The return type that should be defined for the method. +- */ +- String get returnType =3D> _returnType; +- +- /** +- * The return type that should be defined for the method. +- */ +- void set returnType(String value) { +- assert(value !=3D null); +- this._returnType =3D value; +- } +- +- /** +- * True if a getter should be created rather than a method. It is an er= ror if +- * this field is true and the list of parameters is non-empty. +- */ +- bool get createGetter =3D> _createGetter; +- +- /** +- * True if a getter should be created rather than a method. It is an er= ror if +- * this field is true and the list of parameters is non-empty. +- */ +- void set createGetter(bool value) { +- assert(value !=3D null); +- this._createGetter =3D value; +- } +- +- /** +- * The name that the method should be given. +- */ +- String get name =3D> _name; +- +- /** +- * The name that the method should be given. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- /** +- * The parameters that should be defined for the method. +- * +- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL +- * parameter. It is an error if a REQUIRED or POSITIONAL parameter foll= ows a +- * NAMED parameter. +- * +- * - To change the order and/or update proposed parameters, add paramet= ers +- * with the same identifiers as proposed. +- * - To add new parameters, omit their identifier. +- * - To remove some parameters, omit them in this list. +- */ +- List get parameters =3D> _parameters; +- +- /** +- * The parameters that should be defined for the method. +- * +- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL +- * parameter. It is an error if a REQUIRED or POSITIONAL parameter foll= ows a +- * NAMED parameter. +- * +- * - To change the order and/or update proposed parameters, add paramet= ers +- * with the same identifiers as proposed. +- * - To add new parameters, omit their identifier. +- * - To remove some parameters, omit them in this list. +- */ +- void set parameters(List value) { +- assert(value !=3D null); +- this._parameters =3D value; +- } +- +- /** +- * True if all occurrences of the expression or statements should be re= placed +- * by an invocation of the method. The expression or statements used to +- * initiate the refactoring will always be replaced. +- */ +- bool get extractAll =3D> _extractAll; +- +- /** +- * True if all occurrences of the expression or statements should be re= placed +- * by an invocation of the method. The expression or statements used to +- * initiate the refactoring will always be replaced. +- */ +- void set extractAll(bool value) { +- assert(value !=3D null); +- this._extractAll =3D value; +- } +- +- ExtractMethodOptions(String returnType, bool createGetter, String name, +- List parameters, bool extractAll) { +- this.returnType =3D returnType; +- this.createGetter =3D createGetter; +- this.name =3D name; +- this.parameters =3D parameters; +- this.extractAll =3D extractAll; +- } +- +- factory ExtractMethodOptions.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String returnType; +- if (json.containsKey("returnType")) { +- returnType =3D jsonDecoder.decodeString( +- jsonPath + ".returnType", json["returnType"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "returnType"); +- } +- bool createGetter; +- if (json.containsKey("createGetter")) { +- createGetter =3D jsonDecoder.decodeBool( +- jsonPath + ".createGetter", json["createGetter"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "createGetter"); +- } +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- List parameters; +- if (json.containsKey("parameters")) { +- parameters =3D jsonDecoder.decodeList( +- jsonPath + ".parameters", +- json["parameters"], +- (String jsonPath, Object json) =3D> +- new RefactoringMethodParameter.fromJson( +- jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "parameters"); +- } +- bool extractAll; +- if (json.containsKey("extractAll")) { +- extractAll =3D jsonDecoder.decodeBool( +- jsonPath + ".extractAll", json["extractAll"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "extractAll"); +- } +- return new ExtractMethodOptions( +- returnType, createGetter, name, parameters, extractAll); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "extractMethod options", json); +- } +- } +- +- factory ExtractMethodOptions.fromRefactoringParams( +- EditGetRefactoringParams refactoringParams, Request request) { +- return new ExtractMethodOptions.fromJson( +- new RequestDecoder(request), "options", refactoringParams.options= ); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["returnType"] =3D returnType; +- result["createGetter"] =3D createGetter; +- result["name"] =3D name; +- result["parameters"] =3D parameters +- .map((RefactoringMethodParameter value) =3D> value.toJson()) +- .toList(); +- result["extractAll"] =3D extractAll; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ExtractMethodOptions) { +- return returnType =3D=3D other.returnType && +- createGetter =3D=3D other.createGetter && +- name =3D=3D other.name && +- listEqual( +- parameters, +- other.parameters, +- (RefactoringMethodParameter a, RefactoringMethodParameter b= ) =3D> +- a =3D=3D b) && +- extractAll =3D=3D other.extractAll; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, returnType.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, createGetter.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, parameters.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, extractAll.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * FileKind +- * +- * enum { +- * LIBRARY +- * PART +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class FileKind implements Enum { +- static const FileKind LIBRARY =3D const FileKind._("LIBRARY"); +- +- static const FileKind PART =3D const FileKind._("PART"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [LIBRARY, PART]; +- +- @override +- final String name; +- +- const FileKind._(this.name); +- +- factory FileKind(String name) { +- switch (name) { +- case "LIBRARY": +- return LIBRARY; +- case "PART": +- return PART; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory FileKind.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new FileKind(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "FileKind", json); +- } +- +- @override +- String toString() =3D> "FileKind.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * GeneralAnalysisService +- * +- * enum { +- * ANALYZED_FILES +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class GeneralAnalysisService implements Enum { +- static const GeneralAnalysisService ANALYZED_FILES =3D +- const GeneralAnalysisService._("ANALYZED_FILES"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D +- const [ANALYZED_FILES]; +- +- @override +- final String name; +- +- const GeneralAnalysisService._(this.name); +- +- factory GeneralAnalysisService(String name) { +- switch (name) { +- case "ANALYZED_FILES": +- return ANALYZED_FILES; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory GeneralAnalysisService.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new GeneralAnalysisService(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "GeneralAnalysisService", json); +- } +- +- @override +- String toString() =3D> "GeneralAnalysisService.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * HoverInformation +- * +- * { +- * "offset": int +- * "length": int +- * "containingLibraryPath": optional String +- * "containingLibraryName": optional String +- * "containingClassDescription": optional String +- * "dartdoc": optional String +- * "elementDescription": optional String +- * "elementKind": optional String +- * "isDeprecated": optional bool +- * "parameter": optional String +- * "propagatedType": optional String +- * "staticType": optional String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class HoverInformation implements HasToJson { +- int _offset; +- +- int _length; +- +- String _containingLibraryPath; +- +- String _containingLibraryName; +- +- String _containingClassDescription; +- +- String _dartdoc; +- +- String _elementDescription; +- +- String _elementKind; +- +- bool _isDeprecated; +- +- String _parameter; +- +- String _propagatedType; +- +- String _staticType; +- +- /** +- * The offset of the range of characters that encompasses the cursor po= sition +- * and has the same hover information as the cursor position. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the range of characters that encompasses the cursor po= sition +- * and has the same hover information as the cursor position. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the range of characters that encompasses the cursor po= sition +- * and has the same hover information as the cursor position. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the range of characters that encompasses the cursor po= sition +- * and has the same hover information as the cursor position. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * The path to the defining compilation unit of the library in which the +- * referenced element is declared. This data is omitted if there is no +- * referenced element, or if the element is declared inside an HTML fil= e. +- */ +- String get containingLibraryPath =3D> _containingLibraryPath; +- +- /** +- * The path to the defining compilation unit of the library in which the +- * referenced element is declared. This data is omitted if there is no +- * referenced element, or if the element is declared inside an HTML fil= e. +- */ +- void set containingLibraryPath(String value) { +- this._containingLibraryPath =3D value; +- } +- +- /** +- * The name of the library in which the referenced element is declared.= This +- * data is omitted if there is no referenced element, or if the element= is +- * declared inside an HTML file. +- */ +- String get containingLibraryName =3D> _containingLibraryName; +- +- /** +- * The name of the library in which the referenced element is declared.= This +- * data is omitted if there is no referenced element, or if the element= is +- * declared inside an HTML file. +- */ +- void set containingLibraryName(String value) { +- this._containingLibraryName =3D value; +- } +- +- /** +- * A human-readable description of the class declaring the element being +- * referenced. This data is omitted if there is no referenced element, = or if +- * the element is not a class member. +- */ +- String get containingClassDescription =3D> _containingClassDescription; +- +- /** +- * A human-readable description of the class declaring the element being +- * referenced. This data is omitted if there is no referenced element, = or if +- * the element is not a class member. +- */ +- void set containingClassDescription(String value) { +- this._containingClassDescription =3D value; +- } +- +- /** +- * The dartdoc associated with the referenced element. Other than the r= emoval +- * of the comment delimiters, including leading asterisks in the case o= f a +- * block comment, the dartdoc is unprocessed markdown. This data is omi= tted +- * if there is no referenced element, or if the element has no dartdoc. +- */ +- String get dartdoc =3D> _dartdoc; +- +- /** +- * The dartdoc associated with the referenced element. Other than the r= emoval +- * of the comment delimiters, including leading asterisks in the case o= f a +- * block comment, the dartdoc is unprocessed markdown. This data is omi= tted +- * if there is no referenced element, or if the element has no dartdoc. +- */ +- void set dartdoc(String value) { +- this._dartdoc =3D value; +- } +- +- /** +- * A human-readable description of the element being referenced. This d= ata is +- * omitted if there is no referenced element. +- */ +- String get elementDescription =3D> _elementDescription; +- +- /** +- * A human-readable description of the element being referenced. This d= ata is +- * omitted if there is no referenced element. +- */ +- void set elementDescription(String value) { +- this._elementDescription =3D value; +- } +- +- /** +- * A human-readable description of the kind of element being referenced= (such +- * as "class" or "function type alias"). This data is omitted if there = is no +- * referenced element. +- */ +- String get elementKind =3D> _elementKind; +- +- /** +- * A human-readable description of the kind of element being referenced= (such +- * as "class" or "function type alias"). This data is omitted if there = is no +- * referenced element. +- */ +- void set elementKind(String value) { +- this._elementKind =3D value; +- } +- +- /** +- * True if the referenced element is deprecated. +- */ +- bool get isDeprecated =3D> _isDeprecated; +- +- /** +- * True if the referenced element is deprecated. +- */ +- void set isDeprecated(bool value) { +- this._isDeprecated =3D value; +- } +- +- /** +- * A human-readable description of the parameter corresponding to the +- * expression being hovered over. This data is omitted if the location = is not +- * in an argument to a function. +- */ +- String get parameter =3D> _parameter; +- +- /** +- * A human-readable description of the parameter corresponding to the +- * expression being hovered over. This data is omitted if the location = is not +- * in an argument to a function. +- */ +- void set parameter(String value) { +- this._parameter =3D value; +- } +- +- /** +- * The name of the propagated type of the expression. This data is omit= ted if +- * the location does not correspond to an expression or if there is no +- * propagated type information. +- */ +- String get propagatedType =3D> _propagatedType; +- +- /** +- * The name of the propagated type of the expression. This data is omit= ted if +- * the location does not correspond to an expression or if there is no +- * propagated type information. +- */ +- void set propagatedType(String value) { +- this._propagatedType =3D value; +- } +- +- /** +- * The name of the static type of the expression. This data is omitted = if the +- * location does not correspond to an expression. +- */ +- String get staticType =3D> _staticType; +- +- /** +- * The name of the static type of the expression. This data is omitted = if the +- * location does not correspond to an expression. +- */ +- void set staticType(String value) { +- this._staticType =3D value; +- } +- +- HoverInformation(int offset, int length, +- {String containingLibraryPath, +- String containingLibraryName, +- String containingClassDescription, +- String dartdoc, +- String elementDescription, +- String elementKind, +- bool isDeprecated, +- String parameter, +- String propagatedType, +- String staticType}) { +- this.offset =3D offset; +- this.length =3D length; +- this.containingLibraryPath =3D containingLibraryPath; +- this.containingLibraryName =3D containingLibraryName; +- this.containingClassDescription =3D containingClassDescription; +- this.dartdoc =3D dartdoc; +- this.elementDescription =3D elementDescription; +- this.elementKind =3D elementKind; +- this.isDeprecated =3D isDeprecated; +- this.parameter =3D parameter; +- this.propagatedType =3D propagatedType; +- this.staticType =3D staticType; +- } +- +- factory HoverInformation.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- String containingLibraryPath; +- if (json.containsKey("containingLibraryPath")) { +- containingLibraryPath =3D jsonDecoder.decodeString( +- jsonPath + ".containingLibraryPath", json["containingLibraryP= ath"]); +- } +- String containingLibraryName; +- if (json.containsKey("containingLibraryName")) { +- containingLibraryName =3D jsonDecoder.decodeString( +- jsonPath + ".containingLibraryName", json["containingLibraryN= ame"]); +- } +- String containingClassDescription; +- if (json.containsKey("containingClassDescription")) { +- containingClassDescription =3D jsonDecoder.decodeString( +- jsonPath + ".containingClassDescription", +- json["containingClassDescription"]); +- } +- String dartdoc; +- if (json.containsKey("dartdoc")) { +- dartdoc =3D +- jsonDecoder.decodeString(jsonPath + ".dartdoc", json["dartdoc= "]); +- } +- String elementDescription; +- if (json.containsKey("elementDescription")) { +- elementDescription =3D jsonDecoder.decodeString( +- jsonPath + ".elementDescription", json["elementDescription"]); +- } +- String elementKind; +- if (json.containsKey("elementKind")) { +- elementKind =3D jsonDecoder.decodeString( +- jsonPath + ".elementKind", json["elementKind"]); +- } +- bool isDeprecated; +- if (json.containsKey("isDeprecated")) { +- isDeprecated =3D jsonDecoder.decodeBool( +- jsonPath + ".isDeprecated", json["isDeprecated"]); +- } +- String parameter; +- if (json.containsKey("parameter")) { +- parameter =3D jsonDecoder.decodeString( +- jsonPath + ".parameter", json["parameter"]); +- } +- String propagatedType; +- if (json.containsKey("propagatedType")) { +- propagatedType =3D jsonDecoder.decodeString( +- jsonPath + ".propagatedType", json["propagatedType"]); +- } +- String staticType; +- if (json.containsKey("staticType")) { +- staticType =3D jsonDecoder.decodeString( +- jsonPath + ".staticType", json["staticType"]); +- } +- return new HoverInformation(offset, length, +- containingLibraryPath: containingLibraryPath, +- containingLibraryName: containingLibraryName, +- containingClassDescription: containingClassDescription, +- dartdoc: dartdoc, +- elementDescription: elementDescription, +- elementKind: elementKind, +- isDeprecated: isDeprecated, +- parameter: parameter, +- propagatedType: propagatedType, +- staticType: staticType); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "HoverInformation", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- if (containingLibraryPath !=3D null) { +- result["containingLibraryPath"] =3D containingLibraryPath; +- } +- if (containingLibraryName !=3D null) { +- result["containingLibraryName"] =3D containingLibraryName; +- } +- if (containingClassDescription !=3D null) { +- result["containingClassDescription"] =3D containingClassDescription; +- } +- if (dartdoc !=3D null) { +- result["dartdoc"] =3D dartdoc; +- } +- if (elementDescription !=3D null) { +- result["elementDescription"] =3D elementDescription; +- } +- if (elementKind !=3D null) { +- result["elementKind"] =3D elementKind; +- } +- if (isDeprecated !=3D null) { +- result["isDeprecated"] =3D isDeprecated; +- } +- if (parameter !=3D null) { +- result["parameter"] =3D parameter; +- } +- if (propagatedType !=3D null) { +- result["propagatedType"] =3D propagatedType; +- } +- if (staticType !=3D null) { +- result["staticType"] =3D staticType; +- } +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is HoverInformation) { +- return offset =3D=3D other.offset && +- length =3D=3D other.length && +- containingLibraryPath =3D=3D other.containingLibraryPath && +- containingLibraryName =3D=3D other.containingLibraryName && +- containingClassDescription =3D=3D other.containingClassDescript= ion && +- dartdoc =3D=3D other.dartdoc && +- elementDescription =3D=3D other.elementDescription && +- elementKind =3D=3D other.elementKind && +- isDeprecated =3D=3D other.isDeprecated && +- parameter =3D=3D other.parameter && +- propagatedType =3D=3D other.propagatedType && +- staticType =3D=3D other.staticType; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, containingLibraryPath.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, containingLibraryName.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, containingClassDescription.hash= Code); +- hash =3D JenkinsSmiHash.combine(hash, dartdoc.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, elementDescription.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, elementKind.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, isDeprecated.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, parameter.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, propagatedType.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, staticType.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ImplementedClass +- * +- * { +- * "offset": int +- * "length": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ImplementedClass implements HasToJson { +- int _offset; +- +- int _length; +- +- /** +- * The offset of the name of the implemented class. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the name of the implemented class. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the name of the implemented class. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the name of the implemented class. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- ImplementedClass(int offset, int length) { +- this.offset =3D offset; +- this.length =3D length; +- } +- +- factory ImplementedClass.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- return new ImplementedClass(offset, length); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "ImplementedClass", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ImplementedClass) { +- return offset =3D=3D other.offset && length =3D=3D other.length; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ImplementedMember +- * +- * { +- * "offset": int +- * "length": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ImplementedMember implements HasToJson { +- int _offset; +- +- int _length; +- +- /** +- * The offset of the name of the implemented member. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the name of the implemented member. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the name of the implemented member. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the name of the implemented member. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- ImplementedMember(int offset, int length) { +- this.offset =3D offset; +- this.length =3D length; +- } +- +- factory ImplementedMember.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- return new ImplementedMember(offset, length); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "ImplementedMember", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ImplementedMember) { +- return offset =3D=3D other.offset && length =3D=3D other.length; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ImportedElements +- * +- * { +- * "path": FilePath +- * "prefix": String +- * "elements": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ImportedElements implements HasToJson { +- String _path; +- +- String _prefix; +- +- List _elements; +- +- /** +- * The absolute and normalized path of the file containing the library. +- */ +- String get path =3D> _path; +- +- /** +- * The absolute and normalized path of the file containing the library. +- */ +- void set path(String value) { +- assert(value !=3D null); +- this._path =3D value; +- } +- +- /** +- * The prefix that was used when importing the library into the original +- * source. +- */ +- String get prefix =3D> _prefix; +- +- /** +- * The prefix that was used when importing the library into the original +- * source. +- */ +- void set prefix(String value) { +- assert(value !=3D null); +- this._prefix =3D value; +- } +- +- /** +- * The names of the elements imported from the library. +- */ +- List get elements =3D> _elements; +- +- /** +- * The names of the elements imported from the library. +- */ +- void set elements(List value) { +- assert(value !=3D null); +- this._elements =3D value; +- } +- +- ImportedElements(String path, String prefix, List elements) { +- this.path =3D path; +- this.prefix =3D prefix; +- this.elements =3D elements; +- } +- +- factory ImportedElements.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String path; +- if (json.containsKey("path")) { +- path =3D jsonDecoder.decodeString(jsonPath + ".path", json["path"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "path"); +- } +- String prefix; +- if (json.containsKey("prefix")) { +- prefix =3D jsonDecoder.decodeString(jsonPath + ".prefix", json["p= refix"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "prefix"); +- } +- List elements; +- if (json.containsKey("elements")) { +- elements =3D jsonDecoder.decodeList( +- jsonPath + ".elements", json["elements"], jsonDecoder.decodeS= tring); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "elements"); +- } +- return new ImportedElements(path, prefix, elements); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "ImportedElements", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["path"] =3D path; +- result["prefix"] =3D prefix; +- result["elements"] =3D elements; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ImportedElements) { +- return path =3D=3D other.path && +- prefix =3D=3D other.prefix && +- listEqual(elements, other.elements, (String a, String b) =3D> a= =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, path.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, prefix.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, elements.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * inlineLocalVariable feedback +- * +- * { +- * "name": String +- * "occurrences": int +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class InlineLocalVariableFeedback extends RefactoringFeedback { +- String _name; +- +- int _occurrences; +- +- /** +- * The name of the variable being inlined. +- */ +- String get name =3D> _name; +- +- /** +- * The name of the variable being inlined. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- /** +- * The number of times the variable occurs. +- */ +- int get occurrences =3D> _occurrences; +- +- /** +- * The number of times the variable occurs. +- */ +- void set occurrences(int value) { +- assert(value !=3D null); +- this._occurrences =3D value; +- } +- +- InlineLocalVariableFeedback(String name, int occurrences) { +- this.name =3D name; +- this.occurrences =3D occurrences; +- } +- +- factory InlineLocalVariableFeedback.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- int occurrences; +- if (json.containsKey("occurrences")) { +- occurrences =3D jsonDecoder.decodeInt( +- jsonPath + ".occurrences", json["occurrences"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "occurrences"); +- } +- return new InlineLocalVariableFeedback(name, occurrences); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "inlineLocalVariable feedback", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["name"] =3D name; +- result["occurrences"] =3D occurrences; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is InlineLocalVariableFeedback) { +- return name =3D=3D other.name && occurrences =3D=3D other.occurrenc= es; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, occurrences.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * inlineLocalVariable options +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class InlineLocalVariableOptions extends RefactoringOptions +- implements HasToJson { +- @override +- bool operator =3D=3D(other) { +- if (other is InlineLocalVariableOptions) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 540364977; +- } +-} +- +-/** +- * inlineMethod feedback +- * +- * { +- * "className": optional String +- * "methodName": String +- * "isDeclaration": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class InlineMethodFeedback extends RefactoringFeedback { +- String _className; +- +- String _methodName; +- +- bool _isDeclaration; +- +- /** +- * The name of the class enclosing the method being inlined. If not a c= lass +- * member is being inlined, this field will be absent. +- */ +- String get className =3D> _className; +- +- /** +- * The name of the class enclosing the method being inlined. If not a c= lass +- * member is being inlined, this field will be absent. +- */ +- void set className(String value) { +- this._className =3D value; +- } +- +- /** +- * The name of the method (or function) being inlined. +- */ +- String get methodName =3D> _methodName; +- +- /** +- * The name of the method (or function) being inlined. +- */ +- void set methodName(String value) { +- assert(value !=3D null); +- this._methodName =3D value; +- } +- +- /** +- * True if the declaration of the method is selected. So all references +- * should be inlined. +- */ +- bool get isDeclaration =3D> _isDeclaration; +- +- /** +- * True if the declaration of the method is selected. So all references +- * should be inlined. +- */ +- void set isDeclaration(bool value) { +- assert(value !=3D null); +- this._isDeclaration =3D value; +- } +- +- InlineMethodFeedback(String methodName, bool isDeclaration, +- {String className}) { +- this.className =3D className; +- this.methodName =3D methodName; +- this.isDeclaration =3D isDeclaration; +- } +- +- factory InlineMethodFeedback.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String className; +- if (json.containsKey("className")) { +- className =3D jsonDecoder.decodeString( +- jsonPath + ".className", json["className"]); +- } +- String methodName; +- if (json.containsKey("methodName")) { +- methodName =3D jsonDecoder.decodeString( +- jsonPath + ".methodName", json["methodName"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "methodName"); +- } +- bool isDeclaration; +- if (json.containsKey("isDeclaration")) { +- isDeclaration =3D jsonDecoder.decodeBool( +- jsonPath + ".isDeclaration", json["isDeclaration"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isDeclaration"); +- } +- return new InlineMethodFeedback(methodName, isDeclaration, +- className: className); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "inlineMethod feedback", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (className !=3D null) { +- result["className"] =3D className; +- } +- result["methodName"] =3D methodName; +- result["isDeclaration"] =3D isDeclaration; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is InlineMethodFeedback) { +- return className =3D=3D other.className && +- methodName =3D=3D other.methodName && +- isDeclaration =3D=3D other.isDeclaration; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, className.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, methodName.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, isDeclaration.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * inlineMethod options +- * +- * { +- * "deleteSource": bool +- * "inlineAll": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class InlineMethodOptions extends RefactoringOptions { +- bool _deleteSource; +- +- bool _inlineAll; +- +- /** +- * True if the method being inlined should be removed. It is an error i= f this +- * field is true and inlineAll is false. +- */ +- bool get deleteSource =3D> _deleteSource; +- +- /** +- * True if the method being inlined should be removed. It is an error i= f this +- * field is true and inlineAll is false. +- */ +- void set deleteSource(bool value) { +- assert(value !=3D null); +- this._deleteSource =3D value; +- } +- +- /** +- * True if all invocations of the method should be inlined, or false if= only +- * the invocation site used to create this refactoring should be inline= d. +- */ +- bool get inlineAll =3D> _inlineAll; +- +- /** +- * True if all invocations of the method should be inlined, or false if= only +- * the invocation site used to create this refactoring should be inline= d. +- */ +- void set inlineAll(bool value) { +- assert(value !=3D null); +- this._inlineAll =3D value; +- } +- +- InlineMethodOptions(bool deleteSource, bool inlineAll) { +- this.deleteSource =3D deleteSource; +- this.inlineAll =3D inlineAll; +- } +- +- factory InlineMethodOptions.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool deleteSource; +- if (json.containsKey("deleteSource")) { +- deleteSource =3D jsonDecoder.decodeBool( +- jsonPath + ".deleteSource", json["deleteSource"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "deleteSource"); +- } +- bool inlineAll; +- if (json.containsKey("inlineAll")) { +- inlineAll =3D +- jsonDecoder.decodeBool(jsonPath + ".inlineAll", json["inlineA= ll"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "inlineAll"); +- } +- return new InlineMethodOptions(deleteSource, inlineAll); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "inlineMethod options", json); +- } +- } +- +- factory InlineMethodOptions.fromRefactoringParams( +- EditGetRefactoringParams refactoringParams, Request request) { +- return new InlineMethodOptions.fromJson( +- new RequestDecoder(request), "options", refactoringParams.options= ); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["deleteSource"] =3D deleteSource; +- result["inlineAll"] =3D inlineAll; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is InlineMethodOptions) { +- return deleteSource =3D=3D other.deleteSource && inlineAll =3D=3D o= ther.inlineAll; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, deleteSource.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, inlineAll.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * kythe.getKytheEntries params +- * +- * { +- * "file": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class KytheGetKytheEntriesParams implements RequestParams { +- String _file; +- +- /** +- * The file containing the code for which the Kythe Entry objects are b= eing +- * requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the code for which the Kythe Entry objects are b= eing +- * requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- KytheGetKytheEntriesParams(String file) { +- this.file =3D file; +- } +- +- factory KytheGetKytheEntriesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- return new KytheGetKytheEntriesParams(file); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "kythe.getKytheEntries params", json); +- } +- } +- +- factory KytheGetKytheEntriesParams.fromRequest(Request request) { +- return new KytheGetKytheEntriesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "kythe.getKytheEntries", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is KytheGetKytheEntriesParams) { +- return file =3D=3D other.file; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * kythe.getKytheEntries result +- * +- * { +- * "entries": List +- * "files": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class KytheGetKytheEntriesResult implements ResponseResult { +- List _entries; +- +- List _files; +- +- /** +- * The list of KytheEntry objects for the queried file. +- */ +- List get entries =3D> _entries; +- +- /** +- * The list of KytheEntry objects for the queried file. +- */ +- void set entries(List value) { +- assert(value !=3D null); +- this._entries =3D value; +- } +- +- /** +- * The set of files paths that were required, but not in the file syste= m, to +- * give a complete and accurate Kythe graph for the file. This could be= due +- * to a referenced file that does not exist or generated files not being +- * generated or passed before the call to "getKytheEntries". +- */ +- List get files =3D> _files; +- +- /** +- * The set of files paths that were required, but not in the file syste= m, to +- * give a complete and accurate Kythe graph for the file. This could be= due +- * to a referenced file that does not exist or generated files not being +- * generated or passed before the call to "getKytheEntries". +- */ +- void set files(List value) { +- assert(value !=3D null); +- this._files =3D value; +- } +- +- KytheGetKytheEntriesResult(List entries, List files= ) { +- this.entries =3D entries; +- this.files =3D files; +- } +- +- factory KytheGetKytheEntriesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List entries; +- if (json.containsKey("entries")) { +- entries =3D jsonDecoder.decodeList( +- jsonPath + ".entries", +- json["entries"], +- (String jsonPath, Object json) =3D> +- new KytheEntry.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "entries"); +- } +- List files; +- if (json.containsKey("files")) { +- files =3D jsonDecoder.decodeList( +- jsonPath + ".files", json["files"], jsonDecoder.decodeString); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "files"); +- } +- return new KytheGetKytheEntriesResult(entries, files); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "kythe.getKytheEntries result", json); +- } +- } +- +- factory KytheGetKytheEntriesResult.fromResponse(Response response) { +- return new KytheGetKytheEntriesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["entries"] =3D +- entries.map((KytheEntry value) =3D> value.toJson()).toList(); +- result["files"] =3D files; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is KytheGetKytheEntriesResult) { +- return listEqual( +- entries, other.entries, (KytheEntry a, KytheEntry b) =3D> a= =3D=3D b) && +- listEqual(files, other.files, (String a, String b) =3D> a =3D= =3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, entries.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, files.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * moveFile feedback +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class MoveFileFeedback extends RefactoringFeedback implements HasToJson { +- @override +- bool operator =3D=3D(other) { +- if (other is MoveFileFeedback) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 438975893; +- } +-} +- +-/** +- * moveFile options +- * +- * { +- * "newFile": FilePath +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class MoveFileOptions extends RefactoringOptions { +- String _newFile; +- +- /** +- * The new file path to which the given file is being moved. +- */ +- String get newFile =3D> _newFile; +- +- /** +- * The new file path to which the given file is being moved. +- */ +- void set newFile(String value) { +- assert(value !=3D null); +- this._newFile =3D value; +- } +- +- MoveFileOptions(String newFile) { +- this.newFile =3D newFile; +- } +- +- factory MoveFileOptions.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String newFile; +- if (json.containsKey("newFile")) { +- newFile =3D +- jsonDecoder.decodeString(jsonPath + ".newFile", json["newFile= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "newFile"); +- } +- return new MoveFileOptions(newFile); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "moveFile options", json); +- } +- } +- +- factory MoveFileOptions.fromRefactoringParams( +- EditGetRefactoringParams refactoringParams, Request request) { +- return new MoveFileOptions.fromJson( +- new RequestDecoder(request), "options", refactoringParams.options= ); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["newFile"] =3D newFile; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is MoveFileOptions) { +- return newFile =3D=3D other.newFile; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, newFile.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * OverriddenMember +- * +- * { +- * "element": Element +- * "className": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class OverriddenMember implements HasToJson { +- Element _element; +- +- String _className; +- +- /** +- * The element that is being overridden. +- */ +- Element get element =3D> _element; +- +- /** +- * The element that is being overridden. +- */ +- void set element(Element value) { +- assert(value !=3D null); +- this._element =3D value; +- } +- +- /** +- * The name of the class in which the member is defined. +- */ +- String get className =3D> _className; +- +- /** +- * The name of the class in which the member is defined. +- */ +- void set className(String value) { +- assert(value !=3D null); +- this._className =3D value; +- } +- +- OverriddenMember(Element element, String className) { +- this.element =3D element; +- this.className =3D className; +- } +- +- factory OverriddenMember.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- Element element; +- if (json.containsKey("element")) { +- element =3D new Element.fromJson( +- jsonDecoder, jsonPath + ".element", json["element"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "element"); +- } +- String className; +- if (json.containsKey("className")) { +- className =3D jsonDecoder.decodeString( +- jsonPath + ".className", json["className"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "className"); +- } +- return new OverriddenMember(element, className); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "OverriddenMember", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["element"] =3D element.toJson(); +- result["className"] =3D className; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is OverriddenMember) { +- return element =3D=3D other.element && className =3D=3D other.class= Name; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, element.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, className.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * Override +- * +- * { +- * "offset": int +- * "length": int +- * "superclassMember": optional OverriddenMember +- * "interfaceMembers": optional List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class Override implements HasToJson { +- int _offset; +- +- int _length; +- +- OverriddenMember _superclassMember; +- +- List _interfaceMembers; +- +- /** +- * The offset of the name of the overriding member. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the name of the overriding member. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the name of the overriding member. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the name of the overriding member. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * The member inherited from a superclass that is overridden by the +- * overriding member. The field is omitted if there is no superclass me= mber, +- * in which case there must be at least one interface member. +- */ +- OverriddenMember get superclassMember =3D> _superclassMember; +- +- /** +- * The member inherited from a superclass that is overridden by the +- * overriding member. The field is omitted if there is no superclass me= mber, +- * in which case there must be at least one interface member. +- */ +- void set superclassMember(OverriddenMember value) { +- this._superclassMember =3D value; +- } +- +- /** +- * The members inherited from interfaces that are overridden by the +- * overriding member. The field is omitted if there are no interface me= mbers, +- * in which case there must be a superclass member. +- */ +- List get interfaceMembers =3D> _interfaceMembers; +- +- /** +- * The members inherited from interfaces that are overridden by the +- * overriding member. The field is omitted if there are no interface me= mbers, +- * in which case there must be a superclass member. +- */ +- void set interfaceMembers(List value) { +- this._interfaceMembers =3D value; +- } +- +- Override(int offset, int length, +- {OverriddenMember superclassMember, +- List interfaceMembers}) { +- this.offset =3D offset; +- this.length =3D length; +- this.superclassMember =3D superclassMember; +- this.interfaceMembers =3D interfaceMembers; +- } +- +- factory Override.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- OverriddenMember superclassMember; +- if (json.containsKey("superclassMember")) { +- superclassMember =3D new OverriddenMember.fromJson(jsonDecoder, +- jsonPath + ".superclassMember", json["superclassMember"]); +- } +- List interfaceMembers; +- if (json.containsKey("interfaceMembers")) { +- interfaceMembers =3D jsonDecoder.decodeList( +- jsonPath + ".interfaceMembers", +- json["interfaceMembers"], +- (String jsonPath, Object json) =3D> +- new OverriddenMember.fromJson(jsonDecoder, jsonPath, json= )); +- } +- return new Override(offset, length, +- superclassMember: superclassMember, +- interfaceMembers: interfaceMembers); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "Override", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- if (superclassMember !=3D null) { +- result["superclassMember"] =3D superclassMember.toJson(); +- } +- if (interfaceMembers !=3D null) { +- result["interfaceMembers"] =3D interfaceMembers +- .map((OverriddenMember value) =3D> value.toJson()) +- .toList(); +- } +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is Override) { +- return offset =3D=3D other.offset && +- length =3D=3D other.length && +- superclassMember =3D=3D other.superclassMember && +- listEqual(interfaceMembers, other.interfaceMembers, +- (OverriddenMember a, OverriddenMember b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, superclassMember.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, interfaceMembers.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * PostfixTemplateDescriptor +- * +- * { +- * "name": String +- * "key": String +- * "example": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class PostfixTemplateDescriptor implements HasToJson { +- String _name; +- +- String _key; +- +- String _example; +- +- /** +- * The template name, shown in the UI. +- */ +- String get name =3D> _name; +- +- /** +- * The template name, shown in the UI. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- /** +- * The unique template key, not shown in the UI. +- */ +- String get key =3D> _key; +- +- /** +- * The unique template key, not shown in the UI. +- */ +- void set key(String value) { +- assert(value !=3D null); +- this._key =3D value; +- } +- +- /** +- * A short example of the transformation performed when the template is +- * applied. +- */ +- String get example =3D> _example; +- +- /** +- * A short example of the transformation performed when the template is +- * applied. +- */ +- void set example(String value) { +- assert(value !=3D null); +- this._example =3D value; +- } +- +- PostfixTemplateDescriptor(String name, String key, String example) { +- this.name =3D name; +- this.key =3D key; +- this.example =3D example; +- } +- +- factory PostfixTemplateDescriptor.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- String key; +- if (json.containsKey("key")) { +- key =3D jsonDecoder.decodeString(jsonPath + ".key", json["key"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "key"); +- } +- String example; +- if (json.containsKey("example")) { +- example =3D +- jsonDecoder.decodeString(jsonPath + ".example", json["example= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "example"); +- } +- return new PostfixTemplateDescriptor(name, key, example); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "PostfixTemplateDescriptor", j= son); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["name"] =3D name; +- result["key"] =3D key; +- result["example"] =3D example; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is PostfixTemplateDescriptor) { +- return name =3D=3D other.name && key =3D=3D other.key && example = =3D=3D other.example; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, key.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, example.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * PubStatus +- * +- * { +- * "isListingPackageDirs": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class PubStatus implements HasToJson { +- bool _isListingPackageDirs; +- +- /** +- * True if the server is currently running pub to produce a list of pac= kage +- * directories. +- */ +- bool get isListingPackageDirs =3D> _isListingPackageDirs; +- +- /** +- * True if the server is currently running pub to produce a list of pac= kage +- * directories. +- */ +- void set isListingPackageDirs(bool value) { +- assert(value !=3D null); +- this._isListingPackageDirs =3D value; +- } +- +- PubStatus(bool isListingPackageDirs) { +- this.isListingPackageDirs =3D isListingPackageDirs; +- } +- +- factory PubStatus.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool isListingPackageDirs; +- if (json.containsKey("isListingPackageDirs")) { +- isListingPackageDirs =3D jsonDecoder.decodeBool( +- jsonPath + ".isListingPackageDirs", json["isListingPackageDir= s"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isListingPackageDirs"); +- } +- return new PubStatus(isListingPackageDirs); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "PubStatus", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["isListingPackageDirs"] =3D isListingPackageDirs; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is PubStatus) { +- return isListingPackageDirs =3D=3D other.isListingPackageDirs; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, isListingPackageDirs.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * RefactoringFeedback +- * +- * { +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RefactoringFeedback implements HasToJson { +- RefactoringFeedback(); +- +- factory RefactoringFeedback.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json, Map response= Json) { +- return refactoringFeedbackFromJson( +- jsonDecoder, jsonPath, json, responseJson); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is RefactoringFeedback) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * RefactoringOptions +- * +- * { +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RefactoringOptions implements HasToJson { +- RefactoringOptions(); +- +- factory RefactoringOptions.fromJson(JsonDecoder jsonDecoder, String jso= nPath, +- Object json, RefactoringKind kind) { +- return refactoringOptionsFromJson(jsonDecoder, jsonPath, json, kind); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is RefactoringOptions) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * rename feedback +- * +- * { +- * "offset": int +- * "length": int +- * "elementKindName": String +- * "oldName": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RenameFeedback extends RefactoringFeedback { +- int _offset; +- +- int _length; +- +- String _elementKindName; +- +- String _oldName; +- +- /** +- * The offset to the beginning of the name selected to be renamed. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset to the beginning of the name selected to be renamed. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * The length of the name selected to be renamed. +- */ +- int get length =3D> _length; +- +- /** +- * The length of the name selected to be renamed. +- */ +- void set length(int value) { +- assert(value !=3D null); +- this._length =3D value; +- } +- +- /** +- * The human-readable description of the kind of element being renamed = (such +- * as "class" or "function type alias"). +- */ +- String get elementKindName =3D> _elementKindName; +- +- /** +- * The human-readable description of the kind of element being renamed = (such +- * as "class" or "function type alias"). +- */ +- void set elementKindName(String value) { +- assert(value !=3D null); +- this._elementKindName =3D value; +- } +- +- /** +- * The old name of the element before the refactoring. +- */ +- String get oldName =3D> _oldName; +- +- /** +- * The old name of the element before the refactoring. +- */ +- void set oldName(String value) { +- assert(value !=3D null); +- this._oldName =3D value; +- } +- +- RenameFeedback( +- int offset, int length, String elementKindName, String oldName) { +- this.offset =3D offset; +- this.length =3D length; +- this.elementKindName =3D elementKindName; +- this.oldName =3D oldName; +- } +- +- factory RenameFeedback.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- int length; +- if (json.containsKey("length")) { +- length =3D jsonDecoder.decodeInt(jsonPath + ".length", json["leng= th"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "length"); +- } +- String elementKindName; +- if (json.containsKey("elementKindName")) { +- elementKindName =3D jsonDecoder.decodeString( +- jsonPath + ".elementKindName", json["elementKindName"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "elementKindName"); +- } +- String oldName; +- if (json.containsKey("oldName")) { +- oldName =3D +- jsonDecoder.decodeString(jsonPath + ".oldName", json["oldName= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "oldName"); +- } +- return new RenameFeedback(offset, length, elementKindName, oldName); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "rename feedback", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["offset"] =3D offset; +- result["length"] =3D length; +- result["elementKindName"] =3D elementKindName; +- result["oldName"] =3D oldName; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is RenameFeedback) { +- return offset =3D=3D other.offset && +- length =3D=3D other.length && +- elementKindName =3D=3D other.elementKindName && +- oldName =3D=3D other.oldName; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, length.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, elementKindName.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, oldName.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * rename options +- * +- * { +- * "newName": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RenameOptions extends RefactoringOptions { +- String _newName; +- +- /** +- * The name that the element should have after the refactoring. +- */ +- String get newName =3D> _newName; +- +- /** +- * The name that the element should have after the refactoring. +- */ +- void set newName(String value) { +- assert(value !=3D null); +- this._newName =3D value; +- } +- +- RenameOptions(String newName) { +- this.newName =3D newName; +- } +- +- factory RenameOptions.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String newName; +- if (json.containsKey("newName")) { +- newName =3D +- jsonDecoder.decodeString(jsonPath + ".newName", json["newName= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "newName"); +- } +- return new RenameOptions(newName); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "rename options", json); +- } +- } +- +- factory RenameOptions.fromRefactoringParams( +- EditGetRefactoringParams refactoringParams, Request request) { +- return new RenameOptions.fromJson( +- new RequestDecoder(request), "options", refactoringParams.options= ); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["newName"] =3D newName; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is RenameOptions) { +- return newName =3D=3D other.newName; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, newName.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * RequestError +- * +- * { +- * "code": RequestErrorCode +- * "message": String +- * "stackTrace": optional String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RequestError implements HasToJson { +- RequestErrorCode _code; +- +- String _message; +- +- String _stackTrace; +- +- /** +- * A code that uniquely identifies the error that occurred. +- */ +- RequestErrorCode get code =3D> _code; +- +- /** +- * A code that uniquely identifies the error that occurred. +- */ +- void set code(RequestErrorCode value) { +- assert(value !=3D null); +- this._code =3D value; +- } +- +- /** +- * A short description of the error. +- */ +- String get message =3D> _message; +- +- /** +- * A short description of the error. +- */ +- void set message(String value) { +- assert(value !=3D null); +- this._message =3D value; +- } +- +- /** +- * The stack trace associated with processing the request, used for deb= ugging +- * the server. +- */ +- String get stackTrace =3D> _stackTrace; +- +- /** +- * The stack trace associated with processing the request, used for deb= ugging +- * the server. +- */ +- void set stackTrace(String value) { +- this._stackTrace =3D value; +- } +- +- RequestError(RequestErrorCode code, String message, {String stackTrace}= ) { +- this.code =3D code; +- this.message =3D message; +- this.stackTrace =3D stackTrace; +- } +- +- factory RequestError.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- RequestErrorCode code; +- if (json.containsKey("code")) { +- code =3D new RequestErrorCode.fromJson( +- jsonDecoder, jsonPath + ".code", json["code"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "code"); +- } +- String message; +- if (json.containsKey("message")) { +- message =3D +- jsonDecoder.decodeString(jsonPath + ".message", json["message= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "message"); +- } +- String stackTrace; +- if (json.containsKey("stackTrace")) { +- stackTrace =3D jsonDecoder.decodeString( +- jsonPath + ".stackTrace", json["stackTrace"]); +- } +- return new RequestError(code, message, stackTrace: stackTrace); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "RequestError", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["code"] =3D code.toJson(); +- result["message"] =3D message; +- if (stackTrace !=3D null) { +- result["stackTrace"] =3D stackTrace; +- } +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is RequestError) { +- return code =3D=3D other.code && +- message =3D=3D other.message && +- stackTrace =3D=3D other.stackTrace; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, code.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, message.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, stackTrace.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * RequestErrorCode +- * +- * enum { +- * CONTENT_MODIFIED +- * DEBUG_PORT_COULD_NOT_BE_OPENED +- * FILE_NOT_ANALYZED +- * FORMAT_INVALID_FILE +- * FORMAT_WITH_ERRORS +- * GET_ERRORS_INVALID_FILE +- * GET_IMPORTED_ELEMENTS_INVALID_FILE +- * GET_KYTHE_ENTRIES_INVALID_FILE +- * GET_NAVIGATION_INVALID_FILE +- * GET_REACHABLE_SOURCES_INVALID_FILE +- * IMPORT_ELEMENTS_INVALID_FILE +- * INVALID_ANALYSIS_ROOT +- * INVALID_EXECUTION_CONTEXT +- * INVALID_FILE_PATH_FORMAT +- * INVALID_OVERLAY_CHANGE +- * INVALID_PARAMETER +- * INVALID_REQUEST +- * ORGANIZE_DIRECTIVES_ERROR +- * REFACTORING_REQUEST_CANCELLED +- * SERVER_ALREADY_STARTED +- * SERVER_ERROR +- * SORT_MEMBERS_INVALID_FILE +- * SORT_MEMBERS_PARSE_ERRORS +- * UNANALYZED_PRIORITY_FILES +- * UNKNOWN_REQUEST +- * UNKNOWN_SOURCE +- * UNSUPPORTED_FEATURE +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class RequestErrorCode implements Enum { +- /** +- * An "analysis.getErrors" or "analysis.getNavigation" request could no= t be +- * satisfied because the content of the file changed before the request= ed +- * results could be computed. +- */ +- static const RequestErrorCode CONTENT_MODIFIED =3D +- const RequestErrorCode._("CONTENT_MODIFIED"); +- +- /** +- * The server was unable to open a port for the diagnostic server. +- */ +- static const RequestErrorCode DEBUG_PORT_COULD_NOT_BE_OPENED =3D +- const RequestErrorCode._("DEBUG_PORT_COULD_NOT_BE_OPENED"); +- +- /** +- * A request specified a FilePath which does not match a file in an ana= lysis +- * root, or the requested operation is not available for the file. +- */ +- static const RequestErrorCode FILE_NOT_ANALYZED =3D +- const RequestErrorCode._("FILE_NOT_ANALYZED"); +- +- /** +- * An "edit.format" request specified a FilePath which does not match a= Dart +- * file in an analysis root. +- */ +- static const RequestErrorCode FORMAT_INVALID_FILE =3D +- const RequestErrorCode._("FORMAT_INVALID_FILE"); +- +- /** +- * An "edit.format" request specified a file that contains syntax error= s. +- */ +- static const RequestErrorCode FORMAT_WITH_ERRORS =3D +- const RequestErrorCode._("FORMAT_WITH_ERRORS"); +- +- /** +- * An "analysis.getErrors" request specified a FilePath which does not = match +- * a file currently subject to analysis. +- */ +- static const RequestErrorCode GET_ERRORS_INVALID_FILE =3D +- const RequestErrorCode._("GET_ERRORS_INVALID_FILE"); +- +- /** +- * An "analysis.getImportedElements" request specified a FilePath that = does +- * not match a file currently subject to analysis. +- */ +- static const RequestErrorCode GET_IMPORTED_ELEMENTS_INVALID_FILE =3D +- const RequestErrorCode._("GET_IMPORTED_ELEMENTS_INVALID_FILE"); +- +- /** +- * An "analysis.getKytheEntries" request specified a FilePath that does= not +- * match a file that is currently subject to analysis. +- */ +- static const RequestErrorCode GET_KYTHE_ENTRIES_INVALID_FILE =3D +- const RequestErrorCode._("GET_KYTHE_ENTRIES_INVALID_FILE"); +- +- /** +- * An "analysis.getNavigation" request specified a FilePath which does = not +- * match a file currently subject to analysis. +- */ +- static const RequestErrorCode GET_NAVIGATION_INVALID_FILE =3D +- const RequestErrorCode._("GET_NAVIGATION_INVALID_FILE"); +- +- /** +- * An "analysis.getReachableSources" request specified a FilePath which= does +- * not match a file currently subject to analysis. +- */ +- static const RequestErrorCode GET_REACHABLE_SOURCES_INVALID_FILE =3D +- const RequestErrorCode._("GET_REACHABLE_SOURCES_INVALID_FILE"); +- +- /** +- * An "edit.importElements" request specified a FilePath that does not = match +- * a file currently subject to analysis. +- */ +- static const RequestErrorCode IMPORT_ELEMENTS_INVALID_FILE =3D +- const RequestErrorCode._("IMPORT_ELEMENTS_INVALID_FILE"); +- +- /** +- * A path passed as an argument to a request (such as analysis.reanalyz= e) is +- * required to be an analysis root, but isn't. +- */ +- static const RequestErrorCode INVALID_ANALYSIS_ROOT =3D +- const RequestErrorCode._("INVALID_ANALYSIS_ROOT"); +- +- /** +- * The context root used to create an execution context does not exist. +- */ +- static const RequestErrorCode INVALID_EXECUTION_CONTEXT =3D +- const RequestErrorCode._("INVALID_EXECUTION_CONTEXT"); +- +- /** +- * The format of the given file path is invalid, e.g. is not absolute a= nd +- * normalized. +- */ +- static const RequestErrorCode INVALID_FILE_PATH_FORMAT =3D +- const RequestErrorCode._("INVALID_FILE_PATH_FORMAT"); +- +- /** +- * An "analysis.updateContent" request contained a ChangeContentOverlay +- * object which can't be applied, due to an edit having an offset or le= ngth +- * that is out of range. +- */ +- static const RequestErrorCode INVALID_OVERLAY_CHANGE =3D +- const RequestErrorCode._("INVALID_OVERLAY_CHANGE"); +- +- /** +- * One of the method parameters was invalid. +- */ +- static const RequestErrorCode INVALID_PARAMETER =3D +- const RequestErrorCode._("INVALID_PARAMETER"); +- +- /** +- * A malformed request was received. +- */ +- static const RequestErrorCode INVALID_REQUEST =3D +- const RequestErrorCode._("INVALID_REQUEST"); +- +- /** +- * An "edit.organizeDirectives" request specified a Dart file that cann= ot be +- * analyzed. The reason is described in the message. +- */ +- static const RequestErrorCode ORGANIZE_DIRECTIVES_ERROR =3D +- const RequestErrorCode._("ORGANIZE_DIRECTIVES_ERROR"); +- +- /** +- * Another refactoring request was received during processing of this o= ne. +- */ +- static const RequestErrorCode REFACTORING_REQUEST_CANCELLED =3D +- const RequestErrorCode._("REFACTORING_REQUEST_CANCELLED"); +- +- /** +- * The analysis server has already been started (and hence won't accept= new +- * connections). +- * +- * This error is included for future expansion; at present the analysis +- * server can only speak to one client at a time so this error will nev= er +- * occur. +- */ +- static const RequestErrorCode SERVER_ALREADY_STARTED =3D +- const RequestErrorCode._("SERVER_ALREADY_STARTED"); +- +- /** +- * An internal error occurred in the analysis server. Also see the +- * server.error notification. +- */ +- static const RequestErrorCode SERVER_ERROR =3D +- const RequestErrorCode._("SERVER_ERROR"); +- +- /** +- * An "edit.sortMembers" request specified a FilePath which does not ma= tch a +- * Dart file in an analysis root. +- */ +- static const RequestErrorCode SORT_MEMBERS_INVALID_FILE =3D +- const RequestErrorCode._("SORT_MEMBERS_INVALID_FILE"); +- +- /** +- * An "edit.sortMembers" request specified a Dart file that has scan or= parse +- * errors. +- */ +- static const RequestErrorCode SORT_MEMBERS_PARSE_ERRORS =3D +- const RequestErrorCode._("SORT_MEMBERS_PARSE_ERRORS"); +- +- /** +- * An "analysis.setPriorityFiles" request includes one or more files th= at are +- * not being analyzed. +- * +- * This is a legacy error; it will be removed before the API reaches ve= rsion +- * 1.0. +- */ +- static const RequestErrorCode UNANALYZED_PRIORITY_FILES =3D +- const RequestErrorCode._("UNANALYZED_PRIORITY_FILES"); +- +- /** +- * A request was received which the analysis server does not recognize,= or +- * cannot handle in its current configuration. +- */ +- static const RequestErrorCode UNKNOWN_REQUEST =3D +- const RequestErrorCode._("UNKNOWN_REQUEST"); +- +- /** +- * The analysis server was requested to perform an action on a source t= hat +- * does not exist. +- */ +- static const RequestErrorCode UNKNOWN_SOURCE =3D +- const RequestErrorCode._("UNKNOWN_SOURCE"); +- +- /** +- * The analysis server was requested to perform an action which is not +- * supported. +- * +- * This is a legacy error; it will be removed before the API reaches ve= rsion +- * 1.0. +- */ +- static const RequestErrorCode UNSUPPORTED_FEATURE =3D +- const RequestErrorCode._("UNSUPPORTED_FEATURE"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [ +- CONTENT_MODIFIED, +- DEBUG_PORT_COULD_NOT_BE_OPENED, +- FILE_NOT_ANALYZED, +- FORMAT_INVALID_FILE, +- FORMAT_WITH_ERRORS, +- GET_ERRORS_INVALID_FILE, +- GET_IMPORTED_ELEMENTS_INVALID_FILE, +- GET_KYTHE_ENTRIES_INVALID_FILE, +- GET_NAVIGATION_INVALID_FILE, +- GET_REACHABLE_SOURCES_INVALID_FILE, +- IMPORT_ELEMENTS_INVALID_FILE, +- INVALID_ANALYSIS_ROOT, +- INVALID_EXECUTION_CONTEXT, +- INVALID_FILE_PATH_FORMAT, +- INVALID_OVERLAY_CHANGE, +- INVALID_PARAMETER, +- INVALID_REQUEST, +- ORGANIZE_DIRECTIVES_ERROR, +- REFACTORING_REQUEST_CANCELLED, +- SERVER_ALREADY_STARTED, +- SERVER_ERROR, +- SORT_MEMBERS_INVALID_FILE, +- SORT_MEMBERS_PARSE_ERRORS, +- UNANALYZED_PRIORITY_FILES, +- UNKNOWN_REQUEST, +- UNKNOWN_SOURCE, +- UNSUPPORTED_FEATURE +- ]; +- +- @override +- final String name; +- +- const RequestErrorCode._(this.name); +- +- factory RequestErrorCode(String name) { +- switch (name) { +- case "CONTENT_MODIFIED": +- return CONTENT_MODIFIED; +- case "DEBUG_PORT_COULD_NOT_BE_OPENED": +- return DEBUG_PORT_COULD_NOT_BE_OPENED; +- case "FILE_NOT_ANALYZED": +- return FILE_NOT_ANALYZED; +- case "FORMAT_INVALID_FILE": +- return FORMAT_INVALID_FILE; +- case "FORMAT_WITH_ERRORS": +- return FORMAT_WITH_ERRORS; +- case "GET_ERRORS_INVALID_FILE": +- return GET_ERRORS_INVALID_FILE; +- case "GET_IMPORTED_ELEMENTS_INVALID_FILE": +- return GET_IMPORTED_ELEMENTS_INVALID_FILE; +- case "GET_KYTHE_ENTRIES_INVALID_FILE": +- return GET_KYTHE_ENTRIES_INVALID_FILE; +- case "GET_NAVIGATION_INVALID_FILE": +- return GET_NAVIGATION_INVALID_FILE; +- case "GET_REACHABLE_SOURCES_INVALID_FILE": +- return GET_REACHABLE_SOURCES_INVALID_FILE; +- case "IMPORT_ELEMENTS_INVALID_FILE": +- return IMPORT_ELEMENTS_INVALID_FILE; +- case "INVALID_ANALYSIS_ROOT": +- return INVALID_ANALYSIS_ROOT; +- case "INVALID_EXECUTION_CONTEXT": +- return INVALID_EXECUTION_CONTEXT; +- case "INVALID_FILE_PATH_FORMAT": +- return INVALID_FILE_PATH_FORMAT; +- case "INVALID_OVERLAY_CHANGE": +- return INVALID_OVERLAY_CHANGE; +- case "INVALID_PARAMETER": +- return INVALID_PARAMETER; +- case "INVALID_REQUEST": +- return INVALID_REQUEST; +- case "ORGANIZE_DIRECTIVES_ERROR": +- return ORGANIZE_DIRECTIVES_ERROR; +- case "REFACTORING_REQUEST_CANCELLED": +- return REFACTORING_REQUEST_CANCELLED; +- case "SERVER_ALREADY_STARTED": +- return SERVER_ALREADY_STARTED; +- case "SERVER_ERROR": +- return SERVER_ERROR; +- case "SORT_MEMBERS_INVALID_FILE": +- return SORT_MEMBERS_INVALID_FILE; +- case "SORT_MEMBERS_PARSE_ERRORS": +- return SORT_MEMBERS_PARSE_ERRORS; +- case "UNANALYZED_PRIORITY_FILES": +- return UNANALYZED_PRIORITY_FILES; +- case "UNKNOWN_REQUEST": +- return UNKNOWN_REQUEST; +- case "UNKNOWN_SOURCE": +- return UNKNOWN_SOURCE; +- case "UNSUPPORTED_FEATURE": +- return UNSUPPORTED_FEATURE; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory RequestErrorCode.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new RequestErrorCode(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "RequestErrorCode", json); +- } +- +- @override +- String toString() =3D> "RequestErrorCode.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * search.findElementReferences params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "includePotential": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindElementReferencesParams implements RequestParams { +- String _file; +- +- int _offset; +- +- bool _includePotential; +- +- /** +- * The file containing the declaration of or reference to the element u= sed to +- * define the search. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the declaration of or reference to the element u= sed to +- * define the search. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset within the file of the declaration of or reference to the +- * element. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset within the file of the declaration of or reference to the +- * element. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * True if potential matches are to be included in the results. +- */ +- bool get includePotential =3D> _includePotential; +- +- /** +- * True if potential matches are to be included in the results. +- */ +- void set includePotential(bool value) { +- assert(value !=3D null); +- this._includePotential =3D value; +- } +- +- SearchFindElementReferencesParams( +- String file, int offset, bool includePotential) { +- this.file =3D file; +- this.offset =3D offset; +- this.includePotential =3D includePotential; +- } +- +- factory SearchFindElementReferencesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- bool includePotential; +- if (json.containsKey("includePotential")) { +- includePotential =3D jsonDecoder.decodeBool( +- jsonPath + ".includePotential", json["includePotential"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "includePotential"); +- } +- return new SearchFindElementReferencesParams( +- file, offset, includePotential); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findElementReferences params", json); +- } +- } +- +- factory SearchFindElementReferencesParams.fromRequest(Request request) { +- return new SearchFindElementReferencesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- result["includePotential"] =3D includePotential; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "search.findElementReferences", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindElementReferencesParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- includePotential =3D=3D other.includePotential; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, includePotential.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findElementReferences result +- * +- * { +- * "id": optional SearchId +- * "element": optional Element +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindElementReferencesResult implements ResponseResult { +- String _id; +- +- Element _element; +- +- /** +- * The identifier used to associate results with this search request. +- * +- * If no element was found at the given location, this field will be ab= sent, +- * and no results will be reported via the search.results notification. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier used to associate results with this search request. +- * +- * If no element was found at the given location, this field will be ab= sent, +- * and no results will be reported via the search.results notification. +- */ +- void set id(String value) { +- this._id =3D value; +- } +- +- /** +- * The element referenced or defined at the given offset and whose refe= rences +- * will be returned in the search results. +- * +- * If no element was found at the given location, this field will be ab= sent. +- */ +- Element get element =3D> _element; +- +- /** +- * The element referenced or defined at the given offset and whose refe= rences +- * will be returned in the search results. +- * +- * If no element was found at the given location, this field will be ab= sent. +- */ +- void set element(Element value) { +- this._element =3D value; +- } +- +- SearchFindElementReferencesResult({String id, Element element}) { +- this.id =3D id; +- this.element =3D element; +- } +- +- factory SearchFindElementReferencesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } +- Element element; +- if (json.containsKey("element")) { +- element =3D new Element.fromJson( +- jsonDecoder, jsonPath + ".element", json["element"]); +- } +- return new SearchFindElementReferencesResult(id: id, element: eleme= nt); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findElementReferences result", json); +- } +- } +- +- factory SearchFindElementReferencesResult.fromResponse(Response respons= e) { +- return new SearchFindElementReferencesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (id !=3D null) { +- result["id"] =3D id; +- } +- if (element !=3D null) { +- result["element"] =3D element.toJson(); +- } +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindElementReferencesResult) { +- return id =3D=3D other.id && element =3D=3D other.element; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, element.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findMemberDeclarations params +- * +- * { +- * "name": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindMemberDeclarationsParams implements RequestParams { +- String _name; +- +- /** +- * The name of the declarations to be found. +- */ +- String get name =3D> _name; +- +- /** +- * The name of the declarations to be found. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- SearchFindMemberDeclarationsParams(String name) { +- this.name =3D name; +- } +- +- factory SearchFindMemberDeclarationsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- return new SearchFindMemberDeclarationsParams(name); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findMemberDeclarations params", json); +- } +- } +- +- factory SearchFindMemberDeclarationsParams.fromRequest(Request request)= { +- return new SearchFindMemberDeclarationsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["name"] =3D name; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "search.findMemberDeclarations", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindMemberDeclarationsParams) { +- return name =3D=3D other.name; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findMemberDeclarations result +- * +- * { +- * "id": SearchId +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindMemberDeclarationsResult implements ResponseResult { +- String _id; +- +- /** +- * The identifier used to associate results with this search request. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier used to associate results with this search request. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- SearchFindMemberDeclarationsResult(String id) { +- this.id =3D id; +- } +- +- factory SearchFindMemberDeclarationsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- return new SearchFindMemberDeclarationsResult(id); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findMemberDeclarations result", json); +- } +- } +- +- factory SearchFindMemberDeclarationsResult.fromResponse(Response respon= se) { +- return new SearchFindMemberDeclarationsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindMemberDeclarationsResult) { +- return id =3D=3D other.id; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findMemberReferences params +- * +- * { +- * "name": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindMemberReferencesParams implements RequestParams { +- String _name; +- +- /** +- * The name of the references to be found. +- */ +- String get name =3D> _name; +- +- /** +- * The name of the references to be found. +- */ +- void set name(String value) { +- assert(value !=3D null); +- this._name =3D value; +- } +- +- SearchFindMemberReferencesParams(String name) { +- this.name =3D name; +- } +- +- factory SearchFindMemberReferencesParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String name; +- if (json.containsKey("name")) { +- name =3D jsonDecoder.decodeString(jsonPath + ".name", json["name"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "name"); +- } +- return new SearchFindMemberReferencesParams(name); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findMemberReferences params", json); +- } +- } +- +- factory SearchFindMemberReferencesParams.fromRequest(Request request) { +- return new SearchFindMemberReferencesParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["name"] =3D name; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "search.findMemberReferences", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindMemberReferencesParams) { +- return name =3D=3D other.name; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, name.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findMemberReferences result +- * +- * { +- * "id": SearchId +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindMemberReferencesResult implements ResponseResult { +- String _id; +- +- /** +- * The identifier used to associate results with this search request. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier used to associate results with this search request. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- SearchFindMemberReferencesResult(String id) { +- this.id =3D id; +- } +- +- factory SearchFindMemberReferencesResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- return new SearchFindMemberReferencesResult(id); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findMemberReferences result", json); +- } +- } +- +- factory SearchFindMemberReferencesResult.fromResponse(Response response= ) { +- return new SearchFindMemberReferencesResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindMemberReferencesResult) { +- return id =3D=3D other.id; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findTopLevelDeclarations params +- * +- * { +- * "pattern": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindTopLevelDeclarationsParams implements RequestParams { +- String _pattern; +- +- /** +- * The regular expression used to match the names of the declarations t= o be +- * found. +- */ +- String get pattern =3D> _pattern; +- +- /** +- * The regular expression used to match the names of the declarations t= o be +- * found. +- */ +- void set pattern(String value) { +- assert(value !=3D null); +- this._pattern =3D value; +- } +- +- SearchFindTopLevelDeclarationsParams(String pattern) { +- this.pattern =3D pattern; +- } +- +- factory SearchFindTopLevelDeclarationsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String pattern; +- if (json.containsKey("pattern")) { +- pattern =3D +- jsonDecoder.decodeString(jsonPath + ".pattern", json["pattern= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "pattern"); +- } +- return new SearchFindTopLevelDeclarationsParams(pattern); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findTopLevelDeclarations params", json); +- } +- } +- +- factory SearchFindTopLevelDeclarationsParams.fromRequest(Request reques= t) { +- return new SearchFindTopLevelDeclarationsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["pattern"] =3D pattern; +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "search.findTopLevelDeclarations", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindTopLevelDeclarationsParams) { +- return pattern =3D=3D other.pattern; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, pattern.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.findTopLevelDeclarations result +- * +- * { +- * "id": SearchId +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchFindTopLevelDeclarationsResult implements ResponseResult { +- String _id; +- +- /** +- * The identifier used to associate results with this search request. +- */ +- String get id =3D> _id; +- +- /** +- * The identifier used to associate results with this search request. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- SearchFindTopLevelDeclarationsResult(String id) { +- this.id =3D id; +- } +- +- factory SearchFindTopLevelDeclarationsResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- return new SearchFindTopLevelDeclarationsResult(id); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.findTopLevelDeclarations result", json); +- } +- } +- +- factory SearchFindTopLevelDeclarationsResult.fromResponse(Response resp= onse) { +- return new SearchFindTopLevelDeclarationsResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchFindTopLevelDeclarationsResult) { +- return id =3D=3D other.id; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.getTypeHierarchy params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "superOnly": optional bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchGetTypeHierarchyParams implements RequestParams { +- String _file; +- +- int _offset; +- +- bool _superOnly; +- +- /** +- * The file containing the declaration or reference to the type for whi= ch a +- * hierarchy is being requested. +- */ +- String get file =3D> _file; +- +- /** +- * The file containing the declaration or reference to the type for whi= ch a +- * hierarchy is being requested. +- */ +- void set file(String value) { +- assert(value !=3D null); +- this._file =3D value; +- } +- +- /** +- * The offset of the name of the type within the file. +- */ +- int get offset =3D> _offset; +- +- /** +- * The offset of the name of the type within the file. +- */ +- void set offset(int value) { +- assert(value !=3D null); +- this._offset =3D value; +- } +- +- /** +- * True if the client is only requesting superclasses and interfaces +- * hierarchy. +- */ +- bool get superOnly =3D> _superOnly; +- +- /** +- * True if the client is only requesting superclasses and interfaces +- * hierarchy. +- */ +- void set superOnly(bool value) { +- this._superOnly =3D value; +- } +- +- SearchGetTypeHierarchyParams(String file, int offset, {bool superOnly})= { +- this.file =3D file; +- this.offset =3D offset; +- this.superOnly =3D superOnly; +- } +- +- factory SearchGetTypeHierarchyParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String file; +- if (json.containsKey("file")) { +- file =3D jsonDecoder.decodeString(jsonPath + ".file", json["file"= ]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "file"); +- } +- int offset; +- if (json.containsKey("offset")) { +- offset =3D jsonDecoder.decodeInt(jsonPath + ".offset", json["offs= et"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "offset"); +- } +- bool superOnly; +- if (json.containsKey("superOnly")) { +- superOnly =3D +- jsonDecoder.decodeBool(jsonPath + ".superOnly", json["superOn= ly"]); +- } +- return new SearchGetTypeHierarchyParams(file, offset, +- superOnly: superOnly); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.getTypeHierarchy params", json); +- } +- } +- +- factory SearchGetTypeHierarchyParams.fromRequest(Request request) { +- return new SearchGetTypeHierarchyParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["file"] =3D file; +- result["offset"] =3D offset; +- if (superOnly !=3D null) { +- result["superOnly"] =3D superOnly; +- } +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "search.getTypeHierarchy", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchGetTypeHierarchyParams) { +- return file =3D=3D other.file && +- offset =3D=3D other.offset && +- superOnly =3D=3D other.superOnly; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, file.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, offset.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, superOnly.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * search.getTypeHierarchy result +- * +- * { +- * "hierarchyItems": optional List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchGetTypeHierarchyResult implements ResponseResult { +- List _hierarchyItems; +- +- /** +- * A list of the types in the requested hierarchy. The first element of= the +- * list is the item representing the type for which the hierarchy was +- * requested. The index of other elements of the list is unspecified, b= ut +- * correspond to the integers used to reference supertype and subtype i= tems +- * within the items. +- * +- * This field will be absent if the code at the given file and offset d= oes +- * not represent a type, or if the file has not been sufficiently analy= zed to +- * allow a type hierarchy to be produced. +- */ +- List get hierarchyItems =3D> _hierarchyItems; +- +- /** +- * A list of the types in the requested hierarchy. The first element of= the +- * list is the item representing the type for which the hierarchy was +- * requested. The index of other elements of the list is unspecified, b= ut +- * correspond to the integers used to reference supertype and subtype i= tems +- * within the items. +- * +- * This field will be absent if the code at the given file and offset d= oes +- * not represent a type, or if the file has not been sufficiently analy= zed to +- * allow a type hierarchy to be produced. +- */ +- void set hierarchyItems(List value) { +- this._hierarchyItems =3D value; +- } +- +- SearchGetTypeHierarchyResult({List hierarchyItems}) { +- this.hierarchyItems =3D hierarchyItems; +- } +- +- factory SearchGetTypeHierarchyResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List hierarchyItems; +- if (json.containsKey("hierarchyItems")) { +- hierarchyItems =3D jsonDecoder.decodeList( +- jsonPath + ".hierarchyItems", +- json["hierarchyItems"], +- (String jsonPath, Object json) =3D> +- new TypeHierarchyItem.fromJson(jsonDecoder, jsonPath, jso= n)); +- } +- return new SearchGetTypeHierarchyResult(hierarchyItems: hierarchyIt= ems); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "search.getTypeHierarchy result", json); +- } +- } +- +- factory SearchGetTypeHierarchyResult.fromResponse(Response response) { +- return new SearchGetTypeHierarchyResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (hierarchyItems !=3D null) { +- result["hierarchyItems"] =3D hierarchyItems +- .map((TypeHierarchyItem value) =3D> value.toJson()) +- .toList(); +- } +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchGetTypeHierarchyResult) { +- return listEqual(hierarchyItems, other.hierarchyItems, +- (TypeHierarchyItem a, TypeHierarchyItem b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, hierarchyItems.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * SearchResult +- * +- * { +- * "location": Location +- * "kind": SearchResultKind +- * "isPotential": bool +- * "path": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchResult implements HasToJson { +- Location _location; +- +- SearchResultKind _kind; +- +- bool _isPotential; +- +- List _path; +- +- /** +- * The location of the code that matched the search criteria. +- */ +- Location get location =3D> _location; +- +- /** +- * The location of the code that matched the search criteria. +- */ +- void set location(Location value) { +- assert(value !=3D null); +- this._location =3D value; +- } +- +- /** +- * The kind of element that was found or the kind of reference that was +- * found. +- */ +- SearchResultKind get kind =3D> _kind; +- +- /** +- * The kind of element that was found or the kind of reference that was +- * found. +- */ +- void set kind(SearchResultKind value) { +- assert(value !=3D null); +- this._kind =3D value; +- } +- +- /** +- * True if the result is a potential match but cannot be confirmed to b= e a +- * match. For example, if all references to a method m defined in some = class +- * were requested, and a reference to a method m from an unknown class = were +- * found, it would be marked as being a potential match. +- */ +- bool get isPotential =3D> _isPotential; +- +- /** +- * True if the result is a potential match but cannot be confirmed to b= e a +- * match. For example, if all references to a method m defined in some = class +- * were requested, and a reference to a method m from an unknown class = were +- * found, it would be marked as being a potential match. +- */ +- void set isPotential(bool value) { +- assert(value !=3D null); +- this._isPotential =3D value; +- } +- +- /** +- * The elements that contain the result, starting with the most immedia= tely +- * enclosing ancestor and ending with the library. +- */ +- List get path =3D> _path; +- +- /** +- * The elements that contain the result, starting with the most immedia= tely +- * enclosing ancestor and ending with the library. +- */ +- void set path(List value) { +- assert(value !=3D null); +- this._path =3D value; +- } +- +- SearchResult(Location location, SearchResultKind kind, bool isPotential, +- List path) { +- this.location =3D location; +- this.kind =3D kind; +- this.isPotential =3D isPotential; +- this.path =3D path; +- } +- +- factory SearchResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- Location location; +- if (json.containsKey("location")) { +- location =3D new Location.fromJson( +- jsonDecoder, jsonPath + ".location", json["location"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "location"); +- } +- SearchResultKind kind; +- if (json.containsKey("kind")) { +- kind =3D new SearchResultKind.fromJson( +- jsonDecoder, jsonPath + ".kind", json["kind"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "kind"); +- } +- bool isPotential; +- if (json.containsKey("isPotential")) { +- isPotential =3D jsonDecoder.decodeBool( +- jsonPath + ".isPotential", json["isPotential"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isPotential"); +- } +- List path; +- if (json.containsKey("path")) { +- path =3D jsonDecoder.decodeList( +- jsonPath + ".path", +- json["path"], +- (String jsonPath, Object json) =3D> +- new Element.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "path"); +- } +- return new SearchResult(location, kind, isPotential, path); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "SearchResult", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["location"] =3D location.toJson(); +- result["kind"] =3D kind.toJson(); +- result["isPotential"] =3D isPotential; +- result["path"] =3D path.map((Element value) =3D> value.toJson()).toLi= st(); +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchResult) { +- return location =3D=3D other.location && +- kind =3D=3D other.kind && +- isPotential =3D=3D other.isPotential && +- listEqual(path, other.path, (Element a, Element b) =3D> a =3D= =3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, location.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, kind.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, isPotential.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, path.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * SearchResultKind +- * +- * enum { +- * DECLARATION +- * INVOCATION +- * READ +- * READ_WRITE +- * REFERENCE +- * UNKNOWN +- * WRITE +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchResultKind implements Enum { +- /** +- * The declaration of an element. +- */ +- static const SearchResultKind DECLARATION =3D +- const SearchResultKind._("DECLARATION"); +- +- /** +- * The invocation of a function or method. +- */ +- static const SearchResultKind INVOCATION =3D +- const SearchResultKind._("INVOCATION"); +- +- /** +- * A reference to a field, parameter or variable where it is being read. +- */ +- static const SearchResultKind READ =3D const SearchResultKind._("READ"); +- +- /** +- * A reference to a field, parameter or variable where it is being read= and +- * written. +- */ +- static const SearchResultKind READ_WRITE =3D +- const SearchResultKind._("READ_WRITE"); +- +- /** +- * A reference to an element. +- */ +- static const SearchResultKind REFERENCE =3D +- const SearchResultKind._("REFERENCE"); +- +- /** +- * Some other kind of search result. +- */ +- static const SearchResultKind UNKNOWN =3D const SearchResultKind._("UNK= NOWN"); +- +- /** +- * A reference to a field, parameter or variable where it is being writ= ten. +- */ +- static const SearchResultKind WRITE =3D const SearchResultKind._("WRITE= "); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [ +- DECLARATION, +- INVOCATION, +- READ, +- READ_WRITE, +- REFERENCE, +- UNKNOWN, +- WRITE +- ]; +- +- @override +- final String name; +- +- const SearchResultKind._(this.name); +- +- factory SearchResultKind(String name) { +- switch (name) { +- case "DECLARATION": +- return DECLARATION; +- case "INVOCATION": +- return INVOCATION; +- case "READ": +- return READ; +- case "READ_WRITE": +- return READ_WRITE; +- case "REFERENCE": +- return REFERENCE; +- case "UNKNOWN": +- return UNKNOWN; +- case "WRITE": +- return WRITE; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory SearchResultKind.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new SearchResultKind(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "SearchResultKind", json); +- } +- +- @override +- String toString() =3D> "SearchResultKind.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * search.results params +- * +- * { +- * "id": SearchId +- * "results": List +- * "isLast": bool +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class SearchResultsParams implements HasToJson { +- String _id; +- +- List _results; +- +- bool _isLast; +- +- /** +- * The id associated with the search. +- */ +- String get id =3D> _id; +- +- /** +- * The id associated with the search. +- */ +- void set id(String value) { +- assert(value !=3D null); +- this._id =3D value; +- } +- +- /** +- * The search results being reported. +- */ +- List get results =3D> _results; +- +- /** +- * The search results being reported. +- */ +- void set results(List value) { +- assert(value !=3D null); +- this._results =3D value; +- } +- +- /** +- * True if this is that last set of results that will be returned for t= he +- * indicated search. +- */ +- bool get isLast =3D> _isLast; +- +- /** +- * True if this is that last set of results that will be returned for t= he +- * indicated search. +- */ +- void set isLast(bool value) { +- assert(value !=3D null); +- this._isLast =3D value; +- } +- +- SearchResultsParams(String id, List results, bool isLast)= { +- this.id =3D id; +- this.results =3D results; +- this.isLast =3D isLast; +- } +- +- factory SearchResultsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String id; +- if (json.containsKey("id")) { +- id =3D jsonDecoder.decodeString(jsonPath + ".id", json["id"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "id"); +- } +- List results; +- if (json.containsKey("results")) { +- results =3D jsonDecoder.decodeList( +- jsonPath + ".results", +- json["results"], +- (String jsonPath, Object json) =3D> +- new SearchResult.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "results"); +- } +- bool isLast; +- if (json.containsKey("isLast")) { +- isLast =3D jsonDecoder.decodeBool(jsonPath + ".isLast", json["isL= ast"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isLast"); +- } +- return new SearchResultsParams(id, results, isLast); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "search.results params", json); +- } +- } +- +- factory SearchResultsParams.fromNotification(Notification notification)= { +- return new SearchResultsParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["id"] =3D id; +- result["results"] =3D +- results.map((SearchResult value) =3D> value.toJson()).toList(); +- result["isLast"] =3D isLast; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("search.results", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is SearchResultsParams) { +- return id =3D=3D other.id && +- listEqual(results, other.results, +- (SearchResult a, SearchResult b) =3D> a =3D=3D b) && +- isLast =3D=3D other.isLast; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, id.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, results.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, isLast.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * server.connected params +- * +- * { +- * "version": String +- * "pid": int +- * "sessionId": optional String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerConnectedParams implements HasToJson { +- String _version; +- +- int _pid; +- +- String _sessionId; +- +- /** +- * The version number of the analysis server. +- */ +- String get version =3D> _version; +- +- /** +- * The version number of the analysis server. +- */ +- void set version(String value) { +- assert(value !=3D null); +- this._version =3D value; +- } +- +- /** +- * The process id of the analysis server process. +- */ +- int get pid =3D> _pid; +- +- /** +- * The process id of the analysis server process. +- */ +- void set pid(int value) { +- assert(value !=3D null); +- this._pid =3D value; +- } +- +- /** +- * The session id for this session. +- */ +- String get sessionId =3D> _sessionId; +- +- /** +- * The session id for this session. +- */ +- void set sessionId(String value) { +- this._sessionId =3D value; +- } +- +- ServerConnectedParams(String version, int pid, {String sessionId}) { +- this.version =3D version; +- this.pid =3D pid; +- this.sessionId =3D sessionId; +- } +- +- factory ServerConnectedParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String version; +- if (json.containsKey("version")) { +- version =3D +- jsonDecoder.decodeString(jsonPath + ".version", json["version= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "version"); +- } +- int pid; +- if (json.containsKey("pid")) { +- pid =3D jsonDecoder.decodeInt(jsonPath + ".pid", json["pid"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "pid"); +- } +- String sessionId; +- if (json.containsKey("sessionId")) { +- sessionId =3D jsonDecoder.decodeString( +- jsonPath + ".sessionId", json["sessionId"]); +- } +- return new ServerConnectedParams(version, pid, sessionId: sessionId= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "server.connected params", jso= n); +- } +- } +- +- factory ServerConnectedParams.fromNotification(Notification notificatio= n) { +- return new ServerConnectedParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["version"] =3D version; +- result["pid"] =3D pid; +- if (sessionId !=3D null) { +- result["sessionId"] =3D sessionId; +- } +- return result; +- } +- +- Notification toNotification() { +- return new Notification("server.connected", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerConnectedParams) { +- return version =3D=3D other.version && +- pid =3D=3D other.pid && +- sessionId =3D=3D other.sessionId; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, version.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, pid.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, sessionId.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * server.error params +- * +- * { +- * "isFatal": bool +- * "message": String +- * "stackTrace": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerErrorParams implements HasToJson { +- bool _isFatal; +- +- String _message; +- +- String _stackTrace; +- +- /** +- * True if the error is a fatal error, meaning that the server will shu= tdown +- * automatically after sending this notification. +- */ +- bool get isFatal =3D> _isFatal; +- +- /** +- * True if the error is a fatal error, meaning that the server will shu= tdown +- * automatically after sending this notification. +- */ +- void set isFatal(bool value) { +- assert(value !=3D null); +- this._isFatal =3D value; +- } +- +- /** +- * The error message indicating what kind of error was encountered. +- */ +- String get message =3D> _message; +- +- /** +- * The error message indicating what kind of error was encountered. +- */ +- void set message(String value) { +- assert(value !=3D null); +- this._message =3D value; +- } +- +- /** +- * The stack trace associated with the generation of the error, used for +- * debugging the server. +- */ +- String get stackTrace =3D> _stackTrace; +- +- /** +- * The stack trace associated with the generation of the error, used for +- * debugging the server. +- */ +- void set stackTrace(String value) { +- assert(value !=3D null); +- this._stackTrace =3D value; +- } +- +- ServerErrorParams(bool isFatal, String message, String stackTrace) { +- this.isFatal =3D isFatal; +- this.message =3D message; +- this.stackTrace =3D stackTrace; +- } +- +- factory ServerErrorParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- bool isFatal; +- if (json.containsKey("isFatal")) { +- isFatal =3D +- jsonDecoder.decodeBool(jsonPath + ".isFatal", json["isFatal"]= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "isFatal"); +- } +- String message; +- if (json.containsKey("message")) { +- message =3D +- jsonDecoder.decodeString(jsonPath + ".message", json["message= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "message"); +- } +- String stackTrace; +- if (json.containsKey("stackTrace")) { +- stackTrace =3D jsonDecoder.decodeString( +- jsonPath + ".stackTrace", json["stackTrace"]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "stackTrace"); +- } +- return new ServerErrorParams(isFatal, message, stackTrace); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "server.error params", json); +- } +- } +- +- factory ServerErrorParams.fromNotification(Notification notification) { +- return new ServerErrorParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["isFatal"] =3D isFatal; +- result["message"] =3D message; +- result["stackTrace"] =3D stackTrace; +- return result; +- } +- +- Notification toNotification() { +- return new Notification("server.error", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerErrorParams) { +- return isFatal =3D=3D other.isFatal && +- message =3D=3D other.message && +- stackTrace =3D=3D other.stackTrace; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, isFatal.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, message.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, stackTrace.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * server.getVersion params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerGetVersionParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "server.getVersion", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerGetVersionParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 55877452; +- } +-} +- +-/** +- * server.getVersion result +- * +- * { +- * "version": String +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerGetVersionResult implements ResponseResult { +- String _version; +- +- /** +- * The version number of the analysis server. +- */ +- String get version =3D> _version; +- +- /** +- * The version number of the analysis server. +- */ +- void set version(String value) { +- assert(value !=3D null); +- this._version =3D value; +- } +- +- ServerGetVersionResult(String version) { +- this.version =3D version; +- } +- +- factory ServerGetVersionResult.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- String version; +- if (json.containsKey("version")) { +- version =3D +- jsonDecoder.decodeString(jsonPath + ".version", json["version= "]); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "version"); +- } +- return new ServerGetVersionResult(version); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "server.getVersion result", js= on); +- } +- } +- +- factory ServerGetVersionResult.fromResponse(Response response) { +- return new ServerGetVersionResult.fromJson( +- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.= id)), +- "result", +- response.result); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["version"] =3D version; +- return result; +- } +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerGetVersionResult) { +- return version =3D=3D other.version; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, version.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * ServerService +- * +- * enum { +- * STATUS +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerService implements Enum { +- static const ServerService STATUS =3D const ServerService._("STATUS"); +- +- /** +- * A list containing all of the enum values that are defined. +- */ +- static const List VALUES =3D const [STATU= S]; +- +- @override +- final String name; +- +- const ServerService._(this.name); +- +- factory ServerService(String name) { +- switch (name) { +- case "STATUS": +- return STATUS; +- } +- throw new Exception('Illegal enum value: $name'); +- } +- +- factory ServerService.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json is String) { +- try { +- return new ServerService(json); +- } catch (_) { +- // Fall through +- } +- } +- throw jsonDecoder.mismatch(jsonPath, "ServerService", json); +- } +- +- @override +- String toString() =3D> "ServerService.$name"; +- +- String toJson() =3D> name; +-} +- +-/** +- * server.setSubscriptions params +- * +- * { +- * "subscriptions": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerSetSubscriptionsParams implements RequestParams { +- List _subscriptions; +- +- /** +- * A list of the services being subscribed to. +- */ +- List get subscriptions =3D> _subscriptions; +- +- /** +- * A list of the services being subscribed to. +- */ +- void set subscriptions(List value) { +- assert(value !=3D null); +- this._subscriptions =3D value; +- } +- +- ServerSetSubscriptionsParams(List subscriptions) { +- this.subscriptions =3D subscriptions; +- } +- +- factory ServerSetSubscriptionsParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- List subscriptions; +- if (json.containsKey("subscriptions")) { +- subscriptions =3D jsonDecoder.decodeList( +- jsonPath + ".subscriptions", +- json["subscriptions"], +- (String jsonPath, Object json) =3D> +- new ServerService.fromJson(jsonDecoder, jsonPath, json)); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "subscriptions"); +- } +- return new ServerSetSubscriptionsParams(subscriptions); +- } else { +- throw jsonDecoder.mismatch( +- jsonPath, "server.setSubscriptions params", json); +- } +- } +- +- factory ServerSetSubscriptionsParams.fromRequest(Request request) { +- return new ServerSetSubscriptionsParams.fromJson( +- new RequestDecoder(request), "params", request.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["subscriptions"] =3D +- subscriptions.map((ServerService value) =3D> value.toJson()).toLi= st(); +- return result; +- } +- +- @override +- Request toRequest(String id) { +- return new Request(id, "server.setSubscriptions", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerSetSubscriptionsParams) { +- return listEqual(subscriptions, other.subscriptions, +- (ServerService a, ServerService b) =3D> a =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, subscriptions.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * server.setSubscriptions result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerSetSubscriptionsResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerSetSubscriptionsResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 748820900; +- } +-} +- +-/** +- * server.shutdown params +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerShutdownParams implements RequestParams { +- @override +- Map toJson() =3D> {}; +- +- @override +- Request toRequest(String id) { +- return new Request(id, "server.shutdown", null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerShutdownParams) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 366630911; +- } +-} +- +-/** +- * server.shutdown result +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerShutdownResult implements ResponseResult { +- @override +- Map toJson() =3D> {}; +- +- @override +- Response toResponse(String id) { +- return new Response(id, result: null); +- } +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerShutdownResult) { +- return true; +- } +- return false; +- } +- +- @override +- int get hashCode { +- return 193626532; +- } +-} +- +-/** +- * server.status params +- * +- * { +- * "analysis": optional AnalysisStatus +- * "pub": optional PubStatus +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class ServerStatusParams implements HasToJson { +- AnalysisStatus _analysis; +- +- PubStatus _pub; +- +- /** +- * The current status of analysis, including whether analysis is being +- * performed and if so what is being analyzed. +- */ +- AnalysisStatus get analysis =3D> _analysis; +- +- /** +- * The current status of analysis, including whether analysis is being +- * performed and if so what is being analyzed. +- */ +- void set analysis(AnalysisStatus value) { +- this._analysis =3D value; +- } +- +- /** +- * The current status of pub execution, indicating whether we are curre= ntly +- * running pub. +- */ +- PubStatus get pub =3D> _pub; +- +- /** +- * The current status of pub execution, indicating whether we are curre= ntly +- * running pub. +- */ +- void set pub(PubStatus value) { +- this._pub =3D value; +- } +- +- ServerStatusParams({AnalysisStatus analysis, PubStatus pub}) { +- this.analysis =3D analysis; +- this.pub =3D pub; +- } +- +- factory ServerStatusParams.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- AnalysisStatus analysis; +- if (json.containsKey("analysis")) { +- analysis =3D new AnalysisStatus.fromJson( +- jsonDecoder, jsonPath + ".analysis", json["analysis"]); +- } +- PubStatus pub; +- if (json.containsKey("pub")) { +- pub =3D +- new PubStatus.fromJson(jsonDecoder, jsonPath + ".pub", json["= pub"]); +- } +- return new ServerStatusParams(analysis: analysis, pub: pub); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "server.status params", json); +- } +- } +- +- factory ServerStatusParams.fromNotification(Notification notification) { +- return new ServerStatusParams.fromJson( +- new ResponseDecoder(null), "params", notification.params); +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- if (analysis !=3D null) { +- result["analysis"] =3D analysis.toJson(); +- } +- if (pub !=3D null) { +- result["pub"] =3D pub.toJson(); +- } +- return result; +- } +- +- Notification toNotification() { +- return new Notification("server.status", toJson()); +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is ServerStatusParams) { +- return analysis =3D=3D other.analysis && pub =3D=3D other.pub; +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, analysis.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, pub.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +- +-/** +- * TypeHierarchyItem +- * +- * { +- * "classElement": Element +- * "displayName": optional String +- * "memberElement": optional Element +- * "superclass": optional int +- * "interfaces": List +- * "mixins": List +- * "subclasses": List +- * } +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class TypeHierarchyItem implements HasToJson { +- Element _classElement; +- +- String _displayName; +- +- Element _memberElement; +- +- int _superclass; +- +- List _interfaces; +- +- List _mixins; +- +- List _subclasses; +- +- /** +- * The class element represented by this item. +- */ +- Element get classElement =3D> _classElement; +- +- /** +- * The class element represented by this item. +- */ +- void set classElement(Element value) { +- assert(value !=3D null); +- this._classElement =3D value; +- } +- +- /** +- * The name to be displayed for the class. This field will be omitted i= f the +- * display name is the same as the name of the element. The display nam= e is +- * different if there is additional type information to be displayed, s= uch as +- * type arguments. +- */ +- String get displayName =3D> _displayName; +- +- /** +- * The name to be displayed for the class. This field will be omitted i= f the +- * display name is the same as the name of the element. The display nam= e is +- * different if there is additional type information to be displayed, s= uch as +- * type arguments. +- */ +- void set displayName(String value) { +- this._displayName =3D value; +- } +- +- /** +- * The member in the class corresponding to the member on which the hie= rarchy +- * was requested. This field will be omitted if the hierarchy was not +- * requested for a member or if the class does not have a corresponding +- * member. +- */ +- Element get memberElement =3D> _memberElement; +- +- /** +- * The member in the class corresponding to the member on which the hie= rarchy +- * was requested. This field will be omitted if the hierarchy was not +- * requested for a member or if the class does not have a corresponding +- * member. +- */ +- void set memberElement(Element value) { +- this._memberElement =3D value; +- } +- +- /** +- * The index of the item representing the superclass of this class. This +- * field will be omitted if this item represents the class Object. +- */ +- int get superclass =3D> _superclass; +- +- /** +- * The index of the item representing the superclass of this class. This +- * field will be omitted if this item represents the class Object. +- */ +- void set superclass(int value) { +- this._superclass =3D value; +- } +- +- /** +- * The indexes of the items representing the interfaces implemented by = this +- * class. The list will be empty if there are no implemented interfaces. +- */ +- List get interfaces =3D> _interfaces; +- +- /** +- * The indexes of the items representing the interfaces implemented by = this +- * class. The list will be empty if there are no implemented interfaces. +- */ +- void set interfaces(List value) { +- assert(value !=3D null); +- this._interfaces =3D value; +- } +- +- /** +- * The indexes of the items representing the mixins referenced by this = class. +- * The list will be empty if there are no classes mixed in to this clas= s. +- */ +- List get mixins =3D> _mixins; +- +- /** +- * The indexes of the items representing the mixins referenced by this = class. +- * The list will be empty if there are no classes mixed in to this clas= s. +- */ +- void set mixins(List value) { +- assert(value !=3D null); +- this._mixins =3D value; +- } +- +- /** +- * The indexes of the items representing the subtypes of this class. Th= e list +- * will be empty if there are no subtypes or if this item represents a +- * supertype of the pivot type. +- */ +- List get subclasses =3D> _subclasses; +- +- /** +- * The indexes of the items representing the subtypes of this class. Th= e list +- * will be empty if there are no subtypes or if this item represents a +- * supertype of the pivot type. +- */ +- void set subclasses(List value) { +- assert(value !=3D null); +- this._subclasses =3D value; +- } +- +- TypeHierarchyItem(Element classElement, +- {String displayName, +- Element memberElement, +- int superclass, +- List interfaces, +- List mixins, +- List subclasses}) { +- this.classElement =3D classElement; +- this.displayName =3D displayName; +- this.memberElement =3D memberElement; +- this.superclass =3D superclass; +- if (interfaces =3D=3D null) { +- this.interfaces =3D []; +- } else { +- this.interfaces =3D interfaces; +- } +- if (mixins =3D=3D null) { +- this.mixins =3D []; +- } else { +- this.mixins =3D mixins; +- } +- if (subclasses =3D=3D null) { +- this.subclasses =3D []; +- } else { +- this.subclasses =3D subclasses; +- } +- } +- +- factory TypeHierarchyItem.fromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json) { +- if (json =3D=3D null) { +- json =3D {}; +- } +- if (json is Map) { +- Element classElement; +- if (json.containsKey("classElement")) { +- classElement =3D new Element.fromJson( +- jsonDecoder, jsonPath + ".classElement", json["classElement"]= ); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "classElement"); +- } +- String displayName; +- if (json.containsKey("displayName")) { +- displayName =3D jsonDecoder.decodeString( +- jsonPath + ".displayName", json["displayName"]); +- } +- Element memberElement; +- if (json.containsKey("memberElement")) { +- memberElement =3D new Element.fromJson( +- jsonDecoder, jsonPath + ".memberElement", json["memberElement= "]); +- } +- int superclass; +- if (json.containsKey("superclass")) { +- superclass =3D +- jsonDecoder.decodeInt(jsonPath + ".superclass", json["supercl= ass"]); +- } +- List interfaces; +- if (json.containsKey("interfaces")) { +- interfaces =3D jsonDecoder.decodeList(jsonPath + ".interfaces", +- json["interfaces"], jsonDecoder.decodeInt); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "interfaces"); +- } +- List mixins; +- if (json.containsKey("mixins")) { +- mixins =3D jsonDecoder.decodeList( +- jsonPath + ".mixins", json["mixins"], jsonDecoder.decodeInt); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "mixins"); +- } +- List subclasses; +- if (json.containsKey("subclasses")) { +- subclasses =3D jsonDecoder.decodeList(jsonPath + ".subclasses", +- json["subclasses"], jsonDecoder.decodeInt); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "subclasses"); +- } +- return new TypeHierarchyItem(classElement, +- displayName: displayName, +- memberElement: memberElement, +- superclass: superclass, +- interfaces: interfaces, +- mixins: mixins, +- subclasses: subclasses); +- } else { +- throw jsonDecoder.mismatch(jsonPath, "TypeHierarchyItem", json); +- } +- } +- +- @override +- Map toJson() { +- Map result =3D {}; +- result["classElement"] =3D classElement.toJson(); +- if (displayName !=3D null) { +- result["displayName"] =3D displayName; +- } +- if (memberElement !=3D null) { +- result["memberElement"] =3D memberElement.toJson(); +- } +- if (superclass !=3D null) { +- result["superclass"] =3D superclass; +- } +- result["interfaces"] =3D interfaces; +- result["mixins"] =3D mixins; +- result["subclasses"] =3D subclasses; +- return result; +- } +- +- @override +- String toString() =3D> JSON.encode(toJson()); +- +- @override +- bool operator =3D=3D(other) { +- if (other is TypeHierarchyItem) { +- return classElement =3D=3D other.classElement && +- displayName =3D=3D other.displayName && +- memberElement =3D=3D other.memberElement && +- superclass =3D=3D other.superclass && +- listEqual(interfaces, other.interfaces, (int a, int b) =3D> a = =3D=3D b) && +- listEqual(mixins, other.mixins, (int a, int b) =3D> a =3D=3D b)= && +- listEqual(subclasses, other.subclasses, (int a, int b) =3D> a = =3D=3D b); +- } +- return false; +- } +- +- @override +- int get hashCode { +- int hash =3D 0; +- hash =3D JenkinsSmiHash.combine(hash, classElement.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, displayName.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, memberElement.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, superclass.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, interfaces.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, mixins.hashCode); +- hash =3D JenkinsSmiHash.combine(hash, subclasses.hashCode); +- return JenkinsSmiHash.finish(hash); +- } +-} +diff --git a/pkg/analysis_server/lib/src/analysis_logger.dart b/pkg/analys= is_server/lib/src/analysis_logger.dart +deleted file mode 100644 +index 33911961423..00000000000 +--- a/pkg/analysis_server/lib/src/analysis_logger.dart ++++ /dev/null +@@ -1,55 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:logging/logging.dart' as logging; +- +-/** +- * Instances of the class [AnalysisLogger] translate from the analysis en= gine's +- * API to the logging package's API. +- */ +-class AnalysisLogger implements Logger { +- /** +- * The underlying logger that is being wrapped. +- */ +- final logging.Logger baseLogger =3D new logging.Logger('analysis.server= '); +- +- /** +- * The analysis server that is using this logger. +- */ +- final AnalysisServer server; +- +- AnalysisLogger(this.server) { +- assert(server !=3D null); +- logging.Logger.root.onRecord.listen((logging.LogRecord record) { +- AnalysisEngine.instance.instrumentationService.logLogEntry( +- record.level.name, +- record.time, +- record.message, +- record.error, +- record.stackTrace); +- }); +- } +- +- @override +- void logError(String message, [CaughtException exception]) { +- if (exception =3D=3D null) { +- baseLogger.severe(message); +- } else { +- baseLogger.severe(message, exception.exception, exception.stackTrac= e); +- } +- server.sendServerErrorNotification(message, exception, null); +- } +- +- @override +- void logInformation(String message, [CaughtException exception]) { +- if (exception =3D=3D null) { +- baseLogger.info(message); +- } else { +- baseLogger.info(message, exception.exception, exception.stackTrace); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analys= is_server/lib/src/analysis_server.dart +deleted file mode 100644 +index b6ee79a64d1..00000000000 +--- a/pkg/analysis_server/lib/src/analysis_server.dart ++++ /dev/null +@@ -1,1557 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:core'; +-import 'dart:io' as io; +-import 'dart:math' show max; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart' +- hide AnalysisOptions; +-import 'package:analysis_server/src/analysis_logger.dart'; +-import 'package:analysis_server/src/channel/channel.dart'; +-import 'package:analysis_server/src/collections.dart'; +-import 'package:analysis_server/src/computer/computer_highlights.dart'; +-import 'package:analysis_server/src/computer/computer_highlights2.dart'; +-import 'package:analysis_server/src/computer/computer_outline.dart'; +-import 'package:analysis_server/src/computer/new_notifications.dart'; +-import 'package:analysis_server/src/context_manager.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analysis_server/src/domain_analytics.dart'; +-import 'package:analysis_server/src/domain_completion.dart'; +-import 'package:analysis_server/src/domain_diagnostic.dart'; +-import 'package:analysis_server/src/domain_execution.dart'; +-import 'package:analysis_server/src/domain_kythe.dart'; +-import 'package:analysis_server/src/domain_server.dart'; +-import 'package:analysis_server/src/domains/analysis/navigation_dart.dart= '; +-import 'package:analysis_server/src/domains/analysis/occurrences.dart'; +-import 'package:analysis_server/src/domains/analysis/occurrences_dart.dar= t'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analysis_server/src/operation/operation_analysis.dart'; +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/plugin/plugin_watcher.dart'; +-import 'package:analysis_server/src/protocol_server.dart' as server; +-import 'package:analysis_server/src/search/search_domain.dart'; +-import 'package:analysis_server/src/server/diagnostic_server.dart'; +-import 'package:analysis_server/src/services/correction/namespace.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analysis_server/src/services/search/search_engine_interna= l.dart'; +-import 'package:analysis_server/src/utilities/null_string_sink.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/plugin/resolver_provider.dart'; +-import 'package:analyzer/source/pub_package_map_provider.dart'; +-import 'package:analyzer/src/context/builder.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart' as nd; +-import 'package:analyzer/src/dart/analysis/file_state.dart' as nd; +-import 'package:analyzer/src/dart/analysis/status.dart' as nd; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/source_io.dart'; +-import 'package:analyzer/src/generated/utilities_general.dart'; +-import 'package:analyzer/src/util/glob.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +-import 'package:analyzer_plugin/src/utilities/navigation/navigation.dart'; +-import 'package:front_end/byte_store.dart'; +-import 'package:front_end/src/base/performance_logger.dart'; +-import 'package:telemetry/crash_reporting.dart'; +-import 'package:telemetry/telemetry.dart' as telemetry; +-import 'package:watcher/watcher.dart'; +- +-typedef void OptionUpdater(AnalysisOptionsImpl options); +- +-/** +- * Enum representing reasons why analysis might be done for a given file. +- */ +-class AnalysisDoneReason { +- /** +- * Analysis of the file completed successfully. +- */ +- static const AnalysisDoneReason COMPLETE =3D +- const AnalysisDoneReason._('COMPLETE'); +- +- /** +- * Analysis of the file was aborted because the context was removed. +- */ +- static const AnalysisDoneReason CONTEXT_REMOVED =3D +- const AnalysisDoneReason._('CONTEXT_REMOVED'); +- +- /** +- * Textual description of this [AnalysisDoneReason]. +- */ +- final String text; +- +- const AnalysisDoneReason._(this.text); +-} +- +-/** +- * Instances of the class [AnalysisServer] implement a server that listen= s on a +- * [CommunicationChannel] for analysis requests and process them. +- */ +-class AnalysisServer { +- /** +- * The version of the analysis server. The value should be replaced +- * automatically during the build. +- */ +- static final String VERSION =3D '1.18.4'; +- +- /** +- * The options of this server instance. +- */ +- AnalysisServerOptions options; +- +- /** +- * The channel from which requests are received and to which responses = should +- * be sent. +- */ +- final ServerCommunicationChannel channel; +- +- /** +- * The object used to manage sending a subset of notifications to the c= lient. +- * The subset of notifications are those to which plugins may contribut= e. +- * This field is `null` when the new plugin support is disabled. +- */ +- final NotificationManager notificationManager; +- +- /** +- * The object used to manage the execution of plugins. +- */ +- PluginManager pluginManager; +- +- /** +- * The [ResourceProvider] using which paths are converted into [Resourc= e]s. +- */ +- final ResourceProvider resourceProvider; +- +- /** +- * The [SearchEngine] for this server, may be `null` if indexing is dis= abled. +- */ +- SearchEngine searchEngine; +- +- /** +- * A list of the globs used to determine which files should be analyzed= . The +- * list is lazily created and should be accessed using [analyzedFilesGl= obs]. +- */ +- List _analyzedFilesGlobs =3D null; +- +- /** +- * The [ContextManager] that handles the mapping from analysis roots to +- * context directories. +- */ +- ContextManager contextManager; +- +- /** +- * A flag indicating whether the server is running. When false, contex= ts +- * will no longer be added to [contextWorkQueue], and [performOperation= ] will +- * discard any tasks it finds on [contextWorkQueue]. +- */ +- bool running; +- +- /** +- * A flag indicating the value of the 'analyzing' parameter sent in the= last +- * status message to the client. +- */ +- bool statusAnalyzing =3D false; +- +- /** +- * A list of the request handlers used to handle the requests sent to t= his +- * server. +- */ +- List handlers; +- +- /** +- * The object used to manage the SDK's known to this server. +- */ +- DartSdkManager sdkManager; +- +- /** +- * The instrumentation service that is to be used by this analysis serv= er. +- */ +- final InstrumentationService instrumentationService; +- +- /** +- * A set of the [ServerService]s to send notifications for. +- */ +- Set serverServices =3D new HashSet(); +- +- /** +- * A set of the [GeneralAnalysisService]s to send notifications for. +- */ +- Set generalAnalysisServices =3D +- new HashSet(); +- +- /** +- * A table mapping [AnalysisService]s to the file paths for which these +- * notifications should be sent. +- */ +- Map> analysisServices =3D +- new HashMap>(); +- +- /** +- * Performance information before initial analysis is complete. +- */ +- ServerPerformance performanceDuringStartup =3D new ServerPerformance(); +- +- /** +- * Performance information after initial analysis is complete +- * or `null` if the initial analysis is not yet complete +- */ +- ServerPerformance performanceAfterStartup; +- +- /** +- * A [RecentBuffer] of the most recent exceptions encountered by the an= alysis +- * server. +- */ +- final RecentBuffer exceptions =3D new RecentBuffer(10); +- +- /** +- * The class into which performance information is currently being reco= rded. +- * During startup, this will be the same as [performanceDuringStartup] +- * and after startup is complete, this switches to [performanceAfterSta= rtup]. +- */ +- ServerPerformance _performance; +- +- /** +- * The [Completer] that completes when analysis is complete. +- */ +- Completer _onAnalysisCompleteCompleter; +- +- /** +- * The controller that is notified when analysis is started. +- */ +- StreamController _onAnalysisStartedController; +- +- /** +- * The controller that is notified when a single file has been analyzed. +- */ +- StreamController _onFileAnalyzedController; +- +- /** +- * The content overlay for all analysis drivers. +- */ +- final nd.FileContentOverlay fileContentOverlay =3D new nd.FileContentOv= erlay(); +- +- /** +- * The current state of overlays from the client. This is used as the +- * content cache for all contexts. +- */ +- final ContentCache overlayState =3D new ContentCache(); +- +- /** +- * If the "analysis.analyzedFiles" notification is currently being subs= cribed +- * to (see [generalAnalysisServices]), and at least one such notificati= on has +- * been sent since the subscription was enabled, the set of analyzed fi= les +- * that was delivered in the most recently sent notification. Otherwise +- * `null`. +- */ +- Set prevAnalyzedFiles; +- +- /** +- * The default options used to create new analysis contexts. This objec= t is +- * also referenced by the ContextManager. +- */ +- final AnalysisOptionsImpl defaultContextOptions =3D new AnalysisOptions= Impl(); +- +- /** +- * The file resolver provider used to override the way file URI's are +- * resolved in some contexts. +- */ +- ResolverProvider fileResolverProvider; +- +- /** +- * The package resolver provider used to override the way package URI's= are +- * resolved in some contexts. +- */ +- ResolverProvider packageResolverProvider; +- +- PerformanceLog _analysisPerformanceLogger; +- +- ByteStore byteStore; +- nd.AnalysisDriverScheduler analysisDriverScheduler; +- +- /** +- * The controller for [onAnalysisSetChanged]. +- */ +- StreamController _onAnalysisSetChangedController =3D +- new StreamController.broadcast(); +- +- /** +- * This exists as a temporary stopgap for plugins, until the official p= lugin +- * API is complete. +- */ +- StreamController _onFileAddedController; +- +- /** +- * This exists as a temporary stopgap for plugins, until the official p= lugin +- * API is complete. +- */ +- StreamController _onFileChangedController; +- +- /** +- * This exists as a temporary stopgap for plugins, until the official p= lugin +- * API is complete. +- */ +- Function onResultErrorSupplementor; +- +- /** +- * This exists as a temporary stopgap for plugins, until the official p= lugin +- * API is complete. +- */ +- Function onNoAnalysisResult; +- +- /** +- * This exists as a temporary stopgap for plugins, until the official p= lugin +- * API is complete. +- */ +- Function onNoAnalysisCompletion; +- +- /** +- * The set of the files that are currently priority. +- */ +- final Set priorityFiles =3D new Set(); +- +- /** +- * The DiagnosticServer for this AnalysisServer. If available, it can b= e used +- * to start an http diagnostics server or return the port for an existi= ng +- * server. +- */ +- DiagnosticServer diagnosticServer; +- +- /** +- * Initialize a newly created server to receive requests from and send +- * responses to the given [channel]. +- * +- * If [rethrowExceptions] is true, then any exceptions thrown by analys= is are +- * propagated up the call stack. The default is true to allow analysis +- * exceptions to show up in unit tests, but it should be set to false w= hen +- * running a full analysis server. +- */ +- AnalysisServer( +- this.channel, +- this.resourceProvider, +- PubPackageMapProvider packageMapProvider, +- this.options, +- this.sdkManager, +- this.instrumentationService, +- {this.diagnosticServer, +- ResolverProvider fileResolverProvider: null, +- ResolverProvider packageResolverProvider: null}) +- : notificationManager =3D +- new NotificationManager(channel, resourceProvider) { +- _performance =3D performanceDuringStartup; +- +- pluginManager =3D new PluginManager( +- resourceProvider, +- _getByteStorePath(), +- sdkManager.defaultSdkDirectory, +- notificationManager, +- instrumentationService); +- PluginWatcher pluginWatcher =3D +- new PluginWatcher(resourceProvider, pluginManager); +- +- defaultContextOptions.generateImplicitErrors =3D false; +- +- { +- String name =3D options.newAnalysisDriverLog; +- StringSink sink =3D new NullStringSink(); +- if (name !=3D null) { +- if (name =3D=3D 'stdout') { +- sink =3D io.stdout; +- } else if (name.startsWith('file:')) { +- String path =3D name.substring('file:'.length); +- sink =3D new io.File(path).openWrite(mode: io.FileMode.APPEND); +- } +- } +- _analysisPerformanceLogger =3D new PerformanceLog(sink); +- } +- byteStore =3D _createByteStore(); +- analysisDriverScheduler =3D new nd.AnalysisDriverScheduler( +- _analysisPerformanceLogger, +- driverWatcher: pluginWatcher); +- analysisDriverScheduler.status.listen(sendStatusNotificationNew); +- analysisDriverScheduler.start(); +- +- contextManager =3D new ContextManagerImpl( +- resourceProvider, +- sdkManager, +- packageResolverProvider, +- packageMapProvider, +- analyzedFilesGlobs, +- instrumentationService, +- defaultContextOptions); +- this.fileResolverProvider =3D fileResolverProvider; +- this.packageResolverProvider =3D packageResolverProvider; +- ServerContextManagerCallbacks contextManagerCallbacks =3D +- new ServerContextManagerCallbacks(this, resourceProvider); +- contextManager.callbacks =3D contextManagerCallbacks; +- AnalysisEngine.instance.logger =3D new AnalysisLogger(this); +- _onAnalysisStartedController =3D new StreamController.broadcast(); +- _onFileAnalyzedController =3D new StreamController.broadcast(); +- // temporary plugin support: +- _onFileAddedController =3D new StreamController.broadcast(); +- // temporary plugin support: +- _onFileChangedController =3D new StreamController.broadcast(); +- running =3D true; +- onAnalysisStarted.first.then((_) { +- onAnalysisComplete.then((_) { +- performanceAfterStartup =3D new ServerPerformance(); +- _performance =3D performanceAfterStartup; +- }); +- }); +- searchEngine =3D new SearchEngineImpl(driverMap.values); +- Notification notification =3D new ServerConnectedParams(VERSION, io.p= id, +- sessionId: instrumentationService.sessionId) +- .toNotification(); +- channel.sendNotification(notification); +- channel.listen(handleRequest, onDone: done, onError: error); +- handlers =3D [ +- new ServerDomainHandler(this), +- new AnalysisDomainHandler(this), +- new EditDomainHandler(this), +- new SearchDomainHandler(this), +- new CompletionDomainHandler(this), +- new ExecutionDomainHandler(this), +- new DiagnosticDomainHandler(this), +- new AnalyticsDomainHandler(this), +- new KytheDomainHandler(this) +- ]; +- } +- +- /** +- * Return a list of the globs used to determine which files should be a= nalyzed. +- */ +- List get analyzedFilesGlobs { +- if (_analyzedFilesGlobs =3D=3D null) { +- _analyzedFilesGlobs =3D []; +- List patterns =3D [ +- '**/*.${AnalysisEngine.SUFFIX_DART}', +- '**/*.${AnalysisEngine.SUFFIX_HTML}', +- '**/*.${AnalysisEngine.SUFFIX_HTM}', +- '**/${AnalysisEngine.ANALYSIS_OPTIONS_FILE}', +- '**/${AnalysisEngine.ANALYSIS_OPTIONS_YAML_FILE}' +- ]; +- for (String pattern in patterns) { +- try { +- _analyzedFilesGlobs +- .add(new Glob(resourceProvider.pathContext.separator, patte= rn)); +- } catch (exception, stackTrace) { +- AnalysisEngine.instance.logger.logError( +- 'Invalid glob pattern: "$pattern"', +- new CaughtException(exception, stackTrace)); +- } +- } +- } +- return _analyzedFilesGlobs; +- } +- +- /** +- * A table mapping [Folder]s to the [AnalysisDriver]s associated with t= hem. +- */ +- Map get driverMap =3D> contextManager.driver= Map; +- +- /** +- * The [Future] that completes when analysis is complete. +- */ +- Future get onAnalysisComplete { +- if (isAnalysisComplete()) { +- return new Future.value(); +- } +- if (_onAnalysisCompleteCompleter =3D=3D null) { +- _onAnalysisCompleteCompleter =3D new Completer(); +- } +- return _onAnalysisCompleteCompleter.future; +- } +- +- /** +- * The stream that is notified when the analysis set is changed - this = might +- * be a change to a file, external via a watch event, or internal via +- * overlay. This means that the resolved world might have changed. +- * +- * The type of produced elements is not specified and should not be use= d. +- */ +- Stream get onAnalysisSetChanged =3D> _onAnalysisSetChangedController.st= ream; +- +- /** +- * The stream that is notified with `true` when analysis is started. +- */ +- Stream get onAnalysisStarted { +- return _onAnalysisStartedController.stream; +- } +- +- /** +- * The stream that is notified when a single file has been added. This = exists +- * as a temporary stopgap for plugins, until the official plugin API is +- * complete. +- */ +- Stream get onFileAdded =3D> _onFileAddedController.stream; +- +- /** +- * The stream that is notified when a single file has been analyzed. +- */ +- Stream get onFileAnalyzed =3D> _onFileAnalyzedController.stream; +- +- /** +- * The stream that is notified when a single file has been changed. This +- * exists as a temporary stopgap for plugins, until the official plugin= API is +- * complete. +- */ +- Stream get onFileChanged =3D> _onFileChangedController.stream; +- +- /** +- * Return the total time the server's been alive. +- */ +- Duration get uptime { +- DateTime start =3D new DateTime.fromMillisecondsSinceEpoch( +- performanceDuringStartup.startTime); +- return new DateTime.now().difference(start); +- } +- +- /** +- * The socket from which requests are being read has been closed. +- */ +- void done() { +- running =3D false; +- } +- +- /** +- * There was an error related to the socket from which requests are bei= ng +- * read. +- */ +- void error(argument) { +- running =3D false; +- } +- +- /** +- * If the given notice applies to a file contained within an analysis r= oot, +- * notify interested parties that the file has been (at least partially) +- * analyzed. +- */ +- void fileAnalyzed(ChangeNotice notice) { +- if (contextManager.isInAnalysisRoot(notice.source.fullName)) { +- _onFileAnalyzedController.add(notice); +- } +- } +- +- /** +- * Return one of the SDKs that has been created, or `null` if no SDKs h= ave +- * been created yet. +- */ +- DartSdk findSdk() { +- DartSdk sdk =3D sdkManager.anySdk; +- if (sdk !=3D null) { +- return sdk; +- } +- // TODO(brianwilkerson) Should we create an SDK using the default opt= ions? +- return null; +- } +- +- /** +- * Return an analysis driver to which the file with the given [path] is +- * added if one exists, otherwise a driver in which the file was analyz= ed if +- * one exists, otherwise the first driver, otherwise `null`. +- */ +- nd.AnalysisDriver getAnalysisDriver(String path) { +- List drivers =3D driverMap.values.toList(); +- if (drivers.isNotEmpty) { +- // Sort the drivers so that more deeply nested contexts will be che= cked +- // before enclosing contexts. +- drivers.sort((first, second) =3D> +- second.contextRoot.root.length - first.contextRoot.root.length); +- nd.AnalysisDriver driver =3D drivers.firstWhere( +- (driver) =3D> driver.contextRoot.containsFile(path), +- orElse: () =3D> null); +- driver ??=3D drivers.firstWhere( +- (driver) =3D> driver.knownFiles.contains(path), +- orElse: () =3D> null); +- driver ??=3D drivers.first; +- return driver; +- } +- return null; +- } +- +- /** +- * Return the analysis result for the file with the given [path]. The f= ile is +- * analyzed in one of the analysis drivers to which the file was added, +- * otherwise in the first driver, otherwise `null` is returned. +- */ +- Future getAnalysisResult(String path, +- {bool sendCachedToStream: false}) async { +- if (!AnalysisEngine.isDartFileName(path)) { +- return null; +- } +- +- try { +- nd.AnalysisDriver driver =3D getAnalysisDriver(path); +- return await driver?.getResult(path, +- sendCachedToStream: sendCachedToStream); +- } catch (e) { +- // Ignore the exception. +- // We don't want to log the same exception again and again. +- return null; +- } +- } +- +- /** +- * Return the [AstProvider] for the given [path]. +- */ +- AstProvider getAstProvider(String path) { +- nd.AnalysisDriver analysisDriver =3D getAnalysisDriver(path); +- return new AstProviderForDriver(analysisDriver); +- } +- +- /** +- * Return the cached analysis result for the file with the given [path]. +- * If there is no cached result, return `null`. +- */ +- nd.AnalysisResult getCachedAnalysisResult(String path) { +- if (!AnalysisEngine.isDartFileName(path)) { +- return null; +- } +- +- nd.AnalysisDriver driver =3D getAnalysisDriver(path); +- return driver?.getCachedResult(path); +- } +- +- /** +- * Return the [nd.AnalysisDriver] for the "innermost" context whose ass= ociated +- * folder is or contains the given path. ("innermost" refers to the ne= sting +- * of contexts, so if there is a context for path /foo and a context for +- * path /foo/bar, then the innermost context containing /foo/bar/baz.da= rt is +- * the context for /foo/bar.) +- * +- * If no context contains the given path, `null` is returned. +- */ +- nd.AnalysisDriver getContainingDriver(String path) { +- return contextManager.getDriverFor(path); +- } +- +- /** +- * Return a [Future] that completes with the [Element] at the given +- * [offset] of the given [file], or with `null` if there is no node at = the +- * [offset] or the node does not have an element. +- */ +- Future getElementAtOffset(String file, int offset) async { +- AstNode node =3D await getNodeAtOffset(file, offset); +- return getElementOfNode(node); +- } +- +- /** +- * Return the [Element] of the given [node], or `null` if [node] is `nu= ll` or +- * does not have an element. +- */ +- Element getElementOfNode(AstNode node) { +- if (node =3D=3D null) { +- return null; +- } +- if (node is SimpleIdentifier && node.parent is LibraryIdentifier) { +- node =3D node.parent; +- } +- if (node is LibraryIdentifier) { +- node =3D node.parent; +- } +- if (node is StringLiteral && node.parent is UriBasedDirective) { +- return null; +- } +- Element element =3D ElementLocator.locate(node); +- if (node is SimpleIdentifier && element is PrefixElement) { +- element =3D getImportElement(node); +- } +- return element; +- } +- +- /** +- * Return a [Future] that completes with the resolved [AstNode] at the +- * given [offset] of the given [file], or with `null` if there is no no= de as +- * the [offset]. +- */ +- Future getNodeAtOffset(String file, int offset) async { +- nd.AnalysisResult result =3D await getAnalysisResult(file); +- CompilationUnit unit =3D result?.unit; +- if (unit !=3D null) { +- return new NodeLocator(offset).searchWithin(unit); +- } +- return null; +- } +- +- /** +- * Return a [Future] that completes with the resolved [CompilationUnit]= for +- * the Dart file with the given [path], or with `null` if the file is n= ot a +- * Dart file or cannot be resolved. +- */ +- Future getResolvedCompilationUnit(String path) async { +- nd.AnalysisResult result =3D await getAnalysisResult(path); +- return result?.unit; +- } +- +- /** +- * Handle a [request] that was read from the communication channel. +- */ +- void handleRequest(Request request) { +- _performance.logRequest(request); +- runZoned(() { +- ServerPerformanceStatistics.serverRequests.makeCurrentWhile(() { +- int count =3D handlers.length; +- for (int i =3D 0; i < count; i++) { +- try { +- Response response =3D handlers[i].handleRequest(request); +- if (response =3D=3D Response.DELAYED_RESPONSE) { +- return; +- } +- if (response !=3D null) { +- channel.sendResponse(response); +- return; +- } +- } on RequestFailure catch (exception) { +- channel.sendResponse(exception.response); +- return; +- } catch (exception, stackTrace) { +- RequestError error =3D new RequestError( +- RequestErrorCode.SERVER_ERROR, exception.toString()); +- if (stackTrace !=3D null) { +- error.stackTrace =3D stackTrace.toString(); +- } +- Response response =3D new Response(request.id, error: error); +- channel.sendResponse(response); +- return; +- } +- } +- channel.sendResponse(new Response.unknownRequest(request)); +- }); +- }, onError: (exception, stackTrace) { +- sendServerErrorNotification( +- 'Failed to handle request: ${request.toJson()}', +- exception, +- stackTrace, +- fatal: true); +- }); +- } +- +- /** +- * Returns `true` if there is a subscription for the given [service] and +- * [file]. +- */ +- bool hasAnalysisSubscription(AnalysisService service, String file) { +- Set files =3D analysisServices[service]; +- return files !=3D null && files.contains(file); +- } +- +- /** +- * Return `true` if analysis is complete. +- */ +- bool isAnalysisComplete() { +- return !analysisDriverScheduler.isAnalyzing; +- } +- +- /** +- * Return `true` if the given path is a valid `FilePath`. +- * +- * This means that it is absolute and normalized. +- */ +- bool isValidFilePath(String path) { +- return resourceProvider.absolutePathContext.isValid(path); +- } +- +- /** +- * Trigger reanalysis of all files in the given list of analysis [roots= ], or +- * everything if the analysis roots is `null`. +- */ +- void reanalyze(List roots) { +- // Instruct the contextDirectoryManager to rebuild all contexts from +- // scratch. +- contextManager.refresh(roots); +- } +- +- /** +- * Send the given [notification] to the client. +- */ +- void sendNotification(Notification notification) { +- channel.sendNotification(notification); +- } +- +- /** +- * Send the given [response] to the client. +- */ +- void sendResponse(Response response) { +- channel.sendResponse(response); +- } +- +- /** +- * Sends a `server.error` notification. +- */ +- void sendServerErrorNotification(String message, exception, stackTrace, +- {bool fatal: false}) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write(exception ?? 'null exception'); +- if (stackTrace !=3D null) { +- buffer.writeln(); +- buffer.write(stackTrace); +- } else if (exception is! CaughtException) { +- stackTrace =3D StackTrace.current; +- buffer.writeln(); +- buffer.write(stackTrace); +- } +- +- // send the notification +- channel.sendNotification( +- new ServerErrorParams(fatal, message, buffer.toString()) +- .toNotification()); +- +- // send to crash reporting +- if (options.crashReportSender !=3D null) { +- // Catch and ignore any exceptions when reporting exceptions (netwo= rk +- // errors or other). +- options.crashReportSender +- .sendReport(exception, stackTrace: stackTrace) +- .catchError((_) {}); +- } +- +- // remember the last few exceptions +- if (exception is CaughtException) { +- stackTrace ??=3D exception.stackTrace; +- } +- exceptions.add(new ServerException(message, exception, stackTrace, fa= tal)); +- } +- +- /** +- * Send status notification to the client. The state of analysis is giv= en by +- * the [status] information. +- */ +- void sendStatusNotificationNew(nd.AnalysisStatus status) { +- if (status.isAnalyzing) { +- _onAnalysisStartedController.add(true); +- } +- if (_onAnalysisCompleteCompleter !=3D null && !status.isAnalyzing) { +- _onAnalysisCompleteCompleter.complete(); +- _onAnalysisCompleteCompleter =3D null; +- } +- // Perform on-idle actions. +- if (!status.isAnalyzing) { +- if (generalAnalysisServices +- .contains(GeneralAnalysisService.ANALYZED_FILES)) { +- sendAnalysisNotificationAnalyzedFiles(this); +- } +- _scheduleAnalysisImplementedNotification(); +- } +- // Only send status when subscribed. +- if (!serverServices.contains(ServerService.STATUS)) { +- return; +- } +- // Only send status when it changes +- if (statusAnalyzing =3D=3D status.isAnalyzing) { +- return; +- } +- statusAnalyzing =3D status.isAnalyzing; +- AnalysisStatus analysis =3D new AnalysisStatus(status.isAnalyzing); +- channel.sendNotification( +- new ServerStatusParams(analysis: analysis).toNotification()); +- } +- +- /** +- * Implementation for `analysis.setAnalysisRoots`. +- * +- * TODO(scheglov) implement complete projects/contexts semantics. +- * +- * The current implementation is intentionally simplified and expected +- * that only folders are given each given folder corresponds to the exa= ctly +- * one context. +- * +- * So, we can start working in parallel on adding services and improving +- * projects/contexts support. +- */ +- void setAnalysisRoots(String requestId, List includedPaths, +- List excludedPaths, Map packageRoots) { +- if (notificationManager !=3D null) { +- notificationManager.setAnalysisRoots(includedPaths, excludedPaths); +- } +- try { +- contextManager.setRoots(includedPaths, excludedPaths, packageRoots); +- } on UnimplementedError catch (e) { +- throw new RequestFailure( +- new Response.unsupportedFeature(requestId, e.message)); +- } +- } +- +- /** +- * Implementation for `analysis.setSubscriptions`. +- */ +- void setAnalysisSubscriptions( +- Map> subscriptions) { +- if (notificationManager !=3D null) { +- notificationManager.setSubscriptions(subscriptions); +- } +- this.analysisServices =3D subscriptions; +- Set allNewFiles =3D +- subscriptions.values.expand((files) =3D> files).toSet(); +- for (String file in allNewFiles) { +- // The result will be produced by the "results" stream with +- // the fully resolved unit, and processed with sending analysis +- // notifications as it happens after content changes. +- if (AnalysisEngine.isDartFileName(file)) { +- getAnalysisResult(file, sendCachedToStream: true); +- } +- } +- } +- +- /** +- * Implementation for `analysis.setGeneralSubscriptions`. +- */ +- void setGeneralAnalysisSubscriptions( +- List subscriptions) { +- Set newServices =3D subscriptions.toSet(); +- if (newServices.contains(GeneralAnalysisService.ANALYZED_FILES) && +- !generalAnalysisServices +- .contains(GeneralAnalysisService.ANALYZED_FILES) && +- isAnalysisComplete()) { +- sendAnalysisNotificationAnalyzedFiles(this); +- } else if (!newServices.contains(GeneralAnalysisService.ANALYZED_FILE= S) && +- generalAnalysisServices +- .contains(GeneralAnalysisService.ANALYZED_FILES)) { +- prevAnalyzedFiles =3D null; +- } +- generalAnalysisServices =3D newServices; +- } +- +- /** +- * Set the priority files to the given [files]. +- */ +- void setPriorityFiles(String requestId, List files) { +- priorityFiles.clear(); +- priorityFiles.addAll(files); +- // Set priority files in drivers. +- driverMap.values.forEach((driver) { +- driver.priorityFiles =3D files; +- }); +- } +- +- /** +- * Returns `true` if errors should be reported for [file] with the given +- * absolute path. +- */ +- bool shouldSendErrorsNotificationFor(String file) { +- return contextManager.isInAnalysisRoot(file); +- } +- +- Future shutdown() async { +- running =3D false; +- +- await options.analytics +- ?.waitForLastPing(timeout: new Duration(milliseconds: 200)); +- options.analytics?.close(); +- +- // Defer closing the channel and shutting down the instrumentation se= rver so +- // that the shutdown response can be sent and logged. +- new Future(() { +- instrumentationService.shutdown(); +- channel.close(); +- }); +- } +- +- /** +- * Implementation for `analysis.updateContent`. +- */ +- void updateContent(String id, Map changes) { +- _onAnalysisSetChangedController.add(null); +- changes.forEach((file, change) { +- // Prepare the new contents. +- String oldContents =3D fileContentOverlay[file]; +- String newContents; +- if (change is AddContentOverlay) { +- newContents =3D change.content; +- } else if (change is ChangeContentOverlay) { +- if (oldContents =3D=3D null) { +- // The client may only send a ChangeContentOverlay if there is +- // already an existing overlay for the source. +- throw new RequestFailure(new Response(id, +- error: new RequestError(RequestErrorCode.INVALID_OVERLAY_CH= ANGE, +- 'Invalid overlay change'))); +- } +- try { +- newContents =3D SourceEdit.applySequence(oldContents, change.ed= its); +- } on RangeError { +- throw new RequestFailure(new Response(id, +- error: new RequestError(RequestErrorCode.INVALID_OVERLAY_CH= ANGE, +- 'Invalid overlay change'))); +- } +- } else if (change is RemoveContentOverlay) { +- newContents =3D null; +- } else { +- // Protocol parsing should have ensured that we never get here. +- throw new AnalysisException('Illegal change type'); +- } +- +- fileContentOverlay[file] =3D newContents; +- +- driverMap.values.forEach((driver) { +- driver.changeFile(file); +- }); +- +- // temporary plugin support: +- _onFileChangedController.add(file); +- +- // If the file did not exist, and is "overlay only", it still shoul= d be +- // analyzed. Add it to driver to which it should have been added. +- contextManager.getDriverFor(file)?.addFile(file); +- +- // TODO(scheglov) implement other cases +- }); +- } +- +- /** +- * Use the given updaters to update the values of the options in every +- * existing analysis context. +- */ +- void updateOptions(List optionUpdaters) { +- // TODO(scheglov) implement for the new analysis driver +-// // +-// // Update existing contexts. +-// // +-// for (AnalysisContext context in analysisContexts) { +-// AnalysisOptionsImpl options =3D +-// new AnalysisOptionsImpl.from(context.analysisOptions); +-// optionUpdaters.forEach((OptionUpdater optionUpdater) { +-// optionUpdater(options); +-// }); +-// context.analysisOptions =3D options; +-// // TODO(brianwilkerson) As far as I can tell, this doesn't cause = analysis +-// // to be scheduled for this context. +-// } +-// // +-// // Update the defaults used to create new contexts. +-// // +-// optionUpdaters.forEach((OptionUpdater optionUpdater) { +-// optionUpdater(defaultContextOptions); +-// }); +- } +- +- void _computingPackageMap(bool computing) { +- if (serverServices.contains(ServerService.STATUS)) { +- PubStatus pubStatus =3D new PubStatus(computing); +- ServerStatusParams params =3D new ServerStatusParams(pub: pubStatus= ); +- sendNotification(params.toNotification()); +- } +- } +- +- /** +- * If the state location can be accessed, return the file byte store, +- * otherwise return the memory byte store. +- */ +- ByteStore _createByteStore() { +- const int M =3D 1024 * 1024 /*1 MiB*/; +- const int G =3D 1024 * 1024 * 1024 /*1 GiB*/; +- if (resourceProvider is PhysicalResourceProvider) { +- Folder stateLocation =3D +- resourceProvider.getStateLocation('.analysis-driver'); +- if (stateLocation !=3D null) { +- return new MemoryCachingByteStore( +- new EvictingFileByteStore(stateLocation.path, G), 64 * M); +- } +- } +- return new MemoryCachingByteStore(new NullByteStore(), 64 * M); +- } +- +- /** +- * Return the path to the location of the byte store on disk, or `null`= if +- * there is no on-disk byte store. +- */ +- String _getByteStorePath() { +- if (resourceProvider is PhysicalResourceProvider) { +- Folder stateLocation =3D +- resourceProvider.getStateLocation('.analysis-driver'); +- if (stateLocation !=3D null) { +- return stateLocation.path; +- } +- } +- return null; +- } +- +- bool _hasAnalysisServiceSubscription(AnalysisService service, String fi= le) { +- return analysisServices[service]?.contains(file) ?? false; +- } +- +- _scheduleAnalysisImplementedNotification() async { +- Set files =3D analysisServices[AnalysisService.IMPLEMENTED]; +- if (files !=3D null) { +- scheduleImplementedNotification(this, files); +- } +- } +-} +- +-/** +- * Various IDE options. +- */ +-class AnalysisServerOptions { +- bool useAnalysisHighlight2 =3D false; +- +- String fileReadMode =3D 'as-is'; +- String newAnalysisDriverLog; +- +- String clientId; +- String clientVersion; +- +- /** +- * Base path where to cache data. +- */ +- String cacheFolder; +- +- /** +- * The analytics instance; note, this object can be `null`, and should = be +- * accessed via a null-aware operator. +- */ +- telemetry.Analytics analytics; +- +- /** +- * The crash report sender instance; note, this object can be `null`, a= nd +- * should be accessed via a null-aware operator. +- */ +- CrashReportSender crashReportSender; +- +- /** +- * Whether to enable the Dart 2.0 Front End. +- */ +- bool previewDart2 =3D false; +-} +- +-/** +- * A [PriorityChangeEvent] indicates the set the priority files has chang= ed. +- */ +-class PriorityChangeEvent { +- final Source firstSource; +- +- PriorityChangeEvent(this.firstSource); +-} +- +-class ServerContextManagerCallbacks extends ContextManagerCallbacks { +- final AnalysisServer analysisServer; +- +- /** +- * The [ResourceProvider] by which paths are converted into [Resource]s. +- */ +- final ResourceProvider resourceProvider; +- +- ServerContextManagerCallbacks(this.analysisServer, this.resourceProvide= r); +- +- @override +- NotificationManager get notificationManager =3D> +- analysisServer.notificationManager; +- +- @override +- nd.AnalysisDriver addAnalysisDriver( +- Folder folder, ContextRoot contextRoot, AnalysisOptions options) { +- ContextBuilder builder =3D createContextBuilder(folder, options); +- nd.AnalysisDriver analysisDriver =3D builder.buildDriver(contextRoot); +- analysisDriver.results.listen((result) { +- NotificationManager notificationManager =3D +- analysisServer.notificationManager; +- String path =3D result.path; +- if (analysisServer.shouldSendErrorsNotificationFor(path)) { +- if (notificationManager !=3D null) { +- notificationManager.recordAnalysisErrors( +- NotificationManager.serverId, +- path, +- server.doAnalysisError_listFromEngine( +- result.driver.analysisOptions, +- result.lineInfo, +- result.errors)); +- } else { +- new_sendErrorNotification(analysisServer, result); +- } +- } +- CompilationUnit unit =3D result.unit; +- if (unit !=3D null) { +- if (notificationManager !=3D null) { +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.HIGHLIGHTS, path)) { +- _runDelayed(() { +- notificationManager.recordHighlightRegions( +- NotificationManager.serverId, +- path, +- _computeHighlightRegions(unit)); +- }); +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.NAVIGATION, path)) { +- _runDelayed(() { +- notificationManager.recordNavigationParams( +- NotificationManager.serverId, +- path, +- _computeNavigationParams(path, unit)); +- }); +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.OCCURRENCES, path)) { +- _runDelayed(() { +- notificationManager.recordOccurrences( +- NotificationManager.serverId, +- path, +- _computeOccurrences(unit)); +- }); +- } +-// if (analysisServer._hasAnalysisServiceSubscription( +-// AnalysisService.OUTLINE, path)) { +-// _runDelayed(() { +-// // TODO(brianwilkerson) Change NotificationManager to sto= re params +-// // so that fileKind and libraryName can be recorded / pas= sed along. +-// notificationManager.recordOutlines(NotificationManager.se= rverId, +-// path, _computeOutlineParams(path, unit, result.lineIn= fo)); +-// }); +-// } +- } else { +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.HIGHLIGHTS, path)) { +- _runDelayed(() { +- sendAnalysisNotificationHighlights(analysisServer, path, un= it); +- }); +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.NAVIGATION, path)) { +- _runDelayed(() { +- new_sendDartNotificationNavigation(analysisServer, result); +- }); +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.OCCURRENCES, path)) { +- _runDelayed(() { +- new_sendDartNotificationOccurrences(analysisServer, result); +- }); +- } +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.CLOSING_LABELS, path)) { +- _runDelayed(() { +- sendAnalysisNotificationClosingLabels( +- analysisServer, path, result.lineInfo, unit); +- }); +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.OUTLINE, path)) { +- _runDelayed(() { +- SourceKind sourceKind =3D +- unit.directives.any((d) =3D> d is PartOfDirective) +- ? SourceKind.PART +- : SourceKind.LIBRARY; +- sendAnalysisNotificationOutline( +- analysisServer, path, result.lineInfo, sourceKind, unit); +- }); +- } +- if (analysisServer._hasAnalysisServiceSubscription( +- AnalysisService.OVERRIDES, path)) { +- _runDelayed(() { +- sendAnalysisNotificationOverrides(analysisServer, path, unit); +- }); +- } +- // TODO(scheglov) Implement notifications for AnalysisService.IMP= LEMENTED. +- } +- }); +- analysisDriver.exceptions.listen((nd.ExceptionResult result) { +- String message =3D 'Analysis failed: ${result.path}'; +- if (result.contextKey !=3D null) { +- message +=3D ' context: ${result.contextKey}'; +- } +- AnalysisEngine.instance.logger.logError(message, result.exception); +- }); +- analysisServer.driverMap[folder] =3D analysisDriver; +- return analysisDriver; +- } +- +- @override +- void afterWatchEvent(WatchEvent event) { +- analysisServer._onAnalysisSetChangedController.add(null); +- } +- +- @override +- void applyChangesToContext(Folder contextFolder, ChangeSet changeSet) { +- nd.AnalysisDriver analysisDriver =3D analysisServer.driverMap[context= Folder]; +- if (analysisDriver !=3D null) { +- changeSet.addedSources.forEach((source) { +- analysisDriver.addFile(source.fullName); +- // temporary plugin support: +- analysisServer._onFileAddedController.add(source.fullName); +- }); +- changeSet.changedSources.forEach((source) { +- analysisDriver.changeFile(source.fullName); +- // temporary plugin support: +- analysisServer._onFileChangedController.add(source.fullName); +- }); +- changeSet.removedSources.forEach((source) { +- analysisDriver.removeFile(source.fullName); +- }); +- } +- } +- +- @override +- void applyFileRemoved(nd.AnalysisDriver driver, String file) { +- driver.removeFile(file); +- sendAnalysisNotificationFlushResults(analysisServer, [file]); +- } +- +- @override +- void broadcastWatchEvent(WatchEvent event) { +- analysisServer.pluginManager.broadcastWatchEvent(event); +- } +- +- @override +- void computingPackageMap(bool computing) =3D> +- analysisServer._computingPackageMap(computing); +- +- @override +- ContextBuilder createContextBuilder(Folder folder, AnalysisOptions opti= ons) { +- String defaultPackageFilePath =3D null; +- String defaultPackagesDirectoryPath =3D null; +- String path =3D (analysisServer.contextManager as ContextManagerImpl) +- .normalizedPackageRoots[folder.path]; +- if (path !=3D null) { +- Resource resource =3D resourceProvider.getResource(path); +- if (resource.exists) { +- if (resource is File) { +- defaultPackageFilePath =3D path; +- } else { +- defaultPackagesDirectoryPath =3D path; +- } +- } +- } +- +- ContextBuilderOptions builderOptions =3D new ContextBuilderOptions(); +- builderOptions.defaultOptions =3D options; +- builderOptions.defaultPackageFilePath =3D defaultPackageFilePath; +- builderOptions.defaultPackagesDirectoryPath =3D defaultPackagesDirect= oryPath; +- ContextBuilder builder =3D new ContextBuilder(resourceProvider, +- analysisServer.sdkManager, analysisServer.overlayState, +- options: builderOptions); +- builder.fileResolverProvider =3D analysisServer.fileResolverProvider; +- builder.packageResolverProvider =3D analysisServer.packageResolverPro= vider; +- builder.analysisDriverScheduler =3D analysisServer.analysisDriverSche= duler; +- builder.performanceLog =3D analysisServer._analysisPerformanceLogger; +- builder.byteStore =3D analysisServer.byteStore; +- builder.fileContentOverlay =3D analysisServer.fileContentOverlay; +- builder.previewDart2 =3D analysisServer.options.previewDart2; +- return builder; +- } +- +- @override +- void moveContext(Folder from, Folder to) { +- // There is nothing to do. +- // This method is mostly for tests. +- // Context managers manage folders and contexts themselves. +- } +- +- @override +- void removeContext(Folder folder, List flushedFiles) { +- sendAnalysisNotificationFlushResults(analysisServer, flushedFiles); +- nd.AnalysisDriver driver =3D analysisServer.driverMap.remove(folder); +- driver.dispose(); +- } +- +- List _computeHighlightRegions(CompilationUnit unit) { +- if (analysisServer.options.useAnalysisHighlight2) { +- return new DartUnitHighlightsComputer2(unit).compute(); +- } else { +- return new DartUnitHighlightsComputer(unit).compute(); +- } +- } +- +- String _computeLibraryName(CompilationUnit unit) { +- for (Directive directive in unit.directives) { +- if (directive is LibraryDirective && directive.name !=3D null) { +- return directive.name.name; +- } +- } +- for (Directive directive in unit.directives) { +- if (directive is PartOfDirective && directive.libraryName !=3D null= ) { +- return directive.libraryName.name; +- } +- } +- return null; +- } +- +- server.AnalysisNavigationParams _computeNavigationParams( +- String path, CompilationUnit unit) { +- NavigationCollectorImpl collector =3D new NavigationCollectorImpl(); +- computeDartNavigation(collector, unit, null, null); +- collector.createRegions(); +- return new server.AnalysisNavigationParams( +- path, collector.regions, collector.targets, collector.files); +- } +- +- List _computeOccurrences(CompilationUnit unit) { +- OccurrencesCollectorImpl collector =3D new OccurrencesCollectorImpl(); +- addDartOccurrences(collector, unit); +- return collector.allOccurrences; +- } +- +- // ignore: unused_element +- server.AnalysisOutlineParams _computeOutlineParams( +- String path, CompilationUnit unit, LineInfo lineInfo) { +- // compute FileKind +- SourceKind sourceKind =3D unit.directives.any((d) =3D> d is PartOfDir= ective) +- ? SourceKind.PART +- : SourceKind.LIBRARY; +- server.FileKind fileKind =3D server.FileKind.LIBRARY; +- if (sourceKind =3D=3D SourceKind.LIBRARY) { +- fileKind =3D server.FileKind.LIBRARY; +- } else if (sourceKind =3D=3D SourceKind.PART) { +- fileKind =3D server.FileKind.PART; +- } +- // compute library name +- String libraryName =3D _computeLibraryName(unit); +- // compute Outline +- DartUnitOutlineComputer computer =3D +- new DartUnitOutlineComputer(path, lineInfo, unit); +- server.Outline outline =3D computer.compute(); +- return new server.AnalysisOutlineParams(path, fileKind, outline, +- libraryName: libraryName); +- } +- +- /** +- * Run [f] in a new [Future]. +- * +- * This method is used to delay sending notifications. If there is a mo= re +- * important consumer of an analysis results, specifically a code compl= etion +- * computer, we want it to run before spending time of sending notifica= tions. +- * +- * TODO(scheglov) Consider replacing this with full priority based sche= duler. +- * +- * TODO(scheglov) Alternatively, if code completion work in a way that = does +- * not produce (at first) fully resolved unit, but only part of it - a = single +- * method, or a top-level declaration, we would not have this problem -= the +- * completion computer would be the only consumer of the partial analys= is +- * result. +- */ +- void _runDelayed(f()) { +- new Future(f); +- } +-} +- +-/** +- * Used to record server exceptions. +- */ +-class ServerException { +- final String message; +- final dynamic exception; +- final StackTrace stackTrace; +- final bool fatal; +- +- ServerException(this.message, this.exception, this.stackTrace, this.fat= al); +- +- @override +- String toString() =3D> message; +-} +- +-/** +- * A class used by [AnalysisServer] to record performance information +- * such as request latency. +- */ +-class ServerPerformance { +- /** +- * The creation time and the time when performance information +- * started to be recorded here. +- */ +- int startTime =3D new DateTime.now().millisecondsSinceEpoch; +- +- /** +- * The number of requests. +- */ +- int requestCount =3D 0; +- +- /** +- * The total latency (milliseconds) for all recorded requests. +- */ +- int requestLatency =3D 0; +- +- /** +- * The maximum latency (milliseconds) for all recorded requests. +- */ +- int maxLatency =3D 0; +- +- /** +- * The number of requests with latency > 150 milliseconds. +- */ +- int slowRequestCount =3D 0; +- +- /** +- * Log performance information about the given request. +- */ +- void logRequest(Request request) { +- ++requestCount; +- if (request.clientRequestTime !=3D null) { +- int latency =3D +- new DateTime.now().millisecondsSinceEpoch - request.clientReque= stTime; +- requestLatency +=3D latency; +- maxLatency =3D max(maxLatency, latency); +- if (latency > 150) { +- ++slowRequestCount; +- } +- } +- } +-} +- +-/** +- * Container with global [AnalysisServer] performance statistics. +- */ +-class ServerPerformanceStatistics { +- /** +- * The [PerformanceTag] for `package:analysis_server`. +- */ +- static PerformanceTag server =3D new PerformanceTag('server'); +- +- /** +- * The [PerformanceTag] for time spent in [ExecutionDomainHandler]. +- */ +- static PerformanceTag executionNotifications =3D +- new PerformanceTag('executionNotifications'); +- +- /** +- * The [PerformanceTag] for time spent performing a _DartIndexOperation. +- */ +- static PerformanceTag indexOperation =3D new PerformanceTag('indexOpera= tion'); +- +- /** +- * The [PerformanceTag] for time spent between calls to +- * AnalysisServer.performOperation when the server is not idle. +- */ +- static PerformanceTag intertask =3D new PerformanceTag('intertask'); +- +- /** +- * The [PerformanceTag] for time spent between calls to +- * AnalysisServer.performOperation when the server is idle. +- */ +- static PerformanceTag idle =3D new PerformanceTag('idle'); +- +- /** +- * The [PerformanceTag] for time spent in +- * PerformAnalysisOperation._sendNotices. +- */ +- static PerformanceTag notices =3D server.createChild('notices'); +- +- /** +- * The [PerformanceTag] for time spent running pub. +- */ +- static PerformanceTag pub =3D server.createChild('pub'); +- +- /** +- * The [PerformanceTag] for time spent in server communication channels. +- */ +- static PerformanceTag serverChannel =3D server.createChild('channel'); +- +- /** +- * The [PerformanceTag] for time spent in server request handlers. +- */ +- static PerformanceTag serverRequests =3D server.createChild('requests'); +- +- /** +- * The [PerformanceTag] for time spent in split store microtasks. +- */ +- static PerformanceTag splitStore =3D new PerformanceTag('splitStore'); +-} +diff --git a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart = b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart +deleted file mode 100644 +index dce7e5912e1..00000000000 +--- a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart ++++ /dev/null +@@ -1,175 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/channel/channel.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +- +-/** +- * Instances of the class [ByteStreamClientChannel] implement a +- * [ClientCommunicationChannel] that uses a stream and a sink (typically, +- * standard input and standard output) to communicate with servers. +- */ +-class ByteStreamClientChannel implements ClientCommunicationChannel { +- final Stream input; +- final IOSink output; +- +- @override +- Stream responseStream; +- +- @override +- Stream notificationStream; +- +- ByteStreamClientChannel(this.input, this.output) { +- Stream jsonStream =3D input +- .transform(const Utf8Decoder()) +- .transform(new LineSplitter()) +- .transform(new JsonStreamDecoder()) +- .where((json) =3D> json is Map) +- .asBroadcastStream(); +- responseStream =3D jsonStream +- .where((json) =3D> json[Notification.EVENT] =3D=3D null) +- .transform(new ResponseConverter()) +- .asBroadcastStream(); +- notificationStream =3D jsonStream +- .where((json) =3D> json[Notification.EVENT] !=3D null) +- .transform(new NotificationConverter()) +- .asBroadcastStream(); +- } +- +- @override +- Future close() { +- return output.close(); +- } +- +- @override +- Future sendRequest(Request request) async { +- String id =3D request.id; +- output.write(JSON.encode(request.toJson()) + '\n'); +- return await responseStream +- .firstWhere((Response response) =3D> response.id =3D=3D id); +- } +-} +- +-/** +- * Instances of the class [ByteStreamServerChannel] implement a +- * [ServerCommunicationChannel] that uses a stream and a sink (typically, +- * standard input and standard output) to communicate with clients. +- */ +-class ByteStreamServerChannel implements ServerCommunicationChannel { +- final Stream _input; +- +- final IOSink _output; +- +- /** +- * The instrumentation service that is to be used by this analysis serv= er. +- */ +- final InstrumentationService _instrumentationService; +- +- /** +- * Completer that will be signalled when the input stream is closed. +- */ +- final Completer _closed =3D new Completer(); +- +- /** +- * True if [close] has been called. +- */ +- bool _closeRequested =3D false; +- +- ByteStreamServerChannel( +- this._input, this._output, this._instrumentationService); +- +- /** +- * Future that will be completed when the input stream is closed. +- */ +- Future get closed { +- return _closed.future; +- } +- +- @override +- void close() { +- if (!_closeRequested) { +- _closeRequested =3D true; +- assert(!_closed.isCompleted); +- _closed.complete(); +- } +- } +- +- @override +- void listen(void onRequest(Request request), +- {Function onError, void onDone()}) { +- _input.transform(const Utf8Decoder()).transform(new LineSplitter()).l= isten( +- (String data) =3D> _readRequest(data, onRequest), +- onError: onError, onDone: () { +- close(); +- onDone(); +- }); +- } +- +- @override +- void sendNotification(Notification notification) { +- // Don't send any further notifications after the communication chann= el is +- // closed. +- if (_closeRequested) { +- return; +- } +- ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() { +- String jsonEncoding =3D JSON.encode(notification.toJson()); +- _outputLine(jsonEncoding); +- _instrumentationService.logNotification(jsonEncoding); +- }); +- } +- +- @override +- void sendResponse(Response response) { +- // Don't send any further responses after the communication channel is +- // closed. +- if (_closeRequested) { +- return; +- } +- ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() { +- String jsonEncoding =3D JSON.encode(response.toJson()); +- _outputLine(jsonEncoding); +- _instrumentationService.logResponse(jsonEncoding); +- }); +- } +- +- /** +- * Send the string [s] to [_output] followed by a newline. +- */ +- void _outputLine(String s) { +- runZoned(() { +- _output.writeln(s); +- }, onError: (e) { +- close(); +- }); +- } +- +- /** +- * Read a request from the given [data] and use the given function to h= andle +- * the request. +- */ +- void _readRequest(Object data, void onRequest(Request request)) { +- // Ignore any further requests after the communication channel is clo= sed. +- if (_closed.isCompleted) { +- return; +- } +- ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() { +- _instrumentationService.logRequest(data); +- // Parse the string as a JSON descriptor and process the resulting +- // structure as a request. +- Request request =3D new Request.fromString(data); +- if (request =3D=3D null) { +- sendResponse(new Response.invalidRequestFormat()); +- return; +- } +- onRequest(request); +- }); +- } +-} +diff --git a/pkg/analysis_server/lib/src/channel/channel.dart b/pkg/analys= is_server/lib/src/channel/channel.dart +deleted file mode 100644 +index ca75739e2a5..00000000000 +--- a/pkg/analysis_server/lib/src/channel/channel.dart ++++ /dev/null +@@ -1,150 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +- +-/** +- * Instances of the class [ChannelChunkSink] uses a [Converter] to transl= ate +- * chunks. +- */ +-class ChannelChunkSink extends ChunkedConversionSink { +- /** +- * The converter used to translate chunks. +- */ +- final Converter converter; +- +- /** +- * The sink to which the converted chunks are added. +- */ +- final Sink sink; +- +- /** +- * A flag indicating whether the sink has been closed. +- */ +- bool closed =3D false; +- +- /** +- * Initialize a newly create sink to use the given [converter] to conve= rt +- * chunks before adding them to the given [sink]. +- */ +- ChannelChunkSink(this.converter, this.sink); +- +- @override +- void add(S chunk) { +- if (!closed) { +- T convertedChunk =3D converter.convert(chunk); +- if (convertedChunk !=3D null) { +- sink.add(convertedChunk); +- } +- } +- } +- +- @override +- void close() { +- closed =3D true; +- sink.close(); +- } +-} +- +-/** +- * The abstract class [ClientCommunicationChannel] defines the behavior of +- * objects that allow a client to send [Request]s to an [AnalysisServer] = and to +- * receive both [Response]s and [Notification]s. +- */ +-abstract class ClientCommunicationChannel { +- /** +- * The stream of notifications from the server. +- */ +- Stream notificationStream; +- +- /** +- * The stream of responses from the server. +- */ +- Stream responseStream; +- +- /** +- * Close the channel to the server. Once called, all future communicati= on +- * with the server via [sendRequest] will silently be ignored. +- */ +- Future close(); +- +- /** +- * Send the given [request] to the server +- * and return a future with the associated [Response]. +- */ +- Future sendRequest(Request request); +-} +- +-/** +- * Instances of the class [JsonStreamDecoder] convert JSON strings to JSON +- * maps. +- */ +-class JsonStreamDecoder extends Converter { +- @override +- Map convert(String text) =3D> JSON.decode(text); +- +- @override +- ChunkedConversionSink startChunkedConversion(Sink sink) = =3D> +- new ChannelChunkSink(this, sink); +-} +- +-/** +- * Instances of the class [NotificationConverter] convert JSON maps to +- * [Notification]s. +- */ +-class NotificationConverter extends Converter { +- @override +- Notification convert(Map json) =3D> new Notification.fromJson(json); +- +- @override +- ChunkedConversionSink startChunkedConversion(Sink si= nk) =3D> +- new ChannelChunkSink(this, sink); +-} +- +-/** +- * Instances of the class [ResponseConverter] convert JSON maps to [Respo= nse]s. +- */ +-class ResponseConverter extends Converter { +- @override +- Response convert(Map json) =3D> new Response.fromJson(json); +- +- @override +- ChunkedConversionSink startChunkedConversion(Sink sink) = =3D> +- new ChannelChunkSink(this, sink); +-} +- +-/** +- * The abstract class [ServerCommunicationChannel] defines the behavior of +- * objects that allow an [AnalysisServer] to receive [Request]s and to re= turn +- * both [Response]s and [Notification]s. +- */ +-abstract class ServerCommunicationChannel { +- /** +- * Close the communication channel. +- */ +- void close(); +- +- /** +- * Listen to the channel for requests. If a request is received, invoke= the +- * [onRequest] function. If an error is encountered while trying to rea= d from +- * the socket, invoke the [onError] function. If the socket is closed b= y the +- * client, invoke the [onDone] function. +- * Only one listener is allowed per channel. +- */ +- void listen(void onRequest(Request request), +- {Function onError, void onDone()}); +- +- /** +- * Send the given [notification] to the client. +- */ +- void sendNotification(Notification notification); +- +- /** +- * Send the given [response] to the client. +- */ +- void sendResponse(Response response); +-} +diff --git a/pkg/analysis_server/lib/src/collections.dart b/pkg/analysis_s= erver/lib/src/collections.dart +deleted file mode 100644 +index 6c88a0463a3..00000000000 +--- a/pkg/analysis_server/lib/src/collections.dart ++++ /dev/null +@@ -1,71 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Returns the concatenation of the input [iterables]. +- * +- * The returned iterable is a lazily-evaluated view on the input iterable= s. +- */ +-Iterable concat(Iterable> iterables) =3D> +- iterables.expand((x) =3D> x); +- +-/** +- * Returns the concatenation of the input [iterables] as a [List]. +- */ +-List concatToList(Iterable> iterables) =3D> +- concat(iterables).toList(); +- +-/** +- * Returns the given [list] if it is not empty, or `null` otherwise. +- */ +-List nullIfEmpty(List list) { +- if (list =3D=3D null) { +- return null; +- } +- if (list.isEmpty) { +- return null; +- } +- return list; +-} +- +-/// A pair of values. +-class Pair { +- final E first; +- final F last; +- +- Pair(this.first, this.last); +- +- int get hashCode =3D> first.hashCode ^ last.hashCode; +- +- bool operator =3D=3D(other) { +- if (other is! Pair) return false; +- return other.first =3D=3D first && other.last =3D=3D last; +- } +- +- String toString() =3D> '($first, $last)'; +-} +- +-/** +- * A container that remembers the last `n` items added to it. +- * +- * It will never grow larger than [capacity]. It's a LIFO queue - the las= t item +- * added will be the first one returned from [items]. +- */ +-class RecentBuffer { +- final int capacity; +- +- List _buffer =3D []; +- +- RecentBuffer(this.capacity); +- +- Iterable get items =3D> _buffer.reversed; +- +- void add(T item) { +- _buffer.add(item); +- +- if (_buffer.length > capacity) { +- _buffer.removeAt(0); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/computer_closingLabels.d= art b/pkg/analysis_server/lib/src/computer/computer_closingLabels.dart +deleted file mode 100644 +index 71c5ff32838..00000000000 +--- a/pkg/analysis_server/lib/src/computer/computer_closingLabels.dart ++++ /dev/null +@@ -1,105 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-// TODO(devoncarew): We should look into not creating any labels until th= ere's +-// at least 2 levels of nesting. +- +-/** +- * A computer for [CompilationUnit] closing labels. +- */ +-class DartUnitClosingLabelsComputer { +- final LineInfo _lineInfo; +- final CompilationUnit _unit; +- final List _closingLabels =3D []; +- +- DartUnitClosingLabelsComputer(this._lineInfo, this._unit); +- +- /** +- * Returns a list of closing labels, not `null`. +- */ +- List compute() { +- _unit.accept(new _DartUnitClosingLabelsComputerVisitor(this)); +- return _closingLabels; +- } +-} +- +-/** +- * An AST visitor for [DartUnitClosingLabelsComputer]. +- */ +-class _DartUnitClosingLabelsComputerVisitor +- extends RecursiveAstVisitor { +- final DartUnitClosingLabelsComputer computer; +- +- int interpolatedStringsEntered =3D 0; +- +- _DartUnitClosingLabelsComputerVisitor(this.computer); +- +- @override +- Object visitInstanceCreationExpression(InstanceCreationExpression node)= { +- if (node.argumentList !=3D null) { +- var label =3D node.constructorName.type.name.name; +- if (node.constructorName.name !=3D null) { +- label +=3D ".${node.constructorName.name.name}"; +- } +- // We override the node used for doing line calculations because ot= herwise +- // constructors that split over multiple lines (but have parens on = same +- // line) would incorrectly get labels, because node.start on an ins= tance +- // creation expression starts at the start of the expression. +- _addLabel(node, label, checkLinesUsing: node.argumentList); +- } +- +- return super.visitInstanceCreationExpression(node); +- } +- +- @override +- Object visitListLiteral(ListLiteral node) { +- final NodeList args =3D node.typeArguments?.arguments; +- final String typeName =3D args !=3D null ? args[0]?.toString() : null; +- +- if (typeName !=3D null) { +- _addLabel(node, "<$typeName>[]"); +- } +- +- return super.visitListLiteral(node); +- } +- +- @override +- Object visitStringInterpolation(StringInterpolation node) { +- interpolatedStringsEntered++; +- try { +- return super.visitStringInterpolation(node); +- } finally { +- interpolatedStringsEntered--; +- } +- } +- +- void _addLabel(AstNode node, String label, {AstNode checkLinesUsing}) { +- // Never add labels if we're inside strings. +- if (interpolatedStringsEntered > 0) { +- return; +- } +- +- checkLinesUsing =3D checkLinesUsing ?? node; +- +- final LineInfo_Location start =3D +- computer._lineInfo.getLocation(checkLinesUsing.offset); +- final LineInfo_Location end =3D +- computer._lineInfo.getLocation(checkLinesUsing.end - 1); +- +- int spannedLines =3D end.lineNumber - start.lineNumber; +- if (spannedLines < 1) { +- return; +- } +- +- final ClosingLabel closingLabel =3D +- new ClosingLabel(node.offset, node.length, label); +- +- computer._closingLabels.add(closingLabel); +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/computer_highlights.dart= b/pkg/analysis_server/lib/src/computer/computer_highlights.dart +deleted file mode 100644 +index c49b17a4740..00000000000 +--- a/pkg/analysis_server/lib/src/computer/computer_highlights.dart ++++ /dev/null +@@ -1,737 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +- +-/** +- * A computer for [HighlightRegion]s in a Dart [CompilationUnit]. +- */ +-class DartUnitHighlightsComputer { +- final CompilationUnit _unit; +- +- final List _regions =3D []; +- +- DartUnitHighlightsComputer(this._unit); +- +- /** +- * Returns the computed highlight regions, not `null`. +- */ +- List compute() { +- _unit.accept(new _DartUnitHighlightsComputerVisitor(this)); +- _addCommentRanges(); +- return _regions; +- } +- +- void _addCommentRanges() { +- Token token =3D _unit.beginToken; +- while (token !=3D null && token.type !=3D TokenType.EOF) { +- Token commentToken =3D token.precedingComments; +- while (commentToken !=3D null) { +- HighlightRegionType highlightType =3D null; +- if (commentToken.type =3D=3D TokenType.MULTI_LINE_COMMENT) { +- if (commentToken.lexeme.startsWith('/**')) { +- highlightType =3D HighlightRegionType.COMMENT_DOCUMENTATION; +- } else { +- highlightType =3D HighlightRegionType.COMMENT_BLOCK; +- } +- } +- if (commentToken.type =3D=3D TokenType.SINGLE_LINE_COMMENT) { +- highlightType =3D HighlightRegionType.COMMENT_END_OF_LINE; +- } +- if (highlightType !=3D null) { +- _addRegion_token(commentToken, highlightType); +- } +- commentToken =3D commentToken.next; +- } +- token =3D token.next; +- } +- } +- +- void _addIdentifierRegion(SimpleIdentifier node) { +- if (_addIdentifierRegion_keyword(node)) { +- return; +- } +- if (_addIdentifierRegion_class(node)) { +- return; +- } +- if (_addIdentifierRegion_constructor(node)) { +- return; +- } +- if (_addIdentifierRegion_dynamicType(node)) { +- return; +- } +- if (_addIdentifierRegion_getterSetterDeclaration(node)) { +- return; +- } +- if (_addIdentifierRegion_field(node)) { +- return; +- } +- if (_addIdentifierRegion_function(node)) { +- return; +- } +- if (_addIdentifierRegion_functionTypeAlias(node)) { +- return; +- } +- if (_addIdentifierRegion_importPrefix(node)) { +- return; +- } +- if (_addIdentifierRegion_label(node)) { +- return; +- } +- if (_addIdentifierRegion_localVariable(node)) { +- return; +- } +- if (_addIdentifierRegion_method(node)) { +- return; +- } +- if (_addIdentifierRegion_parameter(node)) { +- return; +- } +- if (_addIdentifierRegion_typeParameter(node)) { +- return; +- } +- _addRegion_node(node, HighlightRegionType.IDENTIFIER_DEFAULT); +- } +- +- void _addIdentifierRegion_annotation(Annotation node) { +- ArgumentList arguments =3D node.arguments; +- if (arguments =3D=3D null) { +- _addRegion_node(node, HighlightRegionType.ANNOTATION); +- } else { +- _addRegion_nodeStart_tokenEnd( +- node, arguments.beginToken, HighlightRegionType.ANNOTATION); +- _addRegion_token(arguments.endToken, HighlightRegionType.ANNOTATION= ); +- } +- } +- +- bool _addIdentifierRegion_class(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! ClassElement) { +- return false; +- } +- ClassElement classElement =3D element; +- // prepare type +- HighlightRegionType type; +- if (classElement.isEnum) { +- type =3D HighlightRegionType.ENUM; +- } else { +- type =3D HighlightRegionType.CLASS; +- } +- // add region +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_constructor(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! ConstructorElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.CONSTRUCTOR); +- } +- +- bool _addIdentifierRegion_dynamicType(SimpleIdentifier node) { +- // should be variable +- Element element =3D node.staticElement; +- if (element is! VariableElement) { +- return false; +- } +- // has propagated type +- if (node.propagatedType !=3D null) { +- return false; +- } +- // has dynamic static type +- DartType staticType =3D node.staticType; +- if (staticType =3D=3D null || !staticType.isDynamic) { +- return false; +- } +- // OK +- return _addRegion_node(node, HighlightRegionType.DYNAMIC_TYPE); +- } +- +- bool _addIdentifierRegion_field(SimpleIdentifier node) { +- Element element =3D node.bestElement; +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- if (element is PropertyAccessorElement) { +- element =3D (element as PropertyAccessorElement).variable; +- } +- // prepare type +- HighlightRegionType type; +- if (element is FieldElement) { +- Element enclosingElement =3D element.enclosingElement; +- if (enclosingElement is ClassElement && enclosingElement.isEnum) { +- type =3D HighlightRegionType.ENUM_CONSTANT; +- } else if (element.isStatic) { +- type =3D HighlightRegionType.FIELD_STATIC; +- } else { +- type =3D HighlightRegionType.FIELD; +- } +- } else if (element is TopLevelVariableElement) { +- type =3D HighlightRegionType.TOP_LEVEL_VARIABLE; +- } +- // add region +- if (type !=3D null) { +- return _addRegion_node(node, type); +- } +- return false; +- } +- +- bool _addIdentifierRegion_function(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! FunctionElement) { +- return false; +- } +- HighlightRegionType type; +- if (node.inDeclarationContext()) { +- type =3D HighlightRegionType.FUNCTION_DECLARATION; +- } else { +- type =3D HighlightRegionType.FUNCTION; +- } +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_functionTypeAlias(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! FunctionTypeAliasElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.FUNCTION_TYPE_ALIAS); +- } +- +- bool _addIdentifierRegion_getterSetterDeclaration(SimpleIdentifier node= ) { +- // should be declaration +- AstNode parent =3D node.parent; +- if (!(parent is MethodDeclaration || parent is FunctionDeclaration)) { +- return false; +- } +- // should be property accessor +- Element element =3D node.staticElement; +- if (element is! PropertyAccessorElement) { +- return false; +- } +- // getter or setter +- PropertyAccessorElement propertyAccessorElement =3D +- element as PropertyAccessorElement; +- if (propertyAccessorElement.isGetter) { +- return _addRegion_node(node, HighlightRegionType.GETTER_DECLARATION= ); +- } else { +- return _addRegion_node(node, HighlightRegionType.SETTER_DECLARATION= ); +- } +- } +- +- bool _addIdentifierRegion_importPrefix(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! PrefixElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.IMPORT_PREFIX); +- } +- +- bool _addIdentifierRegion_keyword(SimpleIdentifier node) { +- String name =3D node.name; +- if (name =3D=3D "void") { +- return _addRegion_node(node, HighlightRegionType.KEYWORD); +- } +- return false; +- } +- +- bool _addIdentifierRegion_label(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! LabelElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.LABEL); +- } +- +- bool _addIdentifierRegion_localVariable(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! LocalVariableElement) { +- return false; +- } +- // OK +- HighlightRegionType type; +- if (node.inDeclarationContext()) { +- type =3D HighlightRegionType.LOCAL_VARIABLE_DECLARATION; +- } else { +- type =3D HighlightRegionType.LOCAL_VARIABLE; +- } +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_method(SimpleIdentifier node) { +- Element element =3D node.bestElement; +- if (element is! MethodElement) { +- return false; +- } +- MethodElement methodElement =3D element as MethodElement; +- bool isStatic =3D methodElement.isStatic; +- // OK +- HighlightRegionType type; +- if (node.inDeclarationContext()) { +- if (isStatic) { +- type =3D HighlightRegionType.METHOD_DECLARATION_STATIC; +- } else { +- type =3D HighlightRegionType.METHOD_DECLARATION; +- } +- } else { +- if (isStatic) { +- type =3D HighlightRegionType.METHOD_STATIC; +- } else { +- type =3D HighlightRegionType.METHOD; +- } +- } +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_parameter(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! ParameterElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.PARAMETER); +- } +- +- bool _addIdentifierRegion_typeParameter(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! TypeParameterElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.TYPE_PARAMETER); +- } +- +- void _addRegion(int offset, int length, HighlightRegionType type) { +- _regions.add(new HighlightRegion(type, offset, length)); +- } +- +- bool _addRegion_node(AstNode node, HighlightRegionType type) { +- int offset =3D node.offset; +- int length =3D node.length; +- _addRegion(offset, length, type); +- return true; +- } +- +- void _addRegion_nodeStart_tokenEnd( +- AstNode a, Token b, HighlightRegionType type) { +- int offset =3D a.offset; +- int end =3D b.end; +- _addRegion(offset, end - offset, type); +- } +- +- void _addRegion_token(Token token, HighlightRegionType type) { +- if (token !=3D null) { +- int offset =3D token.offset; +- int length =3D token.length; +- _addRegion(offset, length, type); +- } +- } +- +- void _addRegion_tokenStart_tokenEnd( +- Token a, Token b, HighlightRegionType type) { +- int offset =3D a.offset; +- int end =3D b.end; +- _addRegion(offset, end - offset, type); +- } +-} +- +-/** +- * An AST visitor for [DartUnitHighlightsComputer]. +- */ +-class _DartUnitHighlightsComputerVisitor extends RecursiveAstVisitor { +- final DartUnitHighlightsComputer computer; +- +- _DartUnitHighlightsComputerVisitor(this.computer); +- +- @override +- Object visitAnnotation(Annotation node) { +- computer._addIdentifierRegion_annotation(node); +- return super.visitAnnotation(node); +- } +- +- @override +- Object visitAsExpression(AsExpression node) { +- computer._addRegion_token(node.asOperator, HighlightRegionType.BUILT_= IN); +- return super.visitAsExpression(node); +- } +- +- @override +- Object visitAssertStatement(AssertStatement node) { +- computer._addRegion_token(node.assertKeyword, HighlightRegionType.KEY= WORD); +- return super.visitAssertStatement(node); +- } +- +- @override +- Object visitAwaitExpression(AwaitExpression node) { +- computer._addRegion_token(node.awaitKeyword, HighlightRegionType.BUIL= T_IN); +- return super.visitAwaitExpression(node); +- } +- +- @override +- Object visitBlockFunctionBody(BlockFunctionBody node) { +- _addRegions_functionBody(node); +- return super.visitBlockFunctionBody(node); +- } +- +- @override +- Object visitBooleanLiteral(BooleanLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.KEYWORD); +- computer._addRegion_node(node, HighlightRegionType.LITERAL_BOOLEAN); +- return super.visitBooleanLiteral(node); +- } +- +- @override +- Object visitBreakStatement(BreakStatement node) { +- computer._addRegion_token(node.breakKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitBreakStatement(node); +- } +- +- @override +- Object visitCatchClause(CatchClause node) { +- computer._addRegion_token(node.catchKeyword, HighlightRegionType.KEYW= ORD); +- computer._addRegion_token(node.onKeyword, HighlightRegionType.BUILT_I= N); +- return super.visitCatchClause(node); +- } +- +- @override +- Object visitClassDeclaration(ClassDeclaration node) { +- computer._addRegion_token(node.classKeyword, HighlightRegionType.KEYW= ORD); +- computer._addRegion_token( +- node.abstractKeyword, HighlightRegionType.BUILT_IN); +- return super.visitClassDeclaration(node); +- } +- +- @override +- Object visitClassTypeAlias(ClassTypeAlias node) { +- computer._addRegion_token( +- node.abstractKeyword, HighlightRegionType.BUILT_IN); +- return super.visitClassTypeAlias(node); +- } +- +- @override +- Object visitConstructorDeclaration(ConstructorDeclaration node) { +- computer._addRegion_token( +- node.externalKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.factoryKeyword, HighlightRegionType.BUILT_IN); +- return super.visitConstructorDeclaration(node); +- } +- +- @override +- Object visitContinueStatement(ContinueStatement node) { +- computer._addRegion_token( +- node.continueKeyword, HighlightRegionType.KEYWORD); +- return super.visitContinueStatement(node); +- } +- +- @override +- Object visitDoStatement(DoStatement node) { +- computer._addRegion_token(node.doKeyword, HighlightRegionType.KEYWORD= ); +- computer._addRegion_token(node.whileKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitDoStatement(node); +- } +- +- @override +- Object visitDoubleLiteral(DoubleLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_DOUBLE); +- return super.visitDoubleLiteral(node); +- } +- +- @override +- Object visitEnumDeclaration(EnumDeclaration node) { +- computer._addRegion_token(node.enumKeyword, HighlightRegionType.KEYWO= RD); +- return super.visitEnumDeclaration(node); +- } +- +- @override +- Object visitExportDirective(ExportDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitExportDirective(node); +- } +- +- @override +- Object visitExpressionFunctionBody(ExpressionFunctionBody node) { +- _addRegions_functionBody(node); +- return super.visitExpressionFunctionBody(node); +- } +- +- @override +- Object visitFieldDeclaration(FieldDeclaration node) { +- computer._addRegion_token(node.staticKeyword, HighlightRegionType.BUI= LT_IN); +- return super.visitFieldDeclaration(node); +- } +- +- @override +- Object visitForEachStatement(ForEachStatement node) { +- computer._addRegion_token(node.awaitKeyword, HighlightRegionType.BUIL= T_IN); +- computer._addRegion_token(node.forKeyword, HighlightRegionType.KEYWOR= D); +- computer._addRegion_token(node.inKeyword, HighlightRegionType.KEYWORD= ); +- return super.visitForEachStatement(node); +- } +- +- @override +- Object visitForStatement(ForStatement node) { +- computer._addRegion_token(node.forKeyword, HighlightRegionType.KEYWOR= D); +- return super.visitForStatement(node); +- } +- +- @override +- Object visitFunctionDeclaration(FunctionDeclaration node) { +- computer._addRegion_token( +- node.externalKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.propertyKeyword, HighlightRegionType.BUILT_IN); +- return super.visitFunctionDeclaration(node); +- } +- +- @override +- Object visitFunctionTypeAlias(FunctionTypeAlias node) { +- computer._addRegion_token( +- node.typedefKeyword, HighlightRegionType.BUILT_IN); +- return super.visitFunctionTypeAlias(node); +- } +- +- @override +- Object visitGenericFunctionType(GenericFunctionType node) { +- computer._addRegion_token( +- node.functionKeyword, HighlightRegionType.KEYWORD); +- return super.visitGenericFunctionType(node); +- } +- +- @override +- Object visitGenericTypeAlias(GenericTypeAlias node) { +- computer._addRegion_token(node.typedefKeyword, HighlightRegionType.KE= YWORD); +- return super.visitGenericTypeAlias(node); +- } +- +- @override +- Object visitHideCombinator(HideCombinator node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitHideCombinator(node); +- } +- +- @override +- Object visitIfStatement(IfStatement node) { +- computer._addRegion_token(node.ifKeyword, HighlightRegionType.KEYWORD= ); +- return super.visitIfStatement(node); +- } +- +- @override +- Object visitImplementsClause(ImplementsClause node) { +- computer._addRegion_token( +- node.implementsKeyword, HighlightRegionType.BUILT_IN); +- return super.visitImplementsClause(node); +- } +- +- @override +- Object visitImportDirective(ImportDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.deferredKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token(node.asKeyword, HighlightRegionType.BUILT_I= N); +- return super.visitImportDirective(node); +- } +- +- @override +- Object visitInstanceCreationExpression(InstanceCreationExpression node)= { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitInstanceCreationExpression(node); +- } +- +- @override +- Object visitIntegerLiteral(IntegerLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_INTEGER); +- return super.visitIntegerLiteral(node); +- } +- +- @override +- Object visitIsExpression(IsExpression node) { +- computer._addRegion_token(node.isOperator, HighlightRegionType.KEYWOR= D); +- return super.visitIsExpression(node); +- } +- +- @override +- Object visitLibraryDirective(LibraryDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitLibraryDirective(node); +- } +- +- @override +- Object visitListLiteral(ListLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_LIST); +- computer._addRegion_token(node.constKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitListLiteral(node); +- } +- +- @override +- Object visitMapLiteral(MapLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_MAP); +- computer._addRegion_token(node.constKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitMapLiteral(node); +- } +- +- @override +- Object visitMethodDeclaration(MethodDeclaration node) { +- computer._addRegion_token( +- node.externalKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.modifierKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.operatorKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.propertyKeyword, HighlightRegionType.BUILT_IN); +- return super.visitMethodDeclaration(node); +- } +- +- @override +- Object visitNativeClause(NativeClause node) { +- computer._addRegion_token(node.nativeKeyword, HighlightRegionType.BUI= LT_IN); +- return super.visitNativeClause(node); +- } +- +- @override +- Object visitNativeFunctionBody(NativeFunctionBody node) { +- computer._addRegion_token(node.nativeKeyword, HighlightRegionType.BUI= LT_IN); +- return super.visitNativeFunctionBody(node); +- } +- +- @override +- Object visitPartDirective(PartDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitPartDirective(node); +- } +- +- @override +- Object visitPartOfDirective(PartOfDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_tokenStart_tokenEnd( +- node.partKeyword, node.ofKeyword, HighlightRegionType.BUILT_IN); +- return super.visitPartOfDirective(node); +- } +- +- @override +- Object visitRethrowExpression(RethrowExpression node) { +- computer._addRegion_token(node.rethrowKeyword, HighlightRegionType.KE= YWORD); +- return super.visitRethrowExpression(node); +- } +- +- @override +- Object visitReturnStatement(ReturnStatement node) { +- computer._addRegion_token(node.returnKeyword, HighlightRegionType.KEY= WORD); +- return super.visitReturnStatement(node); +- } +- +- @override +- Object visitShowCombinator(ShowCombinator node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitShowCombinator(node); +- } +- +- @override +- Object visitSimpleIdentifier(SimpleIdentifier node) { +- computer._addIdentifierRegion(node); +- return super.visitSimpleIdentifier(node); +- } +- +- @override +- Object visitSimpleStringLiteral(SimpleStringLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_STRING); +- return super.visitSimpleStringLiteral(node); +- } +- +- @override +- Object visitSuperConstructorInvocation(SuperConstructorInvocation node)= { +- computer._addRegion_token(node.superKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitSuperConstructorInvocation(node); +- } +- +- @override +- Object visitSwitchCase(SwitchCase node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitSwitchCase(node); +- } +- +- @override +- Object visitSwitchDefault(SwitchDefault node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitSwitchDefault(node); +- } +- +- @override +- Object visitSwitchStatement(SwitchStatement node) { +- computer._addRegion_token(node.switchKeyword, HighlightRegionType.KEY= WORD); +- return super.visitSwitchStatement(node); +- } +- +- @override +- Object visitThisExpression(ThisExpression node) { +- computer._addRegion_token(node.thisKeyword, HighlightRegionType.KEYWO= RD); +- return super.visitThisExpression(node); +- } +- +- @override +- Object visitTryStatement(TryStatement node) { +- computer._addRegion_token(node.tryKeyword, HighlightRegionType.KEYWOR= D); +- computer._addRegion_token(node.finallyKeyword, HighlightRegionType.KE= YWORD); +- return super.visitTryStatement(node); +- } +- +- @override +- Object visitTypeName(TypeName node) { +- DartType type =3D node.type; +- if (type !=3D null) { +- if (type.isDynamic && node.name.name =3D=3D "dynamic") { +- computer._addRegion_node(node, HighlightRegionType.TYPE_NAME_DYNA= MIC); +- return null; +- } +- } +- return super.visitTypeName(node); +- } +- +- @override +- Object visitVariableDeclarationList(VariableDeclarationList node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitVariableDeclarationList(node); +- } +- +- @override +- Object visitWhileStatement(WhileStatement node) { +- computer._addRegion_token(node.whileKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitWhileStatement(node); +- } +- +- @override +- Object visitWithClause(WithClause node) { +- computer._addRegion_token(node.withKeyword, HighlightRegionType.KEYWO= RD); +- return super.visitWithClause(node); +- } +- +- @override +- Object visitYieldStatement(YieldStatement node) { +- Token keyword =3D node.yieldKeyword; +- Token star =3D node.star; +- int offset =3D keyword.offset; +- int end =3D star !=3D null ? star.end : keyword.end; +- computer._addRegion(offset, end - offset, HighlightRegionType.BUILT_I= N); +- return super.visitYieldStatement(node); +- } +- +- void _addRegions_functionBody(FunctionBody node) { +- Token keyword =3D node.keyword; +- if (keyword !=3D null) { +- Token star =3D node.star; +- int offset =3D keyword.offset; +- int end =3D star !=3D null ? star.end : keyword.end; +- computer._addRegion(offset, end - offset, HighlightRegionType.BUILT= _IN); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/computer_highlights2.dar= t b/pkg/analysis_server/lib/src/computer/computer_highlights2.dart +deleted file mode 100644 +index 103d64103f5..00000000000 +--- a/pkg/analysis_server/lib/src/computer/computer_highlights2.dart ++++ /dev/null +@@ -1,834 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +- +-/** +- * A computer for [HighlightRegion]s in a Dart [CompilationUnit]. +- */ +-class DartUnitHighlightsComputer2 { +- final CompilationUnit _unit; +- +- final List _regions =3D []; +- +- DartUnitHighlightsComputer2(this._unit); +- +- /** +- * Returns the computed highlight regions, not `null`. +- */ +- List compute() { +- _unit.accept(new _DartUnitHighlightsComputerVisitor2(this)); +- _addCommentRanges(); +- return _regions; +- } +- +- void _addCommentRanges() { +- Token token =3D _unit.beginToken; +- while (token !=3D null && token.type !=3D TokenType.EOF) { +- Token commentToken =3D token.precedingComments; +- while (commentToken !=3D null) { +- HighlightRegionType highlightType =3D null; +- if (commentToken.type =3D=3D TokenType.MULTI_LINE_COMMENT) { +- if (commentToken.lexeme.startsWith('/**')) { +- highlightType =3D HighlightRegionType.COMMENT_DOCUMENTATION; +- } else { +- highlightType =3D HighlightRegionType.COMMENT_BLOCK; +- } +- } +- if (commentToken.type =3D=3D TokenType.SINGLE_LINE_COMMENT) { +- highlightType =3D HighlightRegionType.COMMENT_END_OF_LINE; +- } +- if (highlightType !=3D null) { +- _addRegion_token(commentToken, highlightType); +- } +- commentToken =3D commentToken.next; +- } +- token =3D token.next; +- } +- } +- +- void _addIdentifierRegion(SimpleIdentifier node) { +- if (_addIdentifierRegion_keyword(node)) { +- return; +- } +- if (_addIdentifierRegion_class(node)) { +- return; +- } +- if (_addIdentifierRegion_constructor(node)) { +- return; +- } +- if (_addIdentifierRegion_getterSetterDeclaration(node)) { +- return; +- } +- if (_addIdentifierRegion_field(node)) { +- return; +- } +- if (_addIdentifierRegion_dynamicLocal(node)) { +- return; +- } +- if (_addIdentifierRegion_function(node)) { +- return; +- } +- if (_addIdentifierRegion_functionTypeAlias(node)) { +- return; +- } +- if (_addIdentifierRegion_importPrefix(node)) { +- return; +- } +- if (_addIdentifierRegion_label(node)) { +- return; +- } +- if (_addIdentifierRegion_localVariable(node)) { +- return; +- } +- if (_addIdentifierRegion_method(node)) { +- return; +- } +- if (_addIdentifierRegion_parameter(node)) { +- return; +- } +- if (_addIdentifierRegion_typeParameter(node)) { +- return; +- } +- if (_addIdentifierRegion_unresolvedInstanceMemberReference(node)) { +- return; +- } +- _addRegion_node(node, HighlightRegionType.IDENTIFIER_DEFAULT); +- } +- +- void _addIdentifierRegion_annotation(Annotation node) { +- ArgumentList arguments =3D node.arguments; +- if (arguments =3D=3D null) { +- _addRegion_node(node, HighlightRegionType.ANNOTATION); +- } else { +- _addRegion_nodeStart_tokenEnd( +- node, arguments.beginToken, HighlightRegionType.ANNOTATION); +- _addRegion_token(arguments.endToken, HighlightRegionType.ANNOTATION= ); +- } +- } +- +- bool _addIdentifierRegion_class(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! ClassElement) { +- return false; +- } +- ClassElement classElement =3D element; +- // prepare type +- HighlightRegionType type; +- if (classElement.isEnum) { +- type =3D HighlightRegionType.ENUM; +- } else { +- type =3D HighlightRegionType.CLASS; +- } +- // add region +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_constructor(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! ConstructorElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.CONSTRUCTOR); +- } +- +- bool _addIdentifierRegion_dynamicLocal(SimpleIdentifier node) { +- // no propagated type +- if (node.propagatedType !=3D null) { +- return false; +- } +- // has dynamic static type +- DartType staticType =3D node.staticType; +- if (staticType =3D=3D null || !staticType.isDynamic) { +- return false; +- } +- // OK +- Element element =3D node.staticElement; +- if (element is LocalVariableElement) { +- HighlightRegionType type =3D node.inDeclarationContext() +- ? HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_DECLARATION +- : HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_REFERENCE; +- return _addRegion_node(node, type); +- } +- if (element is ParameterElement) { +- HighlightRegionType type =3D node.inDeclarationContext() +- ? HighlightRegionType.DYNAMIC_PARAMETER_DECLARATION +- : HighlightRegionType.DYNAMIC_PARAMETER_REFERENCE; +- return _addRegion_node(node, type); +- } +- return false; +- } +- +- bool _addIdentifierRegion_field(SimpleIdentifier node) { +- Element element =3D node.bestElement; +- if (element is FieldFormalParameterElement) { +- if (node.parent is FieldFormalParameter) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- } +- // prepare type +- HighlightRegionType type; +- if (element is FieldElement) { +- Element enclosingElement =3D element.enclosingElement; +- if (enclosingElement is ClassElement && enclosingElement.isEnum) { +- type =3D HighlightRegionType.ENUM_CONSTANT; +- } else if (element.isStatic) { +- type =3D HighlightRegionType.STATIC_FIELD_DECLARATION; +- } else { +- type =3D node.inDeclarationContext() +- ? HighlightRegionType.INSTANCE_FIELD_DECLARATION +- : HighlightRegionType.INSTANCE_FIELD_REFERENCE; +- } +- } else if (element is TopLevelVariableElement) { +- type =3D HighlightRegionType.TOP_LEVEL_VARIABLE_DECLARATION; +- } +- if (element is PropertyAccessorElement) { +- PropertyAccessorElement accessor =3D element; +- Element enclosingElement =3D element.enclosingElement; +- if (accessor.variable is TopLevelVariableElement) { +- type =3D accessor.isGetter +- ? HighlightRegionType.TOP_LEVEL_GETTER_REFERENCE +- : HighlightRegionType.TOP_LEVEL_SETTER_REFERENCE; +- } else if (enclosingElement is ClassElement && enclosingElement.isE= num) { +- type =3D HighlightRegionType.ENUM_CONSTANT; +- } else if (accessor.isStatic) { +- type =3D accessor.isGetter +- ? HighlightRegionType.STATIC_GETTER_REFERENCE +- : HighlightRegionType.STATIC_SETTER_REFERENCE; +- } else { +- type =3D accessor.isGetter +- ? HighlightRegionType.INSTANCE_GETTER_REFERENCE +- : HighlightRegionType.INSTANCE_SETTER_REFERENCE; +- } +- } +- // add region +- if (type !=3D null) { +- return _addRegion_node(node, type); +- } +- return false; +- } +- +- bool _addIdentifierRegion_function(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! FunctionElement) { +- return false; +- } +- HighlightRegionType type; +- bool isTopLevel =3D element.enclosingElement is CompilationUnitElemen= t; +- if (node.inDeclarationContext()) { +- type =3D isTopLevel +- ? HighlightRegionType.TOP_LEVEL_FUNCTION_DECLARATION +- : HighlightRegionType.LOCAL_FUNCTION_DECLARATION; +- } else { +- type =3D isTopLevel +- ? HighlightRegionType.TOP_LEVEL_FUNCTION_REFERENCE +- : HighlightRegionType.LOCAL_FUNCTION_REFERENCE; +- } +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_functionTypeAlias(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! FunctionTypeAliasElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.FUNCTION_TYPE_ALIAS); +- } +- +- bool _addIdentifierRegion_getterSetterDeclaration(SimpleIdentifier node= ) { +- // should be declaration +- AstNode parent =3D node.parent; +- if (!(parent is MethodDeclaration || parent is FunctionDeclaration)) { +- return false; +- } +- // should be property accessor +- Element element =3D node.staticElement; +- if (element is! PropertyAccessorElement) { +- return false; +- } +- // getter or setter +- PropertyAccessorElement propertyAccessorElement =3D +- element as PropertyAccessorElement; +- bool isTopLevel =3D element.enclosingElement is CompilationUnitElemen= t; +- HighlightRegionType type; +- if (propertyAccessorElement.isGetter) { +- if (isTopLevel) { +- type =3D HighlightRegionType.TOP_LEVEL_GETTER_DECLARATION; +- } else if (propertyAccessorElement.isStatic) { +- type =3D HighlightRegionType.STATIC_GETTER_DECLARATION; +- } else { +- type =3D HighlightRegionType.INSTANCE_GETTER_DECLARATION; +- } +- } else { +- if (isTopLevel) { +- type =3D HighlightRegionType.TOP_LEVEL_SETTER_DECLARATION; +- } else if (propertyAccessorElement.isStatic) { +- type =3D HighlightRegionType.STATIC_SETTER_DECLARATION; +- } else { +- type =3D HighlightRegionType.INSTANCE_SETTER_DECLARATION; +- } +- } +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_importPrefix(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! PrefixElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.IMPORT_PREFIX); +- } +- +- bool _addIdentifierRegion_keyword(SimpleIdentifier node) { +- String name =3D node.name; +- if (name =3D=3D "void") { +- return _addRegion_node(node, HighlightRegionType.KEYWORD); +- } +- return false; +- } +- +- bool _addIdentifierRegion_label(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! LabelElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.LABEL); +- } +- +- bool _addIdentifierRegion_localVariable(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! LocalVariableElement) { +- return false; +- } +- // OK +- HighlightRegionType type =3D node.inDeclarationContext() +- ? HighlightRegionType.LOCAL_VARIABLE_DECLARATION +- : HighlightRegionType.LOCAL_VARIABLE_REFERENCE; +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_method(SimpleIdentifier node) { +- Element element =3D node.bestElement; +- if (element is! MethodElement) { +- return false; +- } +- MethodElement methodElement =3D element as MethodElement; +- bool isStatic =3D methodElement.isStatic; +- // OK +- HighlightRegionType type; +- if (node.inDeclarationContext()) { +- if (isStatic) { +- type =3D HighlightRegionType.STATIC_METHOD_DECLARATION; +- } else { +- type =3D HighlightRegionType.INSTANCE_METHOD_DECLARATION; +- } +- } else { +- if (isStatic) { +- type =3D HighlightRegionType.STATIC_METHOD_REFERENCE; +- } else { +- type =3D HighlightRegionType.INSTANCE_METHOD_REFERENCE; +- } +- } +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_parameter(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! ParameterElement) { +- return false; +- } +- HighlightRegionType type =3D node.inDeclarationContext() +- ? HighlightRegionType.PARAMETER_DECLARATION +- : HighlightRegionType.PARAMETER_REFERENCE; +- return _addRegion_node(node, type); +- } +- +- bool _addIdentifierRegion_typeParameter(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is! TypeParameterElement) { +- return false; +- } +- return _addRegion_node(node, HighlightRegionType.TYPE_PARAMETER); +- } +- +- bool _addIdentifierRegion_unresolvedInstanceMemberReference( +- SimpleIdentifier node) { +- // unresolved +- Element element =3D node.bestElement; +- if (element !=3D null) { +- return false; +- } +- // invoke / get / set +- bool decorate =3D false; +- AstNode parent =3D node.parent; +- if (parent is MethodInvocation) { +- Expression target =3D parent.realTarget; +- if (parent.methodName =3D=3D node && +- target !=3D null && +- _isDynamicExpression(target)) { +- decorate =3D true; +- } +- } else if (node.inGetterContext() || node.inSetterContext()) { +- if (parent is PrefixedIdentifier) { +- decorate =3D parent.identifier =3D=3D node; +- } else if (parent is PropertyAccess) { +- decorate =3D parent.propertyName =3D=3D node; +- } +- } +- if (decorate) { +- _addRegion_node( +- node, HighlightRegionType.UNRESOLVED_INSTANCE_MEMBER_REFERENCE); +- return true; +- } +- return false; +- } +- +- void _addRegion(int offset, int length, HighlightRegionType type) { +- _regions.add(new HighlightRegion(type, offset, length)); +- } +- +- bool _addRegion_node(AstNode node, HighlightRegionType type) { +- int offset =3D node.offset; +- int length =3D node.length; +- _addRegion(offset, length, type); +- return true; +- } +- +- void _addRegion_nodeStart_tokenEnd( +- AstNode a, Token b, HighlightRegionType type) { +- int offset =3D a.offset; +- int end =3D b.end; +- _addRegion(offset, end - offset, type); +- } +- +- void _addRegion_token(Token token, HighlightRegionType type) { +- if (token !=3D null) { +- int offset =3D token.offset; +- int length =3D token.length; +- _addRegion(offset, length, type); +- } +- } +- +- void _addRegion_tokenStart_tokenEnd( +- Token a, Token b, HighlightRegionType type) { +- int offset =3D a.offset; +- int end =3D b.end; +- _addRegion(offset, end - offset, type); +- } +- +- static bool _isDynamicExpression(Expression e) { +- if (e is SimpleIdentifier && e.staticElement is PrefixElement) { +- return false; +- } +- return resolutionMap.bestTypeForExpression(e).isDynamic; +- } +-} +- +-/** +- * An AST visitor for [DartUnitHighlightsComputer2]. +- */ +-class _DartUnitHighlightsComputerVisitor2 extends RecursiveAstVisitor { +- final DartUnitHighlightsComputer2 computer; +- +- _DartUnitHighlightsComputerVisitor2(this.computer); +- +- @override +- Object visitAnnotation(Annotation node) { +- computer._addIdentifierRegion_annotation(node); +- return super.visitAnnotation(node); +- } +- +- @override +- Object visitAsExpression(AsExpression node) { +- computer._addRegion_token(node.asOperator, HighlightRegionType.BUILT_= IN); +- return super.visitAsExpression(node); +- } +- +- @override +- Object visitAssertStatement(AssertStatement node) { +- computer._addRegion_token(node.assertKeyword, HighlightRegionType.KEY= WORD); +- return super.visitAssertStatement(node); +- } +- +- @override +- Object visitAwaitExpression(AwaitExpression node) { +- computer._addRegion_token(node.awaitKeyword, HighlightRegionType.BUIL= T_IN); +- return super.visitAwaitExpression(node); +- } +- +- @override +- Object visitBlockFunctionBody(BlockFunctionBody node) { +- _addRegions_functionBody(node); +- return super.visitBlockFunctionBody(node); +- } +- +- @override +- Object visitBooleanLiteral(BooleanLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.KEYWORD); +- computer._addRegion_node(node, HighlightRegionType.LITERAL_BOOLEAN); +- return super.visitBooleanLiteral(node); +- } +- +- @override +- Object visitBreakStatement(BreakStatement node) { +- computer._addRegion_token(node.breakKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitBreakStatement(node); +- } +- +- @override +- Object visitCatchClause(CatchClause node) { +- computer._addRegion_token(node.catchKeyword, HighlightRegionType.KEYW= ORD); +- computer._addRegion_token(node.onKeyword, HighlightRegionType.BUILT_I= N); +- return super.visitCatchClause(node); +- } +- +- @override +- Object visitClassDeclaration(ClassDeclaration node) { +- computer._addRegion_token(node.classKeyword, HighlightRegionType.KEYW= ORD); +- computer._addRegion_token( +- node.abstractKeyword, HighlightRegionType.BUILT_IN); +- return super.visitClassDeclaration(node); +- } +- +- @override +- Object visitClassTypeAlias(ClassTypeAlias node) { +- computer._addRegion_token( +- node.abstractKeyword, HighlightRegionType.BUILT_IN); +- return super.visitClassTypeAlias(node); +- } +- +- @override +- Object visitConstructorDeclaration(ConstructorDeclaration node) { +- computer._addRegion_token( +- node.externalKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.factoryKeyword, HighlightRegionType.BUILT_IN); +- return super.visitConstructorDeclaration(node); +- } +- +- @override +- Object visitContinueStatement(ContinueStatement node) { +- computer._addRegion_token( +- node.continueKeyword, HighlightRegionType.KEYWORD); +- return super.visitContinueStatement(node); +- } +- +- @override +- Object visitDoStatement(DoStatement node) { +- computer._addRegion_token(node.doKeyword, HighlightRegionType.KEYWORD= ); +- computer._addRegion_token(node.whileKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitDoStatement(node); +- } +- +- @override +- Object visitDoubleLiteral(DoubleLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_DOUBLE); +- return super.visitDoubleLiteral(node); +- } +- +- @override +- Object visitEnumDeclaration(EnumDeclaration node) { +- computer._addRegion_token(node.enumKeyword, HighlightRegionType.KEYWO= RD); +- return super.visitEnumDeclaration(node); +- } +- +- @override +- Object visitExportDirective(ExportDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitExportDirective(node); +- } +- +- @override +- Object visitExpressionFunctionBody(ExpressionFunctionBody node) { +- _addRegions_functionBody(node); +- return super.visitExpressionFunctionBody(node); +- } +- +- @override +- Object visitFieldDeclaration(FieldDeclaration node) { +- computer._addRegion_token(node.staticKeyword, HighlightRegionType.BUI= LT_IN); +- return super.visitFieldDeclaration(node); +- } +- +- @override +- Object visitForEachStatement(ForEachStatement node) { +- computer._addRegion_token(node.awaitKeyword, HighlightRegionType.BUIL= T_IN); +- computer._addRegion_token(node.forKeyword, HighlightRegionType.KEYWOR= D); +- computer._addRegion_token(node.inKeyword, HighlightRegionType.KEYWORD= ); +- return super.visitForEachStatement(node); +- } +- +- @override +- Object visitForStatement(ForStatement node) { +- computer._addRegion_token(node.forKeyword, HighlightRegionType.KEYWOR= D); +- return super.visitForStatement(node); +- } +- +- @override +- Object visitFunctionDeclaration(FunctionDeclaration node) { +- computer._addRegion_token( +- node.externalKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.propertyKeyword, HighlightRegionType.BUILT_IN); +- return super.visitFunctionDeclaration(node); +- } +- +- @override +- Object visitFunctionTypeAlias(FunctionTypeAlias node) { +- computer._addRegion_token( +- node.typedefKeyword, HighlightRegionType.BUILT_IN); +- return super.visitFunctionTypeAlias(node); +- } +- +- @override +- Object visitGenericFunctionType(GenericFunctionType node) { +- computer._addRegion_token( +- node.functionKeyword, HighlightRegionType.KEYWORD); +- return super.visitGenericFunctionType(node); +- } +- +- @override +- Object visitGenericTypeAlias(GenericTypeAlias node) { +- computer._addRegion_token(node.typedefKeyword, HighlightRegionType.KE= YWORD); +- return super.visitGenericTypeAlias(node); +- } +- +- @override +- Object visitHideCombinator(HideCombinator node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitHideCombinator(node); +- } +- +- @override +- Object visitIfStatement(IfStatement node) { +- computer._addRegion_token(node.ifKeyword, HighlightRegionType.KEYWORD= ); +- return super.visitIfStatement(node); +- } +- +- @override +- Object visitImplementsClause(ImplementsClause node) { +- computer._addRegion_token( +- node.implementsKeyword, HighlightRegionType.BUILT_IN); +- return super.visitImplementsClause(node); +- } +- +- @override +- Object visitImportDirective(ImportDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.deferredKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token(node.asKeyword, HighlightRegionType.BUILT_I= N); +- return super.visitImportDirective(node); +- } +- +- @override +- Object visitInstanceCreationExpression(InstanceCreationExpression node)= { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitInstanceCreationExpression(node); +- } +- +- @override +- Object visitIntegerLiteral(IntegerLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_INTEGER); +- return super.visitIntegerLiteral(node); +- } +- +- @override +- Object visitIsExpression(IsExpression node) { +- computer._addRegion_token(node.isOperator, HighlightRegionType.KEYWOR= D); +- return super.visitIsExpression(node); +- } +- +- @override +- Object visitLibraryDirective(LibraryDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitLibraryDirective(node); +- } +- +- @override +- Object visitLibraryIdentifier(LibraryIdentifier node) { +- computer._addRegion_node(node, HighlightRegionType.LIBRARY_NAME); +- return null; +- } +- +- @override +- Object visitListLiteral(ListLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_LIST); +- computer._addRegion_token(node.constKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitListLiteral(node); +- } +- +- @override +- Object visitMapLiteral(MapLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_MAP); +- computer._addRegion_token(node.constKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitMapLiteral(node); +- } +- +- @override +- Object visitMethodDeclaration(MethodDeclaration node) { +- computer._addRegion_token( +- node.externalKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.modifierKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.operatorKeyword, HighlightRegionType.BUILT_IN); +- computer._addRegion_token( +- node.propertyKeyword, HighlightRegionType.BUILT_IN); +- return super.visitMethodDeclaration(node); +- } +- +- @override +- Object visitNativeClause(NativeClause node) { +- computer._addRegion_token(node.nativeKeyword, HighlightRegionType.BUI= LT_IN); +- return super.visitNativeClause(node); +- } +- +- @override +- Object visitNativeFunctionBody(NativeFunctionBody node) { +- computer._addRegion_token(node.nativeKeyword, HighlightRegionType.BUI= LT_IN); +- return super.visitNativeFunctionBody(node); +- } +- +- @override +- Object visitPartDirective(PartDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitPartDirective(node); +- } +- +- @override +- Object visitPartOfDirective(PartOfDirective node) { +- computer._addRegion_node(node, HighlightRegionType.DIRECTIVE); +- computer._addRegion_tokenStart_tokenEnd( +- node.partKeyword, node.ofKeyword, HighlightRegionType.BUILT_IN); +- return super.visitPartOfDirective(node); +- } +- +- @override +- Object visitRethrowExpression(RethrowExpression node) { +- computer._addRegion_token(node.rethrowKeyword, HighlightRegionType.KE= YWORD); +- return super.visitRethrowExpression(node); +- } +- +- @override +- Object visitReturnStatement(ReturnStatement node) { +- computer._addRegion_token(node.returnKeyword, HighlightRegionType.KEY= WORD); +- return super.visitReturnStatement(node); +- } +- +- @override +- Object visitShowCombinator(ShowCombinator node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.BUILT_IN); +- return super.visitShowCombinator(node); +- } +- +- @override +- Object visitSimpleIdentifier(SimpleIdentifier node) { +- computer._addIdentifierRegion(node); +- return super.visitSimpleIdentifier(node); +- } +- +- @override +- Object visitSimpleStringLiteral(SimpleStringLiteral node) { +- computer._addRegion_node(node, HighlightRegionType.LITERAL_STRING); +- return super.visitSimpleStringLiteral(node); +- } +- +- @override +- Object visitSuperConstructorInvocation(SuperConstructorInvocation node)= { +- computer._addRegion_token(node.superKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitSuperConstructorInvocation(node); +- } +- +- @override +- Object visitSwitchCase(SwitchCase node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitSwitchCase(node); +- } +- +- @override +- Object visitSwitchDefault(SwitchDefault node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitSwitchDefault(node); +- } +- +- @override +- Object visitSwitchStatement(SwitchStatement node) { +- computer._addRegion_token(node.switchKeyword, HighlightRegionType.KEY= WORD); +- return super.visitSwitchStatement(node); +- } +- +- @override +- Object visitThisExpression(ThisExpression node) { +- computer._addRegion_token(node.thisKeyword, HighlightRegionType.KEYWO= RD); +- return super.visitThisExpression(node); +- } +- +- @override +- Object visitTryStatement(TryStatement node) { +- computer._addRegion_token(node.tryKeyword, HighlightRegionType.KEYWOR= D); +- computer._addRegion_token(node.finallyKeyword, HighlightRegionType.KE= YWORD); +- return super.visitTryStatement(node); +- } +- +- @override +- Object visitTypeName(TypeName node) { +- DartType type =3D node.type; +- if (type !=3D null) { +- if (type.isDynamic && node.name.name =3D=3D "dynamic") { +- computer._addRegion_node(node, HighlightRegionType.TYPE_NAME_DYNA= MIC); +- return null; +- } +- } +- return super.visitTypeName(node); +- } +- +- @override +- Object visitVariableDeclarationList(VariableDeclarationList node) { +- computer._addRegion_token(node.keyword, HighlightRegionType.KEYWORD); +- return super.visitVariableDeclarationList(node); +- } +- +- @override +- Object visitWhileStatement(WhileStatement node) { +- computer._addRegion_token(node.whileKeyword, HighlightRegionType.KEYW= ORD); +- return super.visitWhileStatement(node); +- } +- +- @override +- Object visitWithClause(WithClause node) { +- computer._addRegion_token(node.withKeyword, HighlightRegionType.KEYWO= RD); +- return super.visitWithClause(node); +- } +- +- @override +- Object visitYieldStatement(YieldStatement node) { +- Token keyword =3D node.yieldKeyword; +- Token star =3D node.star; +- int offset =3D keyword.offset; +- int end =3D star !=3D null ? star.end : keyword.end; +- computer._addRegion(offset, end - offset, HighlightRegionType.BUILT_I= N); +- return super.visitYieldStatement(node); +- } +- +- void _addRegions_functionBody(FunctionBody node) { +- Token keyword =3D node.keyword; +- if (keyword !=3D null) { +- Token star =3D node.star; +- int offset =3D keyword.offset; +- int end =3D star !=3D null ? star.end : keyword.end; +- computer._addRegion(offset, end - offset, HighlightRegionType.BUILT= _IN); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/computer_hover.dart b/pk= g/analysis_server/lib/src/computer/computer_hover.dart +deleted file mode 100644 +index 96b07f50bdc..00000000000 +--- a/pkg/analysis_server/lib/src/computer/computer_hover.dart ++++ /dev/null +@@ -1,140 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' +- show HoverInformation; +-import 'package:analysis_server/src/computer/computer_overrides.dart'; +-import 'package:analysis_server/src/utilities/documentation.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +- +-/** +- * A computer for the hover at the specified offset of a Dart [Compilatio= nUnit]. +- */ +-class DartUnitHoverComputer { +- final CompilationUnit _unit; +- final int _offset; +- +- DartUnitHoverComputer(this._unit, this._offset); +- +- /** +- * Returns the computed hover, maybe `null`. +- */ +- HoverInformation compute() { +- AstNode node =3D new NodeLocator(_offset).searchWithin(_unit); +- if (node =3D=3D null) { +- return null; +- } +- if (node.parent is TypeName && +- node.parent.parent is ConstructorName && +- node.parent.parent.parent is InstanceCreationExpression) { +- node =3D node.parent.parent.parent; +- } +- if (node.parent is ConstructorName && +- node.parent.parent is InstanceCreationExpression) { +- node =3D node.parent.parent; +- } +- if (node is Expression) { +- Expression expression =3D node; +- HoverInformation hover =3D +- new HoverInformation(expression.offset, expression.length); +- // element +- Element element =3D ElementLocator.locate(expression); +- if (element !=3D null) { +- // variable, if synthetic accessor +- if (element is PropertyAccessorElement) { +- PropertyAccessorElement accessor =3D element; +- if (accessor.isSynthetic) { +- element =3D accessor.variable; +- } +- } +- // description +- hover.elementDescription =3D element.toString(); +- hover.elementKind =3D element.kind.displayName; +- hover.isDeprecated =3D element.isDeprecated; +- // not local element +- if (element.enclosingElement is! ExecutableElement) { +- // containing class +- ClassElement containingClass =3D +- element.getAncestor((e) =3D> e is ClassElement); +- if (containingClass !=3D null) { +- hover.containingClassDescription =3D containingClass.displayN= ame; +- } +- // containing library +- LibraryElement library =3D element.library; +- if (library !=3D null) { +- hover.containingLibraryName =3D library.name; +- hover.containingLibraryPath =3D library.source.fullName; +- } +- } +- // documentation +- hover.dartdoc =3D _computeDocumentation(element); +- } +- // parameter +- hover.parameter =3D _safeToString(expression.bestParameterElement); +- // types +- { +- AstNode parent =3D expression.parent; +- DartType staticType =3D null; +- DartType propagatedType =3D expression.propagatedType; +- if (element is ParameterElement) { +- staticType =3D element.type; +- } else if (element =3D=3D null || element is VariableElement) { +- staticType =3D expression.staticType; +- } +- if (parent is MethodInvocation && parent.methodName =3D=3D expres= sion) { +- staticType =3D parent.staticInvokeType; +- propagatedType =3D parent.propagatedInvokeType; +- if (staticType !=3D null && staticType.isDynamic) { +- staticType =3D null; +- } +- if (propagatedType !=3D null && propagatedType.isDynamic) { +- propagatedType =3D null; +- } +- } +- hover.staticType =3D _safeToString(staticType); +- hover.propagatedType =3D _safeToString(propagatedType); +- } +- // done +- return hover; +- } +- // not an expression +- return null; +- } +- +- String _computeDocumentation(Element element) { +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- if (element is ParameterElement) { +- element =3D element.enclosingElement; +- } +- if (element =3D=3D null) { +- // This can happen when the code is invalid, such as having a field= formal +- // parameter for a field that does not exist. +- return null; +- } +- // The documentation of the element itself. +- if (element.documentationComment !=3D null) { +- return removeDartDocDelimiters(element.documentationComment); +- } +- // Look for documentation comments of overridden members. +- OverriddenElements overridden =3D findOverriddenElements(element); +- for (Element superElement in [] +- ..addAll(overridden.superElements) +- ..addAll(overridden.interfaceElements)) { +- String rawDoc =3D superElement.documentationComment; +- if (rawDoc !=3D null) { +- Element interfaceClass =3D superElement.enclosingElement; +- return removeDartDocDelimiters(rawDoc) + +- '\n\nCopied from `${interfaceClass.displayName}`.'; +- } +- } +- return null; +- } +- +- static _safeToString(obj) =3D> obj?.toString(); +-} +diff --git a/pkg/analysis_server/lib/src/computer/computer_outline.dart b/= pkg/analysis_server/lib/src/computer/computer_outline.dart +deleted file mode 100644 +index c9e4a865798..00000000000 +--- a/pkg/analysis_server/lib/src/computer/computer_outline.dart ++++ /dev/null +@@ -1,488 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/collections.dart'; +-import 'package:analysis_server/src/utilities/flutter.dart' as flutter; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart' as engine; +-import 'package:analyzer/dart/element/type.dart' as engine; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * A computer for [CompilationUnit] outline. +- */ +-class DartUnitOutlineComputer { +- final String file; +- final CompilationUnit unit; +- final LineInfo lineInfo; +- +- DartUnitOutlineComputer(this.file, this.lineInfo, this.unit); +- +- /** +- * Returns the computed outline, not `null`. +- */ +- Outline compute() { +- List unitContents =3D []; +- for (CompilationUnitMember unitMember in unit.declarations) { +- if (unitMember is ClassDeclaration) { +- ClassDeclaration classDeclaration =3D unitMember; +- List classContents =3D []; +- for (ClassMember classMember in classDeclaration.members) { +- if (classMember is ConstructorDeclaration) { +- ConstructorDeclaration constructorDeclaration =3D classMember; +- classContents.add(_newConstructorOutline(constructorDeclarati= on)); +- } +- if (classMember is FieldDeclaration) { +- FieldDeclaration fieldDeclaration =3D classMember; +- VariableDeclarationList fields =3D fieldDeclaration.fields; +- if (fields !=3D null) { +- TypeAnnotation fieldType =3D fields.type; +- String fieldTypeName =3D _safeToSource(fieldType); +- for (VariableDeclaration field in fields.variables) { +- classContents.add(_newVariableOutline(fieldTypeName, +- ElementKind.FIELD, field, fieldDeclaration.isStatic)); +- } +- } +- } +- if (classMember is MethodDeclaration) { +- MethodDeclaration methodDeclaration =3D classMember; +- classContents.add(_newMethodOutline(methodDeclaration)); +- } +- } +- unitContents.add(_newClassOutline(classDeclaration, classContents= )); +- } +- if (unitMember is EnumDeclaration) { +- EnumDeclaration enumDeclaration =3D unitMember; +- List constantOutlines =3D []; +- for (EnumConstantDeclaration constant in enumDeclaration.constant= s) { +- constantOutlines.add(_newEnumConstant(constant)); +- } +- unitContents.add(_newEnumOutline(enumDeclaration, constantOutline= s)); +- } +- if (unitMember is TopLevelVariableDeclaration) { +- TopLevelVariableDeclaration fieldDeclaration =3D unitMember; +- VariableDeclarationList fields =3D fieldDeclaration.variables; +- if (fields !=3D null) { +- TypeAnnotation fieldType =3D fields.type; +- String fieldTypeName =3D _safeToSource(fieldType); +- for (VariableDeclaration field in fields.variables) { +- unitContents.add(_newVariableOutline( +- fieldTypeName, ElementKind.TOP_LEVEL_VARIABLE, field, fal= se)); +- } +- } +- } +- if (unitMember is FunctionDeclaration) { +- FunctionDeclaration functionDeclaration =3D unitMember; +- unitContents.add(_newFunctionOutline(functionDeclaration, true)); +- } +- if (unitMember is ClassTypeAlias) { +- ClassTypeAlias alias =3D unitMember; +- unitContents.add(_newClassTypeAlias(alias)); +- } +- if (unitMember is FunctionTypeAlias) { +- FunctionTypeAlias alias =3D unitMember; +- unitContents.add(_newFunctionTypeAliasOutline(alias)); +- } +- } +- Outline unitOutline =3D _newUnitOutline(unitContents); +- return unitOutline; +- } +- +- List _addFunctionBodyOutlines(FunctionBody body) { +- List contents =3D []; +- body.accept(new _FunctionBodyOutlinesVisitor(this, contents)); +- return contents; +- } +- +- Location _getLocationNode(AstNode node) { +- int offset =3D node.offset; +- int length =3D node.length; +- return _getLocationOffsetLength(offset, length); +- } +- +- Location _getLocationOffsetLength(int offset, int length) { +- LineInfo_Location lineLocation =3D lineInfo.getLocation(offset); +- int startLine =3D lineLocation.lineNumber; +- int startColumn =3D lineLocation.columnNumber; +- return new Location(file, offset, length, startLine, startColumn); +- } +- +- /** +- * Returns the [AstNode]'s source region. +- */ +- SourceRange _getSourceRange(AstNode node) { +- int endOffset =3D node.end; +- // prepare position of the node among its siblings +- int firstOffset; +- List siblings; +- AstNode parent =3D node.parent; +- // field +- if (parent is VariableDeclarationList) { +- VariableDeclarationList variableList =3D parent as VariableDeclarat= ionList; +- List variables =3D variableList.variables; +- int variableIndex =3D variables.indexOf(node); +- if (variableIndex =3D=3D variables.length - 1) { +- endOffset =3D variableList.parent.end; +- } +- if (variableIndex =3D=3D 0) { +- node =3D parent.parent; +- parent =3D node.parent; +- } else if (variableIndex >=3D 1) { +- firstOffset =3D variables[variableIndex - 1].end; +- return new SourceRange(firstOffset, endOffset - firstOffset); +- } +- } +- // unit or class member +- if (parent is CompilationUnit) { +- firstOffset =3D node.offset; +- siblings =3D parent.declarations; +- } else if (parent is ClassDeclaration) { +- firstOffset =3D parent.leftBracket.end; +- siblings =3D parent.members; +- } else { +- int offset =3D node.offset; +- return new SourceRange(offset, endOffset - offset); +- } +- // first child: [endOfParent, endOfNode] +- int index =3D siblings.indexOf(node); +- if (index =3D=3D 0) { +- return new SourceRange(firstOffset, endOffset - firstOffset); +- } +- // not first child: [endOfPreviousSibling, endOfNode] +- int prevSiblingEnd =3D siblings[index - 1].end; +- return new SourceRange(prevSiblingEnd, endOffset - prevSiblingEnd); +- } +- +- Outline _newClassOutline(ClassDeclaration node, List classCont= ents) { +- SimpleIdentifier nameNode =3D node.name; +- String name =3D nameNode.name; +- SourceRange range =3D _getSourceRange(node); +- Element element =3D new Element( +- ElementKind.CLASS, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(node), +- isAbstract: node.isAbstract), +- location: _getLocationNode(nameNode), +- typeParameters: _getTypeParametersStr(node.typeParameters)); +- return new Outline(element, range.offset, range.length, +- children: nullIfEmpty(classContents)); +- } +- +- Outline _newClassTypeAlias(ClassTypeAlias node) { +- SimpleIdentifier nameNode =3D node.name; +- String name =3D nameNode.name; +- SourceRange range =3D _getSourceRange(node); +- Element element =3D new Element( +- ElementKind.CLASS_TYPE_ALIAS, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(node), +- isAbstract: node.isAbstract), +- location: _getLocationNode(nameNode), +- typeParameters: _getTypeParametersStr(node.typeParameters)); +- return new Outline(element, range.offset, range.length); +- } +- +- Outline _newConstructorOutline(ConstructorDeclaration constructor) { +- Identifier returnType =3D constructor.returnType; +- String name =3D returnType.name; +- int offset =3D returnType.offset; +- int length =3D returnType.length; +- SimpleIdentifier constructorNameNode =3D constructor.name; +- bool isPrivate =3D false; +- if (constructorNameNode !=3D null) { +- String constructorName =3D constructorNameNode.name; +- isPrivate =3D Identifier.isPrivateName(constructorName); +- name +=3D '.$constructorName'; +- offset =3D constructorNameNode.offset; +- length =3D constructorNameNode.length; +- } +- SourceRange range =3D _getSourceRange(constructor); +- FormalParameterList parameters =3D constructor.parameters; +- String parametersStr =3D _safeToSource(parameters); +- Element element =3D new Element( +- ElementKind.CONSTRUCTOR, +- name, +- Element.makeFlags( +- isPrivate: isPrivate, isDeprecated: _isDeprecated(constructor= )), +- location: _getLocationOffsetLength(offset, length), +- parameters: parametersStr); +- List contents =3D _addFunctionBodyOutlines(constructor.body); +- Outline outline =3D new Outline(element, range.offset, range.length, +- children: nullIfEmpty(contents)); +- return outline; +- } +- +- Outline _newEnumConstant(EnumConstantDeclaration node) { +- SimpleIdentifier nameNode =3D node.name; +- String name =3D nameNode.name; +- SourceRange range =3D _getSourceRange(node); +- Element element =3D new Element( +- ElementKind.ENUM_CONSTANT, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(node)), +- location: _getLocationNode(nameNode)); +- return new Outline(element, range.offset, range.length); +- } +- +- Outline _newEnumOutline(EnumDeclaration node, List children) { +- SimpleIdentifier nameNode =3D node.name; +- String name =3D nameNode.name; +- SourceRange range =3D _getSourceRange(node); +- Element element =3D new Element( +- ElementKind.ENUM, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(node)), +- location: _getLocationNode(nameNode)); +- return new Outline(element, range.offset, range.length, +- children: nullIfEmpty(children)); +- } +- +- Outline _newFunctionOutline(FunctionDeclaration function, bool isStatic= ) { +- TypeAnnotation returnType =3D function.returnType; +- SimpleIdentifier nameNode =3D function.name; +- String name =3D nameNode.name; +- FunctionExpression functionExpression =3D function.functionExpression; +- FormalParameterList parameters =3D functionExpression.parameters; +- ElementKind kind; +- if (function.isGetter) { +- kind =3D ElementKind.GETTER; +- } else if (function.isSetter) { +- kind =3D ElementKind.SETTER; +- } else { +- kind =3D ElementKind.FUNCTION; +- } +- SourceRange range =3D _getSourceRange(function); +- String parametersStr =3D _safeToSource(parameters); +- String returnTypeStr =3D _safeToSource(returnType); +- Element element =3D new Element( +- kind, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(function), +- isStatic: isStatic), +- location: _getLocationNode(nameNode), +- parameters: parametersStr, +- returnType: returnTypeStr); +- List contents =3D _addFunctionBodyOutlines(functionExpressio= n.body); +- Outline outline =3D new Outline(element, range.offset, range.length, +- children: nullIfEmpty(contents)); +- return outline; +- } +- +- Outline _newFunctionTypeAliasOutline(FunctionTypeAlias node) { +- TypeAnnotation returnType =3D node.returnType; +- SimpleIdentifier nameNode =3D node.name; +- String name =3D nameNode.name; +- SourceRange range =3D _getSourceRange(node); +- FormalParameterList parameters =3D node.parameters; +- String parametersStr =3D _safeToSource(parameters); +- String returnTypeStr =3D _safeToSource(returnType); +- Element element =3D new Element( +- ElementKind.FUNCTION_TYPE_ALIAS, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(node)), +- location: _getLocationNode(nameNode), +- parameters: parametersStr, +- returnType: returnTypeStr, +- typeParameters: _getTypeParametersStr(node.typeParameters)); +- return new Outline(element, range.offset, range.length); +- } +- +- Outline _newMethodOutline(MethodDeclaration method) { +- TypeAnnotation returnType =3D method.returnType; +- SimpleIdentifier nameNode =3D method.name; +- String name =3D nameNode.name; +- FormalParameterList parameters =3D method.parameters; +- ElementKind kind; +- if (method.isGetter) { +- kind =3D ElementKind.GETTER; +- } else if (method.isSetter) { +- kind =3D ElementKind.SETTER; +- } else { +- kind =3D ElementKind.METHOD; +- } +- SourceRange range =3D _getSourceRange(method); +- String parametersStr =3D parameters?.toSource(); +- String returnTypeStr =3D _safeToSource(returnType); +- Element element =3D new Element( +- kind, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(method), +- isAbstract: method.isAbstract, +- isStatic: method.isStatic), +- location: _getLocationNode(nameNode), +- parameters: parametersStr, +- returnType: returnTypeStr); +- List contents =3D _addFunctionBodyOutlines(method.body); +- Outline outline =3D new Outline(element, range.offset, range.length, +- children: nullIfEmpty(contents)); +- return outline; +- } +- +- Outline _newUnitOutline(List unitContents) { +- Element element =3D new Element( +- ElementKind.COMPILATION_UNIT, '', Element.makeFlags(), +- location: _getLocationNode(unit)); +- return new Outline(element, unit.offset, unit.length, +- children: nullIfEmpty(unitContents)); +- } +- +- Outline _newVariableOutline(String typeName, ElementKind kind, +- VariableDeclaration variable, bool isStatic) { +- SimpleIdentifier nameNode =3D variable.name; +- String name =3D nameNode.name; +- SourceRange range =3D _getSourceRange(variable); +- Element element =3D new Element( +- kind, +- name, +- Element.makeFlags( +- isPrivate: Identifier.isPrivateName(name), +- isDeprecated: _isDeprecated(variable), +- isStatic: isStatic, +- isConst: variable.isConst, +- isFinal: variable.isFinal), +- location: _getLocationNode(nameNode), +- returnType: typeName); +- Outline outline =3D new Outline(element, range.offset, range.length); +- return outline; +- } +- +- static String _getTypeParametersStr(TypeParameterList parameters) { +- if (parameters =3D=3D null) { +- return null; +- } +- return parameters.toSource(); +- } +- +- /** +- * Returns `true` if the given [element] is not `null` and deprecated. +- */ +- static bool _isDeprecated(Declaration declaration) { +- engine.Element element =3D declaration.element; +- return element !=3D null && element.isDeprecated; +- } +- +- static String _safeToSource(AstNode node) =3D> +- node =3D=3D null ? '' : node.toSource(); +-} +- +-/** +- * A visitor for building local function outlines. +- */ +-class _FunctionBodyOutlinesVisitor extends RecursiveAstVisitor { +- final DartUnitOutlineComputer outlineComputer; +- final List contents; +- +- _FunctionBodyOutlinesVisitor(this.outlineComputer, this.contents); +- +- /** +- * Return `true` if the given [element] is the method 'group' defined i= n the +- * test package. +- */ +- bool isGroup(engine.ExecutableElement element) { +- return element is engine.FunctionElement && +- element.name =3D=3D 'group' && +- _isInsideTestPackage(element); +- } +- +- /** +- * Return `true` if the given [element] is the method 'test' defined in= the +- * test package. +- */ +- bool isTest(engine.ExecutableElement element) { +- return element is engine.FunctionElement && +- element.name =3D=3D 'test' && +- _isInsideTestPackage(element); +- } +- +- @override +- visitFunctionDeclaration(FunctionDeclaration node) { +- contents.add(outlineComputer._newFunctionOutline(node, false)); +- } +- +- @override +- visitInstanceCreationExpression(InstanceCreationExpression node) { +- if (flutter.isWidgetCreation(node)) { +- List children =3D []; +- node.argumentList +- .accept(new _FunctionBodyOutlinesVisitor(outlineComputer, child= ren)); +- +- String text =3D flutter.getWidgetPresentationText(node); +- Element element =3D new Element(ElementKind.CONSTRUCTOR_INVOCATION,= text, 0, +- location: outlineComputer._getLocationOffsetLength(node.offset,= 0)); +- +- contents.add(new Outline(element, node.offset, node.length, +- children: nullIfEmpty(children))); +- } else { +- super.visitInstanceCreationExpression(node); +- } +- } +- +- @override +- visitMethodInvocation(MethodInvocation node) { +- SimpleIdentifier nameNode =3D node.methodName; +- engine.ExecutableElement executableElement =3D nameNode.bestElement; +- +- String extractString(NodeList arguments) { +- if (arguments !=3D null && arguments.length > 0) { +- Expression argument =3D arguments[0]; +- if (argument is StringLiteral) { +- String value =3D argument.stringValue; +- if (value !=3D null) { +- return value; +- } +- } +- return argument.toSource(); +- } +- return 'unnamed'; +- } +- +- void addOutlineNode(ElementKind kind, [List children]) { +- SourceRange range =3D outlineComputer._getSourceRange(node); +- String kindName =3D kind =3D=3D ElementKind.UNIT_TEST_GROUP ? 'grou= p' : 'test'; +- String name =3D '$kindName("${extractString( +- node.argumentList?.arguments)}")'; +- Element element =3D new Element(kind, name, 0, +- location: outlineComputer._getLocationNode(nameNode)); +- contents.add(new Outline(element, range.offset, range.length, +- children: nullIfEmpty(children))); +- } +- +- if (isGroup(executableElement)) { +- List groupContents =3D []; +- node.argumentList.accept( +- new _FunctionBodyOutlinesVisitor(outlineComputer, groupContents= )); +- addOutlineNode(ElementKind.UNIT_TEST_GROUP, groupContents); +- } else if (isTest(executableElement)) { +- addOutlineNode(ElementKind.UNIT_TEST_TEST); +- } else { +- super.visitMethodInvocation(node); +- } +- } +- +- /** +- * Return `true` if the given [element] is a top-level member of the te= st +- * package. +- */ +- bool _isInsideTestPackage(engine.FunctionElement element) { +- engine.Element parent =3D element.enclosingElement; +- return parent is engine.CompilationUnitElement && +- parent.source.fullName.endsWith('test.dart'); +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/computer_overrides.dart = b/pkg/analysis_server/lib/src/computer/computer_overrides.dart +deleted file mode 100644 +index 5d53fd72d92..00000000000 +--- a/pkg/analysis_server/lib/src/computer/computer_overrides.dart ++++ /dev/null +@@ -1,237 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/collections.dart'; +-import 'package:analysis_server/src/protocol_server.dart' as proto; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +- +-/** +- * Return the elements that the given [element] overrides. +- */ +-OverriddenElements findOverriddenElements(Element element) { +- if (element?.enclosingElement is ClassElement) { +- return new _OverriddenElementsFinder(element).find(); +- } +- return new OverriddenElements(element, [], []); +-} +- +-/** +- * A computer for class member overrides in a Dart [CompilationUnit]. +- */ +-class DartUnitOverridesComputer { +- final CompilationUnit _unit; +- final List _overrides =3D []; +- +- DartUnitOverridesComputer(this._unit); +- +- /** +- * Returns the computed occurrences, not `null`. +- */ +- List compute() { +- for (CompilationUnitMember unitMember in _unit.declarations) { +- if (unitMember is ClassDeclaration) { +- for (ClassMember classMember in unitMember.members) { +- if (classMember is MethodDeclaration) { +- if (classMember.isStatic) { +- continue; +- } +- _addOverride(classMember.name); +- } +- if (classMember is FieldDeclaration) { +- if (classMember.isStatic) { +- continue; +- } +- List fields =3D classMember.fields.varia= bles; +- for (VariableDeclaration field in fields) { +- _addOverride(field.name); +- } +- } +- } +- } +- } +- return _overrides; +- } +- +- /** +- * Add a new [Override] for the declaration with the given name [node]. +- */ +- void _addOverride(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- OverriddenElements overridesResult =3D +- new _OverriddenElementsFinder(element).find(); +- List superElements =3D overridesResult.superElements; +- List interfaceElements =3D overridesResult.interfaceElements; +- if (superElements.isNotEmpty || interfaceElements.isNotEmpty) { +- proto.OverriddenMember superMember =3D superElements.isNotEmpty +- ? proto.newOverriddenMember_fromEngine(superElements.first) +- : null; +- List interfaceMembers =3D interfaceElements +- .map((member) =3D> proto.newOverriddenMember_fromEngine(member)) +- .toList(); +- _overrides.add(new proto.Override(node.offset, node.length, +- superclassMember: superMember, +- interfaceMembers: nullIfEmpty(interfaceMembers))); +- } +- } +-} +- +-/** +- * The container with elements that a class member overrides. +- */ +-class OverriddenElements { +- /** +- * The element that overrides other class members. +- */ +- final Element element; +- +- /** +- * The elements that [element] overrides and which is defined in a clas= s that +- * is a superclass of the class that defines [element]. +- */ +- final List superElements; +- +- /** +- * The elements that [element] overrides and which is defined in a clas= s that +- * which is implemented by the class that defines [element]. +- */ +- final List interfaceElements; +- +- OverriddenElements(this.element, this.superElements, this.interfaceElem= ents); +-} +- +-class _OverriddenElementsFinder { +- static const List FIELD_KINDS =3D const [ +- ElementKind.FIELD, +- ElementKind.GETTER, +- ElementKind.SETTER +- ]; +- +- static const List GETTER_KINDS =3D const [ +- ElementKind.FIELD, +- ElementKind.GETTER +- ]; +- +- static const List METHOD_KINDS =3D const [ +- ElementKind.METHOD +- ]; +- +- static const List SETTER_KINDS =3D const [ +- ElementKind.FIELD, +- ElementKind.SETTER +- ]; +- +- Element _seed; +- LibraryElement _library; +- ClassElement _class; +- String _name; +- List _kinds; +- +- List _superElements =3D []; +- List _interfaceElements =3D []; +- Set _visited =3D new Set(); +- +- _OverriddenElementsFinder(Element seed) { +- _seed =3D seed; +- _class =3D seed.enclosingElement; +- if (_class =3D=3D null) { +- // TODO(brianwilkerson) Remove this code when the issue has been fi= xed +- // (https://github.com/dart-lang/sdk/issues/25884) +- Type type =3D seed.runtimeType; +- String name =3D seed.name; +- throw new ArgumentError( +- 'The $type named $name does not have an enclosing element'); +- } +- _library =3D _class.library; +- _name =3D seed.displayName; +- if (seed is MethodElement) { +- _kinds =3D METHOD_KINDS; +- } else if (seed is PropertyAccessorElement) { +- _kinds =3D seed.isGetter ? GETTER_KINDS : SETTER_KINDS; +- } else { +- _kinds =3D FIELD_KINDS; +- } +- } +- +- /** +- * Add the [OverriddenElements] for this element. +- */ +- OverriddenElements find() { +- _visited.clear(); +- _addSuperOverrides(_class.supertype); +- _visited.clear(); +- _addInterfaceOverrides(_class.type, false); +- _superElements.forEach(_interfaceElements.remove); +- return new OverriddenElements(_seed, _superElements, _interfaceElemen= ts); +- } +- +- void _addInterfaceOverrides(InterfaceType type, bool checkType) { +- if (type =3D=3D null) { +- return; +- } +- if (!_visited.add(type)) { +- return; +- } +- // this type +- if (checkType) { +- Element element =3D _lookupMember(type.element); +- if (element !=3D null && !_interfaceElements.contains(element)) { +- _interfaceElements.add(element); +- } +- } +- // interfaces +- for (InterfaceType interfaceType in type.interfaces) { +- _addInterfaceOverrides(interfaceType, true); +- } +- // super +- _addInterfaceOverrides(type.superclass, checkType); +- } +- +- void _addSuperOverrides(InterfaceType type) { +- if (type =3D=3D null) { +- return; +- } +- if (!_visited.add(type)) { +- return; +- } +- // this type +- Element element =3D _lookupMember(type.element); +- if (element !=3D null && !_superElements.contains(element)) { +- _superElements.add(element); +- } +- // super +- _addSuperOverrides(type.superclass); +- } +- +- Element _lookupMember(ClassElement classElement) { +- if (classElement =3D=3D null) { +- return null; +- } +- Element member; +- // method +- if (_kinds.contains(ElementKind.METHOD)) { +- member =3D classElement.lookUpMethod(_name, _library); +- if (member !=3D null) { +- return member; +- } +- } +- // getter +- if (_kinds.contains(ElementKind.GETTER)) { +- member =3D classElement.lookUpGetter(_name, _library); +- if (member !=3D null) { +- return member; +- } +- } +- // setter +- if (_kinds.contains(ElementKind.SETTER)) { +- member =3D classElement.lookUpSetter(_name + '=3D', _library); +- if (member !=3D null) { +- return member; +- } +- } +- // not found +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/import_elements_computer= .dart b/pkg/analysis_server/lib/src/computer/import_elements_computer.dart +deleted file mode 100644 +index 0b3617e57df..00000000000 +--- a/pkg/analysis_server/lib/src/computer/import_elements_computer.dart ++++ /dev/null +@@ -1,433 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/dart/analysis/results.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/ast_factory.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/ast/ast_factory.dart'; +-import 'package:analyzer/src/dart/ast/token.dart'; +-import 'package:analyzer/src/dart/resolver/scope.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +-import 'package:analyzer_plugin/utilities/change_builder/change_builder_d= art.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +-import 'package:front_end/src/base/syntactic_entity.dart'; +-import 'package:path/src/context.dart'; +- +-/** +- * An object used to compute a set of edits to add imports to a given lib= rary in +- * order to make a given set of elements visible. +- * +- * This is used to implement the `edit.importElements` request. +- */ +-class ImportElementsComputer { +- /** +- * The resource provider used to access the file system. +- */ +- final ResourceProvider resourceProvider; +- +- /** +- * The resolution result associated with the defining compilation unit = of the +- * library to which imports might be added. +- */ +- final ResolveResult libraryResult; +- +- /** +- * Initialize a newly created builder. +- */ +- ImportElementsComputer(this.resourceProvider, this.libraryResult); +- +- /** +- * Create the edits that will cause the list of [importedElements] to be +- * imported into the library at the given [path]. +- */ +- Future createEdits( +- List importedElementsList) async { +- List filteredImportedElements =3D +- _filterImportedElements(importedElementsList); +- LibraryElement libraryElement =3D libraryResult.libraryElement; +- SourceFactory sourceFactory =3D libraryResult.session.sourceFactory; +- List existingImports =3D []; +- for (var directive in libraryResult.unit.directives) { +- if (directive is ImportDirective) { +- existingImports.add(directive); +- } +- } +- +- DartChangeBuilder builder =3D new DartChangeBuilder(libraryResult.ses= sion); +- await builder.addFileEdit(libraryResult.path, +- (DartFileEditBuilder builder) { +- for (ImportedElements importedElements in filteredImportedElements)= { +- List matchingImports =3D +- _findMatchingImports(existingImports, importedElements); +- if (matchingImports.isEmpty) { +- // +- // The required library is not being imported with a matching p= refix, +- // so we need to add an import. +- // +- File importedFile =3D resourceProvider.getFile(importedElements= .path); +- Uri uri =3D sourceFactory.restoreUri(importedFile.createSource(= )); +- Source importedSource =3D importedFile.createSource(uri); +- String importUri =3D +- _getLibrarySourceUri(libraryElement, importedSource); +- _InsertionDescription description =3D +- _getInsertionDescription(importUri); +- builder.addInsertion(description.offset, (DartEditBuilder build= er) { +- for (int i =3D 0; i < description.newLinesBefore; i++) { +- builder.writeln(); +- } +- builder.write("import '"); +- builder.write(importUri); +- builder.write("'"); +- if (importedElements.prefix.isNotEmpty) { +- builder.write(' as '); +- builder.write(importedElements.prefix); +- } +- builder.write(';'); +- for (int i =3D 0; i < description.newLinesAfter; i++) { +- builder.writeln(); +- } +- }); +- } else { +- // +- // There are some imports of the library with a matching prefix= . We +- // need to determine whether the names are already visible or w= hether +- // we need to make edits to make them visible. +- // +- // Compute the edits that need to be made. +- // +- Map updateMap =3D +- {}; +- for (String requiredName in importedElements.elements) { +- _computeUpdate(updateMap, matchingImports, requiredName); +- } +- // +- // Apply the edits. +- // +- for (ImportDirective directive in updateMap.keys) { +- _ImportUpdate update =3D updateMap[directive]; +- List namesToUnhide =3D update.namesToUnhide; +- List namesToShow =3D update.namesToShow; +- namesToShow.sort(); +- NodeList combinators =3D directive.combinators; +- int combinatorCount =3D combinators.length; +- for (int combinatorIndex =3D 0; +- combinatorIndex < combinatorCount; +- combinatorIndex++) { +- Combinator combinator =3D combinators[combinatorIndex]; +- if (combinator is HideCombinator && namesToUnhide.isNotEmpt= y) { +- NodeList hiddenNames =3D combinator.hid= denNames; +- int nameCount =3D hiddenNames.length; +- int first =3D -1; +- for (int nameIndex =3D 0; nameIndex < nameCount; nameInde= x++) { +- if (namesToUnhide.contains(hiddenNames[nameIndex].name)= ) { +- if (first < 0) { +- first =3D nameIndex; +- } +- } else { +- if (first >=3D 0) { +- // Remove a range of names. +- builder.addDeletion(range.startStart( +- hiddenNames[first], hiddenNames[nameIndex])); +- first =3D -1; +- } +- } +- } +- if (first =3D=3D 0) { +- // Remove the whole combinator. +- if (combinatorIndex =3D=3D 0) { +- if (combinatorCount > 1) { +- builder.addDeletion(range.startStart( +- combinator, combinators[combinatorIndex + 1])); +- } else { +- SyntacticEntity precedingNode =3D directive.prefix = ?? +- directive.deferredKeyword ?? +- directive.uri; +- if (precedingNode =3D=3D null) { +- builder.addDeletion(range.node(combinator)); +- } else { +- builder.addDeletion( +- range.endEnd(precedingNode, combinator)); +- } +- } +- } else { +- builder.addDeletion(range.endEnd( +- combinators[combinatorIndex - 1], combinator)); +- } +- } else if (first > 0) { +- // Remove a range of names that includes the last name. +- builder.addDeletion(range.endEnd( +- hiddenNames[first - 1], hiddenNames[nameCount - 1])= ); +- } +- } else if (combinator is ShowCombinator && +- namesToShow.isNotEmpty) { +- // TODO(brianwilkerson) Add the names in alphabetic order. +- builder.addInsertion(combinator.shownNames.last.end, +- (DartEditBuilder builder) { +- for (String nameToShow in namesToShow) { +- builder.write(', '); +- builder.write(nameToShow); +- } +- }); +- } +- } +- } +- } +- } +- }); +- return builder.sourceChange; +- } +- +- /** +- * Choose the import for which the least amount of work is required, +- * preferring to do no work in there is an import that already makes th= e name +- * visible, and preferring to remove hide combinators rather than add s= how +- * combinators. +- * +- * The name is visible without needing any changes if: +- * - there is an import with no combinators, +- * - there is an import with only hide combinators and none of them hid= e the +- * name, +- * - there is an import that shows the name and doesn't subsequently hi= de the +- * name. +- */ +- void _computeUpdate(Map updateMap, +- List matchingImports, String requiredName) { +- /** +- * Return `true` if the [requiredName] is in the given list of [names= ]. +- */ +- bool nameIn(NodeList names) { +- for (SimpleIdentifier name in names) { +- if (name.name =3D=3D requiredName) { +- return true; +- } +- } +- return false; +- } +- +- ImportDirective preferredDirective =3D null; +- int bestEditCount =3D -1; +- bool deleteHide =3D false; +- bool addShow =3D false; +- +- for (ImportDirective directive in matchingImports) { +- NodeList combinators =3D directive.combinators; +- if (combinators.isEmpty) { +- return; +- } +- bool hasHide =3D false; +- bool needsShow =3D false; +- int editCount =3D 0; +- for (Combinator combinator in combinators) { +- if (combinator is HideCombinator) { +- if (nameIn(combinator.hiddenNames)) { +- hasHide =3D true; +- editCount++; +- } +- } else if (combinator is ShowCombinator) { +- if (needsShow || !nameIn(combinator.shownNames)) { +- needsShow =3D true; +- editCount++; +- } +- } +- } +- if (editCount =3D=3D 0) { +- return; +- } else if (bestEditCount < 0 || editCount < bestEditCount) { +- preferredDirective =3D directive; +- bestEditCount =3D editCount; +- deleteHide =3D hasHide; +- addShow =3D needsShow; +- } +- } +- +- _ImportUpdate update =3D updateMap.putIfAbsent( +- preferredDirective, () =3D> new _ImportUpdate(preferredDirective)= ); +- if (deleteHide) { +- update.unhide(requiredName); +- } +- if (addShow) { +- update.show(requiredName); +- } +- } +- +- /** +- * Filter the given list of imported elements ([originalList]) so that = only +- * the names that are not already defined still remain. Names that are = already +- * defined are removed even if they might not resolve to the same name = as in +- * the original source. +- */ +- List _filterImportedElements( +- List originalList) { +- LibraryElement libraryElement =3D libraryResult.libraryElement; +- LibraryScope libraryScope =3D new LibraryScope(libraryElement); +- AstFactory factory =3D new AstFactoryImpl(); +- List filteredList =3D []; +- for (ImportedElements elements in originalList) { +- List originalElements =3D elements.elements; +- List filteredElements =3D originalElements.toList(); +- for (String name in originalElements) { +- Identifier identifier =3D factory +- .simpleIdentifier(new StringToken(TokenType.IDENTIFIER, name,= -1)); +- if (elements.prefix.isNotEmpty) { +- SimpleIdentifier prefix =3D factory.simpleIdentifier( +- new StringToken(TokenType.IDENTIFIER, elements.prefix, -1)); +- Token period =3D new SimpleToken(TokenType.PERIOD, -1); +- identifier =3D factory.prefixedIdentifier(prefix, period, ident= ifier); +- } +- Element element =3D libraryScope.lookup(identifier, libraryElemen= t); +- if (element !=3D null) { +- filteredElements.remove(name); +- } +- } +- if (originalElements.length =3D=3D filteredElements.length) { +- filteredList.add(elements); +- } else if (filteredElements.isNotEmpty) { +- filteredList.add(new ImportedElements( +- elements.path, elements.prefix, filteredElements)); +- } +- } +- return filteredList; +- } +- +- /** +- * Return all of the import elements in the list of [existingImports] t= hat +- * match the given specification of [importedElements], or an empty lis= t if +- * there are no such imports. +- */ +- List _findMatchingImports( +- List existingImports, +- ImportedElements importedElements) { +- List matchingImports =3D []; +- for (ImportDirective existingImport in existingImports) { +- if (_matches(existingImport, importedElements)) { +- matchingImports.add(existingImport); +- } +- } +- return matchingImports; +- } +- +- /** +- * Return the offset at which an import of the given [importUri] should= be +- * inserted. +- * +- * Partially copied from DartFileEditBuilderImpl. +- */ +- _InsertionDescription _getInsertionDescription(String importUri) { +- CompilationUnit unit =3D libraryResult.unit; +- LibraryDirective libraryDirective; +- List importDirectives =3D []; +- List otherDirectives =3D []; +- for (Directive directive in unit.directives) { +- if (directive is LibraryDirective) { +- libraryDirective =3D directive; +- } else if (directive is ImportDirective) { +- importDirectives.add(directive); +- } else { +- otherDirectives.add(directive); +- } +- } +- if (importDirectives.isEmpty) { +- if (libraryDirective =3D=3D null) { +- if (otherDirectives.isEmpty) { +- // TODO(brianwilkerson) Insert after any non-doc comments. +- return new _InsertionDescription(0, after: 2); +- } +- return new _InsertionDescription(otherDirectives[0].offset, after= : 2); +- } +- return new _InsertionDescription(libraryDirective.end, before: 2); +- } +- // TODO(brianwilkerson) Fix this to find the right location. +- // See DartFileEditBuilderImpl._addLibraryImports for inspiration. +- return new _InsertionDescription(importDirectives.last.end, before: 1= ); +- } +- +- /** +- * Computes the best URI to import [what] into [from]. +- * +- * Copied from DartFileEditBuilderImpl. +- */ +- String _getLibrarySourceUri(LibraryElement from, Source what) { +- String whatPath =3D what.fullName; +- // check if an absolute URI (such as 'dart:' or 'package:') +- Uri whatUri =3D what.uri; +- String whatUriScheme =3D whatUri.scheme; +- if (whatUriScheme !=3D '' && whatUriScheme !=3D 'file') { +- return whatUri.toString(); +- } +- // compute a relative URI +- Context context =3D resourceProvider.pathContext; +- String fromFolder =3D context.dirname(from.source.fullName); +- String relativeFile =3D context.relative(whatPath, from: fromFolder); +- return context.split(relativeFile).join('/'); +- } +- +- /** +- * Return `true` if the given [import] matches the given specification = of +- * [importedElements]. They will match if they import the same library = using +- * the same prefix. +- */ +- bool _matches(ImportDirective import, ImportedElements importedElements= ) { +- return (import.element as ImportElement).importedLibrary.source.fullN= ame =3D=3D +- importedElements.path && +- (import.prefix?.name ?? '') =3D=3D importedElements.prefix; +- } +-} +- +-/** +- * Information about how a given import directive needs to be updated in = order +- * to make the required names visible. +- */ +-class _ImportUpdate { +- /** +- * The import directive to be updated. +- */ +- final ImportDirective import; +- +- /** +- * The list of names that are currently hidden that need to not be hidd= en. +- */ +- final List namesToUnhide =3D []; +- +- /** +- * The list of names that need to be added to show clauses. +- */ +- final List namesToShow =3D []; +- +- /** +- * Initialize a newly created information holder to hold information ab= out +- * updates to the given [import]. +- */ +- _ImportUpdate(this.import); +- +- /** +- * Record that the given [name] needs to be added to show combinators. +- */ +- void show(String name) { +- namesToShow.add(name); +- } +- +- /** +- * Record that the given [name] needs to be removed from hide combinato= rs. +- */ +- void unhide(String name) { +- namesToUnhide.add(name); +- } +-} +- +-class _InsertionDescription { +- final int newLinesBefore; +- final int offset; +- final int newLinesAfter; +- +- _InsertionDescription(this.offset, {int before: 0, int after: 0}) +- : this.newLinesBefore =3D before, +- this.newLinesAfter =3D after; +-} +diff --git a/pkg/analysis_server/lib/src/computer/imported_elements_comput= er.dart b/pkg/analysis_server/lib/src/computer/imported_elements_computer.d= art +deleted file mode 100644 +index e7dd9e87ac5..00000000000 +--- a/pkg/analysis_server/lib/src/computer/imported_elements_computer.dart ++++ /dev/null +@@ -1,129 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-/** +- * An object used to compute the list of elements referenced within a giv= en +- * region of a compilation unit that are imported into the compilation un= it's +- * library. +- */ +-class ImportedElementsComputer { +- /** +- * The compilation unit in which the elements are referenced. +- */ +- final CompilationUnit unit; +- +- /** +- * The offset of the region containing the references to be returned. +- */ +- final int offset; +- +- /** +- * The length of the region containing the references to be returned. +- */ +- final int length; +- +- /** +- * Initialize a newly created computer to compute the list of imported +- * elements referenced in the given [unit] within the region with the g= iven +- * [offset] and [length]. +- */ +- ImportedElementsComputer(this.unit, this.offset, this.length); +- +- /** +- * Compute and return the list of imported elements. +- */ +- List compute() { +- _Visitor visitor =3D +- new _Visitor(unit.element.library, offset, offset + length); +- unit.accept(visitor); +- return visitor.importedElements.values.toList(); +- } +-} +- +-/** +- * The visitor used by an [ImportedElementsComputer] to record the names = of all +- * imported elements. +- */ +-class _Visitor extends UnifyingAstVisitor { +- /** +- * The element representing the library containing the code being visit= ed. +- */ +- final LibraryElement containingLibrary; +- +- /** +- * The offset of the start of the region of text being copied. +- */ +- final int startOffset; +- +- /** +- * The offset of the end of the region of text being copied. +- */ +- final int endOffset; +- +- /** +- * A table mapping library path and prefix keys to the imported element= s from +- * that library. +- */ +- Map importedElements =3D {}; +- +- /** +- * Initialize a newly created visitor to visit nodes within a specified +- * region. +- */ +- _Visitor(this.containingLibrary, this.startOffset, this.endOffset); +- +- @override +- Object visitNode(AstNode node) { +- if (node.offset <=3D endOffset && node.end >=3D startOffset) { +- node.visitChildren(this); +- } +- return null; +- } +- +- @override +- Object visitSimpleIdentifier(SimpleIdentifier node) { +- if (!node.inDeclarationContext() && +- node.offset <=3D endOffset && +- node.end >=3D startOffset && +- !_isConstructorDeclarationReturnType(node)) { +- Element nodeElement =3D node.staticElement; +- if (nodeElement !=3D null && +- nodeElement.enclosingElement is CompilationUnitElement) { +- LibraryElement nodeLibrary =3D nodeElement.library; +- String path =3D nodeLibrary.definingCompilationUnit.source.fullNa= me; +- String prefix =3D ''; +- AstNode parent =3D node.parent; +- if (parent is PrefixedIdentifier && parent.identifier =3D=3D node= ) { +- SimpleIdentifier prefixIdentifier =3D parent.prefix; +- if (prefixIdentifier.offset <=3D endOffset && +- prefixIdentifier.end >=3D startOffset) { +- Element prefixElement =3D prefixIdentifier.staticElement; +- if (prefixElement is PrefixElement) { +- prefix =3D prefixElement.name; +- } +- } +- } +- String key =3D '$prefix;$path'; +- ImportedElements elements =3D importedElements.putIfAbsent( +- key, () =3D> new ImportedElements(path, prefix, [])); +- List elementNames =3D elements.elements; +- String elementName =3D nodeElement.name; +- if (!elementNames.contains(elementName)) { +- elementNames.add(elementName); +- } +- } +- } +- return null; +- } +- +- static bool _isConstructorDeclarationReturnType(SimpleIdentifier node) { +- AstNode parent =3D node.parent; +- return parent is ConstructorDeclaration && parent.returnType =3D=3D n= ode; +- } +-} +diff --git a/pkg/analysis_server/lib/src/computer/new_notifications.dart b= /pkg/analysis_server/lib/src/computer/new_notifications.dart +deleted file mode 100644 +index 0e11991a95f..00000000000 +--- a/pkg/analysis_server/lib/src/computer/new_notifications.dart ++++ /dev/null +@@ -1,45 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as prot= ocol; +-import 'package:analysis_server/src/analysis_server.dart' show AnalysisSe= rver; +-import 'package:analysis_server/src/domains/analysis/navigation_dart.dart= '; +-import 'package:analysis_server/src/domains/analysis/occurrences.dart'; +-import 'package:analysis_server/src/domains/analysis/occurrences_dart.dar= t'; +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/src/utilities/navigation/navigation.dart'; +- +-void new_sendDartNotificationNavigation( +- AnalysisServer analysisServer, AnalysisResult result) { +- var unit =3D result.unit; +- if (unit !=3D null) { +- NavigationCollectorImpl collector =3D new NavigationCollectorImpl(); +- computeDartNavigation(collector, unit, null, null); +- collector.createRegions(); +- var params =3D new protocol.AnalysisNavigationParams( +- result.path, collector.regions, collector.targets, collector.file= s); +- analysisServer.sendNotification(params.toNotification()); +- } +-} +- +-void new_sendDartNotificationOccurrences( +- AnalysisServer analysisServer, AnalysisResult result) { +- var unit =3D result.unit; +- if (unit !=3D null) { +- OccurrencesCollectorImpl collector =3D new OccurrencesCollectorImpl(); +- addDartOccurrences(collector, unit); +- var params =3D new protocol.AnalysisOccurrencesParams( +- result.path, collector.allOccurrences); +- analysisServer.sendNotification(params.toNotification()); +- } +-} +- +-void new_sendErrorNotification( +- AnalysisServer analysisServer, AnalysisResult result) { +- var serverErrors =3D protocol.doAnalysisError_listFromEngine( +- result.driver.analysisOptions, result.lineInfo, result.errors); +- var params =3D new protocol.AnalysisErrorsParams(result.path, serverErr= ors); +- analysisServer.sendNotification(params.toNotification()); +-} +diff --git a/pkg/analysis_server/lib/src/constants.dart b/pkg/analysis_ser= ver/lib/src/constants.dart +deleted file mode 100644 +index ab9accf90a0..00000000000 +--- a/pkg/analysis_server/lib/src/constants.dart ++++ /dev/null +@@ -1,100 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-const String ADD =3D 'add'; +-const String ADDED =3D 'added'; +-const String ASSISTS =3D 'assists'; +-const String CHANGE =3D 'change'; +-const String CHILDREN =3D 'children'; +-const String CLASS_ELEMENT =3D 'classElement'; +-const String CLASS_NAME =3D 'className'; +-const String CODE =3D 'code'; +-const String COMPLETION =3D 'completion'; +-const String COMPLETION_RESULTS =3D 'completion.results'; +-const String CONTAINING_LIBRARY_NAME =3D 'containingLibraryName'; +-const String CONTAINING_LIBRARY_PATH =3D 'containingLibraryPath'; +-const String CONTENT =3D 'content'; +-const String CORRECTION =3D 'correction'; +-const String DART_DOC =3D 'dartdoc'; +-const String DEFAULT =3D 'default'; +-const String DISPLAY_NAME =3D 'displayName'; +-const String EDITS =3D 'edits'; +-const String ELEMENT =3D 'element'; // boolean +-const String ELEMENT_DESCRIPTION =3D 'elementDescription'; // boolean +-const String ELEMENT_KIND =3D 'elementKind'; // boolean +-const String ENABLE_ASYNC =3D 'enableAsync'; // boolean +-const String ENABLE_DEFERRED_LOADING =3D 'enableDeferredLoading'; // bool= ean +-const String ENABLE_ENUMS =3D 'enableEnums'; +-const String ERROR =3D 'error'; +-const String ERRORS =3D 'errors'; +-const String EXCLUDED =3D 'excluded'; +-const String FATAL =3D 'fatal'; +-const String FILE =3D 'file'; +-const String FILE_STAMP =3D 'fileStamp'; +-const String FILES =3D 'files'; +-const String FIXES =3D 'fixes'; +-const String FLAGS =3D 'flags'; +-const String GENERATE_DART2JS_HINTS =3D 'generateDart2jsHints'; +-const String GENERATE_HINTS =3D 'generateHints'; +-const String HAS_FIX =3D 'hasFix'; +-const String HIERARCHY_ITEMS =3D 'hierarchyItems'; +-const String HOVERS =3D 'hovers'; +-const String ID =3D 'id'; +-const String INCLUDE_POTENTIAL =3D 'includePotential'; +-const String INCLUDED =3D 'included'; +-const String INTERFACE_MEMBERS =3D 'interfaceMembers'; +-const String INTERFACES =3D 'interfaces'; +-const String IS_ABSTRACT =3D 'isAbstract'; +-const String IS_DEPRECATED =3D 'isDeprecated'; +-const String IS_POTENTIAL =3D 'isPotential'; +-const String IS_STATIC =3D 'isStatic'; +-const String KIND =3D 'kind'; +-const String KINDS =3D 'kinds'; +-const String LAST =3D 'last'; +-const String LENGTH =3D 'length'; +-const String LINKED_EDIT_GROUPS =3D 'linkedEditGroups'; +-const String LOCATION =3D 'location'; +-const String MEMBER_ELEMENT =3D 'memberElement'; +-const String MESSAGE =3D 'message'; +-const String MIXINS =3D 'mixins'; +-const String NAME =3D 'name'; +-const String OCCURRENCES =3D 'occurrences'; +-const String OFFSET =3D 'offset'; +-const String OFFSETS =3D 'offsets'; +-const String OPTIONS =3D 'options'; +-const String OUTLINE =3D 'outline'; +-const String OVERRIDES =3D 'overrides'; +-const String PARAMETER =3D 'parameter'; +-const String PARAMETERS =3D 'parameters'; +-const String PATH =3D 'path'; +-const String PATTERN =3D 'pattern'; +-const String POSITIONS =3D 'positions'; +-const String PROPAGATED_TYPE =3D 'propagatedType'; +-const String REFACTORINGS =3D 'refactorings'; +-const String REGIONS =3D 'regions'; +-const String RELEVANCE =3D 'relevance'; +-const String REMOVE =3D 'remove'; +-const String REMOVED =3D 'removed'; +-const String REPLACEMENT =3D 'replacement'; +-const String REPLACEMENT_LENGTH =3D 'replacementLength'; +-const String REPLACEMENT_OFFSET =3D 'replacementOffset'; +-const String RESULTS =3D 'results'; +-const String RETURN_TYPE =3D 'returnType'; +-const String SELECTION =3D 'selection'; +-const String SELECTION_LENGTH =3D 'selectionLength'; +-const String SELECTION_OFFSET =3D 'selectionOffset'; +-const String SEVERITY =3D 'severity'; +-const String STACK_TRACE =3D 'stackTrace'; +-const String START_COLUMN =3D 'startColumn'; +-const String START_LINE =3D 'startLine'; +-const String STATIC_TYPE =3D 'staticType'; +-const String SUBCLASSES =3D 'subclasses'; +-const String SUBSCRIPTIONS =3D 'subscriptions'; +-const String SUGGESTIONS =3D 'suggestions'; +-const String SUPER_CLASS_MEMBER =3D 'superclassMember'; +-const String SUPERCLASS =3D 'superclass'; +-const String TARGETS =3D 'targets'; +-const String TYPE =3D 'type'; +-const String VALUE =3D 'value'; +-const String VERSION =3D 'version'; +diff --git a/pkg/analysis_server/lib/src/context_manager.dart b/pkg/analys= is_server/lib/src/context_manager.dart +deleted file mode 100644 +index 889282319d3..00000000000 +--- a/pkg/analysis_server/lib/src/context_manager.dart ++++ /dev/null +@@ -1,1817 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:convert'; +-import 'dart:core'; +- +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/plugin/resolver_provider.dart'; +-import 'package:analyzer/source/analysis_options_provider.dart'; +-import 'package:analyzer/source/package_map_provider.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/source/path_filter.dart'; +-import 'package:analyzer/source/pub_package_map_provider.dart'; +-import 'package:analyzer/source/sdk_ext.dart'; +-import 'package:analyzer/src/context/builder.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/sdk/sdk.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/java_engine.dart'; +-import 'package:analyzer/src/generated/java_io.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/source_io.dart'; +-import 'package:analyzer/src/task/options.dart'; +-import 'package:analyzer/src/util/absolute_path.dart'; +-import 'package:analyzer/src/util/glob.dart'; +-import 'package:analyzer/src/util/yaml.dart'; +-import 'package:analyzer_plugin/utilities/analyzer_converter.dart'; +-import 'package:package_config/packages.dart'; +-import 'package:package_config/packages_file.dart' as pkgfile show parse; +-import 'package:package_config/src/packages_impl.dart' show MapPackages; +-import 'package:path/path.dart' as pathos; +-import 'package:watcher/watcher.dart'; +-import 'package:yaml/yaml.dart'; +- +-/** +- * Information tracked by the [ContextManager] for each context. +- */ +-class ContextInfo { +- /** +- * The [Folder] for which this information object is created. +- */ +- final Folder folder; +- +- /// The [PathFilter] used to filter sources from being analyzed. +- final PathFilter pathFilter; +- +- /** +- * The enclosed pubspec-based contexts. +- */ +- final List children =3D []; +- +- /** +- * The package root for this context, or null if there is no package ro= ot. +- */ +- String packageRoot; +- +- /** +- * The [ContextInfo] that encloses this one, or `null` if this is the v= irtual +- * [ContextInfo] object that acts as the ancestor of all other [Context= Info] +- * objects. +- */ +- ContextInfo parent; +- +- /** +- * The package description file path for this context. +- */ +- String packageDescriptionPath; +- +- /** +- * The folder disposition for this context. +- */ +- final FolderDisposition disposition; +- +- /** +- * Paths to files which determine the folder disposition and package ma= p. +- * +- * TODO(paulberry): if any of these files are outside of [folder], they= won't +- * be watched for changes. I believe the use case for watching these f= iles +- * is no longer relevant. +- */ +- Set _dependencies =3D new Set(); +- +- /** +- * The analysis driver that was created for the [folder]. +- */ +- AnalysisDriver analysisDriver; +- +- /** +- * Map from full path to the [Source] object, for each source that has = been +- * added to the context. +- */ +- Map sources =3D new HashMap(); +- +- ContextInfo(ContextManagerImpl contextManager, this.parent, Folder fold= er, +- File packagespecFile, this.packageRoot, this.disposition) +- : folder =3D folder, +- pathFilter =3D new PathFilter( +- folder.path, null, contextManager.resourceProvider.pathContex= t) { +- packageDescriptionPath =3D packagespecFile.path; +- parent.children.add(this); +- } +- +- /** +- * Create the virtual [ContextInfo] which acts as an ancestor to all ot= her +- * [ContextInfo]s. +- */ +- ContextInfo._root() +- : folder =3D null, +- pathFilter =3D null, +- packageRoot =3D null, +- disposition =3D null; +- +- /** +- * Iterate through all [children] and their children, recursively. +- */ +- Iterable get descendants sync* { +- for (ContextInfo child in children) { +- yield child; +- yield* child.descendants; +- } +- } +- +- /** +- * Returns `true` if this is a "top level" context, meaning that the fo= lder +- * associated with it is not contained within any other folders that ha= ve an +- * associated context. +- */ +- bool get isTopLevel =3D> parent.parent =3D=3D null; +- +- /** +- * Returns `true` if [path] is excluded, as it is in one of the childre= n. +- */ +- bool excludes(String path) { +- return children.any((child) { +- return child.folder.contains(path); +- }); +- } +- +- /** +- * Returns `true` if [resource] is excluded, as it is in one of the chi= ldren. +- */ +- bool excludesResource(Resource resource) =3D> excludes(resource.path); +- +- /** +- * Return the first [ContextInfo] in [children] whose associated folder= is or +- * contains [path]. If there is no such [ContextInfo], return `null`. +- */ +- ContextInfo findChildInfoFor(String path) { +- for (ContextInfo info in children) { +- if (info.folder.isOrContains(path)) { +- return info; +- } +- } +- return null; +- } +- +- /** +- * Determine if the given [path] is one of the dependencies most recent= ly +- * passed to [setDependencies]. +- */ +- bool hasDependency(String path) =3D> _dependencies.contains(path); +- +- /// Returns `true` if [path] should be ignored. +- bool ignored(String path) =3D> pathFilter.ignored(path); +- +- /** +- * Returns `true` if [path] is the package description file for this co= ntext +- * (pubspec.yaml or .packages). +- */ +- bool isPathToPackageDescription(String path) =3D> +- path =3D=3D packageDescriptionPath; +- +- /** +- * Update the set of dependencies for this context. +- */ +- void setDependencies(Iterable newDependencies) { +- _dependencies =3D newDependencies.toSet(); +- } +- +- /** +- * Return `true` if the given [path] is managed by this context or by +- * any of its children. +- */ +- bool _managesOrHasChildThatManages(String path) { +- if (parent =3D=3D null) { +- for (ContextInfo child in children) { +- if (child._managesOrHasChildThatManages(path)) { +- return true; +- } +- } +- return false; +- } else { +- if (!folder.isOrContains(path)) { +- return false; +- } +- for (ContextInfo child in children) { +- if (child._managesOrHasChildThatManages(path)) { +- return true; +- } +- } +- return !pathFilter.ignored(path); +- } +- } +-} +- +-/** +- * Class that maintains a mapping from included/excluded paths to a set of +- * folders that should correspond to analysis contexts. +- */ +-abstract class ContextManager { +- // TODO(brianwilkerson) Support: +- // setting the default analysis options +- // setting the default content cache +- // setting the default SDK +- // telling server when a context has been added or removed (see onCon= textsChanged) +- // telling server when a context needs to be re-analyzed +- // notifying the client when results should be flushed +- // using analyzeFileFunctions to determine which files to analyze +- // +- // TODO(brianwilkerson) Move this class to a public library. +- +- /** +- * Get the callback interface used to create, destroy, and update conte= xts. +- */ +- ContextManagerCallbacks get callbacks; +- +- /** +- * Set the callback interface used to create, destroy, and update conte= xts. +- */ +- void set callbacks(ContextManagerCallbacks value); +- +- /** +- * A table mapping [Folder]s to the [AnalysisDriver]s associated with t= hem. +- */ +- Map get driverMap; +- +- /** +- * Return the list of excluded paths (folders and files) most recently = passed +- * to [setRoots]. +- */ +- List get excludedPaths; +- +- /** +- * Return the list of included paths (folders and files) most recently = passed +- * to [setRoots]. +- */ +- List get includedPaths; +- +- /** +- * Like [getDriverFor], but returns the [Folder] which allows plugins to +- * create & manage their own tree of drivers just like using [getDriver= For]. +- * +- * This folder should be the root of analysis context, not just the con= taining +- * folder of the path (like basename), as this is NOT just a file API. +- * +- * This exists at least temporarily, for plugin support until the new A= PI is +- * ready. +- */ +- Folder getContextFolderFor(String path); +- +- /** +- * Return the [AnalysisDriver] for the "innermost" context whose associ= ated +- * folder is or contains the given path. ("innermost" refers to the ne= sting +- * of contexts, so if there is a context for path /foo and a context for +- * path /foo/bar, then the innermost context containing /foo/bar/baz.da= rt is +- * the context for /foo/bar.) +- * +- * If no driver contains the given path, `null` is returned. +- */ +- AnalysisDriver getDriverFor(String path); +- +- /** +- * Return a list of all of the analysis drivers reachable from the given +- * [analysisRoot] (the driver associated with [analysisRoot] and all of= its +- * descendants). +- */ +- List getDriversInAnalysisRoot(Folder analysisRoot); +- +- /** +- * Return `true` if the given [path] is ignored by a [ContextInfo] whose +- * folder contains it. +- */ +- bool isIgnored(String path); +- +- /** +- * Return `true` if the given absolute [path] is in one of the current +- * root folders and is not excluded. +- */ +- bool isInAnalysisRoot(String path); +- +- /** +- * Return the number of contexts reachable from the given [analysisRoot= ] (the +- * context associated with [analysisRoot] and all of its descendants). +- */ +- int numberOfContextsInAnalysisRoot(Folder analysisRoot); +- +- /** +- * Rebuild the set of contexts from scratch based on the data last sent= to +- * [setRoots]. Only contexts contained in the given list of analysis [r= oots] +- * will be rebuilt, unless the list is `null`, in which case every cont= ext +- * will be rebuilt. +- */ +- void refresh(List roots); +- +- /** +- * Change the set of paths which should be used as starting points to +- * determine the context directories. +- */ +- void setRoots(List includedPaths, List excludedPaths, +- Map packageRoots); +-} +- +-/** +- * Callback interface used by [ContextManager] to (a) request that contex= ts be +- * created, destroyed or updated, (b) inform the client when "pub list" +- * operations are in progress, and (c) determine which files should be +- * analyzed. +- * +- * TODO(paulberry): eliminate this interface, and instead have [ContextMa= nager] +- * operations return data structures describing how context state should = be +- * modified. +- */ +-abstract class ContextManagerCallbacks { +- /** +- * Return the notification manager associated with the server. +- */ +- NotificationManager get notificationManager; +- +- /** +- * Create and return a new analysis driver rooted at the given [folder]= , with +- * the given analysis [options]. +- */ +- AnalysisDriver addAnalysisDriver( +- Folder folder, ContextRoot contextRoot, AnalysisOptions options); +- +- /** +- * An [event] was processed, so analysis state might be different now. +- */ +- void afterWatchEvent(WatchEvent event); +- +- /** +- * Called when the set of files associated with a context have changed = (or +- * some of those files have been modified). [changeSet] is the set of +- * changes that need to be applied to the context. +- */ +- void applyChangesToContext(Folder contextFolder, ChangeSet changeSet); +- +- /** +- * The given [file] was removed from the folder analyzed in the [driver= ]. +- */ +- void applyFileRemoved(AnalysisDriver driver, String file); +- +- /** +- * Sent the given watch [event] to any interested plugins. +- */ +- void broadcastWatchEvent(WatchEvent event); +- +- /** +- * Signals that the context manager has started to compute a package ma= p (if +- * [computing] is `true`) or has finished (if [computing] is `false`). +- */ +- void computingPackageMap(bool computing); +- +- /** +- * Create and return a context builder that can be used to create a con= text +- * for the files in the given [folder] when analyzed using the given [o= ptions]. +- */ +- ContextBuilder createContextBuilder(Folder folder, AnalysisOptions opti= ons); +- +- /** +- * Called when the context manager changes the folder with which a cont= ext is +- * associated. Currently this is mostly FYI, and used only in tests. +- */ +- void moveContext(Folder from, Folder to); +- +- /** +- * Remove the context associated with the given [folder]. [flushedFile= s] is +- * a list of the files which will be "orphaned" by removing this context +- * (they will no longer be analyzed by any context). +- */ +- void removeContext(Folder folder, List flushedFiles); +-} +- +-/** +- * Class that maintains a mapping from included/excluded paths to a set of +- * folders that should correspond to analysis contexts. +- */ +-class ContextManagerImpl implements ContextManager { +- /** +- * The name of the `doc` directory. +- */ +- static const String DOC_DIR_NAME =3D 'doc'; +- +- /** +- * The name of the `lib` directory. +- */ +- static const String LIB_DIR_NAME =3D 'lib'; +- +- /** +- * The name of `packages` folders. +- */ +- static const String PACKAGES_NAME =3D 'packages'; +- +- /** +- * File name of pubspec files. +- */ +- static const String PUBSPEC_NAME =3D 'pubspec.yaml'; +- +- /** +- * File name of package spec files. +- */ +- static const String PACKAGE_SPEC_NAME =3D '.packages'; +- +- /** +- * The name of the key in an embedder file whose value is the list of +- * libraries in the SDK. +- * TODO(brianwilkerson) This is also defined in sdk.dart. +- */ +- static const String _EMBEDDED_LIB_MAP_KEY =3D 'embedded_libs'; +- +- /** +- * The [ResourceProvider] using which paths are converted into [Resourc= e]s. +- */ +- final ResourceProvider resourceProvider; +- +- /** +- * The manager used to access the SDK that should be associated with a +- * particular context. +- */ +- final DartSdkManager sdkManager; +- +- /** +- * The context used to work with absolute file system paths. +- * +- * TODO(scheglov) remove [pathContext]. +- */ +- AbsolutePathContext absolutePathContext; +- +- /** +- * The context used to work with file system paths. +- */ +- pathos.Context pathContext; +- +- /** +- * The list of excluded paths (folders and files) most recently passed = to +- * [setRoots]. +- */ +- List excludedPaths =3D []; +- +- /** +- * The list of included paths (folders and files) most recently passed = to +- * [setRoots]. +- */ +- List includedPaths =3D []; +- +- /** +- * The map of package roots most recently passed to [setRoots]. +- */ +- Map packageRoots =3D {}; +- +- /** +- * Same as [packageRoots], except that source folders have been normali= zed +- * and non-folders have been removed. +- */ +- Map normalizedPackageRoots =3D {}; +- +- /** +- * A function that will return a [UriResolver] that can be used to reso= lve +- * `package:` URI's within a given folder, or `null` if we should fall = back +- * to the standard URI resolver. +- */ +- final ResolverProvider packageResolverProvider; +- +- /** +- * Provider which is used to determine the mapping from package name to +- * package folder. +- */ +- final PubPackageMapProvider _packageMapProvider; +- +- /** +- * A list of the globs used to determine which files should be analyzed. +- */ +- final List analyzedFilesGlobs; +- +- /** +- * The default options used to create new analysis contexts. +- */ +- final AnalysisOptionsImpl defaultContextOptions; +- +- /** +- * The instrumentation service used to report instrumentation data. +- */ +- final InstrumentationService _instrumentationService; +- +- @override +- ContextManagerCallbacks callbacks; +- +- /** +- * Virtual [ContextInfo] which acts as the ancestor of all other +- * [ContextInfo]s. +- */ +- final ContextInfo rootInfo =3D new ContextInfo._root(); +- +- @override +- final Map driverMap =3D +- new HashMap(); +- +- /** +- * Stream subscription we are using to watch each analysis root directo= ry for +- * changes. +- */ +- final Map> changeSubscriptions = =3D +- >{}; +- +- ContextManagerImpl( +- this.resourceProvider, +- this.sdkManager, +- this.packageResolverProvider, +- this._packageMapProvider, +- this.analyzedFilesGlobs, +- this._instrumentationService, +- this.defaultContextOptions) { +- absolutePathContext =3D resourceProvider.absolutePathContext; +- pathContext =3D resourceProvider.pathContext; +- } +- +- /** +- * Check if this map defines embedded libraries. +- */ +- bool definesEmbeddedLibs(Map map) =3D> map[_EMBEDDED_LIB_MAP_KEY] !=3D = null; +- +- Folder getContextFolderFor(String path) { +- return _getInnermostContextInfoFor(path)?.folder; +- } +- +- /** +- * For testing: get the [ContextInfo] object for the given [folder], if= any. +- */ +- ContextInfo getContextInfoFor(Folder folder) { +- ContextInfo info =3D _getInnermostContextInfoFor(folder.path); +- if (info !=3D null && folder =3D=3D info.folder) { +- return info; +- } +- return null; +- } +- +- @override +- AnalysisDriver getDriverFor(String path) { +- return _getInnermostContextInfoFor(path)?.analysisDriver; +- } +- +- @override +- List getDriversInAnalysisRoot(Folder analysisRoot) { +- List drivers =3D []; +- void addContextAndDescendants(ContextInfo info) { +- drivers.add(info.analysisDriver); +- info.children.forEach(addContextAndDescendants); +- } +- +- ContextInfo innermostContainingInfo =3D +- _getInnermostContextInfoFor(analysisRoot.path); +- if (innermostContainingInfo !=3D null) { +- if (analysisRoot =3D=3D innermostContainingInfo.folder) { +- addContextAndDescendants(innermostContainingInfo); +- } else { +- for (ContextInfo info in innermostContainingInfo.children) { +- if (analysisRoot.isOrContains(info.folder.path)) { +- addContextAndDescendants(info); +- } +- } +- } +- } +- return drivers; +- } +- +- @override +- bool isIgnored(String path) { +- ContextInfo info =3D rootInfo; +- do { +- info =3D info.findChildInfoFor(path); +- if (info =3D=3D null) { +- return false; +- } +- if (info.ignored(path)) { +- return true; +- } +- } while (true); +- } +- +- @override +- bool isInAnalysisRoot(String path) { +- // check if excluded +- if (_isExcluded(path)) { +- return false; +- } +- // check if in one of the roots +- for (ContextInfo info in rootInfo.children) { +- if (info.folder.contains(path)) { +- return true; +- } +- } +- // no +- return false; +- } +- +- @override +- int numberOfContextsInAnalysisRoot(Folder analysisRoot) { +- int count =3D 0; +- void addContextAndDescendants(ContextInfo info) { +- count++; +- info.children.forEach(addContextAndDescendants); +- } +- +- ContextInfo innermostContainingInfo =3D +- _getInnermostContextInfoFor(analysisRoot.path); +- if (innermostContainingInfo !=3D null) { +- if (analysisRoot =3D=3D innermostContainingInfo.folder) { +- addContextAndDescendants(innermostContainingInfo); +- } else { +- for (ContextInfo info in innermostContainingInfo.children) { +- if (analysisRoot.isOrContains(info.folder.path)) { +- addContextAndDescendants(info); +- } +- } +- } +- } +- return count; +- } +- +- /** +- * Process [options] for the given context [info]. +- */ +- void processOptionsForDriver(ContextInfo info, +- AnalysisOptionsImpl analysisOptions, Map options) { +- if (options =3D=3D null) { +- return; +- } +- +- // Check for embedded options. +- Map embeddedOptions =3D _getEmbeddedOptions(info); +- if (embeddedOptions !=3D null) { +- options =3D _toStringMap(new Merger().merge(embeddedOptions, option= s)); +- } +- +- applyToAnalysisOptions(analysisOptions, options); +- +- var analyzer =3D options[AnalyzerOptions.analyzer]; +- if (analyzer is Map) { +- // Set ignore patterns. +- YamlList exclude =3D analyzer[AnalyzerOptions.exclude]; +- List excludeList =3D toStringList(exclude); +- if (excludeList !=3D null) { +- setIgnorePatternsForContext(info, excludeList); +- } +- } +- } +- +- @override +- void refresh(List roots) { +- // Destroy old contexts +- List contextInfos =3D rootInfo.descendants.toList(); +- if (roots =3D=3D null) { +- contextInfos.forEach(_destroyContext); +- } else { +- roots.forEach((Resource resource) { +- contextInfos.forEach((ContextInfo contextInfo) { +- if (resource is Folder && +- resource.isOrContains(contextInfo.folder.path)) { +- _destroyContext(contextInfo); +- } +- }); +- }); +- } +- +- // Rebuild contexts based on the data last sent to setRoots(). +- setRoots(includedPaths, excludedPaths, packageRoots); +- } +- +- /** +- * Sets the [ignorePatterns] for the context having info [info]. +- */ +- void setIgnorePatternsForContext( +- ContextInfo info, List ignorePatterns) { +- info.pathFilter.setIgnorePatterns(ignorePatterns); +- } +- +- @override +- void setRoots(List includedPaths, List excludedPaths, +- Map packageRoots) { +- this.packageRoots =3D packageRoots; +- +- // Normalize all package root sources by mapping them to folders on t= he +- // filesystem. Ignore any package root sources that aren't folders. +- normalizedPackageRoots =3D {}; +- packageRoots.forEach((String sourcePath, String targetPath) { +- Resource resource =3D resourceProvider.getResource(sourcePath); +- if (resource is Folder) { +- normalizedPackageRoots[resource.path] =3D targetPath; +- } +- }); +- +- List contextInfos =3D rootInfo.descendants.toList(); +- // included +- List includedFolders =3D []; +- { +- // Sort paths to ensure that outer roots are handled before inner r= oots, +- // so we can correctly ignore inner roots, which are already managed +- // by outer roots. +- LinkedHashSet uniqueIncludedPaths =3D +- new LinkedHashSet.from(includedPaths); +- List sortedIncludedPaths =3D uniqueIncludedPaths.toList(); +- sortedIncludedPaths.sort((a, b) =3D> a.length - b.length); +- // Convert paths to folders. +- for (String path in sortedIncludedPaths) { +- Resource resource =3D resourceProvider.getResource(path); +- if (resource is Folder) { +- includedFolders.add(resource); +- } else if (!resource.exists) { +- // Non-existent resources are ignored. TODO(paulberry): we sho= uld set +- // up a watcher to ensure that if the resource appears later, w= e will +- // begin analyzing it. +- } else { +- // TODO(scheglov) implemented separate files analysis +- throw new UnimplementedError('$path is not a folder. ' +- 'Only support for folder analysis is implemented currently.= '); +- } +- } +- } +- this.includedPaths =3D includedPaths; +- // excluded +- List oldExcludedPaths =3D this.excludedPaths; +- this.excludedPaths =3D excludedPaths; +- // destroy old contexts +- for (ContextInfo contextInfo in contextInfos) { +- bool isIncluded =3D includedFolders.any((folder) { +- return folder.isOrContains(contextInfo.folder.path); +- }); +- if (!isIncluded) { +- _destroyContext(contextInfo); +- } +- } +- // Update package roots for existing contexts +- for (ContextInfo info in rootInfo.descendants) { +- String newPackageRoot =3D normalizedPackageRoots[info.folder.path]; +- if (info.packageRoot !=3D newPackageRoot) { +- info.packageRoot =3D newPackageRoot; +- _recomputeFolderDisposition(info); +- } +- } +- // create new contexts +- for (Folder includedFolder in includedFolders) { +- String includedPath =3D includedFolder.path; +- bool isManaged =3D rootInfo._managesOrHasChildThatManages(includedP= ath); +- if (!isManaged) { +- ContextInfo parent =3D _getParentForNewContext(includedPath); +- changeSubscriptions[includedFolder] =3D +- includedFolder.changes.listen(_handleWatchEvent); +- _createContexts(parent, includedFolder, excludedPaths, false); +- } +- } +- // remove newly excluded sources +- for (ContextInfo info in rootInfo.descendants) { +- // prepare excluded sources +- Map excludedSources =3D new HashMap= (); +- info.sources.forEach((String path, Source source) { +- if (_isExcludedBy(excludedPaths, path) && +- !_isExcludedBy(oldExcludedPaths, path)) { +- excludedSources[path] =3D source; +- } +- }); +- // apply exclusion +- ChangeSet changeSet =3D new ChangeSet(); +- excludedSources.forEach((String path, Source source) { +- info.sources.remove(path); +- changeSet.removedSource(source); +- }); +- callbacks.applyChangesToContext(info.folder, changeSet); +- } +- // add previously excluded sources +- for (ContextInfo info in rootInfo.descendants) { +- ChangeSet changeSet =3D new ChangeSet(); +- _addPreviouslyExcludedSources( +- info, changeSet, info.folder, oldExcludedPaths); +- callbacks.applyChangesToContext(info.folder, changeSet); +- } +- } +- +- /** +- * Recursively adds all Dart and HTML files to the [changeSet]. +- */ +- void _addPreviouslyExcludedSources(ContextInfo info, ChangeSet changeSe= t, +- Folder folder, List oldExcludedPaths) { +- if (info.excludesResource(folder)) { +- return; +- } +- List children; +- try { +- children =3D folder.getChildren(); +- } on FileSystemException { +- // The folder no longer exists, or cannot be read, to there's nothi= ng to +- // do. +- return; +- } +- for (Resource child in children) { +- String path =3D child.path; +- // Path is being ignored. +- if (info.ignored(path)) { +- continue; +- } +- // add files, recurse into folders +- if (child is File) { +- // ignore if should not be analyzed at all +- if (!_shouldFileBeAnalyzed(child)) { +- continue; +- } +- // ignore if was not excluded +- bool wasExcluded =3D _isExcludedBy(oldExcludedPaths, path) && +- !_isExcludedBy(excludedPaths, path); +- if (!wasExcluded) { +- continue; +- } +- // do add the file +- Source source =3D createSourceInContext(info.analysisDriver, chil= d); +- changeSet.addedSource(source); +- info.sources[path] =3D source; +- } else if (child is Folder) { +- if (child.shortName =3D=3D PACKAGES_NAME) { +- continue; +- } +- _addPreviouslyExcludedSources(info, changeSet, child, oldExcluded= Paths); +- } +- } +- } +- +- /** +- * Recursively adds all Dart and HTML files to the [changeSet]. +- */ +- void _addSourceFiles(ChangeSet changeSet, Folder folder, ContextInfo in= fo) { +- if (info.excludesResource(folder) || +- folder.shortName.startsWith('.') || +- _isInTopLevelDocDir(info.folder.path, folder.path)) { +- return; +- } +- List children =3D null; +- try { +- children =3D folder.getChildren(); +- } on FileSystemException { +- // The directory either doesn't exist or cannot be read. Either way= , there +- // are no children that need to be added. +- return; +- } +- for (Resource child in children) { +- String path =3D child.path; +- // ignore excluded files or folders +- if (_isExcluded(path) || info.excludes(path) || info.ignored(path))= { +- continue; +- } +- // add files, recurse into folders +- if (child is File) { +- if (_shouldFileBeAnalyzed(child)) { +- Source source =3D createSourceInContext(info.analysisDriver, ch= ild); +- changeSet.addedSource(source); +- info.sources[path] =3D source; +- } +- } else if (child is Folder) { +- String shortName =3D child.shortName; +- if (shortName =3D=3D PACKAGES_NAME) { +- continue; +- } +- _addSourceFiles(changeSet, child, info); +- } +- } +- } +- +- /** +- * Use the given analysis [driver] to analyze the content of the analys= is +- * options file at the given [path]. +- */ +- void _analyzeAnalysisOptionsFile(AnalysisDriver driver, String path) { +- String content =3D driver.fsState.getFileForPath(path).content; +- List errors =3D +- GenerateOptionsErrorsTask.analyzeAnalysisOptions( +- resourceProvider.getFile(path).createSource(), +- content, +- driver.sourceFactory); +- AnalyzerConverter converter =3D new AnalyzerConverter(); +- LineInfo lineInfo =3D _computeLineInfo(content); +- callbacks.notificationManager.recordAnalysisErrors( +- NotificationManager.serverId, +- path, +- converter.convertAnalysisErrors(errors, +- lineInfo: lineInfo, options: driver.analysisOptions)); +- } +- +- void _checkForAnalysisOptionsUpdate( +- String path, ContextInfo info, ChangeType changeType) { +- if (AnalysisEngine.isAnalysisOptionsFileName(path, pathContext)) { +- AnalysisDriver driver =3D info.analysisDriver; +- if (driver =3D=3D null) { +- // I suspect that this happens as a result of a race condition: s= erver +- // has determined that the file (at [path]) is in a context, but = hasn't +- // yet created a driver for that context. +- return; +- } +- String contextRoot =3D info.folder.path; +- ContextBuilder builder =3D +- callbacks.createContextBuilder(info.folder, defaultContextOptio= ns); +- AnalysisOptions options =3D builder.getAnalysisOptions(contextRoot, +- contextRoot: driver.contextRoot); +- SourceFactory factory =3D builder.createSourceFactory(contextRoot, = options); +- driver.configure(analysisOptions: options, sourceFactory: factory); +- // TODO(brianwilkerson) Set exclusion patterns. +- _analyzeAnalysisOptionsFile(driver, path); +- } +- } +- +- void _checkForPackagespecUpdate( +- String path, ContextInfo info, Folder folder) { +- // Check to see if this is the .packages file for this context and if= so, +- // update the context's source factory. +- if (absolutePathContext.basename(path) =3D=3D PACKAGE_SPEC_NAME) { +- String contextRoot =3D info.folder.path; +- ContextBuilder builder =3D +- callbacks.createContextBuilder(info.folder, defaultContextOptio= ns); +- AnalysisDriver driver =3D info.analysisDriver; +- if (driver !=3D null) { +- AnalysisOptions options =3D builder.getAnalysisOptions(contextRoo= t, +- contextRoot: driver.contextRoot); +- SourceFactory factory =3D +- builder.createSourceFactory(contextRoot, options); +- driver.configure(analysisOptions: options, sourceFactory: factory= ); +- } +- } +- } +- +- /** +- * Compute the set of files that are being flushed, this is defined as +- * the set of sources in the removed context (context.sources), that are +- * orphaned by this context being removed (no other context includes th= is +- * file.) +- */ +- List _computeFlushedFiles(ContextInfo info) { +- Set flushedFiles =3D info.analysisDriver.addedFiles.toSet(); +- for (ContextInfo contextInfo in rootInfo.descendants) { +- AnalysisDriver other =3D contextInfo.analysisDriver; +- if (other !=3D info.analysisDriver) { +- flushedFiles.removeAll(other.addedFiles); +- } +- } +- return flushedFiles.toList(growable: false); +- } +- +- /** +- * Compute the appropriate [FolderDisposition] for [folder]. Use +- * [addDependency] to indicate which files needed to be consulted in or= der to +- * figure out the [FolderDisposition]; these dependencies will be watch= ed in +- * order to determine when it is necessary to call this function again. +- * +- * TODO(paulberry): use [addDependency] for tracking all folder disposi= tion +- * dependencies (currently we only use it to track "pub list" dependenc= ies). +- */ +- FolderDisposition _computeFolderDisposition( +- Folder folder, void addDependency(String path), File packagespecFil= e) { +- String packageRoot =3D normalizedPackageRoots[folder.path]; +- if (packageRoot !=3D null) { +- // TODO(paulberry): We shouldn't be using JavaFile here because it +- // makes the code untestable (see dartbug.com/23909). +- JavaFile packagesDirOrFile =3D new JavaFile(packageRoot); +- Map> packageMap =3D new Map>(); +- if (packagesDirOrFile.isDirectory()) { +- for (JavaFile file in packagesDirOrFile.listFiles()) { +- // Ensure symlinks in packages directory are canonicalized +- // to prevent 'type X cannot be assigned to type X' warnings +- String path; +- try { +- path =3D file.getCanonicalPath(); +- } catch (e, s) { +- // Ignore packages that do not exist +- _instrumentationService.logException(e, s); +- continue; +- } +- Resource res =3D resourceProvider.getResource(path); +- if (res is Folder) { +- packageMap[file.getName()] =3D [res]; +- } +- } +- return new PackageMapDisposition(packageMap, packageRoot: package= Root); +- } else if (packagesDirOrFile.isFile()) { +- File packageSpecFile =3D resourceProvider.getFile(packageRoot); +- Packages packages =3D _readPackagespec(packageSpecFile); +- if (packages !=3D null) { +- return new PackagesFileDisposition(packages); +- } +- } +- // The package root does not exist (or is not a folder). Since +- // [setRoots] ignores any package roots that don't exist (or aren't +- // folders), the only way we should be able to get here is due to a= race +- // condition. In any case, the package root folder is gone, so we = can't +- // resolve packages. +- return new NoPackageFolderDisposition(packageRoot: packageRoot); +- } else { +- PackageMapInfo packageMapInfo; +- callbacks.computingPackageMap(true); +- try { +- // Try .packages first. +- if (absolutePathContext.basename(packagespecFile.path) =3D=3D +- PACKAGE_SPEC_NAME) { +- Packages packages =3D _readPackagespec(packagespecFile); +- return new PackagesFileDisposition(packages); +- } +- if (packageResolverProvider !=3D null) { +- UriResolver resolver =3D packageResolverProvider(folder); +- if (resolver !=3D null) { +- return new CustomPackageResolverDisposition(resolver); +- } +- } +- +- packageMapInfo =3D _packageMapProvider.computePackageMap(folder); +- } finally { +- callbacks.computingPackageMap(false); +- } +- for (String dependencyPath in packageMapInfo.dependencies) { +- addDependency(dependencyPath); +- } +- if (packageMapInfo.packageMap =3D=3D null) { +- return new NoPackageFolderDisposition(); +- } +- return new PackageMapDisposition(packageMapInfo.packageMap); +- } +- } +- +- /** +- * Compute line information for the given [content]. +- */ +- LineInfo _computeLineInfo(String content) { +- List lineStarts =3D StringUtilities.computeLineStarts(content); +- return new LineInfo(lineStarts); +- } +- +- /** +- * Create an object that can be used to find and read the analysis opti= ons +- * file for code being analyzed using the given [packages]. +- */ +- AnalysisOptionsProvider _createAnalysisOptionsProvider(Packages package= s) { +- Map> packageMap =3D +- new ContextBuilder(resourceProvider, null, null) +- .convertPackagesToMap(packages); +- List resolvers =3D [ +- new ResourceUriResolver(resourceProvider), +- new PackageMapUriResolver(resourceProvider, packageMap), +- ]; +- SourceFactory sourceFactory =3D +- new SourceFactory(resolvers, packages, resourceProvider); +- return new AnalysisOptionsProvider(sourceFactory); +- } +- +- /** +- * Create a new empty context associated with [folder], having parent +- * [parent] and using [packagesFile] to resolve package URI's. +- */ +- ContextInfo _createContext(ContextInfo parent, Folder folder, +- List excludedPaths, File packagesFile) { +- List dependencies =3D []; +- FolderDisposition disposition =3D +- _computeFolderDisposition(folder, dependencies.add, packagesFile); +- ContextInfo info =3D new ContextInfo(this, parent, folder, packagesFi= le, +- normalizedPackageRoots[folder.path], disposition); +- +- File optionsFile =3D null; +- Map optionMap =3D null; +- try { +- AnalysisOptionsProvider provider =3D +- _createAnalysisOptionsProvider(disposition.packages); +- optionsFile =3D provider.getOptionsFile(info.folder, crawlUp: true); +- if (optionsFile !=3D null) { +- optionMap =3D provider.getOptionsFromFile(optionsFile); +- } +- } catch (_) { +- // Parse errors are reported elsewhere. +- } +- AnalysisOptions options =3D +- new AnalysisOptionsImpl.from(defaultContextOptions); +- applyToAnalysisOptions(options, optionMap); +- +- info.setDependencies(dependencies); +- String includedPath =3D folder.path; +- List containedExcludedPaths =3D excludedPaths +- .where((String excludedPath) =3D> +- pathContext.isWithin(includedPath, excludedPath)) +- .toList(); +- processOptionsForDriver(info, options, optionMap); +- ContextRoot contextRoot =3D +- new ContextRoot(folder.path, containedExcludedPaths); +- if (optionsFile !=3D null) { +- contextRoot.optionsFilePath =3D optionsFile.path; +- } +- info.analysisDriver =3D +- callbacks.addAnalysisDriver(folder, contextRoot, options); +- if (optionsFile !=3D null) { +- _analyzeAnalysisOptionsFile(info.analysisDriver, optionsFile.path); +- } +- return info; +- } +- +- /** +- * Potentially create a new context associated with the given [folder]. +- * +- * If there are subfolders with 'pubspec.yaml' files, separate contexts= are +- * created for them and excluded from the context associated with the +- * [folder]. +- * +- * If [withPackageSpecOnly] is `true`, a context will be created only i= f there +- * is a 'pubspec.yaml' or '.packages' file in the [folder]. +- * +- * [parent] should be the parent of any contexts that are created. +- */ +- void _createContexts(ContextInfo parent, Folder folder, +- List excludedPaths, bool withPackageSpecOnly) { +- if (_isExcluded(folder.path) || +- folder.shortName.startsWith('.') || +- folder.shortName =3D=3D 'packages') { +- return; +- } +- // Decide whether a context needs to be created for [folder] here, an= d if +- // so, create it. +- File packageSpec =3D _findPackageSpecFile(folder); +- bool createContext =3D packageSpec.exists || !withPackageSpecOnly; +- if (withPackageSpecOnly && +- packageSpec.exists && +- parent !=3D null && +- parent.ignored(packageSpec.path)) { +- // Don't create a context if the package spec is required and ignor= ed. +- createContext =3D false; +- } +- if (createContext) { +- parent =3D _createContext(parent, folder, excludedPaths, packageSpe= c); +- } +- +- // Try to find subfolders with pubspecs or .packages files. +- try { +- for (Resource child in folder.getChildren()) { +- if (child is Folder) { +- if (!parent.ignored(child.path)) { +- _createContexts(parent, child, excludedPaths, true); +- } +- } +- } +- } on FileSystemException { +- // The directory either doesn't exist or cannot be read. Either way= , there +- // are no subfolders that need to be added. +- } +- +- if (createContext) { +- // Now that the child contexts have been created, add the sources t= hat +- // don't belong to the children. +- ChangeSet changeSet =3D new ChangeSet(); +- _addSourceFiles(changeSet, folder, parent); +- callbacks.applyChangesToContext(folder, changeSet); +- } +- } +- +- /** +- * Set up a [SourceFactory] that resolves packages as appropriate for t= he +- * given [folder]. +- */ +- SourceFactory _createSourceFactory(AnalysisOptions options, Folder fold= er) { +- ContextBuilder builder =3D callbacks.createContextBuilder(folder, opt= ions); +- return builder.createSourceFactory(folder.path, options); +- } +- +- /** +- * Clean up and destroy the context associated with the given folder. +- */ +- void _destroyContext(ContextInfo info) { +- changeSubscriptions.remove(info.folder)?.cancel(); +- callbacks.removeContext(info.folder, _computeFlushedFiles(info)); +- bool wasRemoved =3D info.parent.children.remove(info); +- assert(wasRemoved); +- } +- +- /** +- * Extract a new [packagespecFile]-based context from [oldInfo]. +- */ +- void _extractContext(ContextInfo oldInfo, File packagespecFile) { +- Folder newFolder =3D packagespecFile.parent; +- ContextInfo newInfo =3D +- _createContext(oldInfo, newFolder, excludedPaths, packagespecFile= ); +- // prepare sources to extract +- Map extractedSources =3D new HashMap(= ); +- oldInfo.sources.forEach((path, source) { +- if (newFolder.contains(path)) { +- extractedSources[path] =3D source; +- } +- }); +- // update new context +- { +- ChangeSet changeSet =3D new ChangeSet(); +- extractedSources.forEach((path, source) { +- newInfo.sources[path] =3D source; +- changeSet.addedSource(source); +- }); +- callbacks.applyChangesToContext(newFolder, changeSet); +- } +- // update old context +- { +- ChangeSet changeSet =3D new ChangeSet(); +- extractedSources.forEach((path, source) { +- oldInfo.sources.remove(path); +- changeSet.removedSource(source); +- }); +- callbacks.applyChangesToContext(oldInfo.folder, changeSet); +- } +- // TODO(paulberry): every context that was previously a child of oldI= nfo is +- // is still a child of oldInfo. This is wrong--some of them ought to= be +- // adopted by newInfo now. +- } +- +- /** +- * Find the file that should be used to determine whether a context nee= ds to +- * be created here--this is either the ".packages" file or the "pubspec= .yaml" +- * file. +- */ +- File _findPackageSpecFile(Folder folder) { +- // Decide whether a context needs to be created for [folder] here, an= d if +- // so, create it. +- File packageSpec; +- +- // Start by looking for .packages. +- packageSpec =3D folder.getChild(PACKAGE_SPEC_NAME); +- +- // Fall back to looking for a pubspec. +- if (packageSpec =3D=3D null || !packageSpec.exists) { +- packageSpec =3D folder.getChild(PUBSPEC_NAME); +- } +- return packageSpec; +- } +- +- /// Get analysis options inherited from an `_embedder.yaml` (deprecated) +- /// and/or a package specified configuration. If more than one +- /// `_embedder.yaml` is associated with the given context, the embedder= is +- /// skipped. +- /// +- /// Returns null if there are no embedded/configured options. +- Map _getEmbeddedOptions(ContextInfo info) { +- Map embeddedOptions =3D null; +- EmbedderYamlLocator locator =3D +- info.disposition.getEmbedderLocator(resourceProvider); +- Iterable maps =3D locator.embedderYamls.values; +- if (maps.length =3D=3D 1) { +- embeddedOptions =3D maps.first; +- } +- return embeddedOptions; +- } +- +- /** +- * Return the [ContextInfo] for the "innermost" context whose associated +- * folder is or contains the given path. ("innermost" refers to the ne= sting +- * of contexts, so if there is a context for path /foo and a context for +- * path /foo/bar, then the innermost context containing /foo/bar/baz.da= rt is +- * the context for /foo/bar.) +- * +- * If no context contains the given path, `null` is returned. +- */ +- ContextInfo _getInnermostContextInfoFor(String path) { +- ContextInfo info =3D rootInfo.findChildInfoFor(path); +- if (info =3D=3D null) { +- return null; +- } +- while (true) { +- ContextInfo childInfo =3D info.findChildInfoFor(path); +- if (childInfo =3D=3D null) { +- return info; +- } +- info =3D childInfo; +- } +- } +- +- /** +- * Return the parent for a new [ContextInfo] with the given [path] fold= er. +- */ +- ContextInfo _getParentForNewContext(String path) { +- ContextInfo parent =3D _getInnermostContextInfoFor(path); +- if (parent !=3D null) { +- return parent; +- } +- return rootInfo; +- } +- +- void _handleWatchEvent(WatchEvent event) { +- callbacks.broadcastWatchEvent(event); +- _handleWatchEventImpl(event); +- callbacks.afterWatchEvent(event); +- } +- +- void _handleWatchEventImpl(WatchEvent event) { +- // Figure out which context this event applies to. +- // TODO(brianwilkerson) If a file is explicitly included in one conte= xt +- // but implicitly referenced in another context, we will only send a +- // changeSet to the context that explicitly includes the file (because +- // that's the only context that's watching the file). +- String path =3D event.path; +- ChangeType type =3D event.type; +- ContextInfo info =3D _getInnermostContextInfoFor(path); +- if (info =3D=3D null) { +- // This event doesn't apply to any context. This could happen due = to a +- // race condition (e.g. a context was removed while one of its even= ts was +- // in the event loop). The event is inapplicable now, so just igno= re it. +- return; +- } +- _instrumentationService.logWatchEvent( +- info.folder.path, path, type.toString()); +- // First handle changes that affect folderDisposition (since these ne= ed to +- // be processed regardless of whether they are part of an excluded/ig= nored +- // path). +- if (info.hasDependency(path)) { +- _recomputeFolderDisposition(info); +- } +- // maybe excluded globally +- if (_isExcluded(path) || +- _isContainedInDotFolder(info.folder.path, path) || +- _isInPackagesDir(info.folder.path, path) || +- _isInTopLevelDocDir(info.folder.path, path)) { +- return; +- } +- // maybe excluded from the context, so other context will handle it +- if (info.excludes(path)) { +- return; +- } +- if (info.ignored(path)) { +- return; +- } +- // handle the change +- switch (type) { +- case ChangeType.ADD: +- Resource resource =3D resourceProvider.getResource(path); +- +- String directoryPath =3D absolutePathContext.dirname(path); +- +- // Check to see if we need to create a new context. +- if (info.isTopLevel) { +- // Only create a new context if this is not the same directory +- // described by our info object. +- if (info.folder.path !=3D directoryPath) { +- if (_isPubspec(path)) { +- // Check for a sibling .packages file. +- if (!resourceProvider +- .getFile(absolutePathContext.append( +- directoryPath, PACKAGE_SPEC_NAME)) +- .exists) { +- _extractContext(info, resource); +- return; +- } +- } +- if (_isPackagespec(path)) { +- // Check for a sibling pubspec.yaml file. +- if (!resourceProvider +- .getFile( +- absolutePathContext.append(directoryPath, PUBSPEC_N= AME)) +- .exists) { +- _extractContext(info, resource); +- return; +- } +- } +- } +- } +- +- // If the file went away and was replaced by a folder before we +- // had a chance to process the event, resource might be a Folder.= In +- // that case don't add it. +- if (resource is File) { +- File file =3D resource; +- if (_shouldFileBeAnalyzed(file)) { +- info.analysisDriver.addFile(path); +- } +- } +- break; +- case ChangeType.REMOVE: +- +- // If package spec info is removed, check to see if we can merge = contexts. +- // Note that it's important to verify that there is NEITHER a .pa= ckages nor a +- // lingering pubspec.yaml before merging. +- if (!info.isTopLevel) { +- String directoryPath =3D absolutePathContext.dirname(path); +- +- // Only merge if this is the same directory described by our in= fo object. +- if (info.folder.path =3D=3D directoryPath) { +- if (_isPubspec(path)) { +- // Check for a sibling .packages file. +- if (!resourceProvider +- .getFile(absolutePathContext.append( +- directoryPath, PACKAGE_SPEC_NAME)) +- .exists) { +- _mergeContext(info); +- return; +- } +- } +- if (_isPackagespec(path)) { +- // Check for a sibling pubspec.yaml file. +- if (!resourceProvider +- .getFile( +- absolutePathContext.append(directoryPath, PUBSPEC_N= AME)) +- .exists) { +- _mergeContext(info); +- return; +- } +- } +- } +- } +- +- callbacks.applyFileRemoved(info.analysisDriver, path); +- break; +- case ChangeType.MODIFY: +- for (AnalysisDriver driver in driverMap.values) { +- driver.changeFile(path); +- } +- break; +- } +- _checkForPackagespecUpdate(path, info, info.folder); +- _checkForAnalysisOptionsUpdate(path, info, type); +- } +- +- /** +- * Determine whether the given [path], when interpreted relative to the +- * context root [root], contains a folder whose name starts with '.'. +- */ +- bool _isContainedInDotFolder(String root, String path) { +- String pathDir =3D absolutePathContext.dirname(path); +- String suffixPath =3D absolutePathContext.suffix(root, pathDir); +- if (suffixPath =3D=3D null) { +- return false; +- } +- for (String pathComponent in absolutePathContext.split(suffixPath)) { +- if (pathComponent.startsWith('.') && +- pathComponent !=3D '.' && +- pathComponent !=3D '..') { +- return true; +- } +- } +- return false; +- } +- +- /** +- * Returns `true` if the given [path] is excluded by [excludedPaths]. +- */ +- bool _isExcluded(String path) =3D> _isExcludedBy(excludedPaths, path); +- +- /** +- * Returns `true` if the given [path] is excluded by [excludedPaths]. +- */ +- bool _isExcludedBy(List excludedPaths, String path) { +- return excludedPaths.any((excludedPath) { +- if (absolutePathContext.isWithin(excludedPath, path)) { +- return true; +- } +- return path =3D=3D excludedPath; +- }); +- } +- +- /** +- * Determine whether the given [path], when interpreted relative to the +- * context root [root], contains a 'packages' folder. +- */ +- bool _isInPackagesDir(String root, String path) { +- String suffixPath =3D absolutePathContext.suffix(root, path); +- if (suffixPath =3D=3D null) { +- return false; +- } +- List pathParts =3D absolutePathContext.split(suffixPath); +- return pathParts.contains(PACKAGES_NAME); +- } +- +- /** +- * Determine whether the given [path] is in the direct 'doc' folder of = the +- * context root [root]. +- */ +- bool _isInTopLevelDocDir(String root, String path) { +- String suffixPath =3D absolutePathContext.suffix(root, path); +- if (suffixPath =3D=3D null) { +- return false; +- } +- return suffixPath =3D=3D DOC_DIR_NAME || +- suffixPath.startsWith(DOC_DIR_NAME + absolutePathContext.separato= r); +- } +- +- bool _isPackagespec(String path) =3D> +- absolutePathContext.basename(path) =3D=3D PACKAGE_SPEC_NAME; +- +- bool _isPubspec(String path) =3D> +- absolutePathContext.basename(path) =3D=3D PUBSPEC_NAME; +- +- /** +- * Merges [info] context into its parent. +- */ +- void _mergeContext(ContextInfo info) { +- // destroy the context +- _destroyContext(info); +- // add files to the parent context +- ContextInfo parentInfo =3D info.parent; +- if (parentInfo !=3D null) { +- parentInfo.children.remove(info); +- ChangeSet changeSet =3D new ChangeSet(); +- info.sources.forEach((path, source) { +- parentInfo.sources[path] =3D source; +- changeSet.addedSource(source); +- }); +- callbacks.applyChangesToContext(parentInfo.folder, changeSet); +- } +- } +- +- Packages _readPackagespec(File specFile) { +- try { +- String contents =3D specFile.readAsStringSync(); +- Map map =3D +- pkgfile.parse(UTF8.encode(contents), new Uri.file(specFile.path= )); +- return new MapPackages(map); +- } catch (_) { +- //TODO(pquitslund): consider creating an error for the spec file. +- return null; +- } +- } +- +- /** +- * Recompute the [FolderDisposition] for the context described by [info= ], +- * and update the client appropriately. +- */ +- void _recomputeFolderDisposition(ContextInfo info) { +- // TODO(paulberry): when computePackageMap is changed into an +- // asynchronous API call, we'll want to suspend analysis for this con= text +- // while we're rerunning "pub list", since any analysis we complete w= hile +- // "pub list" is in progress is just going to get thrown away anyhow. +- List dependencies =3D []; +- info.setDependencies(dependencies); +- _updateContextPackageUriResolver(info.folder); +- } +- +- /** +- * Return `true` if the given [file] should be analyzed. +- */ +- bool _shouldFileBeAnalyzed(File file) { +- for (Glob glob in analyzedFilesGlobs) { +- if (glob.matches(file.path)) { +- // Emacs creates dummy links to track the fact that a file is ope= n for +- // editing and has unsaved changes (e.g. having unsaved changes to +- // 'foo.dart' causes a link '.#foo.dart' to be created, which poi= nts to +- // the non-existent file 'username@hostname.pid'. To avoid these = dummy +- // links causing the analyzer to thrash, just ignore links to +- // non-existent files. +- return file.exists; +- } +- } +- return false; +- } +- +- /** +- * If the given [object] is a map, and all of the keys in the map are s= trings, +- * return a map containing the same mappings. Otherwise, return `null`. +- */ +- Map _toStringMap(Object object) { +- if (object is Map) { +- Map stringMap =3D new HashMap(); +- for (var key in object.keys) { +- if (key is String) { +- stringMap[key] =3D object[key]; +- } else { +- return null; +- } +- } +- return stringMap; +- } +- return null; +- } +- +- void _updateContextPackageUriResolver(Folder contextFolder) { +- ContextInfo info =3D getContextInfoFor(contextFolder); +- AnalysisDriver driver =3D info.analysisDriver; +- SourceFactory sourceFactory =3D +- _createSourceFactory(driver.analysisOptions, contextFolder); +- driver.configure(sourceFactory: sourceFactory); +- } +- +- /** +- * Create and return a source representing the given [file] within the = given +- * [driver]. +- */ +- static Source createSourceInContext(AnalysisDriver driver, File file) { +- // TODO(brianwilkerson) Optimize this, by allowing support for source +- // factories to restore URI's from a file path rather than a source. +- Source source =3D file.createSource(); +- if (driver =3D=3D null) { +- return source; +- } +- Uri uri =3D driver.sourceFactory.restoreUri(source); +- return file.createSource(uri); +- } +-} +- +-/** +- * Concrete [FolderDisposition] object indicating that the context for a = given +- * folder should resolve package URIs using a custom URI resolver. +- */ +-class CustomPackageResolverDisposition extends FolderDisposition { +- /** +- * The [UriResolver] that should be used to resolve package URIs. +- */ +- UriResolver resolver; +- +- CustomPackageResolverDisposition(this.resolver); +- +- @override +- String get packageRoot =3D> null; +- +- @override +- Packages get packages =3D> null; +- +- @override +- Iterable createPackageUriResolvers( +- ResourceProvider resourceProvider) =3D> +- [resolver]; +- +- @override +- EmbedderYamlLocator getEmbedderLocator(ResourceProvider resourceProvide= r) =3D> +- new EmbedderYamlLocator(null); +- +- @override +- SdkExtensionFinder getSdkExtensionFinder(ResourceProvider resourceProvi= der) =3D> +- new SdkExtensionFinder(null); +-} +- +-/** +- * An instance of the class [FolderDisposition] represents the information +- * gathered by the [ContextManagerImpl] to determine how to create an ana= lysis +- * driver for a given folder. +- * +- * Note: [ContextManagerImpl] may use equality testing and hash codes to +- * determine when two folders should share the same context, so derived c= lasses +- * may need to override operator=3D=3D and hashCode() if object identity = is +- * insufficient. +- * +- * TODO(paulberry): consider adding a flag to indicate that it is not nec= essary +- * to recurse into the given folder looking for additional contexts to cr= eate +- * or files to analyze (this could help avoid unnecessarily weighing down= the +- * system with file watchers). +- */ +-abstract class FolderDisposition { +- /** +- * If this [FolderDisposition] was created based on a package root +- * folder, the absolute path to that folder. Otherwise `null`. +- */ +- String get packageRoot; +- +- /** +- * If contexts governed by this [FolderDisposition] should resolve pack= ages +- * using the ".packages" file mechanism (DEP 5), retrieve the [Packages] +- * object that resulted from parsing the ".packages" file. +- */ +- Packages get packages; +- +- /** +- * Create all the [UriResolver]s which should be used to resolve packag= es in +- * contexts governed by this [FolderDisposition]. +- * +- * [resourceProvider] is provided since it is needed to construct most +- * [UriResolver]s. +- */ +- Iterable createPackageUriResolvers( +- ResourceProvider resourceProvider); +- +- /** +- * Return the locator used to locate the _embedder.yaml file used to co= nfigure +- * the SDK. The [resourceProvider] is used to access the file system in= cases +- * where that is necessary. +- */ +- EmbedderYamlLocator getEmbedderLocator(ResourceProvider resourceProvide= r); +- +- /** +- * Return the extension finder used to locate the `_sdkext` file used t= o add +- * extensions to the SDK. The [resourceProvider] is used to access the = file +- * system in cases where that is necessary. +- */ +- SdkExtensionFinder getSdkExtensionFinder(ResourceProvider resourceProvi= der); +-} +- +-/** +- * Concrete [FolderDisposition] object indicating that the context for a = given +- * folder should not resolve "package:" URIs at all. +- */ +-class NoPackageFolderDisposition extends FolderDisposition { +- @override +- final String packageRoot; +- +- NoPackageFolderDisposition({this.packageRoot}); +- +- @override +- Packages get packages =3D> null; +- +- @override +- Iterable createPackageUriResolvers( +- ResourceProvider resourceProvider) =3D> +- const []; +- +- @override +- EmbedderYamlLocator getEmbedderLocator(ResourceProvider resourceProvide= r) =3D> +- new EmbedderYamlLocator(null); +- +- @override +- SdkExtensionFinder getSdkExtensionFinder(ResourceProvider resourceProvi= der) =3D> +- new SdkExtensionFinder(null); +-} +- +-/** +- * Concrete [FolderDisposition] object indicating that the context for a = given +- * folder should resolve packages using a package map. +- */ +-class PackageMapDisposition extends FolderDisposition { +- final Map> packageMap; +- +- EmbedderYamlLocator _embedderLocator; +- SdkExtensionFinder _sdkExtensionFinder; +- +- @override +- final String packageRoot; +- +- PackageMapDisposition(this.packageMap, {this.packageRoot}); +- +- @override +- Packages get packages =3D> null; +- +- @override +- Iterable createPackageUriResolvers( +- ResourceProvider resourceProvider) =3D> +- [ +- new SdkExtUriResolver(packageMap), +- new PackageMapUriResolver(resourceProvider, packageMap) +- ]; +- +- @override +- EmbedderYamlLocator getEmbedderLocator(ResourceProvider resourceProvide= r) { +- if (_embedderLocator =3D=3D null) { +- _embedderLocator =3D new EmbedderYamlLocator(packageMap); +- } +- return _embedderLocator; +- } +- +- @override +- SdkExtensionFinder getSdkExtensionFinder(ResourceProvider resourceProvi= der) { +- return _sdkExtensionFinder ??=3D new SdkExtensionFinder(packageMap); +- } +-} +- +-/** +- * Concrete [FolderDisposition] object indicating that the context for a = given +- * folder should resolve packages using a ".packages" file. +- */ +-class PackagesFileDisposition extends FolderDisposition { +- @override +- final Packages packages; +- +- Map> packageMap; +- +- EmbedderYamlLocator _embedderLocator; +- SdkExtensionFinder _sdkExtensionFinder; +- +- PackagesFileDisposition(this.packages); +- +- @override +- String get packageRoot =3D> null; +- +- Map> buildPackageMap(ResourceProvider resourceProv= ider) { +- if (packageMap =3D=3D null) { +- packageMap =3D >{}; +- if (packages !=3D null) { +- packages.asMap().forEach((String name, Uri uri) { +- if (uri.scheme =3D=3D 'file' || uri.scheme =3D=3D '' /* unspeci= fied */) { +- var path =3D resourceProvider.pathContext.fromUri(uri); +- packageMap[name] =3D [resourceProvider.getFolder(path= )]; +- } +- }); +- } +- } +- return packageMap; +- } +- +- @override +- Iterable createPackageUriResolvers( +- ResourceProvider resourceProvider) { +- if (packages !=3D null) { +- // Construct package map for the SdkExtUriResolver. +- Map> packageMap =3D buildPackageMap(resourcePr= ovider); +- return [new SdkExtUriResolver(packageMap)]; +- } else { +- return const []; +- } +- } +- +- @override +- EmbedderYamlLocator getEmbedderLocator(ResourceProvider resourceProvide= r) { +- if (_embedderLocator =3D=3D null) { +- _embedderLocator =3D +- new EmbedderYamlLocator(buildPackageMap(resourceProvider)); +- } +- return _embedderLocator; +- } +- +- @override +- SdkExtensionFinder getSdkExtensionFinder(ResourceProvider resourceProvi= der) { +- return _sdkExtensionFinder ??=3D +- new SdkExtensionFinder(buildPackageMap(resourceProvider)); +- } +-} +diff --git a/pkg/analysis_server/lib/src/domain_abstract.dart b/pkg/analys= is_server/lib/src/domain_abstract.dart +deleted file mode 100644 +index 65a2dd41902..00000000000 +--- a/pkg/analysis_server/lib/src/domain_abstract.dart ++++ /dev/null +@@ -1,78 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:math' as math; +- +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart' as p= lugin; +- +-/** +- * An abstract implementation of a request handler. +- */ +-abstract class AbstractRequestHandler implements RequestHandler { +- /** +- * The analysis server that is using this handler to process requests. +- */ +- final AnalysisServer server; +- +- /** +- * Initialize a newly created request handler to be associated with the= given +- * analysis [server]. +- */ +- AbstractRequestHandler(this.server); +- +- /** +- * Given a mapping from plugins to futures that will complete when the = plugin +- * has responded to a request, wait for a finite amount of time for eac= h of +- * the plugins to respond. Return a list of the responses from each of = the +- * plugins. If a plugin fails to return a response, notify the plugin m= anager +- * associated with the server so that non-responsive plugins can be kil= led or +- * restarted. The [timeout] is the maximum amount of time that will be = spent +- * waiting for plugins to respond. +- */ +- Future> waitForResponses( +- Map> futures, +- {plugin.RequestParams requestParameters, +- int timeout: 500}) async { +- // TODO(brianwilkerson) requestParameters might need to be required. +- int endTime =3D new DateTime.now().millisecondsSinceEpoch + timeout; +- List responses =3D []; +- for (PluginInfo pluginInfo in futures.keys) { +- Future future =3D futures[pluginInfo]; +- try { +- int startTime =3D new DateTime.now().millisecondsSinceEpoch; +- plugin.Response response =3D await future.timeout( +- new Duration(milliseconds: math.max(endTime - startTime, 0))); +- if (response.error !=3D null) { +- // TODO(brianwilkerson) Report the error to the plugin manager. +- server.instrumentationService.logPluginError( +- pluginInfo.data, +- response.error.code.name, +- response.error.message, +- response.error.stackTrace); +- } else { +- responses.add(response); +- } +- } on TimeoutException { +- // TODO(brianwilkerson) Report the timeout to the plugin manager. +- server.instrumentationService.logPluginTimeout( +- pluginInfo.data, +- new JsonEncoder() +- .convert(requestParameters?.toRequest('-')?.toJson() ?? {= })); +- } catch (exception, stackTrace) { +- // TODO(brianwilkerson) Report the exception to the plugin manage= r. +- server.instrumentationService +- .logPluginException(pluginInfo.data, exception, stackTrace); +- } +- } +- return responses; +- } +-} +diff --git a/pkg/analysis_server/lib/src/domain_analysis.dart b/pkg/analys= is_server/lib/src/domain_analysis.dart +deleted file mode 100644 +index dc826cc4bc1..00000000000 +--- a/pkg/analysis_server/lib/src/domain_analysis.dart ++++ /dev/null +@@ -1,432 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:core'; +- +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/computer/computer_hover.dart'; +-import 'package:analysis_server/src/computer/imported_elements_computer.d= art'; +-import 'package:analysis_server/src/domain_abstract.dart'; +-import 'package:analysis_server/src/domains/analysis/navigation_dart.dart= '; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/plugin/request_converter.dart'; +-import 'package:analysis_server/src/plugin/result_merger.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart'; +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/engine.dart' as engine; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:analyzer_plugin/src/utilities/navigation/navigation.dart'; +- +-/** +- * Instances of the class [AnalysisDomainHandler] implement a [RequestHan= dler] +- * that handles requests in the `analysis` domain. +- */ +-class AnalysisDomainHandler extends AbstractRequestHandler { +- /** +- * Initialize a newly created handler to handle requests for the given = [server]. +- */ +- AnalysisDomainHandler(AnalysisServer server) : super(server); +- +- /** +- * Implement the `analysis.getErrors` request. +- */ +- Future getErrors(Request request) async { +- String file =3D new AnalysisGetErrorsParams.fromRequest(request).file; +- +- void send(engine.AnalysisOptions analysisOptions, LineInfo lineInfo, +- List errors) { +- if (lineInfo =3D=3D null) { +- server.sendResponse(new Response.getErrorsInvalidFile(request)); +- } else { +- List protocolErrors =3D +- doAnalysisError_listFromEngine(analysisOptions, lineInfo, err= ors); +- server.sendResponse( +- new AnalysisGetErrorsResult(protocolErrors).toResponse(reques= t.id)); +- } +- } +- +- AnalysisResult result =3D await server.getAnalysisResult(file); +- +- if (server.onResultErrorSupplementor !=3D null) { +- if (result !=3D null) { +- await server.onResultErrorSupplementor(file, result.errors); +- } else { +- server.onNoAnalysisResult(file, send); +- return; +- } +- } +- +- send(result?.driver?.analysisOptions, result?.lineInfo, result?.error= s); +- } +- +- /** +- * Implement the `analysis.getHover` request. +- */ +- Future getHover(Request request) async { +- var params =3D new AnalysisGetHoverParams.fromRequest(request); +- +- // Prepare the resolved units. +- AnalysisResult result =3D await server.getAnalysisResult(params.file); +- CompilationUnit unit =3D result?.unit; +- +- // Prepare the hovers. +- List hovers =3D []; +- if (unit !=3D null) { +- HoverInformation hoverInformation =3D +- new DartUnitHoverComputer(unit, params.offset).compute(); +- if (hoverInformation !=3D null) { +- hovers.add(hoverInformation); +- } +- } +- +- // Send the response. +- server.sendResponse( +- new AnalysisGetHoverResult(hovers).toResponse(request.id)); +- } +- +- /** +- * Implement the `analysis.getImportedElements` request. +- */ +- Future getImportedElements(Request request) async { +- AnalysisGetImportedElementsParams params =3D +- new AnalysisGetImportedElementsParams.fromRequest(request); +- // +- // Prepare the resolved unit. +- // +- AnalysisResult result =3D await server.getAnalysisResult(params.file); +- if (result =3D=3D null) { +- server.sendResponse(new Response.getImportedElementsInvalidFile(req= uest)); +- } +- // +- // Compute the list of imported elements. +- // +- List elements =3D +- new ImportedElementsComputer(result.unit, params.offset, params.l= ength) +- .compute(); +- // +- // Send the response. +- // +- server.sendResponse( +- new AnalysisGetImportedElementsResult(elements).toResponse(reques= t.id)); +- } +- +- /** +- * Implement the `analysis.getLibraryDependencies` request. +- */ +- Response getLibraryDependencies(Request request) { +- return new Response.unsupportedFeature(request.id, +- 'Please contact the Dart analyzer team if you need this request.'= ); +-// server.onAnalysisComplete.then((_) { +-// LibraryDependencyCollector collector =3D +-// new LibraryDependencyCollector(server.analysisContexts); +-// Set libraries =3D collector.collectLibraryDependencies(); +-// Map>> packageMap =3D +-// collector.calculatePackageMap(server.folderMap); +-// server.sendResponse(new AnalysisGetLibraryDependenciesResult( +-// libraries.toList(growable: false), packageMap) +-// .toResponse(request.id)); +-// }).catchError((error, st) { +-// server.sendResponse(new Response.serverError(request, error, st)); +-// }); +-// // delay response +-// return Response.DELAYED_RESPONSE; +- } +- +- /** +- * Implement the `analysis.getNavigation` request. +- */ +- Future getNavigation(Request request) async { +- var params =3D new AnalysisGetNavigationParams.fromRequest(request); +- String file =3D params.file; +- int offset =3D params.offset; +- int length =3D params.length; +- +- AnalysisDriver driver =3D server.getAnalysisDriver(file); +- if (driver =3D=3D null) { +- server.sendResponse(new Response.getNavigationInvalidFile(request)); +- } else { +- // +- // Allow plugins to start computing navigation data. +- // +- plugin.AnalysisGetNavigationParams requestParams =3D +- new plugin.AnalysisGetNavigationParams(file, offset, length); +- Map> pluginFutures =3D server +- .pluginManager +- .broadcastRequest(requestParams, contextRoot: driver.contextRoo= t); +- // +- // Compute navigation data generated by server. +- // +- List allResults =3D []; +- AnalysisResult result =3D await server.getAnalysisResult(file); +- CompilationUnit unit =3D result?.unit; +- if (unit !=3D null && result.exists) { +- NavigationCollectorImpl collector =3D new NavigationCollectorImpl= (); +- computeDartNavigation(collector, unit, offset, length); +- collector.createRegions(); +- allResults.add(new AnalysisNavigationParams( +- file, collector.regions, collector.targets, collector.files)); +- } +- // +- // Add the navigation data produced by plugins to the server-genera= ted +- // navigation data. +- // +- if (pluginFutures !=3D null) { +- List responses =3D await waitForResponses(plugin= Futures, +- requestParameters: requestParams); +- for (plugin.Response response in responses) { +- plugin.AnalysisGetNavigationResult result =3D +- new plugin.AnalysisGetNavigationResult.fromResponse(respons= e); +- allResults.add(new AnalysisNavigationParams( +- file, result.regions, result.targets, result.files)); +- } +- } +- // +- // Return the result. +- // +- ResultMerger merger =3D new ResultMerger(); +- AnalysisNavigationParams mergedResults =3D +- merger.mergeNavigation(allResults); +- if (mergedResults =3D=3D null) { +- server.sendResponse(new AnalysisGetNavigationResult( +- [], [], []) +- .toResponse(request.id)); +- } else { +- server.sendResponse(new AnalysisGetNavigationResult(mergedResults= .files, +- mergedResults.targets, mergedResults.regions) +- .toResponse(request.id)); +- } +- } +- } +- +- /** +- * Implement the `analysis.getReachableSources` request. +- */ +- Response getReachableSources(Request request) { +- return new Response.unsupportedFeature(request.id, +- 'Please contact the Dart analyzer team if you need this request.'= ); +-// AnalysisGetReachableSourcesParams params =3D +-// new AnalysisGetReachableSourcesParams.fromRequest(request); +-// ContextSourcePair pair =3D server.getContextSourcePair(params.file); +-// if (pair.context =3D=3D null || pair.source =3D=3D null) { +-// return new Response.getReachableSourcesInvalidFile(request); +-// } +-// Map> sources =3D +-// new ReachableSourceCollector(pair.source, pair.context) +-// .collectSources(); +-// return new AnalysisGetReachableSourcesResult(sources) +-// .toResponse(request.id); +- } +- +- @override +- Response handleRequest(Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D ANALYSIS_REQUEST_GET_ERRORS) { +- getErrors(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D ANALYSIS_REQUEST_GET_HOVER) { +- getHover(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D ANALYSIS_REQUEST_GET_IMPORTED_ELEMENT= S) { +- getImportedElements(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D ANALYSIS_REQUEST_GET_LIBRARY_DEPENDEN= CIES) { +- return getLibraryDependencies(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_GET_NAVIGATION) { +- getNavigation(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D ANALYSIS_REQUEST_GET_REACHABLE_SOURCE= S) { +- return getReachableSources(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_REANALYZE) { +- return reanalyze(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS) { +- return setAnalysisRoots(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_SET_GENERAL_SUBSCRIP= TIONS) { +- return setGeneralSubscriptions(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_SET_PRIORITY_FILES) { +- return setPriorityFiles(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_SET_SUBSCRIPTIONS) { +- return setSubscriptions(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_UPDATE_CONTENT) { +- return updateContent(request); +- } else if (requestName =3D=3D ANALYSIS_REQUEST_UPDATE_OPTIONS) { +- return updateOptions(request); +- } +- } on RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +- +- /** +- * Implement the 'analysis.reanalyze' request. +- */ +- Response reanalyze(Request request) { +- server.options.analytics?.sendEvent('analysis', 'reanalyze'); +- +- AnalysisReanalyzeParams params =3D +- new AnalysisReanalyzeParams.fromRequest(request); +- List roots =3D params.roots; +- if (roots =3D=3D null || roots.isNotEmpty) { +- List includedPaths =3D server.contextManager.includedPaths; +- List rootResources =3D null; +- if (roots !=3D null) { +- rootResources =3D []; +- for (String rootPath in roots) { +- if (!includedPaths.contains(rootPath)) { +- return new Response.invalidAnalysisRoot(request, rootPath); +- } +- rootResources.add(server.resourceProvider.getResource(rootPath)= ); +- } +- } +- server.reanalyze(rootResources); +- } +- // +- // Restart all of the plugins. This is an async operation that will h= appen +- // in the background. +- // +- server.pluginManager.restartPlugins(); +- // +- // Send the response. +- // +- return new AnalysisReanalyzeResult().toResponse(request.id); +- } +- +- /** +- * Implement the 'analysis.setAnalysisRoots' request. +- */ +- Response setAnalysisRoots(Request request) { +- var params =3D new AnalysisSetAnalysisRootsParams.fromRequest(request= ); +- List includedPathList =3D params.included; +- List excludedPathList =3D params.excluded; +- +- server.options.analytics?.sendEvent('analysis', 'setAnalysisRoots', +- value: includedPathList.length); +- +- // validate +- for (String path in includedPathList) { +- if (!server.isValidFilePath(path)) { +- return new Response.invalidFilePathFormat(request, path); +- } +- } +- for (String path in excludedPathList) { +- if (!server.isValidFilePath(path)) { +- return new Response.invalidFilePathFormat(request, path); +- } +- } +- // continue in server +- server.setAnalysisRoots(request.id, includedPathList, excludedPathLis= t, +- params.packageRoots ?? {}); +- return new AnalysisSetAnalysisRootsResult().toResponse(request.id); +- } +- +- /** +- * Implement the 'analysis.setGeneralSubscriptions' request. +- */ +- Response setGeneralSubscriptions(Request request) { +- AnalysisSetGeneralSubscriptionsParams params =3D +- new AnalysisSetGeneralSubscriptionsParams.fromRequest(request); +- server.setGeneralAnalysisSubscriptions(params.subscriptions); +- return new AnalysisSetGeneralSubscriptionsResult().toResponse(request= .id); +- } +- +- /** +- * Implement the 'analysis.setPriorityFiles' request. +- */ +- Response setPriorityFiles(Request request) { +- var params =3D new AnalysisSetPriorityFilesParams.fromRequest(request= ); +- server.setPriorityFiles(request.id, params.files); +- // +- // Forward the request to the plugins. +- // +- RequestConverter converter =3D new RequestConverter(); +- server.pluginManager.setAnalysisSetPriorityFilesParams( +- converter.convertAnalysisSetPriorityFilesParams(params)); +- // +- // Send the response. +- // +- return new AnalysisSetPriorityFilesResult().toResponse(request.id); +- } +- +- /** +- * Implement the 'analysis.setSubscriptions' request. +- */ +- Response setSubscriptions(Request request) { +- var params =3D new AnalysisSetSubscriptionsParams.fromRequest(request= ); +- // parse subscriptions +- Map> subMap =3D mapMap(params.subscripti= ons, +- valueCallback: (List subscriptions) =3D> subscriptions.to= Set()); +- server.setAnalysisSubscriptions(subMap); +- // +- // Forward the request to the plugins. +- // +- RequestConverter converter =3D new RequestConverter(); +- server.pluginManager.setAnalysisSetSubscriptionsParams( +- converter.convertAnalysisSetSubscriptionsParams(params)); +- // +- // Send the response. +- // +- return new AnalysisSetSubscriptionsResult().toResponse(request.id); +- } +- +- /** +- * Implement the 'analysis.updateContent' request. +- */ +- Response updateContent(Request request) { +- var params =3D new AnalysisUpdateContentParams.fromRequest(request); +- server.updateContent(request.id, params.files); +- // +- // Forward the request to the plugins. +- // +- RequestConverter converter =3D new RequestConverter(); +- server.pluginManager.setAnalysisUpdateContentParams( +- converter.convertAnalysisUpdateContentParams(params)); +- // +- // Send the response. +- // +- return new AnalysisUpdateContentResult().toResponse(request.id); +- } +- +- /** +- * Implement the 'analysis.updateOptions' request. +- */ +- Response updateOptions(Request request) { +- // options +- var params =3D new AnalysisUpdateOptionsParams.fromRequest(request); +- AnalysisOptions newOptions =3D params.options; +- List updaters =3D new List(); +- if (newOptions.generateDart2jsHints !=3D null) { +- updaters.add((engine.AnalysisOptionsImpl options) { +- options.dart2jsHint =3D newOptions.generateDart2jsHints; +- }); +- } +- if (newOptions.generateHints !=3D null) { +- updaters.add((engine.AnalysisOptionsImpl options) { +- options.hint =3D newOptions.generateHints; +- }); +- } +- if (newOptions.generateLints !=3D null) { +- updaters.add((engine.AnalysisOptionsImpl options) { +- options.lint =3D newOptions.generateLints; +- }); +- } +- if (newOptions.enableSuperMixins !=3D null) { +- updaters.add((engine.AnalysisOptionsImpl options) { +- options.enableSuperMixins =3D newOptions.enableSuperMixins; +- }); +- } +- server.updateOptions(updaters); +- return new AnalysisUpdateOptionsResult().toResponse(request.id); +- } +-} +diff --git a/pkg/analysis_server/lib/src/domain_analytics.dart b/pkg/analy= sis_server/lib/src/domain_analytics.dart +deleted file mode 100644 +index f6ad37e675a..00000000000 +--- a/pkg/analysis_server/lib/src/domain_analytics.dart ++++ /dev/null +@@ -1,60 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:core'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +- +-/// Instances of the class [AnalyticsDomainHandler] implement a [RequestH= andler] +-/// that handles requests in the `analytics` domain. +-class AnalyticsDomainHandler implements RequestHandler { +- final AnalysisServer server; +- +- bool enabled =3D false; +- +- AnalyticsDomainHandler(this.server); +- +- // TODO(devoncarew): This implementation is currently mocked out. +- Response handleEnable(Request request) { +- // TODO(devoncarew): Implement. +- AnalyticsEnableParams params =3D +- new AnalyticsEnableParams.fromRequest(request); +- enabled =3D params.value; +- return new AnalyticsEnableResult().toResponse(request.id); +- } +- +- Response handleIsEnabled(Request request) { +- // TODO(devoncarew): Implement. +- return new AnalyticsIsEnabledResult(enabled).toResponse(request.id); +- } +- +- @override +- Response handleRequest(Request request) { +- String requestName =3D request.method; +- if (requestName =3D=3D ANALYTICS_REQUEST_IS_ENABLED) { +- return handleIsEnabled(request); +- } else if (requestName =3D=3D ANALYTICS_REQUEST_ENABLE) { +- return handleEnable(request); +- } else if (requestName =3D=3D ANALYTICS_REQUEST_SEND_EVENT) { +- return handleSendEvent(request); +- } else if (requestName =3D=3D ANALYTICS_REQUEST_SEND_TIMING) { +- return handleSendTiming(request); +- } +- +- return null; +- } +- +- Response handleSendEvent(Request request) { +- // TODO(devoncarew): Implement. +- return new AnalyticsSendEventResult().toResponse(request.id); +- } +- +- Response handleSendTiming(Request request) { +- // TODO(devoncarew): Implement. +- return new AnalyticsSendTimingResult().toResponse(request.id); +- } +-} +diff --git a/pkg/analysis_server/lib/src/domain_completion.dart b/pkg/anal= ysis_server/lib/src/domain_completion.dart +deleted file mode 100644 +index 5e9f2a64b81..00000000000 +--- a/pkg/analysis_server/lib/src/domain_completion.dart ++++ /dev/null +@@ -1,298 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/collections.dart'; +-import 'package:analysis_server/src/domain_abstract.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart'; +-import 'package:analysis_server/src/services/completion/completion_core.d= art'; +-import 'package:analysis_server/src/services/completion/completion_perfor= mance.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +- +-/** +- * Instances of the class [CompletionDomainHandler] implement a [RequestH= andler] +- * that handles requests in the completion domain. +- */ +-class CompletionDomainHandler extends AbstractRequestHandler { +- /** +- * The maximum number of performance measurements to keep. +- */ +- static const int performanceListMaxLength =3D 50; +- +- /** +- * The next completion response id. +- */ +- int _nextCompletionId =3D 0; +- +- /** +- * Code completion performance for the last completion operation. +- */ +- CompletionPerformance performance; +- +- /** +- * A list of code completion performance measurements for the latest +- * completion operation up to [performanceListMaxLength] measurements. +- */ +- final RecentBuffer performanceList =3D +- new RecentBuffer(performanceListMaxLength); +- +- /** +- * Performance for the last priority change event. +- */ +- CompletionPerformance computeCachePerformance; +- +- /** +- * The current request being processed or `null` if none. +- */ +- CompletionRequestImpl _currentRequest; +- +- /** +- * Initialize a new request handler for the given [server]. +- */ +- CompletionDomainHandler(AnalysisServer server) : super(server); +- +- /** +- * Compute completion results for the given request and append them to = the stream. +- * Clients should not call this method directly as it is automatically = called +- * when a client listens to the stream returned by [results]. +- * Subclasses should override this method, append at least one result +- * to the [controller], and close the controller stream once complete. +- */ +- Future computeSuggestions(CompletionRequestImpl reque= st, +- CompletionGetSuggestionsParams params) async { +- // +- // Allow plugins to start computing fixes. +- // +- Map> pluginFutures; +- plugin.CompletionGetSuggestionsParams requestParams; +- String file =3D params.file; +- int offset =3D params.offset; +- AnalysisDriver driver =3D server.getAnalysisDriver(file); +- if (driver !=3D null) { +- requestParams =3D new plugin.CompletionGetSuggestionsParams(file, o= ffset); +- pluginFutures =3D server.pluginManager +- .broadcastRequest(requestParams, contextRoot: driver.contextRoo= t); +- } +- // +- // Compute completions generated by server. +- // +- List suggestions =3D []; +- if (request.result !=3D null) { +- const COMPUTE_SUGGESTIONS_TAG =3D 'computeSuggestions'; +- performance.logStartTime(COMPUTE_SUGGESTIONS_TAG); +- +- CompletionContributor contributor =3D new DartCompletionManager(); +- String contributorTag =3D 'computeSuggestions - ${contributor +- .runtimeType}'; +- performance.logStartTime(contributorTag); +- try { +- suggestions.addAll(await contributor.computeSuggestions(request)); +- } on AbortCompletion { +- suggestions.clear(); +- } +- performance.logElapseTime(contributorTag); +- performance.logElapseTime(COMPUTE_SUGGESTIONS_TAG); +- } +- // TODO (danrubel) if request is obsolete (processAnalysisRequest ret= urns +- // false) then send empty results +- +- // +- // Add the fixes produced by plugins to the server-generated fixes. +- // +- if (pluginFutures !=3D null) { +- List responses =3D await waitForResponses(pluginFu= tures, +- requestParameters: requestParams); +- for (plugin.Response response in responses) { +- plugin.CompletionGetSuggestionsResult result =3D +- new plugin.CompletionGetSuggestionsResult.fromResponse(respon= se); +- if (result.results !=3D null && result.results.isNotEmpty) { +- if (suggestions.isEmpty) { +- request.replacementOffset =3D result.replacementOffset; +- request.replacementLength =3D result.replacementLength; +- } else if (request.replacementOffset !=3D result.replacementOff= set && +- request.replacementLength !=3D result.replacementLength) { +- server.instrumentationService +- .logError('Plugin completion-results dropped due to confl= icting' +- ' replacement offset/length: ${result.toJson()}'); +- continue; +- } +- suggestions.addAll(result.results); +- } +- } +- } +- // +- // Return the result. +- // +- return new CompletionResult( +- request.replacementOffset, request.replacementLength, suggestions= ); +- } +- +- @override +- Response handleRequest(Request request) { +- return runZoned(() { +- String requestName =3D request.method; +- if (requestName =3D=3D COMPLETION_REQUEST_GET_SUGGESTIONS) { +- processRequest(request); +- return Response.DELAYED_RESPONSE; +- } +- return null; +- }, onError: (exception, stackTrace) { +- server.sendServerErrorNotification( +- 'Failed to handle completion domain request: ${request.toJson()= }', +- exception, +- stackTrace); +- }); +- } +- +- void ifMatchesRequestClear(CompletionRequest completionRequest) { +- if (_currentRequest =3D=3D completionRequest) { +- _currentRequest =3D null; +- } +- } +- +- /** +- * Process a `completion.getSuggestions` request. +- */ +- Future processRequest(Request request) async { +- performance =3D new CompletionPerformance(); +- +- // extract and validate params +- CompletionGetSuggestionsParams params =3D +- new CompletionGetSuggestionsParams.fromRequest(request); +- String filePath =3D params.file; +- int offset =3D params.offset; +- +- AnalysisResult result =3D await server.getAnalysisResult(filePath); +- Source source; +- +- if (result =3D=3D null || !result.exists) { +- if (server.onNoAnalysisCompletion !=3D null) { +- String completionId =3D (_nextCompletionId++).toString(); +- await server.onNoAnalysisCompletion( +- request, this, params, performance, completionId); +- return; +- } +- source =3D server.resourceProvider.getFile(filePath).createSource(); +- } else { +- if (offset < 0 || offset > result.content.length) { +- server.sendResponse(new Response.invalidParameter( +- request, +- 'params.offset', +- 'Expected offset between 0 and source length inclusive,' +- ' but found $offset')); +- return; +- } +- source =3D +- server.resourceProvider.getFile(result.path).createSource(resul= t.uri); +- +- recordRequest(performance, source, result.content, offset); +- } +- CompletionRequestImpl completionRequest =3D new CompletionRequestImpl( +- result, server.resourceProvider, source, offset, performance); +- +- String completionId =3D (_nextCompletionId++).toString(); +- +- setNewRequest(completionRequest); +- +- // initial response without results +- server.sendResponse(new CompletionGetSuggestionsResult(completionId) +- .toResponse(request.id)); +- +- // Compute suggestions in the background +- computeSuggestions(completionRequest, params) +- .then((CompletionResult result) { +- const SEND_NOTIFICATION_TAG =3D 'send notification'; +- performance.logStartTime(SEND_NOTIFICATION_TAG); +- sendCompletionNotification(completionId, result.replacementOffset, +- result.replacementLength, result.suggestions); +- performance.logElapseTime(SEND_NOTIFICATION_TAG); +- performance.notificationCount =3D 1; +- performance.logFirstNotificationComplete('notification 1 complete'); +- performance.suggestionCountFirst =3D result.suggestions.length; +- performance.suggestionCountLast =3D result.suggestions.length; +- performance.complete(); +- }).whenComplete(() { +- ifMatchesRequestClear(completionRequest); +- }); +- } +- +- /** +- * If tracking code completion performance over time, then +- * record addition information about the request in the performance rec= ord. +- */ +- void recordRequest(CompletionPerformance performance, Source source, +- String content, int offset) { +- performance.source =3D source; +- if (performanceListMaxLength =3D=3D 0 || source =3D=3D null) { +- return; +- } +- performance.setContentsAndOffset(content, offset); +- performanceList.add(performance); +- } +- +- /** +- * Send completion notification results. +- */ +- void sendCompletionNotification(String completionId, int replacementOff= set, +- int replacementLength, Iterable results) { +- server.sendNotification(new CompletionResultsParams( +- completionId, replacementOffset, replacementLength, results, = true) +- .toNotification()); +- } +- +- void setNewRequest(CompletionRequest completionRequest) { +- _abortCurrentRequest(); +- _currentRequest =3D completionRequest; +- } +- +- /** +- * Abort the current completion request, if any. +- */ +- void _abortCurrentRequest() { +- if (_currentRequest !=3D null) { +- _currentRequest.abort(); +- _currentRequest =3D null; +- } +- } +-} +- +-/** +- * The result of computing suggestions for code completion. +- */ +-class CompletionResult { +- /** +- * The length of the text to be replaced if the remainder of the identi= fier +- * containing the cursor is to be replaced when the suggestion is appli= ed +- * (that is, the number of characters in the existing identifier). +- */ +- final int replacementLength; +- +- /** +- * The offset of the start of the text to be replaced. This will be dif= ferent +- * than the offset used to request the completion suggestions if there = was a +- * portion of an identifier before the original offset. In particular, = the +- * replacementOffset will be the offset of the beginning of said identi= fier. +- */ +- final int replacementOffset; +- +- /** +- * The suggested completions. +- */ +- final List suggestions; +- +- CompletionResult( +- this.replacementOffset, this.replacementLength, this.suggestions); +-} +diff --git a/pkg/analysis_server/lib/src/domain_diagnostic.dart b/pkg/anal= ysis_server/lib/src/domain_diagnostic.dart +deleted file mode 100644 +index 81bff6b0d40..00000000000 +--- a/pkg/analysis_server/lib/src/domain_diagnostic.dart ++++ /dev/null +@@ -1,75 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:core'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +- +-/// Instances of the class [DiagnosticDomainHandler] implement a +-/// [RequestHandler] that handles requests in the `diagnostic` domain. +-class DiagnosticDomainHandler implements RequestHandler { +- /// The analysis server that is using this handler to process requests. +- final AnalysisServer server; +- +- /// Initialize a newly created handler to handle requests for the given +- /// [server]. +- DiagnosticDomainHandler(this.server); +- +- /// Answer the `diagnostic.getDiagnostics` request. +- Response computeDiagnostics(Request request) { +- List contexts =3D +- server.driverMap.values.map(extractDataFromDriver).toList(); +- return new DiagnosticGetDiagnosticsResult(contexts).toResponse(reques= t.id); +- } +- +- /// Extract context data from the given [driver]. +- ContextData extractDataFromDriver(AnalysisDriver driver) { +- int explicitFileCount =3D driver.addedFiles.length; +- int knownFileCount =3D driver.knownFiles.length; +- return new ContextData(driver.name, explicitFileCount, +- knownFileCount - explicitFileCount, driver.numberOfFilesToAnalyze= , []); +- } +- +- /// Answer the `diagnostic.getServerPort` request. +- Future handleGetServerPort(Request request) async { +- try { +- // Open a port (or return the existing one). +- int port =3D await server.diagnosticServer.getServerPort(); +- server.sendResponse( +- new DiagnosticGetServerPortResult(port).toResponse(request.id)); +- } catch (error) { +- server +- .sendResponse(new Response.debugPortCouldNotBeOpened(request, e= rror)); +- } +- } +- +- @override +- Response handleRequest(Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D DIAGNOSTIC_REQUEST_GET_DIAGNOSTICS) { +- return computeDiagnostics(request); +- } else if (requestName =3D=3D DIAGNOSTIC_REQUEST_GET_SERVER_PORT) { +- handleGetServerPort(request); +- return Response.DELAYED_RESPONSE; +- } +- } on RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +-} +- +-class MemoryCpuSample { +- final DateTime time; +- final double cpuPercentage; +- final int memoryKB; +- +- MemoryCpuSample(this.time, this.cpuPercentage, this.memoryKB); +-} +diff --git a/pkg/analysis_server/lib/src/domain_execution.dart b/pkg/analy= sis_server/lib/src/domain_execution.dart +deleted file mode 100644 +index ea17e60cefd..00000000000 +--- a/pkg/analysis_server/lib/src/domain_execution.dart ++++ /dev/null +@@ -1,147 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:core'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * Instances of the class [ExecutionDomainHandler] implement a [RequestHa= ndler] +- * that handles requests in the `execution` domain. +- */ +-class ExecutionDomainHandler implements RequestHandler { +- /** +- * The analysis server that is using this handler to process requests. +- */ +- final AnalysisServer server; +- +- /** +- * The next execution context identifier to be returned. +- */ +- int nextContextId =3D 0; +- +- /** +- * A table mapping execution context id's to the root of the context. +- */ +- Map contextMap =3D new HashMap(); +- +- /** +- * The subscription to the 'onAnalysisComplete' events, +- * used to send notifications when +- */ +- StreamSubscription onFileAnalyzed; +- +- /** +- * Initialize a newly created handler to handle requests for the given = [server]. +- */ +- ExecutionDomainHandler(this.server); +- +- /** +- * Implement the `execution.createContext` request. +- */ +- Response createContext(Request request) { +- String file =3D +- new ExecutionCreateContextParams.fromRequest(request).contextRoot; +- String contextId =3D (nextContextId++).toString(); +- contextMap[contextId] =3D file; +- return new ExecutionCreateContextResult(contextId).toResponse(request= .id); +- } +- +- /** +- * Implement the `execution.deleteContext` request. +- */ +- Response deleteContext(Request request) { +- String contextId =3D new ExecutionDeleteContextParams.fromRequest(req= uest).id; +- contextMap.remove(contextId); +- return new ExecutionDeleteContextResult().toResponse(request.id); +- } +- +- @override +- Response handleRequest(Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D EXECUTION_REQUEST_CREATE_CONTEXT) { +- return createContext(request); +- } else if (requestName =3D=3D EXECUTION_REQUEST_DELETE_CONTEXT) { +- return deleteContext(request); +- } else if (requestName =3D=3D EXECUTION_REQUEST_MAP_URI) { +- return mapUri(request); +- } else if (requestName =3D=3D EXECUTION_REQUEST_SET_SUBSCRIPTIONS) { +- return setSubscriptions(request); +- } +- } on RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +- +- /** +- * Implement the 'execution.mapUri' request. +- */ +- Response mapUri(Request request) { +- ExecutionMapUriParams params =3D +- new ExecutionMapUriParams.fromRequest(request); +- String contextId =3D params.id; +- String path =3D contextMap[contextId]; +- if (path =3D=3D null) { +- return new Response.invalidParameter(request, 'id', +- 'There is no execution context with an id of $contextId'); +- } +- +- AnalysisDriver driver =3D server.getAnalysisDriver(path); +- if (driver =3D=3D null) { +- return new Response.invalidExecutionContext(request, contextId); +- } +- SourceFactory sourceFactory =3D driver.sourceFactory; +- +- String file =3D params.file; +- String uri =3D params.uri; +- if (file !=3D null) { +- if (uri !=3D null) { +- return new Response.invalidParameter(request, 'file', +- 'Either file or uri must be provided, but not both'); +- } +- Resource resource =3D server.resourceProvider.getResource(file); +- if (!resource.exists) { +- return new Response.invalidParameter(request, 'file', 'Must exist= '); +- } else if (resource is! File) { +- return new Response.invalidParameter( +- request, 'file', 'Must not refer to a directory'); +- } +- +- Source source =3D driver.fsState.getFileForPath(file).source; +- if (source.uriKind !=3D UriKind.FILE_URI) { +- uri =3D source.uri.toString(); +- } else { +- uri =3D sourceFactory.restoreUri(source).toString(); +- } +- return new ExecutionMapUriResult(uri: uri).toResponse(request.id); +- } else if (uri !=3D null) { +- Source source =3D sourceFactory.forUri(uri); +- if (source =3D=3D null) { +- return new Response.invalidParameter(request, 'uri', 'Invalid URI= '); +- } +- file =3D source.fullName; +- return new ExecutionMapUriResult(file: file).toResponse(request.id); +- } +- return new Response.invalidParameter( +- request, 'file', 'Either file or uri must be provided'); +- } +- +- /** +- * Implement the 'execution.setSubscriptions' request. +- */ +- Response setSubscriptions(Request request) { +- // Under the analysis driver, setSubscriptions() becomes a no-op. +- return new ExecutionSetSubscriptionsResult().toResponse(request.id); +- } +-} +diff --git a/pkg/analysis_server/lib/src/domain_kythe.dart b/pkg/analysis_= server/lib/src/domain_kythe.dart +deleted file mode 100644 +index 895bd82119d..00000000000 +--- a/pkg/analysis_server/lib/src/domain_kythe.dart ++++ /dev/null +@@ -1,114 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:core'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/domain_abstract.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/plugin/result_merger.dart'; +-import 'package:analysis_server/src/services/kythe/kythe_visitors.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/resolver/inheritance_manager.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +- +-/** +- * Instances of the class [KytheDomainHandler] implement a [RequestHandle= r] +- * that handles requests in the `kythe` domain. +- */ +-class KytheDomainHandler extends AbstractRequestHandler { +- /** +- * Initialize a newly created handler to handle requests for the given = [server]. +- */ +- KytheDomainHandler(AnalysisServer server) : super(server); +- +- /** +- * Implement the `kythe.getKytheEntries` request. +- */ +- Future getKytheEntries(Request request) async { +- String file =3D new KytheGetKytheEntriesParams.fromRequest(request).f= ile; +- AnalysisDriver driver =3D server.getAnalysisDriver(file); +- if (driver =3D=3D null) { +- server.sendResponse(new Response.getKytheEntriesInvalidFile(request= )); +- } else { +- // +- // Allow plugins to start computing entries. +- // +- plugin.KytheGetKytheEntriesParams requestParams =3D +- new plugin.KytheGetKytheEntriesParams(file); +- Map> pluginFutures =3D server +- .pluginManager +- .broadcastRequest(requestParams, contextRoot: driver.contextRoo= t); +- // +- // Compute entries generated by server. +- // +- List allResults =3D +- []; +- AnalysisResult result =3D await server.getAnalysisResult(file); +- CompilationUnit unit =3D result?.unit; +- if (unit !=3D null && result.exists) { +- List entries =3D []; +- // TODO(brianwilkerson) Figure out how to get the list of files. +- List files =3D []; +- result.unit.accept(new KytheDartVisitor( +- server.resourceProvider, +- entries, +- file, +- new InheritanceManager(result.libraryElement), +- result.content)); +- allResults.add(new KytheGetKytheEntriesResult(entries, files)); +- } +- // +- // Add the entries produced by plugins to the server-generated entr= ies. +- // +- if (pluginFutures !=3D null) { +- List responses =3D await waitForResponses(plugin= Futures, +- requestParameters: requestParams); +- for (plugin.Response response in responses) { +- plugin.KytheGetKytheEntriesResult result =3D +- new plugin.KytheGetKytheEntriesResult.fromResponse(response= ); +- allResults.add( +- new KytheGetKytheEntriesResult(result.entries, result.files= )); +- } +- } +- // +- // Return the result. +- // +- ResultMerger merger =3D new ResultMerger(); +- KytheGetKytheEntriesResult mergedResults =3D +- merger.mergeKytheEntries(allResults); +- if (mergedResults =3D=3D null) { +- server.sendResponse( +- new KytheGetKytheEntriesResult([], []) +- .toResponse(request.id)); +- } else { +- server.sendResponse(new KytheGetKytheEntriesResult( +- mergedResults.entries, mergedResults.files) +- .toResponse(request.id)); +- } +- } +- } +- +- @override +- Response handleRequest(Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D KYTHE_REQUEST_GET_KYTHE_ENTRIES) { +- getKytheEntries(request); +- return Response.DELAYED_RESPONSE; +- } +- } on RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/domain_server.dart b/pkg/analysis= _server/lib/src/domain_server.dart +deleted file mode 100644 +index ccd12bc9dbc..00000000000 +--- a/pkg/analysis_server/lib/src/domain_server.dart ++++ /dev/null +@@ -1,74 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +- +-/** +- * Instances of the class [ServerDomainHandler] implement a [RequestHandl= er] +- * that handles requests in the server domain. +- */ +-class ServerDomainHandler implements RequestHandler { +- /** +- * The analysis server that is using this handler to process requests. +- */ +- final AnalysisServer server; +- +- /** +- * Initialize a newly created handler to handle requests for the given = [server]. +- */ +- ServerDomainHandler(this.server); +- +- /** +- * Return the version number of the analysis server. +- */ +- Response getVersion(Request request) { +- return new ServerGetVersionResult(AnalysisServer.VERSION) +- .toResponse(request.id); +- } +- +- @override +- Response handleRequest(Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D SERVER_REQUEST_GET_VERSION) { +- return getVersion(request); +- } else if (requestName =3D=3D SERVER_REQUEST_SET_SUBSCRIPTIONS) { +- return setSubscriptions(request); +- } else if (requestName =3D=3D SERVER_REQUEST_SHUTDOWN) { +- shutdown(request); +- return Response.DELAYED_RESPONSE; +- } +- } on RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +- +- /** +- * Subscribe for services. +- * +- * All previous subscriptions are replaced by the given set of subscrip= tions. +- */ +- Response setSubscriptions(Request request) { +- server.serverServices =3D +- new ServerSetSubscriptionsParams.fromRequest(request) +- .subscriptions +- .toSet(); +- return new ServerSetSubscriptionsResult().toResponse(request.id); +- } +- +- /** +- * Cleanly shutdown the analysis server. +- */ +- Future shutdown(Request request) async { +- await server.shutdown(); +- Response response =3D new ServerShutdownResult().toResponse(request.i= d); +- server.sendResponse(response); +- } +-} +diff --git a/pkg/analysis_server/lib/src/domains/analysis/implemented_dart= .dart b/pkg/analysis_server/lib/src/domains/analysis/implemented_dart.dart +deleted file mode 100644 +index 54f99734920..00000000000 +--- a/pkg/analysis_server/lib/src/domains/analysis/implemented_dart.dart ++++ /dev/null +@@ -1,79 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-class ImplementedComputer { +- final SearchEngine searchEngine; +- final CompilationUnitElement unitElement; +- +- List classes =3D = []; +- List members =3D []; +- +- Set subtypeMembers; +- +- ImplementedComputer(this.searchEngine, this.unitElement); +- +- compute() async { +- for (ClassElement type in unitElement.types) { +- // Always include Object and its members. +- if (type.supertype =3D=3D null) { +- _addImplementedClass(type); +- type.accessors.forEach(_addImplementedMember); +- type.fields.forEach(_addImplementedMember); +- type.methods.forEach(_addImplementedMember); +- continue; +- } +- +- // Analyze subtypes. +- subtypeMembers =3D await searchEngine.membersOfSubtypes(type); +- if (subtypeMembers !=3D null) { +- _addImplementedClass(type); +- type.accessors.forEach(_addMemberIfImplemented); +- type.fields.forEach(_addMemberIfImplemented); +- type.methods.forEach(_addMemberIfImplemented); +- } +- } +- } +- +- void _addImplementedClass(ClassElement type) { +- int offset =3D type.nameOffset; +- int length =3D type.nameLength; +- classes.add(new protocol.ImplementedClass(offset, length)); +- } +- +- void _addImplementedMember(Element member) { +- int offset =3D member.nameOffset; +- int length =3D member.nameLength; +- members.add(new protocol.ImplementedMember(offset, length)); +- } +- +- void _addMemberIfImplemented(Element element) { +- if (element.isSynthetic || _isStatic(element)) { +- return; +- } +- if (_hasOverride(element)) { +- _addImplementedMember(element); +- } +- } +- +- bool _hasOverride(Element element) { +- String name =3D element.displayName; +- return subtypeMembers.contains(name); +- } +- +- /** +- * Return `true` if the given [element] is a static element. +- */ +- static bool _isStatic(Element element) { +- if (element is ExecutableElement) { +- return element.isStatic; +- } else if (element is PropertyInducingElement) { +- return element.isStatic; +- } +- return false; +- } +-} +diff --git a/pkg/analysis_server/lib/src/domains/analysis/navigation_dart.= dart b/pkg/analysis_server/lib/src/domains/analysis/navigation_dart.dart +deleted file mode 100644 +index 5ed3bcefafe..00000000000 +--- a/pkg/analysis_server/lib/src/domains/analysis/navigation_dart.dart ++++ /dev/null +@@ -1,360 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/element.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/navigation/navigation.dart'; +- +-NavigationCollector computeDartNavigation(NavigationCollector collector, +- CompilationUnit unit, int offset, int length) { +- _DartNavigationCollector dartCollector =3D +- new _DartNavigationCollector(collector); +- _DartNavigationComputerVisitor visitor =3D +- new _DartNavigationComputerVisitor(dartCollector); +- if (offset =3D=3D null || length =3D=3D null) { +- unit.accept(visitor); +- } else { +- AstNode node =3D _getNodeForRange(unit, offset, length); +- node?.accept(visitor); +- } +- return collector; +-} +- +-AstNode _getNodeForRange(CompilationUnit unit, int offset, int length) { +- AstNode node =3D new NodeLocator(offset, offset + length).searchWithin(= unit); +- for (AstNode n =3D node; n !=3D null; n =3D n.parent) { +- if (n is Directive) { +- return n; +- } +- } +- return node; +-} +- +-/** +- * A Dart specific wrapper around [NavigationCollector]. +- */ +-class _DartNavigationCollector { +- final NavigationCollector collector; +- +- _DartNavigationCollector(this.collector); +- +- void _addRegion(int offset, int length, Element element) { +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- if (element =3D=3D null || element =3D=3D DynamicElementImpl.instance= ) { +- return; +- } +- if (element.location =3D=3D null) { +- return; +- } +- protocol.ElementKind kind =3D protocol.convertElementKind(element.kin= d); +- protocol.Location location =3D protocol.newLocation_fromElement(eleme= nt); +- if (location =3D=3D null) { +- return; +- } +- collector.addRegion(offset, length, kind, location); +- } +- +- void _addRegion_nodeStart_nodeEnd(AstNode a, AstNode b, Element element= ) { +- int offset =3D a.offset; +- int length =3D b.end - offset; +- _addRegion(offset, length, element); +- } +- +- void _addRegionForNode(AstNode node, Element element) { +- if (node =3D=3D null) { +- return; +- } +- int offset =3D node.offset; +- int length =3D node.length; +- _addRegion(offset, length, element); +- } +- +- void _addRegionForToken(Token token, Element element) { +- int offset =3D token.offset; +- int length =3D token.length; +- _addRegion(offset, length, element); +- } +-} +- +-class _DartNavigationComputerVisitor extends RecursiveAstVisitor { +- final _DartNavigationCollector computer; +- +- _DartNavigationComputerVisitor(this.computer); +- +- @override +- visitAnnotation(Annotation node) { +- Element element =3D node.element; +- if (element is ConstructorElement && element.isSynthetic) { +- element =3D element.enclosingElement; +- } +- Identifier name =3D node.name; +- if (name is PrefixedIdentifier) { +- // use constructor in: @PrefixClass.constructorName +- Element prefixElement =3D name.prefix.staticElement; +- if (prefixElement is ClassElement) { +- prefixElement =3D element; +- } +- computer._addRegionForNode(name.prefix, prefixElement); +- // always constructor +- computer._addRegionForNode(name.identifier, element); +- } else { +- computer._addRegionForNode(name, element); +- } +- computer._addRegionForNode(node.constructorName, element); +- // arguments +- node.arguments?.accept(this); +- } +- +- @override +- visitAssignmentExpression(AssignmentExpression node) { +- node.leftHandSide?.accept(this); +- computer._addRegionForToken(node.operator, node.bestElement); +- node.rightHandSide?.accept(this); +- } +- +- @override +- visitBinaryExpression(BinaryExpression node) { +- node.leftOperand?.accept(this); +- computer._addRegionForToken(node.operator, node.bestElement); +- node.rightOperand?.accept(this); +- } +- +- @override +- visitCompilationUnit(CompilationUnit unit) { +- // prepare top-level nodes sorted by their offsets +- List nodes =3D []; +- nodes.addAll(unit.directives); +- nodes.addAll(unit.declarations); +- nodes.sort((a, b) { +- return a.offset - b.offset; +- }); +- // visit sorted nodes +- for (AstNode node in nodes) { +- node.accept(this); +- } +- } +- +- @override +- visitConstructorDeclaration(ConstructorDeclaration node) { +- // associate constructor with "T" or "T.name" +- { +- AstNode firstNode =3D node.returnType; +- AstNode lastNode =3D node.name; +- if (lastNode =3D=3D null) { +- lastNode =3D firstNode; +- } +- if (firstNode !=3D null && lastNode !=3D null) { +- computer._addRegion_nodeStart_nodeEnd( +- firstNode, lastNode, node.element); +- } +- } +- super.visitConstructorDeclaration(node); +- } +- +- @override +- visitConstructorName(ConstructorName node) { +- AstNode parent =3D node.parent; +- if (parent is InstanceCreationExpression && +- parent.constructorName =3D=3D node) { +- _addConstructorName(parent, node); +- } else if (parent is ConstructorDeclaration && +- parent.redirectedConstructor =3D=3D node) { +- _addConstructorName(node, node); +- } +- } +- +- @override +- visitDeclaredIdentifier(DeclaredIdentifier node) { +- if (node.type =3D=3D null) { +- Token token =3D node.keyword; +- if (token?.keyword =3D=3D Keyword.VAR) { +- DartType inferredType =3D node.identifier?.bestType; +- Element element =3D inferredType?.element; +- if (element !=3D null) { +- computer._addRegionForToken(token, element); +- } +- } +- } +- super.visitDeclaredIdentifier(node); +- } +- +- @override +- visitExportDirective(ExportDirective node) { +- ExportElement exportElement =3D node.element; +- if (exportElement !=3D null) { +- Element libraryElement =3D exportElement.exportedLibrary; +- _addUriDirectiveRegion(node, libraryElement); +- } +- super.visitExportDirective(node); +- } +- +- @override +- visitImportDirective(ImportDirective node) { +- ImportElement importElement =3D node.element; +- if (importElement !=3D null) { +- Element libraryElement =3D importElement.importedLibrary; +- _addUriDirectiveRegion(node, libraryElement); +- } +- super.visitImportDirective(node); +- } +- +- @override +- visitIndexExpression(IndexExpression node) { +- super.visitIndexExpression(node); +- MethodElement element =3D node.bestElement; +- computer._addRegionForToken(node.leftBracket, element); +- computer._addRegionForToken(node.rightBracket, element); +- } +- +- @override +- visitLibraryDirective(LibraryDirective node) { +- computer._addRegionForNode(node.name, node.element); +- } +- +- @override +- visitPartDirective(PartDirective node) { +- _addUriDirectiveRegion(node, node.element); +- super.visitPartDirective(node); +- } +- +- @override +- visitPartOfDirective(PartOfDirective node) { +- computer._addRegionForNode(node.libraryName, node.element); +- super.visitPartOfDirective(node); +- } +- +- @override +- visitPostfixExpression(PostfixExpression node) { +- super.visitPostfixExpression(node); +- computer._addRegionForToken(node.operator, node.bestElement); +- } +- +- @override +- visitPrefixExpression(PrefixExpression node) { +- computer._addRegionForToken(node.operator, node.bestElement); +- super.visitPrefixExpression(node); +- } +- +- @override +- visitRedirectingConstructorInvocation(RedirectingConstructorInvocation = node) { +- Element element =3D node.staticElement; +- if (element !=3D null && element.isSynthetic) { +- element =3D element.enclosingElement; +- } +- // add region +- computer._addRegionForToken(node.thisKeyword, element); +- computer._addRegionForNode(node.constructorName, element); +- // process arguments +- node.argumentList?.accept(this); +- } +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- if (node.parent is ConstructorDeclaration) { +- return; +- } +- Element element =3D node.bestElement; +- computer._addRegionForNode(node, element); +- } +- +- @override +- visitSuperConstructorInvocation(SuperConstructorInvocation node) { +- Element element =3D node.staticElement; +- if (element !=3D null && element.isSynthetic) { +- element =3D element.enclosingElement; +- } +- // add region +- computer._addRegionForToken(node.superKeyword, element); +- computer._addRegionForNode(node.constructorName, element); +- // process arguments +- node.argumentList?.accept(this); +- } +- +- @override +- visitVariableDeclarationList(VariableDeclarationList node) { +- /** +- * Return the element for the type inferred for each of the variables= in the +- * given list of [variables], or `null` if not all variable have the = same +- * inferred type. +- */ +- Element getCommonElement(List variables) { +- Element firstElement =3D variables[0].name?.bestType?.element; +- if (firstElement =3D=3D null) { +- return null; +- } +- for (int i =3D 1; i < variables.length; i++) { +- Element element =3D variables[1].name?.bestType?.element; +- if (element !=3D firstElement) { +- return null; +- } +- } +- return firstElement; +- } +- +- if (node.type =3D=3D null) { +- Token token =3D node.keyword; +- if (token?.keyword =3D=3D Keyword.VAR) { +- Element element =3D getCommonElement(node.variables); +- if (element !=3D null) { +- computer._addRegionForToken(token, element); +- } +- } +- } +- super.visitVariableDeclarationList(node); +- } +- +- void _addConstructorName(AstNode parent, ConstructorName node) { +- Element element =3D node.staticElement; +- if (element =3D=3D null) { +- return; +- } +- // if a synthetic constructor, navigate to the class +- if (element.isSynthetic) { +- element =3D element.enclosingElement; +- } +- // add regions +- TypeName typeName =3D node.type; +- // [prefix].ClassName +- { +- Identifier name =3D typeName.name; +- Identifier className =3D name; +- if (name is PrefixedIdentifier) { +- name.prefix.accept(this); +- className =3D name.identifier; +- } +- computer._addRegionForNode(className, element); +- } +- // +- TypeArgumentList typeArguments =3D typeName.typeArguments; +- if (typeArguments !=3D null) { +- typeArguments.accept(this); +- } +- // optional "name" +- if (node.name !=3D null) { +- computer._addRegionForNode(node.name, element); +- } +- } +- +- /** +- * If the source of the given [element] (referenced by the [node]) exis= ts, +- * then add the navigation region from the [node] to the [element]. +- */ +- void _addUriDirectiveRegion(UriBasedDirective node, Element element) { +- if (element !=3D null) { +- Source source =3D element.source; +- if (element.context.exists(source)) { +- computer._addRegionForNode(node.uri, element); +- } +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/domains/analysis/occurrences.dart= b/pkg/analysis_server/lib/src/domains/analysis/occurrences.dart +deleted file mode 100644 +index 3862078c0e0..00000000000 +--- a/pkg/analysis_server/lib/src/domains/analysis/occurrences.dart ++++ /dev/null +@@ -1,33 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/plugin/analysis/occurrences/occurrences_c= ore.dart'; +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +- +-/** +- * A concrete implementation of [OccurrencesCollector]. +- */ +-class OccurrencesCollectorImpl implements OccurrencesCollector { +- Map elementOccurrences =3D +- {}; +- +- List get allOccurrences { +- return elementOccurrences.values.toList(); +- } +- +- @override +- void addOccurrences(protocol.Occurrences current) { +- protocol.Element element =3D current.element; +- protocol.Occurrences existing =3D elementOccurrences[element]; +- if (existing !=3D null) { +- List offsets =3D _merge(existing.offsets, current.offsets); +- current =3D new protocol.Occurrences(element, offsets, existing.len= gth); +- } +- elementOccurrences[element] =3D current; +- } +- +- static List _merge(List a, List b) { +- return []..addAll(a)..addAll(b); +- } +-} +diff --git a/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart= .dart b/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart.dart +deleted file mode 100644 +index f9774ab457a..00000000000 +--- a/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart.dart ++++ /dev/null +@@ -1,63 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/plugin/analysis/occurrences/occurrences_c= ore.dart'; +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/member.dart'; +- +-void addDartOccurrences(OccurrencesCollector collector, CompilationUnit u= nit) { +- _DartUnitOccurrencesComputerVisitor visitor =3D +- new _DartUnitOccurrencesComputerVisitor(); +- unit.accept(visitor); +- visitor.elementsOffsets.forEach((engineElement, offsets) { +- int length =3D engineElement.nameLength; +- protocol.Element serverElement =3D protocol.convertElement(engineElem= ent); +- protocol.Occurrences occurrences =3D +- new protocol.Occurrences(serverElement, offsets, length); +- collector.addOccurrences(occurrences); +- }); +-} +- +-class _DartUnitOccurrencesComputerVisitor extends RecursiveAstVisitor { +- final Map> elementsOffsets =3D >{= }; +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- Element element =3D node.bestElement; +- if (element !=3D null) { +- _addOccurrence(element, node.offset); +- } +- return super.visitSimpleIdentifier(node); +- } +- +- void _addOccurrence(Element element, int offset) { +- element =3D _canonicalizeElement(element); +- if (element =3D=3D null || element =3D=3D DynamicElementImpl.instance= ) { +- return; +- } +- List offsets =3D elementsOffsets[element]; +- if (offsets =3D=3D null) { +- offsets =3D []; +- elementsOffsets[element] =3D offsets; +- } +- offsets.add(offset); +- } +- +- Element _canonicalizeElement(Element element) { +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- if (element is PropertyAccessorElement) { +- element =3D (element as PropertyAccessorElement).variable; +- } +- if (element is Member) { +- element =3D (element as Member).baseElement; +- } +- return element; +- } +-} +diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analy= sis_server/lib/src/edit/edit_domain.dart +deleted file mode 100644 +index c1fd4e5b28a..00000000000 +--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart ++++ /dev/null +@@ -1,1062 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/plugin/edit/assist/assist_core.dart'; +-import 'package:analysis_server/plugin/edit/assist/assist_dart.dart'; +-import 'package:analysis_server/plugin/edit/fix/fix_core.dart'; +-import 'package:analysis_server/plugin/edit/fix/fix_dart.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/collections.dart'; +-import 'package:analysis_server/src/computer/import_elements_computer.dar= t'; +-import 'package:analysis_server/src/domain_abstract.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/plugin/result_converter.dart'; +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/completion/postfix/postfix_c= ompletion.dart'; +-import 'package:analysis_server/src/services/completion/statement/stateme= nt_completion.dart'; +-import 'package:analysis_server/src/services/correction/assist_internal.d= art'; +-import 'package:analysis_server/src/services/correction/fix_internal.dart= '; +-import 'package:analysis_server/src/services/correction/organize_directiv= es.dart'; +-import 'package:analysis_server/src/services/correction/sort_members.dart= '; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/dart/scanner/scanner.dart' as engine; +-import 'package:analyzer/src/error/codes.dart' as engine; +-import 'package:analyzer/src/generated/engine.dart' as engine; +-import 'package:analyzer/src/generated/parser.dart' as engine; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:dart_style/dart_style.dart'; +- +-int test_resetCount =3D 0; +- +-bool test_simulateRefactoringException_change =3D false; +-bool test_simulateRefactoringException_final =3D false; +-bool test_simulateRefactoringException_init =3D false; +- +-bool test_simulateRefactoringReset_afterCreateChange =3D false; +-bool test_simulateRefactoringReset_afterFinalConditions =3D false; +-bool test_simulateRefactoringReset_afterInitialConditions =3D false; +- +-/** +- * Instances of the class [EditDomainHandler] implement a [RequestHandler] +- * that handles requests in the edit domain. +- */ +-class EditDomainHandler extends AbstractRequestHandler { +- /** +- * The [SearchEngine] for this server. +- */ +- SearchEngine searchEngine; +- +- /** +- * The object used to manage uncompleted refactorings. +- */ +- _RefactoringManager refactoringManager; +- +- /** +- * Initialize a newly created handler to handle requests for the given = [server]. +- */ +- EditDomainHandler(AnalysisServer server) : super(server) { +- searchEngine =3D server.searchEngine; +- _newRefactoringManager(); +- } +- +- Response format(Request request) { +- server.options.analytics?.sendEvent('edit', 'format'); +- +- EditFormatParams params =3D new EditFormatParams.fromRequest(request); +- String file =3D params.file; +- +- String unformattedSource; +- try { +- Source source =3D server.resourceProvider.getFile(file).createSourc= e(); +- unformattedSource =3D +- server.fileContentOverlay[file] ?? source.contents.data; +- } catch (e) { +- return new Response.formatInvalidFile(request); +- } +- +- int start =3D params.selectionOffset; +- int length =3D params.selectionLength; +- +- // No need to preserve 0,0 selection +- if (start =3D=3D 0 && length =3D=3D 0) { +- start =3D null; +- length =3D null; +- } +- +- SourceCode code =3D new SourceCode(unformattedSource, +- uri: null, +- isCompilationUnit: true, +- selectionStart: start, +- selectionLength: length); +- DartFormatter formatter =3D new DartFormatter(pageWidth: params.lineL= ength); +- SourceCode formattedResult; +- try { +- formattedResult =3D formatter.formatSource(code); +- } on FormatterException { +- return new Response.formatWithErrors(request); +- } +- String formattedSource =3D formattedResult.text; +- +- List edits =3D []; +- +- if (formattedSource !=3D unformattedSource) { +- //TODO: replace full replacements with smaller, more targeted edits +- SourceEdit edit =3D +- new SourceEdit(0, unformattedSource.length, formattedSource); +- edits.add(edit); +- } +- +- int newStart =3D formattedResult.selectionStart; +- int newLength =3D formattedResult.selectionLength; +- +- // Sending null start/length values would violate protocol, so conver= t back +- // to 0. +- if (newStart =3D=3D null) { +- newStart =3D 0; +- } +- if (newLength =3D=3D null) { +- newLength =3D 0; +- } +- +- return new EditFormatResult(edits, newStart, newLength) +- .toResponse(request.id); +- } +- +- Future getAssists(Request request) async { +- EditGetAssistsParams params =3D new EditGetAssistsParams.fromRequest(= request); +- String file =3D params.file; +- int offset =3D params.offset; +- int length =3D params.length; +- +- List changes =3D []; +- // +- // Allow plugins to start computing assists. +- // +- Map> pluginFutures; +- plugin.EditGetAssistsParams requestParams =3D +- new plugin.EditGetAssistsParams(file, offset, length); +- AnalysisDriver driver =3D server.getAnalysisDriver(file); +- if (driver =3D=3D null) { +- pluginFutures =3D >{}; +- } else { +- pluginFutures =3D server.pluginManager +- .broadcastRequest(requestParams, contextRoot: driver.contextRoo= t); +- } +- // +- // Compute fixes associated with server-generated errors. +- // +- AnalysisResult result =3D await server.getAnalysisResult(file); +- if (result !=3D null) { +- CompilationUnit unit =3D result.unit; +- CompilationUnitElement compilationUnitElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(unit); +- DartAssistContext dartAssistContext =3D new _DartAssistContextForVa= lues( +- compilationUnitElement.source, +- offset, +- length, +- driver, +- new AstProviderForDriver(driver), +- unit); +- try { +- AssistProcessor processor =3D new AssistProcessor(dartAssistConte= xt); +- List assists =3D await processor.compute(); +- for (Assist assist in assists) { +- changes.add(assist.change); +- } +- } catch (_) {} +- } +- // +- // Add the fixes produced by plugins to the server-generated fixes. +- // +- List responses =3D +- await waitForResponses(pluginFutures, requestParameters: requestP= arams); +- ResultConverter converter =3D new ResultConverter(); +- List pluginChanges =3D +- []; +- for (plugin.Response response in responses) { +- plugin.EditGetAssistsResult result =3D +- new plugin.EditGetAssistsResult.fromResponse(response); +- pluginChanges.addAll(result.assists); +- } +- pluginChanges +- .sort((first, second) =3D> first.priority.compareTo(second.priori= ty)); +- changes.addAll(pluginChanges.map(converter.convertPrioritizedSourceCh= ange)); +- // +- // Send the response. +- // +- server +- .sendResponse(new EditGetAssistsResult(changes).toResponse(reques= t.id)); +- } +- +- Future getFixes(Request request) async { +- var params =3D new EditGetFixesParams.fromRequest(request); +- String file =3D params.file; +- int offset =3D params.offset; +- +- List errorFixesList =3D []; +- // +- // Allow plugins to start computing fixes. +- // +- Map> pluginFutures; +- plugin.EditGetFixesParams requestParams =3D +- new plugin.EditGetFixesParams(file, offset); +- AnalysisDriver driver =3D server.getAnalysisDriver(file); +- if (driver =3D=3D null) { +- pluginFutures =3D >{}; +- } else { +- pluginFutures =3D server.pluginManager +- .broadcastRequest(requestParams, contextRoot: driver.contextRoo= t); +- } +- // +- // Compute fixes associated with server-generated errors. +- // +- AnalysisResult result =3D await server.getAnalysisResult(file); +- if (result !=3D null) { +- CompilationUnit unit =3D result.unit; +- LineInfo lineInfo =3D result.lineInfo; +- int requestLine =3D lineInfo.getLocation(offset).lineNumber; +- for (engine.AnalysisError error in result.errors) { +- int errorLine =3D lineInfo.getLocation(error.offset).lineNumber; +- if (errorLine =3D=3D requestLine) { +- var context =3D new _DartFixContextImpl(server.resourceProvider, +- result.driver, new AstProviderForDriver(driver), unit, erro= r); +- List fixes =3D +- await new DefaultFixContributor().internalComputeFixes(cont= ext); +- if (fixes.isNotEmpty) { +- fixes.sort(Fix.SORT_BY_RELEVANCE); +- AnalysisError serverError =3D +- newAnalysisError_fromEngine(lineInfo, error); +- AnalysisErrorFixes errorFixes =3D new AnalysisErrorFixes(serv= erError); +- errorFixesList.add(errorFixes); +- fixes.forEach((fix) { +- errorFixes.fixes.add(fix.change); +- }); +- } +- } +- } +- } +- // +- // Add the fixes produced by plugins to the server-generated fixes. +- // +- List responses =3D +- await waitForResponses(pluginFutures, requestParameters: requestP= arams); +- ResultConverter converter =3D new ResultConverter(); +- for (plugin.Response response in responses) { +- plugin.EditGetFixesResult result =3D +- new plugin.EditGetFixesResult.fromResponse(response); +- errorFixesList +- .addAll(result.fixes.map(converter.convertAnalysisErrorFixes)); +- } +- // +- // Send the response. +- // +- server.sendResponse( +- new EditGetFixesResult(errorFixesList).toResponse(request.id)); +- } +- +- Future getPostfixCompletion(Request request) async { +- server.options.analytics?.sendEvent('edit', 'getPostfixCompletion'); +- +- var params =3D new EditGetPostfixCompletionParams.fromRequest(request= ); +- SourceChange change; +- +- AnalysisResult result =3D await server.getAnalysisResult(params.file); +- if (result !=3D null) { +- CompilationUnit unit =3D result.unit; +- CompilationUnitElement unitElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(unit); +- if (unitElement.context !=3D null) { +- PostfixCompletionContext context =3D new PostfixCompletionContext( +- params.file, +- result.lineInfo, +- params.offset, +- params.key, +- result.driver, +- unit, +- unitElement, +- result.errors); +- PostfixCompletionProcessor processor =3D +- new PostfixCompletionProcessor(context); +- PostfixCompletion completion =3D await processor.compute(); +- change =3D completion?.change; +- } +- } +- if (change =3D=3D null) { +- change =3D new SourceChange("", edits: []); +- } +- +- Response response =3D +- new EditGetPostfixCompletionResult(change).toResponse(request.id); +- server.sendResponse(response); +- } +- +- Future getStatementCompletion(Request request) async { +- var params =3D new EditGetStatementCompletionParams.fromRequest(reque= st); +- SourceChange change; +- +- AnalysisResult result =3D await server.getAnalysisResult(params.file); +- if (result !=3D null) { +- CompilationUnit unit =3D result.unit; +- CompilationUnitElement unitElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(unit); +- if (unitElement.context !=3D null) { +- StatementCompletionContext context =3D new StatementCompletionCon= text( +- params.file, +- result.lineInfo, +- params.offset, +- unit, +- unitElement, +- result.errors); +- StatementCompletionProcessor processor =3D +- new StatementCompletionProcessor(context); +- StatementCompletion completion =3D await processor.compute(); +- change =3D completion.change; +- } +- } +- if (change =3D=3D null) { +- change =3D new SourceChange("", edits: []); +- } +- +- Response response =3D new EditGetStatementCompletionResult(change, fa= lse) +- .toResponse(request.id); +- server.sendResponse(response); +- } +- +- @override +- Response handleRequest(Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D EDIT_REQUEST_FORMAT) { +- return format(request); +- } else if (requestName =3D=3D EDIT_REQUEST_GET_ASSISTS) { +- getAssists(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_GET_AVAILABLE_REFACTORIN= GS) { +- return _getAvailableRefactorings(request); +- } else if (requestName =3D=3D EDIT_REQUEST_GET_FIXES) { +- getFixes(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_GET_REFACTORING) { +- return _getRefactoring(request); +- } else if (requestName =3D=3D EDIT_REQUEST_IMPORT_ELEMENTS) { +- importElements(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_ORGANIZE_DIRECTIVES) { +- organizeDirectives(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_SORT_MEMBERS) { +- sortMembers(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_GET_STATEMENT_COMPLETION= ) { +- getStatementCompletion(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_IS_POSTFIX_COMPLETION_AP= PLICABLE) { +- isPostfixCompletionApplicable(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D EDIT_REQUEST_GET_POSTFIX_COMPLETION) { +- getPostfixCompletion(request); +- return Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D +- EDIT_REQUEST_LIST_POSTFIX_COMPLETION_TEMPLATES) { +- listPostfixCompletionTemplates(request); +- return Response.DELAYED_RESPONSE; +- } +- } on RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +- +- /** +- * Implement the `edit.importElements` request. +- */ +- Future importElements(Request request) async { +- EditImportElementsParams params =3D +- new EditImportElementsParams.fromRequest(request); +- // +- // Prepare the resolved unit. +- // +- AnalysisResult result =3D await server.getAnalysisResult(params.file); +- if (result =3D=3D null) { +- server.sendResponse(new Response.importElementsInvalidFile(request)= ); +- } +- CompilationUnitElement libraryUnit =3D +- result.libraryElement.definingCompilationUnit; +- if (libraryUnit !=3D result.unit.element) { +- // The file in the request is a part of a library. We need to pass = the +- // defining compilation unit to the computer, not the part. +- result =3D await server.getAnalysisResult(libraryUnit.source.fullNa= me); +- if (result =3D=3D null) { +- server.sendResponse(new Response.importElementsInvalidFile(reques= t)); +- } +- } +- // +- // Compute the edits required to import the required elements. +- // +- ImportElementsComputer computer =3D +- new ImportElementsComputer(server.resourceProvider, result); +- SourceChange change =3D await computer.createEdits(params.elements); +- // +- // Send the response. +- // +- server.sendResponse( +- new EditImportElementsResult(change.edits[0]).toResponse(request.= id)); +- } +- +- Future isPostfixCompletionApplicable(Request request) async { +- var params =3D new EditGetPostfixCompletionParams.fromRequest(request= ); +- bool value =3D false; +- +- AnalysisResult result =3D await server.getAnalysisResult(params.file); +- if (result !=3D null) { +- CompilationUnit unit =3D result.unit; +- CompilationUnitElement unitElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(unit); +- if (unitElement.context !=3D null) { +- PostfixCompletionContext context =3D new PostfixCompletionContext( +- params.file, +- result.lineInfo, +- params.offset, +- params.key, +- result.driver, +- unit, +- unitElement, +- result.errors); +- PostfixCompletionProcessor processor =3D +- new PostfixCompletionProcessor(context); +- value =3D await processor.isApplicable(); +- } +- } +- +- Response response =3D new EditIsPostfixCompletionApplicableResult(val= ue) +- .toResponse(request.id); +- server.sendResponse(response); +- } +- +- Future listPostfixCompletionTemplates(Request request) async { +- var templates =3D DartPostfixCompletion.ALL_TEMPLATES +- .map((pfc) =3D> +- new PostfixTemplateDescriptor(pfc.name, pfc.key, pfc.example)) +- .toList(); +- +- Response response =3D new EditListPostfixCompletionTemplatesResult(te= mplates) +- .toResponse(request.id); +- server.sendResponse(response); +- } +- +- Future organizeDirectives(Request request) async { +- server.options.analytics?.sendEvent('edit', 'organizeDirectives'); +- +- var params =3D new EditOrganizeDirectivesParams.fromRequest(request); +- // prepare file +- String file =3D params.file; +- if (!engine.AnalysisEngine.isDartFileName(file)) { +- server.sendResponse(new Response.fileNotAnalyzed(request, file)); +- return; +- } +- // Prepare the file information. +- AnalysisResult result =3D await server.getAnalysisResult(file); +- if (result =3D=3D null) { +- server.sendResponse(new Response.fileNotAnalyzed(request, file)); +- return; +- } +- int fileStamp =3D -1; +- String code =3D result.content; +- CompilationUnit unit =3D result.unit; +- List errors =3D result.errors; +- // check if there are scan/parse errors in the file +- int numScanParseErrors =3D _getNumberOfScanParseErrors(errors); +- if (numScanParseErrors !=3D 0) { +- server.sendResponse(new Response.organizeDirectivesError( +- request, 'File has $numScanParseErrors scan/parse errors.')); +- return; +- } +- // do organize +- DirectiveOrganizer sorter =3D new DirectiveOrganizer(code, unit, erro= rs); +- List edits =3D sorter.organize(); +- SourceFileEdit fileEdit =3D new SourceFileEdit(file, fileStamp, edits= : edits); +- server.sendResponse( +- new EditOrganizeDirectivesResult(fileEdit).toResponse(request.id)= ); +- } +- +- Future sortMembers(Request request) async { +- var params =3D new EditSortMembersParams.fromRequest(request); +- // prepare file +- String file =3D params.file; +- if (!engine.AnalysisEngine.isDartFileName(file)) { +- server.sendResponse(new Response.sortMembersInvalidFile(request)); +- return; +- } +- // Prepare the file information. +- AnalysisDriver driver =3D server.getAnalysisDriver(file); +- ParseResult result =3D await driver?.parseFile(file); +- if (result =3D=3D null) { +- server.sendResponse(new Response.fileNotAnalyzed(request, file)); +- return; +- } +- int fileStamp =3D -1; +- String code =3D result.content; +- CompilationUnit unit =3D result.unit; +- List errors =3D result.errors; +- // Check if there are scan/parse errors in the file. +- int numScanParseErrors =3D _getNumberOfScanParseErrors(errors); +- if (numScanParseErrors !=3D 0) { +- server.sendResponse( +- new Response.sortMembersParseErrors(request, numScanParseErrors= )); +- return; +- } +- // Do sort. +- MemberSorter sorter =3D new MemberSorter(code, unit); +- List edits =3D sorter.sort(); +- SourceFileEdit fileEdit =3D new SourceFileEdit(file, fileStamp, edits= : edits); +- server.sendResponse( +- new EditSortMembersResult(fileEdit).toResponse(request.id)); +- } +- +- Response _getAvailableRefactorings(Request request) { +- _getAvailableRefactoringsImpl(request); +- return Response.DELAYED_RESPONSE; +- } +- +- Future _getAvailableRefactoringsImpl(Request request) async { +- // prepare parameters +- var params =3D new EditGetAvailableRefactoringsParams.fromRequest(req= uest); +- String file =3D params.file; +- int offset =3D params.offset; +- int length =3D params.length; +- // add refactoring kinds +- List kinds =3D []; +- // try EXTRACT_* +- if (length !=3D 0) { +- kinds.add(RefactoringKind.EXTRACT_LOCAL_VARIABLE); +- kinds.add(RefactoringKind.EXTRACT_METHOD); +- } +- // check elements +- { +- Element element =3D await server.getElementAtOffset(file, offset); +- if (element !=3D null) { +- // try CONVERT_METHOD_TO_GETTER +- if (element is ExecutableElement) { +- Refactoring refactoring =3D new ConvertMethodToGetterRefactorin= g( +- searchEngine, server.getAstProvider(file), element); +- RefactoringStatus status =3D await refactoring.checkInitialCond= itions(); +- if (!status.hasFatalError) { +- kinds.add(RefactoringKind.CONVERT_METHOD_TO_GETTER); +- } +- } +- // try RENAME +- { +- RenameRefactoring renameRefactoring =3D new RenameRefactoring( +- searchEngine, server.getAstProvider(file), element); +- if (renameRefactoring !=3D null) { +- kinds.add(RefactoringKind.RENAME); +- } +- } +- } +- } +- // respond +- var result =3D new EditGetAvailableRefactoringsResult(kinds); +- server.sendResponse(result.toResponse(request.id)); +- } +- +- Response _getRefactoring(Request request) { +- if (refactoringManager.hasPendingRequest) { +- refactoringManager.cancel(); +- _newRefactoringManager(); +- } +- refactoringManager.getRefactoring(request); +- return Response.DELAYED_RESPONSE; +- } +- +- /** +- * Initializes [refactoringManager] with a new instance. +- */ +- void _newRefactoringManager() { +- refactoringManager =3D new _RefactoringManager(server, searchEngine); +- } +- +- static int _getNumberOfScanParseErrors(List error= s) { +- int numScanParseErrors =3D 0; +- for (engine.AnalysisError error in errors) { +- if (error.errorCode is engine.ScannerErrorCode || +- error.errorCode is engine.ParserErrorCode) { +- numScanParseErrors++; +- } +- } +- return numScanParseErrors; +- } +-} +- +-/** +- * Implementation of [DartAssistContext] that is based on the values pass= ed +- * in the constructor, as opposite to be partially based on [AssistContex= t]. +- */ +-class _DartAssistContextForValues implements DartAssistContext { +- @override +- final Source source; +- +- @override +- final int selectionOffset; +- +- @override +- final int selectionLength; +- +- @override +- final AnalysisDriver analysisDriver; +- +- @override +- final AstProvider astProvider; +- +- @override +- final CompilationUnit unit; +- +- _DartAssistContextForValues(this.source, this.selectionOffset, +- this.selectionLength, this.analysisDriver, this.astProvider, this.u= nit); +-} +- +-/** +- * And implementation of [DartFixContext]. +- */ +-class _DartFixContextImpl implements DartFixContext { +- @override +- final ResourceProvider resourceProvider; +- +- @override +- final AnalysisDriver analysisDriver; +- +- @override +- final AstProvider astProvider; +- +- @override +- final CompilationUnit unit; +- +- @override +- final engine.AnalysisError error; +- +- _DartFixContextImpl(this.resourceProvider, this.analysisDriver, +- this.astProvider, this.unit, this.error); +- +- @override +- GetTopLevelDeclarations get getTopLevelDeclarations =3D> +- analysisDriver.getTopLevelNameDeclarations; +-} +- +-/** +- * An object managing a single [Refactoring] instance. +- * +- * The instance is identified by its kind, file, offset and length. +- * It is initialized when the a set of parameters is given for the first = time. +- * All subsequent requests are performed on this [Refactoring] instance. +- * +- * Once new set of parameters is received, the previous [Refactoring] ins= tance +- * is invalidated and a new one is created and initialized. +- */ +-class _RefactoringManager { +- static const List EMPTY_PROBLEM_LIST =3D +- const []; +- +- final AnalysisServer server; +- final SearchEngine searchEngine; +- StreamSubscription subscriptionToReset; +- +- RefactoringKind kind; +- String file; +- int offset; +- int length; +- Refactoring refactoring; +- RefactoringFeedback feedback; +- RefactoringStatus initStatus; +- RefactoringStatus optionsStatus; +- RefactoringStatus finalStatus; +- +- Request request; +- EditGetRefactoringResult result; +- +- _RefactoringManager(this.server, this.searchEngine) { +- _reset(); +- } +- +- /** +- * Returns `true` if a response for the current request has not yet bee= n sent. +- */ +- bool get hasPendingRequest =3D> request !=3D null; +- +- bool get _hasFatalError { +- return initStatus.hasFatalError || +- optionsStatus.hasFatalError || +- finalStatus.hasFatalError; +- } +- +- /** +- * Checks if [refactoring] requires options. +- */ +- bool get _requiresOptions { +- return refactoring is ExtractLocalRefactoring || +- refactoring is ExtractMethodRefactoring || +- refactoring is InlineMethodRefactoring || +- refactoring is RenameRefactoring; +- } +- +- /** +- * Cancels processing of the current request and cleans up. +- */ +- void cancel() { +- if (request !=3D null) { +- server.sendResponse(new Response.refactoringRequestCancelled(reques= t)); +- request =3D null; +- } +- _reset(); +- } +- +- void getRefactoring(Request _request) { +- // prepare for processing the request +- request =3D _request; +- result =3D new EditGetRefactoringResult( +- EMPTY_PROBLEM_LIST, EMPTY_PROBLEM_LIST, EMPTY_PROBLEM_LIST); +- // process the request +- var params =3D new EditGetRefactoringParams.fromRequest(_request); +- +- if (params.kind !=3D null) { +- server.options.analytics +- ?.sendEvent('refactor', params.kind.name.toLowerCase()); +- } +- +- runZoned(() async { +- await _init(params.kind, params.file, params.offset, params.length); +- if (initStatus.hasFatalError) { +- feedback =3D null; +- _sendResultResponse(); +- return; +- } +- // set options +- if (_requiresOptions) { +- if (params.options =3D=3D null) { +- optionsStatus =3D new RefactoringStatus(); +- _sendResultResponse(); +- return; +- } +- optionsStatus =3D _setOptions(params); +- if (_hasFatalError) { +- _sendResultResponse(); +- return; +- } +- } +- // done if just validation +- if (params.validateOnly) { +- finalStatus =3D new RefactoringStatus(); +- _sendResultResponse(); +- return; +- } +- // simulate an exception +- if (test_simulateRefactoringException_final) { +- throw 'A simulated refactoring exception - final.'; +- } +- // validation and create change +- finalStatus =3D await refactoring.checkFinalConditions(); +- _checkForReset_afterFinalConditions(); +- if (_hasFatalError) { +- _sendResultResponse(); +- return; +- } +- // simulate an exception +- if (test_simulateRefactoringException_change) { +- throw 'A simulated refactoring exception - change.'; +- } +- // create change +- result.change =3D await refactoring.createChange(); +- result.potentialEdits =3D nullIfEmpty(refactoring.potentialEditIds); +- _checkForReset_afterCreateChange(); +- _sendResultResponse(); +- }, onError: (exception, stackTrace) { +- if (exception is _ResetError) { +- cancel(); +- } else { +- server.instrumentationService.logException(exception, stackTrace); +- server.sendResponse( +- new Response.serverError(_request, exception, stackTrace)); +- } +- _reset(); +- }); +- } +- +- void _checkForReset_afterCreateChange() { +- if (test_simulateRefactoringReset_afterCreateChange) { +- _reset(); +- } +- if (refactoring =3D=3D null) { +- throw new _ResetError(); +- } +- } +- +- void _checkForReset_afterFinalConditions() { +- if (test_simulateRefactoringReset_afterFinalConditions) { +- _reset(); +- } +- if (refactoring =3D=3D null) { +- throw new _ResetError(); +- } +- } +- +- void _checkForReset_afterInitialConditions() { +- if (test_simulateRefactoringReset_afterInitialConditions) { +- _reset(); +- } +- if (refactoring =3D=3D null) { +- throw new _ResetError(); +- } +- } +- +- /** +- * Initializes this context to perform a refactoring with the specified +- * parameters. The existing [Refactoring] is reused or created as neede= d. +- */ +- Future _init( +- RefactoringKind kind, String file, int offset, int length) async { +- // check if we can continue with the existing Refactoring instance +- if (this.kind =3D=3D kind && +- this.file =3D=3D file && +- this.offset =3D=3D offset && +- this.length =3D=3D length) { +- return; +- } +- _reset(); +- _resetOnAnalysisSetChanged(); +- this.kind =3D kind; +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- // simulate an exception +- if (test_simulateRefactoringException_init) { +- throw 'A simulated refactoring exception - init.'; +- } +- // create a new Refactoring instance +- if (kind =3D=3D RefactoringKind.CONVERT_GETTER_TO_METHOD) { +- Element element =3D await server.getElementAtOffset(file, offset); +- if (element !=3D null) { +- if (element is ExecutableElement) { +- refactoring =3D new ConvertGetterToMethodRefactoring( +- searchEngine, server.getAstProvider(file), element); +- } +- } +- } +- if (kind =3D=3D RefactoringKind.CONVERT_METHOD_TO_GETTER) { +- Element element =3D await server.getElementAtOffset(file, offset); +- if (element !=3D null) { +- if (element is ExecutableElement) { +- refactoring =3D new ConvertMethodToGetterRefactoring( +- searchEngine, server.getAstProvider(file), element); +- } +- } +- } +- if (kind =3D=3D RefactoringKind.EXTRACT_LOCAL_VARIABLE) { +- CompilationUnit unit =3D await server.getResolvedCompilationUnit(fi= le); +- if (unit !=3D null) { +- refactoring =3D new ExtractLocalRefactoring(unit, offset, length); +- feedback =3D new ExtractLocalVariableFeedback( +- [], [], [], +- coveringExpressionOffsets: [], +- coveringExpressionLengths: []); +- } +- } +- if (kind =3D=3D RefactoringKind.EXTRACT_METHOD) { +- CompilationUnit unit =3D await server.getResolvedCompilationUnit(fi= le); +- if (unit !=3D null) { +- refactoring =3D new ExtractMethodRefactoring( +- searchEngine, server.getAstProvider(file), unit, offset, leng= th); +- feedback =3D new ExtractMethodFeedback(offset, length, '', [], +- false, [], [], []); +- } +- } +- if (kind =3D=3D RefactoringKind.INLINE_LOCAL_VARIABLE) { +- CompilationUnit unit =3D await server.getResolvedCompilationUnit(fi= le); +- if (unit !=3D null) { +- refactoring =3D new InlineLocalRefactoring( +- searchEngine, server.getAstProvider(file), unit, offset); +- } +- } +- if (kind =3D=3D RefactoringKind.INLINE_METHOD) { +- CompilationUnit unit =3D await server.getResolvedCompilationUnit(fi= le); +- if (unit !=3D null) { +- refactoring =3D new InlineMethodRefactoring( +- searchEngine, server.getAstProvider(file), unit, offset); +- } +- } +- if (kind =3D=3D RefactoringKind.MOVE_FILE) { +- // TODO(brianwilkerson) Re-implement this refactoring under the new= analysis driver +-// _resetOnAnalysisStarted(); +-// ContextSourcePair contextSource =3D server.getContextSourcePair(f= ile); +-// engine.AnalysisContext context =3D contextSource.context; +-// Source source =3D contextSource.source; +-// refactoring =3D new MoveFileRefactoring( +-// server.resourceProvider, searchEngine, context, source, file); +- } +- if (kind =3D=3D RefactoringKind.RENAME) { +- AstNode node =3D await server.getNodeAtOffset(file, offset); +- Element element =3D server.getElementOfNode(node); +- if (node !=3D null && element !=3D null) { +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- // climb from "Class" in "new Class.named()" to "Class.named" +- if (node.parent is TypeName && node.parent.parent is ConstructorN= ame) { +- ConstructorName constructor =3D node.parent.parent; +- node =3D constructor; +- element =3D constructor.staticElement; +- } +- // do create the refactoring +- refactoring =3D new RenameRefactoring( +- searchEngine, server.getAstProvider(file), element); +- feedback =3D +- new RenameFeedback(node.offset, node.length, 'kind', 'oldName= '); +- } +- } +- if (refactoring =3D=3D null) { +- initStatus =3D +- new RefactoringStatus.fatal('Unable to create a refactoring'); +- return; +- } +- // check initial conditions +- initStatus =3D await refactoring.checkInitialConditions(); +- _checkForReset_afterInitialConditions(); +- if (refactoring is ExtractLocalRefactoring) { +- ExtractLocalRefactoring refactoring =3D this.refactoring; +- ExtractLocalVariableFeedback feedback =3D this.feedback; +- feedback.names =3D refactoring.names; +- feedback.offsets =3D refactoring.offsets; +- feedback.lengths =3D refactoring.lengths; +- feedback.coveringExpressionOffsets =3D +- refactoring.coveringExpressionOffsets; +- feedback.coveringExpressionLengths =3D +- refactoring.coveringExpressionLengths; +- } +- if (refactoring is ExtractMethodRefactoring) { +- ExtractMethodRefactoring refactoring =3D this.refactoring; +- ExtractMethodFeedback feedback =3D this.feedback; +- feedback.canCreateGetter =3D refactoring.canCreateGetter; +- feedback.returnType =3D refactoring.returnType; +- feedback.names =3D refactoring.names; +- feedback.parameters =3D refactoring.parameters; +- feedback.offsets =3D refactoring.offsets; +- feedback.lengths =3D refactoring.lengths; +- } +- if (refactoring is InlineLocalRefactoring) { +- InlineLocalRefactoring refactoring =3D this.refactoring; +- if (!initStatus.hasFatalError) { +- feedback =3D new InlineLocalVariableFeedback( +- refactoring.variableName, refactoring.referenceCount); +- } +- } +- if (refactoring is InlineMethodRefactoring) { +- InlineMethodRefactoring refactoring =3D this.refactoring; +- if (!initStatus.hasFatalError) { +- feedback =3D new InlineMethodFeedback( +- refactoring.methodName, refactoring.isDeclaration, +- className: refactoring.className); +- } +- } +- if (refactoring is RenameRefactoring) { +- RenameRefactoring refactoring =3D this.refactoring; +- RenameFeedback feedback =3D this.feedback; +- feedback.elementKindName =3D refactoring.elementKindName; +- feedback.oldName =3D refactoring.oldName; +- } +- } +- +- void _reset() { +- test_resetCount++; +- kind =3D null; +- offset =3D null; +- length =3D null; +- refactoring =3D null; +- feedback =3D null; +- initStatus =3D new RefactoringStatus(); +- optionsStatus =3D new RefactoringStatus(); +- finalStatus =3D new RefactoringStatus(); +- subscriptionToReset?.cancel(); +- subscriptionToReset =3D null; +- } +- +- void _resetOnAnalysisSetChanged() { +- subscriptionToReset?.cancel(); +- subscriptionToReset =3D server.onAnalysisSetChanged.listen((_) { +- _reset(); +- }); +- } +- +- void _sendResultResponse() { +- // ignore if was cancelled +- if (request =3D=3D null) { +- return; +- } +- // set feedback +- result.feedback =3D feedback; +- // set problems +- result.initialProblems =3D initStatus.problems; +- result.optionsProblems =3D optionsStatus.problems; +- result.finalProblems =3D finalStatus.problems; +- // send the response +- server.sendResponse(result.toResponse(request.id)); +- // done with this request +- request =3D null; +- result =3D null; +- } +- +- RefactoringStatus _setOptions(EditGetRefactoringParams params) { +- if (refactoring is ExtractLocalRefactoring) { +- ExtractLocalRefactoring extractRefactoring =3D refactoring; +- ExtractLocalVariableOptions extractOptions =3D params.options; +- extractRefactoring.name =3D extractOptions.name; +- extractRefactoring.extractAll =3D extractOptions.extractAll; +- return extractRefactoring.checkName(); +- } +- if (refactoring is ExtractMethodRefactoring) { +- ExtractMethodRefactoring extractRefactoring =3D this.refactoring; +- ExtractMethodOptions extractOptions =3D params.options; +- extractRefactoring.createGetter =3D extractOptions.createGetter; +- extractRefactoring.extractAll =3D extractOptions.extractAll; +- extractRefactoring.name =3D extractOptions.name; +- if (extractOptions.parameters !=3D null) { +- extractRefactoring.parameters =3D extractOptions.parameters; +- } +- extractRefactoring.returnType =3D extractOptions.returnType; +- return extractRefactoring.checkName(); +- } +- if (refactoring is InlineMethodRefactoring) { +- InlineMethodRefactoring inlineRefactoring =3D this.refactoring; +- InlineMethodOptions inlineOptions =3D params.options; +- inlineRefactoring.deleteSource =3D inlineOptions.deleteSource; +- inlineRefactoring.inlineAll =3D inlineOptions.inlineAll; +- return new RefactoringStatus(); +- } +- if (refactoring is RenameRefactoring) { +- RenameRefactoring renameRefactoring =3D refactoring; +- RenameOptions renameOptions =3D params.options; +- renameRefactoring.newName =3D renameOptions.newName; +- return renameRefactoring.checkNewName(); +- } +- return new RefactoringStatus(); +- } +-} +- +-/** +- * [_RefactoringManager] throws instances of this class internally to stop +- * processing in a manager that was reset. +- */ +-class _ResetError {} +diff --git a/pkg/analysis_server/lib/src/operation/operation_analysis.dart= b/pkg/analysis_server/lib/src/operation/operation_analysis.dart +deleted file mode 100644 +index 60bfdae9c11..00000000000 +--- a/pkg/analysis_server/lib/src/operation/operation_analysis.dart ++++ /dev/null +@@ -1,164 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/computer/computer_closingLabels.dart'; +-import 'package:analysis_server/src/computer/computer_highlights.dart'; +-import 'package:analysis_server/src/computer/computer_highlights2.dart'; +-import 'package:analysis_server/src/computer/computer_outline.dart'; +-import 'package:analysis_server/src/computer/computer_overrides.dart'; +-import 'package:analysis_server/src/domains/analysis/implemented_dart.dar= t'; +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-Future scheduleImplementedNotification( +- AnalysisServer server, Iterable files) async { +- SearchEngine searchEngine =3D server.searchEngine; +- if (searchEngine =3D=3D null) { +- return; +- } +- for (String file in files) { +- CompilationUnit unit =3D server.getCachedAnalysisResult(file)?.unit; +- CompilationUnitElement unitElement =3D unit?.element; +- if (unitElement !=3D null) { +- try { +- ImplementedComputer computer =3D +- new ImplementedComputer(searchEngine, unitElement); +- await computer.compute(); +- var params =3D new protocol.AnalysisImplementedParams( +- file, computer.classes, computer.members); +- server.sendNotification(params.toNotification()); +- } catch (exception, stackTrace) { +- server.sendServerErrorNotification( +- 'Failed to send analysis.implemented notification.', +- exception, +- stackTrace); +- } +- } +- } +-} +- +-void sendAnalysisNotificationAnalyzedFiles(AnalysisServer server) { +- _sendNotification(server, () { +- Set analyzedFiles =3D server.driverMap.values +- .map((driver) =3D> driver.knownFiles) +- .expand((files) =3D> files) +- .toSet(); +- +- // Exclude *.yaml files because IDEA Dart plugin attempts to index +- // all the files in folders which contain analyzed files. +- analyzedFiles.removeWhere((file) =3D> file.endsWith('.yaml')); +- +- Set prevAnalyzedFiles =3D server.prevAnalyzedFiles; +- if (prevAnalyzedFiles !=3D null && +- prevAnalyzedFiles.length =3D=3D analyzedFiles.length && +- prevAnalyzedFiles.difference(analyzedFiles).isEmpty) { +- // No change to the set of analyzed files. No need to send another +- // notification. +- return; +- } +- server.prevAnalyzedFiles =3D analyzedFiles; +- protocol.AnalysisAnalyzedFilesParams params =3D +- new protocol.AnalysisAnalyzedFilesParams(analyzedFiles.toList()); +- server.sendNotification(params.toNotification()); +- }); +-} +- +-void sendAnalysisNotificationClosingLabels(AnalysisServer server, String = file, +- LineInfo lineInfo, CompilationUnit dartUnit) { +- _sendNotification(server, () { +- var labels =3D +- new DartUnitClosingLabelsComputer(lineInfo, dartUnit).compute(); +- var params =3D new protocol.AnalysisClosingLabelsParams(file, labels); +- server.sendNotification(params.toNotification()); +- }); +-} +- +-void sendAnalysisNotificationFlushResults( +- AnalysisServer server, List files) { +- _sendNotification(server, () { +- if (files !=3D null && files.isNotEmpty) { +- var params =3D new protocol.AnalysisFlushResultsParams(files); +- server.sendNotification(params.toNotification()); +- } +- }); +-} +- +-void sendAnalysisNotificationHighlights( +- AnalysisServer server, String file, CompilationUnit dartUnit) { +- _sendNotification(server, () { +- List regions; +- if (server.options.useAnalysisHighlight2) { +- regions =3D new DartUnitHighlightsComputer2(dartUnit).compute(); +- } else { +- regions =3D new DartUnitHighlightsComputer(dartUnit).compute(); +- } +- var params =3D new protocol.AnalysisHighlightsParams(file, regions); +- server.sendNotification(params.toNotification()); +- }); +-} +- +-void sendAnalysisNotificationOutline(AnalysisServer server, String file, +- LineInfo lineInfo, SourceKind sourceKind, CompilationUnit dartUnit) { +- _sendNotification(server, () { +- // compute FileKind +- protocol.FileKind fileKind =3D protocol.FileKind.LIBRARY; +- if (sourceKind =3D=3D SourceKind.LIBRARY) { +- fileKind =3D protocol.FileKind.LIBRARY; +- } else if (sourceKind =3D=3D SourceKind.PART) { +- fileKind =3D protocol.FileKind.PART; +- } +- // compute library name +- String libraryName =3D _computeLibraryName(dartUnit); +- // compute Outline +- var computer =3D new DartUnitOutlineComputer(file, lineInfo, dartUnit= ); +- protocol.Outline outline =3D computer.compute(); +- // send notification +- var params =3D new protocol.AnalysisOutlineParams(file, fileKind, out= line, +- libraryName: libraryName); +- server.sendNotification(params.toNotification()); +- }); +-} +- +-void sendAnalysisNotificationOverrides( +- AnalysisServer server, String file, CompilationUnit dartUnit) { +- _sendNotification(server, () { +- var overrides =3D new DartUnitOverridesComputer(dartUnit).compute(); +- var params =3D new protocol.AnalysisOverridesParams(file, overrides); +- server.sendNotification(params.toNotification()); +- }); +-} +- +-String _computeLibraryName(CompilationUnit unit) { +- for (Directive directive in unit.directives) { +- if (directive is LibraryDirective && directive.name !=3D null) { +- return directive.name.name; +- } +- } +- for (Directive directive in unit.directives) { +- if (directive is PartOfDirective && directive.libraryName !=3D null) { +- return directive.libraryName.name; +- } +- } +- return null; +-} +- +-/** +- * Runs the given notification producing function [f], catching exception= s. +- */ +-void _sendNotification(AnalysisServer server, f()) { +- ServerPerformanceStatistics.notices.makeCurrentWhile(() { +- try { +- f(); +- } catch (exception, stackTrace) { +- server.sendServerErrorNotification( +- 'Failed to send notification', exception, stackTrace); +- } +- }); +-} +diff --git a/pkg/analysis_server/lib/src/plugin/notification_manager.dart = b/pkg/analysis_server/lib/src/plugin/notification_manager.dart +deleted file mode 100644 +index 9aad4d53e86..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/notification_manager.dart ++++ /dev/null +@@ -1,365 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:collection'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analysis_server/src/channel/channel.dart'; +-import 'package:analysis_server/src/plugin/result_collector.dart'; +-import 'package:analysis_server/src/plugin/result_converter.dart'; +-import 'package:analysis_server/src/plugin/result_merger.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +- +-/** +- * The object used to coordinate the results of notifications from the an= alysis +- * server and multiple plugins. +- */ +-class NotificationManager { +- /** +- * The identifier used to identify results from the server. +- */ +- static const String serverId =3D 'server'; +- +- /** +- * The channel used to send notifications to the client. +- */ +- final ServerCommunicationChannel channel; +- +- /** +- * The resource provider used to get the path context. +- */ +- final ResourceProvider provider; +- +- /** +- * A list of the paths of files and directories that are included for a= nalysis. +- */ +- List includedPaths =3D []; +- +- /** +- * A list of the paths of files and directories that are excluded from +- * analysis. +- */ +- List excludedPaths =3D []; +- +- /** +- * The current set of subscriptions to which the client has subscribed. +- */ +- Map> currentSubscriptions =3D +- >{}; +- +- /** +- * The collector being used to collect the analysis errors from the plu= gins. +- */ +- ResultCollector> errors; +- +- /** +- * The collector being used to collect the folding regions from the plu= gins. +- */ +- ResultCollector> folding; +- +- /** +- * The collector being used to collect the highlight regions from the p= lugins. +- */ +- ResultCollector> highlights; +- +- /** +- * The collector being used to collect the navigation parameters from t= he +- * plugins. +- */ +- ResultCollector navigation; +- +- /** +- * The collector being used to collect the occurrences from the plugins. +- */ +- ResultCollector> occurrences; +- +- /** +- * The collector being used to collect the outlines from the plugins. +- */ +- ResultCollector> outlines; +- +- /** +- * The object used to convert results. +- */ +- ResultConverter converter =3D new ResultConverter(); +- +- /** +- * The object used to merge results. +- */ +- ResultMerger merger =3D new ResultMerger(); +- +- /** +- * Initialize a newly created notification manager. +- */ +- NotificationManager(this.channel, this.provider) { +- errors =3D new ResultCollector>(serverId, +- predicate: _isIncluded); +- folding =3D new ResultCollector>(serverId); +- highlights =3D new ResultCollector>(serverId); +- navigation =3D new ResultCollector(s= erverId); +- occurrences =3D new ResultCollector>(serverId); +- outlines =3D new ResultCollector>(serverId); +- } +- +- /** +- * Handle the given [notification] from the plugin with the given [plug= inId]. +- */ +- void handlePluginNotification( +- String pluginId, plugin.Notification notification) { +- String event =3D notification.event; +- switch (event) { +- case plugin.ANALYSIS_NOTIFICATION_ERRORS: +- plugin.AnalysisErrorsParams params =3D +- new plugin.AnalysisErrorsParams.fromNotification(notification= ); +- recordAnalysisErrors(pluginId, params.file, params.errors); +- break; +- case plugin.ANALYSIS_NOTIFICATION_FOLDING: +- plugin.AnalysisFoldingParams params =3D +- new plugin.AnalysisFoldingParams.fromNotification(notificatio= n); +- recordFoldingRegions(pluginId, params.file, params.regions); +- break; +- case plugin.ANALYSIS_NOTIFICATION_HIGHLIGHTS: +- plugin.AnalysisHighlightsParams params =3D +- new plugin.AnalysisHighlightsParams.fromNotification(notifica= tion); +- recordHighlightRegions(pluginId, params.file, params.regions); +- break; +- case plugin.ANALYSIS_NOTIFICATION_NAVIGATION: +- plugin.AnalysisNavigationParams params =3D +- new plugin.AnalysisNavigationParams.fromNotification(notifica= tion); +- recordNavigationParams(pluginId, params.file, +- converter.convertAnalysisNavigationParams(params)); +- break; +- case plugin.ANALYSIS_NOTIFICATION_OCCURRENCES: +- plugin.AnalysisOccurrencesParams params =3D +- new plugin.AnalysisOccurrencesParams.fromNotification(notific= ation); +- recordOccurrences(pluginId, params.file, params.occurrences); +- break; +- case plugin.ANALYSIS_NOTIFICATION_OUTLINE: +- plugin.AnalysisOutlineParams params =3D +- new plugin.AnalysisOutlineParams.fromNotification(notificatio= n); +- recordOutlines(pluginId, params.file, params.outline); +- break; +- case plugin.PLUGIN_NOTIFICATION_ERROR: +- plugin.PluginErrorParams params =3D +- new plugin.PluginErrorParams.fromNotification(notification); +- // TODO(brianwilkerson) There is no indication for the client as = to the +- // fact that the error came from a plugin, let alone which plugin= it +- // came from. We should consider whether we really want to send t= hem to +- // the client. +- channel.sendNotification(new server.ServerErrorParams( +- params.isFatal, params.message, params.stackTrace) +- .toNotification()); +- break; +- } +- } +- +- /** +- * Record error information from the plugin with the given [pluginId] f= or the +- * file with the given [filePath]. +- */ +- void recordAnalysisErrors( +- String pluginId, String filePath, List errorData) { +- if (errors.isCollectingFor(filePath)) { +- errors.putResults(filePath, pluginId, errorData); +- List> unmergedErrors =3D errors.getResults(file= Path); +- List mergedErrors =3D +- merger.mergeAnalysisErrors(unmergedErrors); +- channel.sendNotification( +- new server.AnalysisErrorsParams(filePath, mergedErrors) +- .toNotification()); +- } +- } +- +- /** +- * Record folding information from the plugin with the given [pluginId]= for +- * the file with the given [filePath]. +- */ +- void recordFoldingRegions( +- String pluginId, String filePath, List foldingData) { +- if (folding.isCollectingFor(filePath)) { +- folding.putResults(filePath, pluginId, foldingData); +- List> unmergedFolding =3D folding.getResults(fi= lePath); +- List mergedFolding =3D +- merger.mergeFoldingRegions(unmergedFolding); +- channel.sendNotification( +- new server.AnalysisFoldingParams(filePath, mergedFolding) +- .toNotification()); +- } +- } +- +- /** +- * Record highlight information from the plugin with the given [pluginI= d] for +- * the file with the given [filePath]. +- */ +- void recordHighlightRegions( +- String pluginId, String filePath, List highlightDa= ta) { +- if (highlights.isCollectingFor(filePath)) { +- highlights.putResults(filePath, pluginId, highlightData); +- List> unmergedHighlights =3D +- highlights.getResults(filePath); +- List mergedHighlights =3D +- merger.mergeHighlightRegions(unmergedHighlights); +- channel.sendNotification( +- new server.AnalysisHighlightsParams(filePath, mergedHighlights) +- .toNotification()); +- } +- } +- +- /** +- * Record navigation information from the plugin with the given [plugin= Id] for +- * the file with the given [filePath]. +- */ +- void recordNavigationParams(String pluginId, String filePath, +- server.AnalysisNavigationParams navigationData) { +- if (navigation.isCollectingFor(filePath)) { +- navigation.putResults(filePath, pluginId, navigationData); +- List unmergedNavigations =3D +- navigation.getResults(filePath); +- server.AnalysisNavigationParams mergedNavigations =3D +- merger.mergeNavigation(unmergedNavigations); +- channel.sendNotification(mergedNavigations.toNotification()); +- } +- } +- +- /** +- * Record occurrences information from the plugin with the given [plugi= nId] +- * for the file with the given [filePath]. +- */ +- void recordOccurrences( +- String pluginId, String filePath, List occurrencesData= ) { +- if (occurrences.isCollectingFor(filePath)) { +- occurrences.putResults(filePath, pluginId, occurrencesData); +- List> unmergedOccurrences =3D +- occurrences.getResults(filePath); +- List mergedOccurrences =3D +- merger.mergeOccurrences(unmergedOccurrences); +- channel.sendNotification( +- new server.AnalysisOccurrencesParams(filePath, mergedOccurrence= s) +- .toNotification()); +- } +- } +- +- /** +- * Record outline information from the plugin with the given [pluginId]= for +- * the file with the given [filePath]. +- */ +- void recordOutlines( +- String pluginId, String filePath, List outlineData) { +- if (outlines.isCollectingFor(filePath)) { +- outlines.putResults(filePath, pluginId, outlineData); +- List> unmergedOutlines =3D outlines.getResults(filePa= th); +- List mergedOutlines =3D merger.mergeOutline(unmergedOutlin= es); +- channel.sendNotification(new server.AnalysisOutlineParams( +- filePath, server.FileKind.LIBRARY, mergedOutlines[0]) +- .toNotification()); +- } +- } +- +- /** +- * Set the lists of [included] and [excluded] files. +- */ +- void setAnalysisRoots(List included, List excluded) { +- includedPaths =3D included; +- excludedPaths =3D excluded; +- } +- +- /** +- * Set the current subscriptions to the given set of [newSubscriptions]. +- */ +- void setSubscriptions( +- Map> newSubscriptions) { +- /** +- * Return the collector associated with the given service, or `null` = if the +- * service is not handled by this manager. +- */ +- ResultCollector collectorFor(server.AnalysisService service) { +- switch (service) { +- case server.AnalysisService.FOLDING: +- return folding; +- case server.AnalysisService.HIGHLIGHTS: +- return highlights; +- case server.AnalysisService.NAVIGATION: +- return navigation; +- case server.AnalysisService.OCCURRENCES: +- return occurrences; +- case server.AnalysisService.OUTLINE: +- return outlines; +- } +- return null; +- } +- +- Set services =3D +- new HashSet(); +- services.addAll(currentSubscriptions.keys); +- services.addAll(newSubscriptions.keys); +- services.forEach((server.AnalysisService service) { +- ResultCollector collector =3D collectorFor(service); +- if (collector !=3D null) { +- Set currentPaths =3D currentSubscriptions[service]; +- Set newPaths =3D newSubscriptions[service]; +- if (currentPaths =3D=3D null) { +- if (newPaths =3D=3D null) { +- // This should not happen. +- return; +- } +- // All of the [newPaths] need to be added. +- newPaths.forEach((String filePath) { +- collector.startCollectingFor(filePath); +- }); +- } else if (newPaths =3D=3D null) { +- // All of the [currentPaths] need to be removed. +- currentPaths.forEach((String filePath) { +- collector.stopCollectingFor(filePath); +- }); +- } else { +- // Compute the difference of the two sets. +- newPaths.forEach((String filePath) { +- if (!currentPaths.contains(filePath)) { +- collector.startCollectingFor(filePath); +- } +- }); +- currentPaths.forEach((String filePath) { +- if (!newPaths.contains(filePath)) { +- collector.stopCollectingFor(filePath); +- } +- }); +- } +- } +- }); +- currentSubscriptions =3D newSubscriptions; +- } +- +- /** +- * Return `true` if errors should be collected for the file with the gi= ven +- * [path] (because it is being analyzed). +- */ +- bool _isIncluded(String path) { +- bool isIncluded() { +- for (String includedPath in includedPaths) { +- if (provider.pathContext.isWithin(includedPath, path) || +- provider.pathContext.equals(includedPath, path)) { +- return true; +- } +- } +- return false; +- } +- +- bool isExcluded() { +- for (String excludedPath in excludedPaths) { +- if (provider.pathContext.isWithin(excludedPath, path)) { +- return true; +- } +- } +- return false; +- } +- +- // TODO(brianwilkerson) Return false if error notifications are globa= lly +- // disabled. +- return isIncluded() && !isExcluded(); +- } +-} +diff --git a/pkg/analysis_server/lib/src/plugin/plugin_locator.dart b/pkg/= analysis_server/lib/src/plugin/plugin_locator.dart +deleted file mode 100644 +index ba53ab348cb..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/plugin_locator.dart ++++ /dev/null +@@ -1,105 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/file_system/file_system.dart'; +- +-/** +- * An object used to locate a plugin within a package. +- */ +-class PluginLocator { +- /** +- * The key used in the `pubspec.yaml` file to specify the location of t= he +- * analysis plugin. +- */ +- static const String analyzerPluginKey =3D 'analyzer_plugin'; +- +- /** +- * The name of the default plugin directory, located within the `tools` +- * directory. +- */ +- static const String defaultPluginFolderName =3D 'analyzer_plugin'; +- +- /** +- * The name of the `pubspec.yaml` file. +- */ +- static const String pubspecFileName =3D 'pubspec.yaml'; +- +- /** +- * The name of the `tools` directory, in which the default plugin direc= tory is +- * located. +- */ +- static const String toolsFolderName =3D 'tools'; +- +- /** +- * The resource provider used to access the file system. +- */ +- final ResourceProvider resourceProvider; +- +- final Map pluginMap =3D {}; +- +- /** +- * Initialize a newly created plugin locator to use the given +- * [resourceProvider] to access the file system. +- */ +- PluginLocator(this.resourceProvider); +- +- /** +- * Given the root directory of a package (the [packageRoot]), return th= e path +- * to the plugin associated with the package, or `null` if there is no = plugin +- * associated with the package. +- * +- * This will look first in the `pubspec.yaml` file in the package root = for a +- * top-level key (`analysis_plugin`) indicating where the plugin is loc= ated. +- * The value associated with the key is expected to be the path of the = plugin +- * relative to the package root. If the directory exists, the it is ret= urned. +- * +- * If the key is not defined in the `pubspec.yaml` file, or if the dire= ctory +- * given does not exist, then this method will look for the directory +- * `tools/analysis_plugin` relative to the package root. If the directo= ry +- * exists, then it is returned. +- * +- * This method does not validate the content of the plugin directory be= fore +- * returning it. +- */ +- String findPlugin(String packageRoot) { +- return pluginMap.putIfAbsent(packageRoot, () =3D> _findPlugin(package= Root)); +- } +- +- /** +- * The implementation of [findPlugin]. +- */ +- String _findPlugin(String packageRoot) { +- Folder packageFolder =3D resourceProvider.getFolder(packageRoot); +- // TODO(brianwilkerson) Re-enable this after deciding how we want to = deal +- // with discovery of plugins. +-// import 'package:yaml/yaml.dart'; +-// File pubspecFile =3D packageFolder.getChildAssumingFile(pubspecFile= Name); +-// if (pubspecFile.exists) { +-// try { +-// YamlDocument document =3D loadYamlDocument(pubspecFile.readAsSt= ringSync(), +-// sourceUrl: pubspecFile.toUri()); +-// YamlNode contents =3D document.contents; +-// if (contents is YamlMap) { +-// String pluginPath =3D contents[analyzerPluginKey]; +-// if (pluginPath !=3D null) { +-// Folder pluginFolder =3D +-// packageFolder.getChildAssumingFolder(pluginPath); +-// if (pluginFolder.exists) { +-// return pluginFolder.path; +-// } +-// } +-// } +-// } catch (exception) { +-// // If we can't read the file, or if it isn't valid YAML, then i= gnore it. +-// } +-// } +- Folder pluginFolder =3D packageFolder +- .getChildAssumingFolder(toolsFolderName) +- .getChildAssumingFolder(defaultPluginFolderName); +- if (pluginFolder.exists) { +- return pluginFolder.path; +- } +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart b/pkg/= analysis_server/lib/src/plugin/plugin_manager.dart +deleted file mode 100644 +index cf271e5a00f..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart ++++ /dev/null +@@ -1,1102 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:convert'; +-import 'dart:io' show Platform, Process, ProcessResult; +- +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analyzer/context/context_root.dart' as analyzer; +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/generated/bazel.dart'; +-import 'package:analyzer/src/generated/gn.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/workspace.dart'; +-import 'package:analyzer/src/util/glob.dart'; +-import 'package:analyzer_plugin/channel/channel.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/src/channel/isolate_channel.dart'; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart'; +-import 'package:convert/convert.dart'; +-import 'package:crypto/crypto.dart'; +-import 'package:meta/meta.dart'; +-import 'package:path/path.dart' as path; +-import 'package:watcher/watcher.dart' as watcher; +-import 'package:yaml/yaml.dart'; +- +-/** +- * Information about a plugin that is built-in. +- */ +-class BuiltInPluginInfo extends PluginInfo { +- /** +- * The entry point function that will be executed in the plugin's isola= te. +- */ +- final EntryPoint entryPoint; +- +- @override +- final String pluginId; +- +- /** +- * Initialize a newly created built-in plugin. +- */ +- BuiltInPluginInfo( +- this.entryPoint, +- this.pluginId, +- NotificationManager notificationManager, +- InstrumentationService instrumentationService) +- : super(notificationManager, instrumentationService); +- +- @override +- ServerCommunicationChannel _createChannel() { +- return new ServerIsolateChannel.builtIn( +- entryPoint, pluginId, instrumentationService); +- } +-} +- +-/** +- * Information about a plugin that was discovered. +- */ +-class DiscoveredPluginInfo extends PluginInfo { +- /** +- * The path to the root directory of the definition of the plugin on di= sk (the +- * directory containing the 'pubspec.yaml' file and the 'bin' directory= ). +- */ +- final String path; +- +- /** +- * The path to the 'plugin.dart' file that will be executed in an isola= te. +- */ +- final String executionPath; +- +- /** +- * The path to the '.packages' file used to control the resolution of +- * 'package:' URIs. +- */ +- final String packagesPath; +- +- /** +- * Initialize the newly created information about a plugin. +- */ +- DiscoveredPluginInfo( +- this.path, +- this.executionPath, +- this.packagesPath, +- NotificationManager notificationManager, +- InstrumentationService instrumentationService) +- : super(notificationManager, instrumentationService); +- +- @override +- bool get canBeStarted =3D> executionPath !=3D null; +- +- @override +- String get pluginId =3D> path; +- +- @override +- ServerCommunicationChannel _createChannel() { +- return new ServerIsolateChannel.discovered( +- new Uri.file(executionPath, windows: Platform.isWindows), +- new Uri.file(packagesPath, windows: Platform.isWindows), +- instrumentationService); +- } +-} +- +-/** +- * An indication of a problem with the execution of a plugin that occurs = prior +- * to the execution of the plugin's entry point in an isolate. +- */ +-class PluginException implements Exception { +- /** +- * A message describing the problem. +- */ +- final String message; +- +- /** +- * Initialize a newly created exception to have the given [message]. +- */ +- PluginException(this.message); +- +- @override +- String toString() =3D> message; +-} +- +-/** +- * Information about a single plugin. +- */ +-abstract class PluginInfo { +- /** +- * The object used to manage the receiving and sending of notifications. +- */ +- final NotificationManager notificationManager; +- +- /** +- * The instrumentation service that is being used by the analysis serve= r. +- */ +- final InstrumentationService instrumentationService; +- +- /** +- * The context roots that are currently using the results produced by t= he +- * plugin. +- */ +- Set contextRoots =3D new HashSet(); +- +- /** +- * The current execution of the plugin, or `null` if the plugin is not +- * currently being executed. +- */ +- PluginSession currentSession; +- +- /** +- * The exception that occurred that prevented the plugin from being sta= rted, +- * or `null` if there was no exception (possibly because no attempt has= yet +- * been made to start the plugin). +- */ +- CaughtException exception; +- +- /** +- * Initialize the newly created information about a plugin. +- */ +- PluginInfo(this.notificationManager, this.instrumentationService); +- +- /** +- * Return `true` if this plugin can be started, or `false` if there is a +- * reason why it cannot be started. For example, a plugin cannot be sta= rted if +- * there was an error with a previous attempt to start running it or if= the +- * plugin is not correctly configured. +- */ +- bool get canBeStarted =3D> true; +- +- /** +- * Return the data known about this plugin. +- */ +- PluginData get data =3D> +- new PluginData(pluginId, currentSession?.name, currentSession?.vers= ion); +- +- /** +- * Return the id of this plugin, used to identify the plugin to users. +- */ +- String get pluginId; +- +- /** +- * Add the given [contextRoot] to the set of context roots being analyz= ed by +- * this plugin. +- */ +- void addContextRoot(analyzer.ContextRoot contextRoot) { +- if (contextRoots.add(contextRoot)) { +- _updatePluginRoots(); +- } +- } +- +- /** +- * Add the given context [roots] to the set of context roots being anal= yzed by +- * this plugin. +- */ +- void addContextRoots(Iterable roots) { +- bool changed =3D false; +- for (analyzer.ContextRoot contextRoot in roots) { +- if (contextRoots.add(contextRoot)) { +- changed =3D true; +- } +- } +- if (changed) { +- _updatePluginRoots(); +- } +- } +- +- /** +- * Return `true` if at least one of the context roots being analyzed co= ntains +- * the file with the given [filePath]. +- */ +- bool isAnalyzing(String filePath) { +- for (var contextRoot in contextRoots) { +- if (contextRoot.containsFile(filePath)) { +- return true; +- } +- } +- return false; +- } +- +- /** +- * Remove the given [contextRoot] from the set of context roots being a= nalyzed +- * by this plugin. +- */ +- void removeContextRoot(analyzer.ContextRoot contextRoot) { +- if (contextRoots.remove(contextRoot)) { +- _updatePluginRoots(); +- } +- } +- +- /** +- * If the plugin is currently running, send a request based on the given +- * [params] to the plugin. If the plugin is not running, the request wi= ll +- * silently be dropped. +- */ +- void sendRequest(RequestParams params) { +- currentSession?.sendRequest(params); +- } +- +- /** +- * Start a new isolate that is running the plugin. Return the state obj= ect +- * used to interact with the plugin, or `null` if the plugin could not = be run. +- */ +- Future start(String byteStorePath, String sdkPath) async= { +- if (currentSession !=3D null) { +- throw new StateError('Cannot start a plugin that is already running= .'); +- } +- currentSession =3D new PluginSession(this); +- bool isRunning =3D await currentSession.start(byteStorePath, sdkPath); +- if (!isRunning) { +- currentSession =3D null; +- } +- return currentSession; +- } +- +- /** +- * Request that the plugin shutdown. +- */ +- Future stop() { +- if (currentSession =3D=3D null) { +- throw new StateError('Cannot stop a plugin that is not running.'); +- } +- Future doneFuture =3D currentSession.stop(); +- currentSession =3D null; +- return doneFuture; +- } +- +- /** +- * Create and return the channel used to communicate with the server. +- */ +- ServerCommunicationChannel _createChannel(); +- +- /** +- * Update the context roots that the plugin should be analyzing. +- */ +- void _updatePluginRoots() { +- if (currentSession !=3D null) { +- AnalysisSetContextRootsParams params =3D new AnalysisSetContextRoot= sParams( +- contextRoots +- .map((analyzer.ContextRoot contextRoot) =3D> new ContextRoo= t( +- contextRoot.root, contextRoot.exclude, +- optionsFile: contextRoot.optionsFilePath)) +- .toList()); +- currentSession.sendRequest(params); +- } +- } +-} +- +-/** +- * An object used to manage the currently running plugins. +- */ +-class PluginManager { +- /** +- * A table, keyed by both a plugin and a request method, to a list of t= he +- * times that it took the plugin to return a response to requests with = the +- * method. +- */ +- static Map>> pluginResponseTimes =3D +- >>{}; +- +- /** +- * The resource provider used to access the file system. +- */ +- final ResourceProvider resourceProvider; +- +- /** +- * The absolute path of the directory containing the on-disk byte store= , or +- * `null` if there is no on-disk store. +- */ +- final String byteStorePath; +- +- /** +- * The absolute path of the directory containing the SDK. +- */ +- final String sdkPath; +- +- /** +- * The object used to manage the receiving and sending of notifications. +- */ +- final NotificationManager notificationManager; +- +- /** +- * The instrumentation service that is being used by the analysis serve= r. +- */ +- final InstrumentationService instrumentationService; +- +- /** +- * A table mapping the paths of plugins to information about those plug= ins. +- */ +- Map _pluginMap =3D {}; +- +- /** +- * The parameters for the last 'analysis.setPriorityFiles' request that= was +- * received from the client. Because plugins are lazily discovered, thi= s needs +- * to be retained so that it can be sent after a plugin has been starte= d. +- */ +- AnalysisSetPriorityFilesParams _analysisSetPriorityFilesParams; +- +- /** +- * The parameters for the last 'analysis.setSubscriptions' request that= was +- * received from the client. Because plugins are lazily discovered, thi= s needs +- * to be retained so that it can be sent after a plugin has been starte= d. +- */ +- AnalysisSetSubscriptionsParams _analysisSetSubscriptionsParams; +- +- /** +- * The current state of content overlays. Because plugins are lazily +- * discovered, the state needs to be retained so that it can be sent af= ter a +- * plugin has been started. +- */ +- Map _overlayState =3D {}; +- +- /** +- * Initialize a newly created plugin manager. The notifications from the +- * running plugins will be handled by the given [notificationManager]. +- */ +- PluginManager(this.resourceProvider, this.byteStorePath, this.sdkPath, +- this.notificationManager, this.instrumentationService); +- +- /** +- * Return a list of all of the plugins that are currently known. +- */ +- @visibleForTesting +- List get plugins =3D> _pluginMap.values.toList(); +- +- /** +- * Add the plugin with the given [path] to the list of plugins that sho= uld be +- * used when analyzing code for the given [contextRoot]. If the plugin = had not +- * yet been started, then it will be started by this method. +- */ +- Future addPluginToContextRoot( +- analyzer.ContextRoot contextRoot, String path) async { +- PluginInfo plugin =3D _pluginMap[path]; +- bool isNew =3D plugin =3D=3D null; +- if (isNew) { +- List pluginPaths; +- try { +- pluginPaths =3D pathsFor(path); +- } catch (exception, stackTrace) { +- plugin =3D new DiscoveredPluginInfo( +- path, null, null, notificationManager, instrumentationService= ); +- plugin.exception =3D new CaughtException(exception, stackTrace); +- _pluginMap[path] =3D plugin; +- return; +- } +- plugin =3D new DiscoveredPluginInfo(path, pluginPaths[0], pluginPat= hs[1], +- notificationManager, instrumentationService); +- _pluginMap[path] =3D plugin; +- if (pluginPaths[0] !=3D null) { +- try { +- PluginSession session =3D await plugin.start(byteStorePath, sdk= Path); +- session?.onDone?.then((_) { +- _pluginMap.remove(path); +- }); +- } catch (exception, stackTrace) { +- // Record the exception (for debugging purposes) and record the= fact +- // that we should not try to communicate with the plugin. +- plugin.exception =3D new CaughtException(exception, stackTrace); +- isNew =3D false; +- } +- } +- } +- plugin.addContextRoot(contextRoot); +- if (isNew) { +- if (_analysisSetSubscriptionsParams !=3D null) { +- plugin.sendRequest(_analysisSetSubscriptionsParams); +- } +- if (_overlayState.isNotEmpty) { +- plugin.sendRequest(new AnalysisUpdateContentParams(_overlayState)= ); +- } +- if (_analysisSetPriorityFilesParams !=3D null) { +- plugin.sendRequest(_analysisSetPriorityFilesParams); +- } +- } +- } +- +- /** +- * Broadcast a request built from the given [params] to all of the plug= ins +- * that are currently associated with the given [contextRoot]. Return a= list +- * containing futures that will complete when each of the plugins have = sent a +- * response. +- */ +- Map> broadcastRequest(RequestParams params, +- {analyzer.ContextRoot contextRoot}) { +- List plugins =3D pluginsForContextRoot(contextRoot); +- Map> responseMap =3D +- >{}; +- for (PluginInfo plugin in plugins) { +- responseMap[plugin] =3D plugin.currentSession?.sendRequest(params); +- } +- return responseMap; +- } +- +- /** +- * Broadcast the given [watchEvent] to all of the plugins that are anal= yzing +- * in contexts containing the file associated with the event. Return a = list +- * containing futures that will complete when each of the plugins have = sent a +- * response. +- */ +- Future>> broadcastWatchEvent( +- watcher.WatchEvent watchEvent) async { +- String filePath =3D watchEvent.path; +- +- /** +- * Return `true` if the given glob [pattern] matches the file being w= atched. +- */ +- bool matches(String pattern) =3D> +- new Glob(resourceProvider.pathContext.separator, pattern) +- .matches(filePath); +- +- WatchEvent event =3D null; +- List> responses =3D >[]; +- for (PluginInfo plugin in _pluginMap.values) { +- PluginSession session =3D plugin.currentSession; +- if (session !=3D null && +- plugin.isAnalyzing(filePath) && +- session.interestingFiles !=3D null && +- session.interestingFiles.any(matches)) { +- // The list of interesting file globs is `null` if the plugin has= not +- // yet responded to the plugin.versionCheck request. If that happ= ens +- // then the plugin hasn't had a chance to analyze anything yet, a= nd +- // hence it does not needed to get watch events. +- event ??=3D _convertWatchEvent(watchEvent); +- AnalysisHandleWatchEventsParams params =3D +- new AnalysisHandleWatchEventsParams([event]); +- responses.add(session.sendRequest(params)); +- } +- } +- return responses; +- } +- +- /** +- * Return the execution path and .packages path associated with the plu= gin at +- * the given [path]. Throw a [PluginException] if there is a problem th= at +- * prevents the plugin from being executing. +- */ +- @visibleForTesting +- List pathsFor(String pluginPath) { +- Folder pluginFolder =3D resourceProvider.getFolder(pluginPath); +- File pubspecFile =3D pluginFolder.getChildAssumingFile('pubspec.yaml'= ); +- if (!pubspecFile.exists) { +- // If there's no pubspec file, then we don't need to copy the packa= ge +- // because we won't be running pub. +- return _computePaths(pluginFolder); +- } +- Workspace workspace =3D +- BazelWorkspace.find(resourceProvider, pluginFolder.path) ?? +- GnWorkspace.find(resourceProvider, pluginFolder.path); +- if (workspace !=3D null) { +- // Similarly, we won't be running pub if we're in a workspace becau= se +- // there is exactly one version of each package. +- return _computePaths(pluginFolder, workspace: workspace); +- } +- // +- // Copy the plugin directory to a unique subdirectory of the plugin +- // manager's state location. The subdirectory's name is selected such= that +- // it will be invariant across sessions, reducing the number of times= the +- // plugin will need to be copied and pub will need to be run. +- // +- Folder stateFolder =3D resourceProvider.getStateLocation('.plugin_man= ager'); +- String stateName =3D _uniqueDirectoryName(pluginPath); +- Folder parentFolder =3D stateFolder.getChildAssumingFolder(stateName); +- if (parentFolder.exists) { +- Folder executionFolder =3D +- parentFolder.getChildAssumingFolder(pluginFolder.shortName); +- return _computePaths(executionFolder); +- } +- Folder executionFolder =3D pluginFolder.copyTo(parentFolder); +- return _computePaths(executionFolder, runPub: true); +- } +- +- /** +- * Return a list of all of the plugins that are currently associated wi= th the +- * given [contextRoot]. +- */ +- @visibleForTesting +- List pluginsForContextRoot(analyzer.ContextRoot contextRoot= ) { +- if (contextRoot =3D=3D null) { +- return _pluginMap.values.toList(); +- } +- List plugins =3D []; +- for (PluginInfo plugin in _pluginMap.values) { +- if (plugin.contextRoots.contains(contextRoot)) { +- plugins.add(plugin); +- } +- } +- return plugins; +- } +- +- /** +- * Record a failure to run the plugin associated with the host package = with +- * the given [hostPackageName]. The failure is described by the [messag= e], and +- * is expected to have occurred before a path could be computed, and he= nce +- * before [addPluginToContextRoot] could be invoked. +- */ +- void recordPluginFailure(String hostPackageName, String message) { +- try { +- throw new PluginException(message); +- } catch (exception, stackTrace) { +- String pluginPath =3D +- path.join(hostPackageName, 'tools', 'analyzer_plugin'); +- DiscoveredPluginInfo plugin =3D new DiscoveredPluginInfo( +- pluginPath, null, null, notificationManager, instrumentationSer= vice); +- plugin.exception =3D new CaughtException(exception, stackTrace); +- _pluginMap[pluginPath] =3D plugin; +- } +- } +- +- /** +- * The given [contextRoot] is no longer being analyzed. +- */ +- void removedContextRoot(analyzer.ContextRoot contextRoot) { +- List plugins =3D _pluginMap.values.toList(); +- for (PluginInfo plugin in plugins) { +- plugin.removeContextRoot(contextRoot); +- if (plugin is DiscoveredPluginInfo && plugin.contextRoots.isEmpty) { +- _pluginMap.remove(plugin.path); +- plugin.stop(); +- } +- } +- } +- +- /** +- * Restart all currently running plugins. +- */ +- Future restartPlugins() async { +- for (PluginInfo plugin in _pluginMap.values.toList()) { +- if (plugin.currentSession !=3D null) { +- // +- // Capture needed state. +- // +- Set contextRoots =3D plugin.contextRoots; +- String path =3D plugin.pluginId; +- // +- // Stop the plugin. +- // +- await plugin.stop(); +- // +- // Restart the plugin. +- // +- _pluginMap[path] =3D plugin; +- PluginSession session =3D await plugin.start(byteStorePath, sdkPa= th); +- session?.onDone?.then((_) { +- _pluginMap.remove(path); +- }); +- // +- // Re-initialize the plugin. +- // +- plugin.addContextRoots(contextRoots); +- if (_analysisSetSubscriptionsParams !=3D null) { +- plugin.sendRequest(_analysisSetSubscriptionsParams); +- } +- if (_overlayState.isNotEmpty) { +- plugin.sendRequest(new AnalysisUpdateContentParams(_overlayStat= e)); +- } +- if (_analysisSetPriorityFilesParams !=3D null) { +- plugin.sendRequest(_analysisSetPriorityFilesParams); +- } +- } +- } +- } +- +- /** +- * Send a request based on the given [params] to existing plugins to se= t the +- * priority files to those specified by the [params]. As a side-effect,= record +- * the parameters so that they can be sent to any newly started plugins. +- */ +- void setAnalysisSetPriorityFilesParams( +- AnalysisSetPriorityFilesParams params) { +- for (PluginInfo plugin in _pluginMap.values) { +- plugin.sendRequest(params); +- } +- _analysisSetPriorityFilesParams =3D params; +- } +- +- /** +- * Send a request based on the given [params] to existing plugins to se= t the +- * subscriptions to those specified by the [params]. As a side-effect, = record +- * the parameters so that they can be sent to any newly started plugins. +- */ +- void setAnalysisSetSubscriptionsParams( +- AnalysisSetSubscriptionsParams params) { +- for (PluginInfo plugin in _pluginMap.values) { +- plugin.sendRequest(params); +- } +- _analysisSetSubscriptionsParams =3D params; +- } +- +- /** +- * Send a request based on the given [params] to existing plugins to se= t the +- * content overlays to those specified by the [params]. As a side-effec= t, +- * update the overlay state so that it can be sent to any newly started +- * plugins. +- */ +- void setAnalysisUpdateContentParams(AnalysisUpdateContentParams params)= { +- for (PluginInfo plugin in _pluginMap.values) { +- plugin.sendRequest(params); +- } +- Map files =3D params.files; +- for (String file in files.keys) { +- Object overlay =3D files[file]; +- if (overlay is RemoveContentOverlay) { +- _overlayState.remove(file); +- } else if (overlay is AddContentOverlay) { +- _overlayState[file] =3D overlay; +- } else if (overlay is ChangeContentOverlay) { +- AddContentOverlay previousOverlay =3D _overlayState[file]; +- String newContent =3D +- SourceEdit.applySequence(previousOverlay.content, overlay.edi= ts); +- _overlayState[file] =3D new AddContentOverlay(newContent); +- } else { +- throw new ArgumentError( +- 'Invalid class of overlay: ${overlay.runtimeType}'); +- } +- } +- } +- +- /** +- * Stop all of the plugins that are currently running. +- */ +- Future> stopAll() { +- return Future.wait(_pluginMap.values.map((PluginInfo info) =3D> info.= stop())); +- } +- +- /** +- * Compute the paths to be returned by the enclosing method given that = the +- * plugin should exist in the given [pluginFolder]. +- */ +- List _computePaths(Folder pluginFolder, +- {bool runPub: false, Workspace workspace}) { +- File pluginFile =3D pluginFolder +- .getChildAssumingFolder('bin') +- .getChildAssumingFile('plugin.dart'); +- if (!pluginFile.exists) { +- throw new PluginException('File "${pluginFile.path}" does not exist= .'); +- } +- String reason; +- File packagesFile =3D pluginFolder.getChildAssumingFile('.packages'); +- if (!packagesFile.exists) { +- if (runPub) { +- String vmPath =3D Platform.executable; +- String pubPath =3D path.join(path.dirname(vmPath), 'pub'); +- ProcessResult result =3D Process.runSync(pubPath, ['get'], +- stderrEncoding: UTF8, +- stdoutEncoding: UTF8, +- workingDirectory: pluginFolder.path); +- if (result.exitCode !=3D 0) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.writeln('Failed to run pub get'); +- buffer.writeln(' pluginFolder =3D ${pluginFolder.path}'); +- buffer.writeln(' exitCode =3D ${result.exitCode}'); +- buffer.writeln(' stdout =3D ${result.stdout}'); +- buffer.writeln(' stderr =3D ${result.stderr}'); +- reason =3D buffer.toString(); +- instrumentationService.logError(reason); +- } +- if (!packagesFile.exists) { +- reason ??=3D 'File "${packagesFile.path}" does not exist.'; +- packagesFile =3D null; +- } +- } else if (workspace !=3D null) { +- packagesFile =3D +- _createPackagesFile(pluginFolder, workspace.packageUriResolve= r); +- if (packagesFile =3D=3D null) { +- reason =3D 'Could not create .packages file in workspace $works= pace.'; +- } +- } else { +- reason =3D 'Could not create "${packagesFile.path}".'; +- packagesFile =3D null; +- } +- } +- if (packagesFile =3D=3D null) { +- throw new PluginException(reason); +- } +- return [pluginFile.path, packagesFile.path]; +- } +- +- WatchEventType _convertChangeType(watcher.ChangeType type) { +- switch (type) { +- case watcher.ChangeType.ADD: +- return WatchEventType.ADD; +- case watcher.ChangeType.MODIFY: +- return WatchEventType.MODIFY; +- case watcher.ChangeType.REMOVE: +- return WatchEventType.REMOVE; +- default: +- throw new StateError('Unknown change type: $type'); +- } +- } +- +- WatchEvent _convertWatchEvent(watcher.WatchEvent watchEvent) { +- return new WatchEvent(_convertChangeType(watchEvent.type), watchEvent= .path); +- } +- +- /** +- * Return a temporary `.packages` file that is appropriate for the plug= in in +- * the given [pluginFolder]. The [packageUriResolver] is used to determ= ine the +- * location of the packages that need to be included in the packages fi= le. +- */ +- File _createPackagesFile( +- Folder pluginFolder, UriResolver packageUriResolver) { +- String pluginPath =3D pluginFolder.path; +- Folder stateFolder =3D resourceProvider.getStateLocation('.plugin_man= ager'); +- String stateName =3D _uniqueDirectoryName(pluginPath) + '.packages'; +- File packagesFile =3D stateFolder.getChildAssumingFile(stateName); +- if (!packagesFile.exists) { +- File pluginPubspec =3D pluginFolder.getChildAssumingFile('pubspec.y= aml'); +- if (!pluginPubspec.exists) { +- return null; +- } +- +- try { +- Map visitedPackages =3D {}; +- path.Context context =3D resourceProvider.pathContext; +- visitedPackages[context.basename(pluginPath)] =3D +- context.join(pluginFolder.path, 'lib'); +- List pubspecFiles =3D []; +- pubspecFiles.add(pluginPubspec); +- while (pubspecFiles.isNotEmpty) { +- File pubspecFile =3D pubspecFiles.removeLast(); +- for (String packageName in _readDependecies(pubspecFile)) { +- if (!visitedPackages.containsKey(packageName)) { +- Uri uri =3D Uri.parse('package:$packageName/$packageName.da= rt'); +- Source packageSource =3D packageUriResolver.resolveAbsolute= (uri); +- String libDirPath =3D context.dirname(packageSource.fullNam= e); +- visitedPackages[packageName] =3D libDirPath; +- String pubspecPath =3D +- context.join(context.dirname(libDirPath), 'pubspec.yaml= '); +- pubspecFiles.add(resourceProvider.getFile(pubspecPath)); +- } +- } +- } +- +- StringBuffer buffer =3D new StringBuffer(); +- visitedPackages.forEach((String name, String path) { +- buffer.write(name); +- buffer.write(':'); +- buffer.writeln(new Uri.file(path)); +- }); +- packagesFile.writeAsStringSync(buffer.toString()); +- } catch (exception) { +- // If we are not able to produce a .packages file, return null so= that +- // callers will not try to load the plugin. +- return null; +- } +- } +- return packagesFile; +- } +- +- /** +- * Return the names of packages that are listed as dependencies in the = given +- * [pubspecFile]. +- */ +- Iterable _readDependecies(File pubspecFile) { +- YamlDocument document =3D loadYamlDocument(pubspecFile.readAsStringSy= nc(), +- sourceUrl: pubspecFile.toUri()); +- YamlNode contents =3D document.contents; +- if (contents is YamlMap) { +- YamlNode dependencies =3D contents['dependencies']; +- if (dependencies is YamlMap) { +- return dependencies.keys; +- } +- } +- return const []; +- } +- +- /** +- * Return a hex-encoded MD5 signature of the given file [path]. +- */ +- String _uniqueDirectoryName(String path) { +- List bytes =3D md5.convert(path.codeUnits).bytes; +- return hex.encode(bytes); +- } +- +- /** +- * Record the fact that the given [plugin] responded to a request with = the +- * given [method] in the given [time]. +- */ +- static void recordResponseTime(PluginInfo plugin, String method, int ti= me) { +- pluginResponseTimes +- .putIfAbsent(plugin, () =3D> >{}) +- .putIfAbsent(method, () =3D> []) +- .add(time); +- } +-} +- +-/** +- * Information about the execution a single plugin. +- */ +-@visibleForTesting +-class PluginSession { +- /** +- * The maximum number of milliseconds that server should wait for a res= ponse +- * from a plugin before deciding that the plugin is hung. +- */ +- static const Duration MAXIMUM_RESPONSE_TIME =3D const Duration(minutes:= 2); +- +- /** +- * The length of time to wait after sending a 'plugin.shutdown' request= before +- * a failure to terminate will cause the isolate to be killed. +- */ +- static const Duration WAIT_FOR_SHUTDOWN_DURATION =3D +- const Duration(seconds: 10); +- +- /** +- * The information about the plugin being executed. +- */ +- final PluginInfo info; +- +- /** +- * The completer used to signal when the plugin has stopped. +- */ +- Completer pluginStoppedCompleter =3D new Completer(); +- +- /** +- * The channel used to communicate with the plugin. +- */ +- ServerCommunicationChannel channel; +- +- /** +- * The index of the next request to be sent to the plugin. +- */ +- int requestId =3D 0; +- +- /** +- * A table mapping the id's of requests to the functions used to handle= the +- * response to those requests. +- */ +- Map pendingRequests =3D {}; +- +- /** +- * A boolean indicating whether the plugin is compatible with the versi= on of +- * the plugin API being used by this server. +- */ +- bool isCompatible =3D true; +- +- /** +- * The contact information to include when reporting problems related t= o the +- * plugin. +- */ +- String contactInfo; +- +- /** +- * The glob patterns of files that the plugin is interested in knowing = about. +- */ +- List interestingFiles; +- +- /** +- * The name to be used when reporting problems related to the plugin. +- */ +- String name; +- +- /** +- * The version number to be used when reporting problems related to the +- * plugin. +- */ +- String version; +- +- /** +- * Initialize the newly created information about the execution of a pl= ugin. +- */ +- PluginSession(this.info); +- +- /** +- * Return the next request id, encoded as a string and increment the id= so +- * that a different result will be returned on each invocation. +- */ +- String get nextRequestId =3D> (requestId++).toString(); +- +- /** +- * Return a future that will complete when the plugin has stopped. +- */ +- Future get onDone =3D> pluginStoppedCompleter.future; +- +- /** +- * Handle the given [notification]. +- */ +- void handleNotification(Notification notification) { +- if (notification.event =3D=3D PLUGIN_NOTIFICATION_ERROR) { +- PluginErrorParams params =3D +- new PluginErrorParams.fromNotification(notification); +- if (params.isFatal) { +- info.stop(); +- stop(); +- } +- } +- info.notificationManager +- .handlePluginNotification(info.pluginId, notification); +- } +- +- /** +- * Handle the fact that the plugin has stopped. +- */ +- void handleOnDone() { +- if (channel !=3D null) { +- channel.close(); +- channel =3D null; +- } +- pluginStoppedCompleter.complete(null); +- } +- +- /** +- * Handle the fact that an unhandled error has occurred in the plugin. +- */ +- void handleOnError(List errorPair) { +- StackTrace stackTrace =3D new StackTrace.fromString(errorPair[1]); +- info.exception =3D +- new CaughtException(new PluginException(errorPair[0]), stackTrace= ); +- info.instrumentationService +- .logPluginException(info.data, errorPair[0], stackTrace); +- } +- +- /** +- * Handle a [response] from the plugin by completing the future that was +- * created when the request was sent. +- */ +- void handleResponse(Response response) { +- _PendingRequest requestData =3D pendingRequests.remove(response.id); +- int responseTime =3D new DateTime.now().millisecondsSinceEpoch; +- int duration =3D responseTime - requestData.requestTime; +- PluginManager.recordResponseTime(info, requestData.method, duration); +- Completer completer =3D requestData.completer; +- if (completer !=3D null) { +- completer.complete(response); +- } +- } +- +- /** +- * Return `true` if there are any requests that have not been responded= to +- * within the maximum allowed amount of time. +- */ +- bool isNonResponsive() { +- // TODO(brianwilkerson) Figure out when to invoke this method in orde= r to +- // identify non-responsive plugins and kill them. +- int cutOffTime =3D new DateTime.now().millisecondsSinceEpoch - +- MAXIMUM_RESPONSE_TIME.inMilliseconds; +- for (var requestData in pendingRequests.values) { +- if (requestData.requestTime < cutOffTime) { +- return true; +- } +- } +- return false; +- } +- +- /** +- * Send a request, based on the given [parameters]. Return a future tha= t will +- * complete when a response is received. +- */ +- Future sendRequest(RequestParams parameters) { +- if (channel =3D=3D null) { +- throw new StateError( +- 'Cannot send a request to a plugin that has stopped.'); +- } +- String id =3D nextRequestId; +- Completer completer =3D new Completer(); +- int requestTime =3D new DateTime.now().millisecondsSinceEpoch; +- Request request =3D parameters.toRequest(id); +- pendingRequests[id] =3D +- new _PendingRequest(request.method, requestTime, completer); +- channel.sendRequest(request); +- return completer.future; +- } +- +- /** +- * Start a new isolate that is running this plugin. The plugin will be = sent +- * the given [byteStorePath]. Return `true` if the plugin is compatible= and +- * running. +- */ +- Future start(String byteStorePath, String sdkPath) async { +- if (channel !=3D null) { +- throw new StateError('Cannot start a plugin that is already running= .'); +- } +- if (byteStorePath =3D=3D null || byteStorePath.isEmpty) { +- throw new StateError('Missing byte store path'); +- } +- if (!isCompatible) { +- info.exception =3D new CaughtException( +- new PluginException('Plugin is not compatible.'), null); +- return false; +- } +- if (!info.canBeStarted) { +- info.exception =3D new CaughtException( +- new PluginException('Plugin cannot be started.'), null); +- return false; +- } +- channel =3D info._createChannel(); +- await channel.listen(handleResponse, handleNotification, +- onDone: handleOnDone, onError: handleOnError); +- if (channel =3D=3D null) { +- // If there is an error when starting the isolate, the channel will= invoke +- // handleOnDone, which will cause `channel` to be set to `null`. +- info.exception ??=3D new CaughtException( +- new PluginException('Unrecorded error while starting the plugin= .'), +- null); +- return false; +- } +- Response response =3D await sendRequest(new PluginVersionCheckParams( +- byteStorePath ?? '', sdkPath, '1.0.0-alpha.0')); +- PluginVersionCheckResult result =3D +- new PluginVersionCheckResult.fromResponse(response); +- isCompatible =3D result.isCompatible; +- contactInfo =3D result.contactInfo; +- interestingFiles =3D result.interestingFiles; +- name =3D result.name; +- version =3D result.version; +- if (!isCompatible) { +- sendRequest(new PluginShutdownParams()); +- info.exception =3D new CaughtException( +- new PluginException('Plugin is not compatible.'), null); +- return false; +- } +- return true; +- } +- +- /** +- * Request that the plugin shutdown. +- */ +- Future stop() { +- if (channel =3D=3D null) { +- throw new StateError('Cannot stop a plugin that is not running.'); +- } +- sendRequest(new PluginShutdownParams()); +- new Future.delayed(WAIT_FOR_SHUTDOWN_DURATION, () { +- if (channel !=3D null) { +- channel.kill(); +- channel =3D null; +- } +- }); +- return pluginStoppedCompleter.future; +- } +-} +- +-/** +- * Information about a request that has been sent but for which a respons= e has +- * not yet been received. +- */ +-class _PendingRequest { +- /** +- * The method of the request. +- */ +- final String method; +- +- /** +- * The time at which the request was sent to the plugin. +- */ +- final int requestTime; +- +- /** +- * The completer that will be used to complete the future when the resp= onse is +- * received from the plugin. +- */ +- final Completer completer; +- +- /** +- * Initialize a pending request. +- */ +- _PendingRequest(this.method, this.requestTime, this.completer); +-} +diff --git a/pkg/analysis_server/lib/src/plugin/plugin_watcher.dart b/pkg/= analysis_server/lib/src/plugin/plugin_watcher.dart +deleted file mode 100644 +index 8de5ea28564..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/plugin_watcher.dart ++++ /dev/null +@@ -1,134 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/plugin/plugin_locator.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/util/absolute_path.dart'; +-import 'package:front_end/src/base/source.dart'; +-import 'package:path/src/context.dart'; +- +-/** +- * An object that watches the results produced by analysis drivers to ide= ntify +- * references to previously unseen packages and, if those packages have p= lugins +- * associated with them, causes the plugin to be associated with the driv= er's +- * context root (which in turn might cause the plugin to be started). +- */ +-class PluginWatcher implements DriverWatcher { +- /** +- * The resource provider used to access the file system. +- */ +- final ResourceProvider resourceProvider; +- +- /** +- * The object managing the execution of plugins. +- */ +- final PluginManager manager; +- +- /** +- * The object used to locate plugins within packages. +- */ +- final PluginLocator _locator; +- +- /** +- * A table mapping analysis drivers to information related to the drive= r. +- */ +- Map _driverInfo =3D +- {}; +- +- /** +- * Initialize a newly created plugin watcher. +- */ +- PluginWatcher(this.resourceProvider, this.manager) +- : _locator =3D new PluginLocator(resourceProvider); +- +- /** +- * The context manager has just added the given analysis [driver]. This= method +- * must be called before the driver has been allowed to perform any ana= lysis. +- */ +- void addedDriver(AnalysisDriver driver, ContextRoot contextRoot) { +- _driverInfo[driver] =3D new _DriverInfo( +- contextRoot, [contextRoot.root, _getSdkPath(driver)]); +- List enabledPlugins =3D driver.analysisOptions.enabledPluginN= ames; +- for (String hostPackageName in enabledPlugins) { +- // +- // Determine whether the package exists and defines a plugin. +- // +- String uri =3D 'package:$hostPackageName/$hostPackageName.dart'; +- Source source =3D driver.sourceFactory.forUri(uri); +- if (source =3D=3D null) { +- manager.recordPluginFailure(hostPackageName, +- 'Could not resolve "$uri" in ${contextRoot.root}.'); +- } else { +- Context context =3D resourceProvider.pathContext; +- String packageRoot =3D context.dirname(context.dirname(source.ful= lName)); +- String pluginPath =3D _locator.findPlugin(packageRoot); +- if (pluginPath =3D=3D null) { +- manager.recordPluginFailure( +- hostPackageName, 'Could not find plugin in "$packageRoot".'= ); +- } else { +- // +- // Add the plugin to the context root. +- // +- // TODO(brianwilkerson) Do we need to wait for the plugin to be= added? +- // If we don't, then tests don't have any way to know when to e= xpect +- // that the list of plugins has been updated. +- manager.addPluginToContextRoot(contextRoot, pluginPath); +- } +- } +- } +- } +- +- /** +- * The context manager has just removed the given analysis [driver]. +- */ +- void removedDriver(AnalysisDriver driver) { +- _DriverInfo info =3D _driverInfo[driver]; +- if (info =3D=3D null) { +- throw new StateError('Cannot remove a driver that was not added'); +- } +- manager.removedContextRoot(info.contextRoot); +- _driverInfo.remove(driver); +- } +- +- /** +- * Return the path to the root of the SDK being used by the given analy= sis +- * [driver]. +- */ +- String _getSdkPath(AnalysisDriver driver) { +- AbsolutePathContext context =3D resourceProvider.absolutePathContext; +- String sdkRoot =3D driver.sourceFactory.forUri('dart:core').fullName; +- while (context.basename(sdkRoot) !=3D 'lib') { +- String parent =3D context.dirname(sdkRoot); +- if (parent =3D=3D sdkRoot) { +- break; +- } +- sdkRoot =3D parent; +- } +- return sdkRoot; +- } +-} +- +-/** +- * Information related to an analysis driver. +- */ +-class _DriverInfo { +- /** +- * The context root representing the context being analyzed by the driv= er. +- */ +- final ContextRoot contextRoot; +- +- /** +- * A list of the absolute paths of directories inside of which we have = already +- * searched for a plugin. +- */ +- final List packageRoots; +- +- /** +- * Initialize a newly created information holder. +- */ +- _DriverInfo(this.contextRoot, this.packageRoots); +-} +diff --git a/pkg/analysis_server/lib/src/plugin/request_converter.dart b/p= kg/analysis_server/lib/src/plugin/request_converter.dart +deleted file mode 100644 +index 5caa0710217..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/request_converter.dart ++++ /dev/null +@@ -1,46 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analysis_server/src/protocol/protocol_internal.dart' as s= erver; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +- +-/** +- * An object used to convert between similar objects defined by both the = plugin +- * protocol and the server protocol. +- */ +-class RequestConverter { +- plugin.AnalysisService convertAnalysisService( +- server.AnalysisService service) { +- return new plugin.AnalysisService(service.name); +- } +- +- plugin.AnalysisSetPriorityFilesParams convertAnalysisSetPriorityFilesPa= rams( +- server.AnalysisSetPriorityFilesParams params) { +- return new plugin.AnalysisSetPriorityFilesParams(params.files); +- } +- +- plugin.AnalysisSetSubscriptionsParams convertAnalysisSetSubscriptionsPa= rams( +- server.AnalysisSetSubscriptionsParams params) { +- Map> serverSubscriptions =3D +- params.subscriptions; +- Map> pluginSubscriptions =3D +- >{}; +- for (server.AnalysisService service in serverSubscriptions.keys) { +- try { +- pluginSubscriptions[convertAnalysisService(service)] =3D +- serverSubscriptions[service]; +- } catch (exception) { +- // Ignore the exception. It indicates that the service isn't one = that +- // should be passed along to plugins. +- } +- } +- return new plugin.AnalysisSetSubscriptionsParams(pluginSubscriptions); +- } +- +- plugin.AnalysisUpdateContentParams convertAnalysisUpdateContentParams( +- server.AnalysisUpdateContentParams params) { +- return new plugin.AnalysisUpdateContentParams(params.files); +- } +-} +diff --git a/pkg/analysis_server/lib/src/plugin/result_collector.dart b/pk= g/analysis_server/lib/src/plugin/result_collector.dart +deleted file mode 100644 +index c2e32742943..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/result_collector.dart ++++ /dev/null +@@ -1,124 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * A function used to determine whether results should be collected for t= he +- * file with the given [path]. +- */ +-typedef bool ShouldCollectPredicate(String path); +- +-/** +- * An object used to collect partial results (of type [E]) where the part= ial +- * results are contributed by plugins. +- */ +-class ResultCollector { +- /** +- * The id used as a plugin id for contributions from the server. +- */ +- final String serverId; +- +- /** +- * A function used to determine whether results should be collected for= the +- * file whose path is passed in as an argument. +- */ +- final ShouldCollectPredicate _shouldCollect; +- +- /** +- * A multi-keyed map, where the first key is the (normalized and absolu= te) +- * path to the file associated with the results, and the second is the = id of +- * the plugin that provided the partial results. The value is the parti= al +- * results contributed by the plugin for the file. +- */ +- Map> resultMap =3D >{}; +- +- /** +- * Initialize a newly created result manager. +- */ +- ResultCollector(this.serverId, {ShouldCollectPredicate predicate}) +- : _shouldCollect =3D predicate; +- +- /** +- * Clear any results that have been contributed for the file with the g= iven +- * [filePath], but continue to collect results for the file. This is us= ed when +- * the results for the specified file are known to be invalid, typically +- * because the content of the file has been modified. +- */ +- void clearResultsForFile(String filePath) { +- resultMap[filePath]?.clear(); +- } +- +- /** +- * Clear any results that have been contributed by the plugin with the = given +- * [pluginId]. +- */ +- void clearResultsFromPlugin(String pluginId) { +- for (Map partialResults in resultMap.values) { +- partialResults.remove(pluginId); +- } +- } +- +- /** +- * Return an iterator producing the partial results that have been cont= ributed +- * for the given [filePath]. +- */ +- List getResults(String filePath) { +- Map partialResultMap =3D resultMap[filePath]; +- if (partialResultMap =3D=3D null) { +- return []; +- } +- List values =3D partialResultMap.values.toList(); +- // +- // Ensure that the server's contributions are always first in the lis= t. +- // +- E serverContributions =3D partialResultMap[serverId]; +- if (serverContributions !=3D null && values.remove(serverContribution= s)) { +- values.insert(0, serverContributions); +- } +- return values; +- } +- +- /** +- * Return `true` if this collector is collecting results associated wit= h the +- * given [filePath]. +- */ +- bool isCollectingFor(String filePath) { +- if (_shouldCollect !=3D null) { +- return _shouldCollect(filePath); +- } +- return resultMap.containsKey(filePath); +- } +- +- /** +- * Record the [partialResults] as having been contributed for the given +- * [filePath] by the plugin with the given [pluginId]. +- */ +- void putResults(String filePath, String pluginId, E partialResults) { +- Map fileResults =3D resultMap[filePath]; +- if (fileResults =3D=3D null) { +- if (_shouldCollect !=3D null && _shouldCollect(filePath)) { +- resultMap[filePath] =3D {pluginId: partialResults}; +- } +- } else { +- fileResults[pluginId] =3D partialResults; +- } +- } +- +- /** +- * Start collecting results contributed for the file with the given +- * [filePath]. Unless the collector is told to collect results for a fi= le, any +- * results that are contributed for that file are discarded. +- */ +- void startCollectingFor(String filePath) { +- resultMap.putIfAbsent(filePath, () =3D> {}); +- } +- +- /** +- * Stop collecting results contributed for the file with the given [fil= ePath]. +- * Until the collector is told to start collecting results for the file= , any +- * results that are contributed for the file are discarded. +- */ +- void stopCollectingFor(String filePath) { +- resultMap.remove(filePath); +- } +-} +diff --git a/pkg/analysis_server/lib/src/plugin/result_converter.dart b/pk= g/analysis_server/lib/src/plugin/result_converter.dart +deleted file mode 100644 +index 40a5d2b8035..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/result_converter.dart ++++ /dev/null +@@ -1,46 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analysis_server/src/protocol/protocol_internal.dart' as s= erver; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +- +-/** +- * An object used to convert between similar objects defined by both the = plugin +- * protocol and the server protocol. +- */ +-class ResultConverter { +- /** +- * The decoder used to decode Json representations of server objects. +- */ +- static final server.ResponseDecoder decoder =3D +- new server.ResponseDecoder(null); +- +- server.AnalysisErrorFixes convertAnalysisErrorFixes( +- plugin.AnalysisErrorFixes fixes) { +- List changes =3D fixes.fixes +- .map((plugin.PrioritizedSourceChange change) =3D> +- convertPrioritizedSourceChange(change)) +- .toList(); +- return new server.AnalysisErrorFixes(fixes.error, fixes: changes); +- } +- +- server.AnalysisNavigationParams convertAnalysisNavigationParams( +- plugin.AnalysisNavigationParams params) { +- return new server.AnalysisNavigationParams.fromJson( +- decoder, '', params.toJson()); +- } +- +- server.EditGetRefactoringResult convertEditGetRefactoringResult( +- RefactoringKind kind, plugin.EditGetRefactoringResult result) { +- return new server.EditGetRefactoringResult.fromJson( +- new server.ResponseDecoder(kind), '', result.toJson()); +- } +- +- SourceChange convertPrioritizedSourceChange( +- plugin.PrioritizedSourceChange change) { +- return change.change; +- } +-} +diff --git a/pkg/analysis_server/lib/src/plugin/result_merger.dart b/pkg/a= nalysis_server/lib/src/plugin/result_merger.dart +deleted file mode 100644 +index 06f08405ee2..00000000000 +--- a/pkg/analysis_server/lib/src/plugin/result_merger.dart ++++ /dev/null +@@ -1,846 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:collection'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:meta/meta.dart'; +- +-/** +- * An object used to merge partial lists of results that were contributed= by +- * plugins. +- * +- * All of the methods in this class assume that the contributions from the +- * analysis server are the first partial result in the list of partial re= sults +- * to be merged. +- */ +-class ResultMerger { +- /** +- * Return a list of fixes composed by merging the lists of fixes in the +- * [partialResultList]. +- * +- * The resulting list of fixes will contain exactly one fix for every a= nalysis +- * error for which there are fixes. If two or more plugins contribute t= he same +- * fix for a given error, the resulting list will contain duplications. +- */ +- List mergeAnalysisErrorFixes( +- List> partialResultList) { +- /** +- * Return a key encoding the unique attributes of the given [error]. +- */ +- String computeKey(AnalysisError error) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write(error.location.offset); +- buffer.write(';'); +- buffer.write(error.code); +- buffer.write(';'); +- buffer.write(error.message); +- buffer.write(';'); +- buffer.write(error.correction); +- return buffer.toString(); +- } +- +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- Map fixesMap =3D +- {}; +- for (plugin.AnalysisErrorFixes fix in partialResultList[0]) { +- fixesMap[computeKey(fix.error)] =3D fix; +- } +- for (int i =3D 1; i < count; i++) { +- for (plugin.AnalysisErrorFixes fix in partialResultList[i]) { +- String key =3D computeKey(fix.error); +- plugin.AnalysisErrorFixes mergedFix =3D fixesMap[key]; +- if (mergedFix =3D=3D null) { +- fixesMap[key] =3D fix; +- } else { +- // If more than two plugins contribute fixes for the same error= , this +- // will result in extra copy operations. +- List mergedChanges =3D +- mergedFix.fixes.toList(); +- mergedChanges.addAll(fix.fixes); +- plugin.AnalysisErrorFixes copiedFix =3D new plugin.AnalysisErro= rFixes( +- mergedFix.error, +- fixes: mergedChanges); +- fixesMap[key] =3D copiedFix; +- } +- } +- } +- List mergedFixes =3D fixesMap.values.toLis= t(); +- for (plugin.AnalysisErrorFixes fixes in mergedFixes) { +- fixes.fixes.sort((first, second) =3D> first.priority - second.prior= ity); +- } +- return mergedFixes; +- } +- +- /** +- * Return a list of errors composed by merging the lists of errors in t= he +- * [partialResultList]. +- * +- * The resulting list will contain all of the analysis errors from all = of the +- * plugins. If two or more plugins contribute the same error the result= ing +- * list will contain duplications. +- */ +- List mergeAnalysisErrors( +- List> partialResultList) { +- // TODO(brianwilkerson) Consider merging duplicate errors (same code, +- // location, and messages). If we do that, we should return the logic= al-or +- // of the hasFix fields from the merged errors. +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedErrors =3D []; +- for (List partialResults in partialResultList) { +- mergedErrors.addAll(partialResults); +- } +- return mergedErrors; +- } +- +- /** +- * Return a list of suggestions composed by merging the lists of sugges= tions +- * in the [partialResultList]. +- * +- * The resulting list will contain all of the suggestions from all of t= he +- * plugins. If two or more plugins contribute the same suggestion the +- * resulting list will contain duplications. +- */ +- List mergeCompletionSuggestions( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedSuggestions =3D []; +- for (List partialResults in partialResultList) { +- mergedSuggestions.addAll(partialResults); +- } +- return mergedSuggestions; +- } +- +- /** +- * Return a list of regions composed by merging the lists of regions in= the +- * [partialResultList]. +- * +- * The resulting list will contain all of the folding regions from all = of the +- * plugins. If a plugin contributes a folding region that overlaps a re= gion +- * from a previous plugin, the overlapping region will be omitted. (For= these +- * purposes, if either region is fully contained within the other they = are not +- * considered to be overlapping.) +- */ +- List mergeFoldingRegions( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedRegions =3D partialResultList[0].toList(); +- +- /** +- * Return `true` if the [newRegion] does not overlap any of the regio= ns in +- * the collection of [mergedRegions]. +- */ +- bool isNonOverlapping(FoldingRegion newRegion) { +- int newStart =3D newRegion.offset; +- int newEnd =3D newStart + newRegion.length; +- for (FoldingRegion existingRegion in mergedRegions) { +- int existingStart =3D existingRegion.offset; +- int existingEnd =3D existingStart + existingRegion.length; +- if (overlaps(newStart, newEnd, existingStart, existingEnd, +- allowNesting: true)) { +- return false; +- } +- } +- return true; +- } +- +- for (int i =3D 1; i < count; i++) { +- List partialResults =3D partialResultList[i]; +- for (FoldingRegion region in partialResults) { +- if (isNonOverlapping(region)) { +- mergedRegions.add(region); +- } +- } +- } +- return mergedRegions; +- } +- +- /** +- * Return a list of regions composed by merging the lists of regions in= the +- * [partialResultList]. +- * +- * The resulting list will contain all of the highlight regions from al= l of +- * the plugins. If two or more plugins contribute the same highlight re= gion +- * the resulting list will contain duplications. +- */ +- List mergeHighlightRegions( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedRegions =3D []; +- for (List partialResults in partialResultList) { +- mergedRegions.addAll(partialResults); +- } +- return mergedRegions; +- } +- +- /** +- * Return kythe entry result parameters composed by merging the paramet= ers in +- * the [partialResultList]. +- * +- * The resulting list will contain all of the kythe entries from all of= the +- * plugins. If a plugin contributes a kythe entry that is the same as t= he +- * entry from a different plugin, the entry will appear twice in the li= st. +- */ +- KytheGetKytheEntriesResult mergeKytheEntries( +- List partialResultList) { +- List mergedEntries =3D []; +- Set mergedFiles =3D new Set(); +- for (KytheGetKytheEntriesResult partialResult in partialResultList) { +- mergedEntries.addAll(partialResult.entries); +- mergedFiles.addAll(partialResult.files); +- } +- return new KytheGetKytheEntriesResult(mergedEntries, mergedFiles.toLi= st()); +- } +- +- /** +- * Return navigation notification parameters composed by merging the +- * parameters in the [partialResultList]. +- * +- * The resulting list will contain all of the navigation regions from a= ll of +- * the plugins. If a plugin contributes a navigation region that overla= ps a +- * region from a previous plugin, the overlapping region will be omitte= d. (For +- * these purposes, nested regions are considered to be overlapping.) +- */ +- AnalysisNavigationParams mergeNavigation( +- List partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return null; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- AnalysisNavigationParams base =3D partialResultList[0]; +- String file =3D base.file; +- List mergedRegions =3D base.regions.toList(); +- List mergedTargets =3D base.targets.toList(); +- List mergedFiles =3D base.files.toList(); +- +- /** +- * Return `true` if the [newRegion] does not overlap any of the regio= ns in +- * the collection of [mergedRegions]. +- */ +- bool isNonOverlapping(NavigationRegion newRegion) { +- int newStart =3D newRegion.offset; +- int newEnd =3D newStart + newRegion.length; +- for (NavigationRegion mergedRegion in mergedRegions) { +- int mergedStart =3D mergedRegion.offset; +- int mergedEnd =3D mergedStart + mergedRegion.length; +- if (overlaps(newStart, newEnd, mergedStart, mergedEnd)) { +- return false; +- } +- } +- return true; +- } +- +- /** +- * Return the index of the region in the collection of [mergedRegions= ] that +- * covers exactly the same region as the [newRegion], or `-1` if ther= e is no +- * such region. +- */ +- int matchingRegion(newRegion) { +- int newOffset =3D newRegion.offset; +- int newLength =3D newRegion.length; +- for (int i =3D 0; i < mergedRegions.length; i++) { +- NavigationRegion mergedRegion =3D mergedRegions[i]; +- if (newOffset =3D=3D mergedRegion.offset && +- newLength =3D=3D mergedRegion.length) { +- return i; +- } +- } +- return -1; +- } +- +- for (int i =3D 1; i < count; i++) { +- // For now we take the optimistic approach of assuming that most or= all of +- // the regions will not overlap and that we therefore don't need to= remove +- // any unreferenced files or targets from the lists. If that isn't = true +- // then this could result in server sending more data to the client= than +- // is necessary. +- AnalysisNavigationParams result =3D partialResultList[i]; +- List regions =3D result.regions; +- List targets =3D result.targets; +- List files =3D result.files; +- // +- // Merge the file data. +- // +- Map fileMap =3D {}; +- for (int j =3D 0; j < files.length; j++) { +- String file =3D files[j]; +- int index =3D mergedFiles.indexOf(file); +- if (index < 0) { +- index =3D mergedFiles.length; +- mergedFiles.add(file); +- } +- fileMap[j] =3D index; +- } +- // +- // Merge the target data. +- // +- Map targetMap =3D {}; +- for (int j =3D 0; j < targets.length; j++) { +- NavigationTarget target =3D targets[j]; +- int newIndex =3D fileMap[target.fileIndex]; +- if (target.fileIndex !=3D newIndex) { +- target =3D new NavigationTarget(target.kind, newIndex, target.o= ffset, +- target.length, target.startLine, target.startColumn); +- } +- int index =3D mergedTargets.indexOf(target); +- if (index < 0) { +- index =3D mergedTargets.length; +- mergedTargets.add(target); +- } +- targetMap[j] =3D index; +- } +- // +- // Merge the region data. +- // +- for (int j =3D 0; j < regions.length; j++) { +- NavigationRegion region =3D regions[j]; +- List newTargets =3D region.targets +- .map((int oldTarget) =3D> targetMap[oldTarget]) +- .toList(); +- if (region.targets !=3D newTargets) { +- region =3D +- new NavigationRegion(region.offset, region.length, newTarge= ts); +- } +- int index =3D matchingRegion(region); +- if (index >=3D 0) { +- NavigationRegion mergedRegion =3D mergedRegions[index]; +- List mergedTargets =3D mergedRegion.targets; +- bool added =3D false; +- for (int target in region.targets) { +- if (!mergedTargets.contains(target)) { +- if (added) { +- mergedTargets.add(target); +- } else { +- // +- // This is potentially inefficient. If a merged region ma= tches +- // regions from multiple plugins it will be copied multip= le +- // times. The likelihood seems small enough to not warrant +- // optimizing this further. +- // +- mergedTargets =3D mergedTargets.toList(); +- mergedTargets.add(target); +- mergedRegion =3D new NavigationRegion( +- mergedRegion.offset, mergedRegion.length, mergedTarge= ts); +- mergedRegions[index] =3D mergedRegion; +- added =3D true; +- } +- } +- } +- if (added) { +- mergedTargets.sort(); +- } +- } else if (isNonOverlapping(region)) { +- mergedRegions.add(region); +- } +- } +- } +- return new AnalysisNavigationParams( +- file, mergedRegions, mergedTargets, mergedFiles); +- } +- +- /** +- * Return a list of occurrences composed by merging the lists of occurr= ences +- * in the [partialResultList]. +- * +- * The resulting list of occurrences will contain exactly one occurrenc= es for +- * every element for which there is at least one occurrences. If two or= more +- * plugins contribute an occurrences for the same element, the resulting +- * occurrences for that element will include all of the locations from = all of +- * the plugins without duplications. +- */ +- List mergeOccurrences( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- Map> elementMap =3D >{}; +- for (List partialResults in partialResultList) { +- for (Occurrences occurances in partialResults) { +- Element element =3D occurances.element; +- Set offsets =3D +- elementMap.putIfAbsent(element, () =3D> new HashSet()); +- offsets.addAll(occurances.offsets); +- } +- } +- List mergedOccurrences =3D []; +- elementMap.forEach((Element element, Set offsets) { +- List sortedOffsets =3D offsets.toList(); +- sortedOffsets.sort(); +- mergedOccurrences +- .add(new Occurrences(element, sortedOffsets, element.name.lengt= h)); +- }); +- return mergedOccurrences; +- } +- +- /** +- * Return a list of outlines composed by merging the lists of outlines = in the +- * [partialResultList]. +- * +- * The resulting list of outlines will contain ... +- * +- * Throw an exception if any of the outlines are associated with an ele= ment +- * that does not have a location. +- * +- * Throw an exception if any outline has children that are also childre= n of +- * another outline. No exception is thrown if a plugin contributes a to= p-level +- * outline that is a child of an outline contributed by a different plu= gin. +- */ +- List mergeOutline(List> partialResultList) { +- /** +- * Return a key encoding the unique attributes of the given [element]. +- */ +- String computeKey(Element element) { +- Location location =3D element.location; +- if (location =3D=3D null) { +- throw new StateError( +- 'Elements in an outline are expected to have a location'); +- } +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write(location.offset); +- buffer.write(';'); +- buffer.write(element.kind.name); +- return buffer.toString(); +- } +- +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedOutlines =3D partialResultList[0].toList(); +- Map outlineMap =3D {}; +- Map copyMap =3D {}; +- +- /** +- * Add the given [outline] and all of its children to the [outlineMap= ]. +- */ +- void addToMap(Outline outline) { +- String key =3D computeKey(outline.element); +- if (outlineMap.containsKey(key)) { +- // TODO(brianwilkerson) Decide how to handle this more gracefully. +- throw new StateError('Inconsistent outlines'); +- } +- outlineMap[key] =3D outline; +- outline.children?.forEach(addToMap); +- } +- +- /** +- * Merge the children of the [newOutline] into the list of children o= f the +- * [mergedOutline]. +- */ +- void mergeChildren(Outline mergedOutline, Outline newOutline) { +- for (Outline newChild in newOutline.children) { +- Outline mergedChild =3D outlineMap[computeKey(newChild.element)]; +- if (mergedChild =3D=3D null) { +- // The [newChild] isn't in the existing list. +- Outline copiedOutline =3D copyMap.putIfAbsent( +- mergedOutline, +- () =3D> new Outline(mergedOutline.element, mergedOutline.of= fset, +- mergedOutline.length, +- children: mergedOutline.children.toList())); +- copiedOutline.children.add(newChild); +- addToMap(newChild); +- } else { +- mergeChildren(mergedChild, newChild); +- } +- } +- } +- +- mergedOutlines.forEach(addToMap); +- for (int i =3D 1; i < count; i++) { +- for (Outline outline in partialResultList[i]) { +- Outline mergedOutline =3D outlineMap[computeKey(outline.element)]; +- if (mergedOutline =3D=3D null) { +- // The [outline] does not correspond to any previously merged o= utline. +- mergedOutlines.add(outline); +- addToMap(outline); +- } else { +- // The [outline] corresponds to a previously merged outline, so= we +- // just need to add its children to the merged outline's childr= en. +- mergeChildren(mergedOutline, outline); +- } +- } +- } +- +- /** +- * Perform a depth first traversal of the outline structure rooted at= the +- * given [outline] item, re-building each item if any of its children= have +- * been updated by the merge process. +- */ +- Outline traverse(Outline outline) { +- Outline copiedOutline =3D copyMap[outline]; +- bool isCopied =3D copiedOutline !=3D null; +- copiedOutline ??=3D outline; +- List currentChildren =3D copiedOutline.children; +- if (currentChildren =3D=3D null || currentChildren.isEmpty) { +- return outline; +- } +- List updatedChildren =3D +- currentChildren.map((Outline child) =3D> traverse(child)).toLis= t(); +- if (currentChildren !=3D updatedChildren) { +- if (!isCopied) { +- return new Outline( +- copiedOutline.element, copiedOutline.offset, copiedOutline.= length, +- children: updatedChildren); +- } +- copiedOutline.children =3D updatedChildren; +- return copiedOutline; +- } +- return outline; +- } +- +- for (int i =3D 0; i < mergedOutlines.length; i++) { +- mergedOutlines[i] =3D traverse(mergedOutlines[i]); +- } +- return mergedOutlines; +- } +- +- /** +- * Return a list of source changes composed by merging the lists of sou= rce +- * changes in the [partialResultList]. +- * +- * The resulting list will contain all of the source changes from all o= f the +- * plugins. If two or more plugins contribute the same source change the +- * resulting list will contain duplications. +- */ +- List mergePrioritizedSourceChanges( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedChanges =3D +- []; +- for (List partialResults +- in partialResultList) { +- mergedChanges.addAll(partialResults); +- } +- mergedChanges.sort((first, second) =3D> first.priority - second.prior= ity); +- return mergedChanges; +- } +- +- /** +- * Return a refactoring feedback composed by merging the refactoring fe= edbacks +- * in the [partialResultList]. +- * +- * The content of the resulting feedback depends on the kind of feedbac= ks +- * being merged. +- * +- * Throw an exception if the refactoring feedbacks are of an unhandled = type. +- * +- * The feedbacks in the [partialResultList] are expected to all be of t= he same +- * type. If that expectation is violated, and exception might be thrown. +- */ +- RefactoringFeedback mergeRefactoringFeedbacks( +- List feedbacks) { +- int count =3D feedbacks.length; +- if (count =3D=3D 0) { +- return null; +- } else if (count =3D=3D 1) { +- return feedbacks[0]; +- } +- RefactoringFeedback first =3D feedbacks[0]; +- if (first is ConvertGetterToMethodFeedback) { +- // The feedbacks are empty, so there's nothing to merge. +- return first; +- } else if (first is ConvertMethodToGetterFeedback) { +- // The feedbacks are empty, so there's nothing to merge. +- return first; +- } else if (first is ExtractLocalVariableFeedback) { +- List coveringExpressionOffsets =3D +- first.coveringExpressionOffsets =3D=3D null +- ? [] +- : first.coveringExpressionOffsets.toList(); +- List coveringExpressionLengths =3D +- first.coveringExpressionLengths =3D=3D null +- ? [] +- : first.coveringExpressionLengths.toList(); +- List names =3D first.names.toList(); +- List offsets =3D first.offsets.toList(); +- List lengths =3D first.lengths.toList(); +- for (int i =3D 1; i < count; i++) { +- ExtractLocalVariableFeedback feedback =3D feedbacks[i]; +- // TODO(brianwilkerson) This doesn't ensure that the covering dat= a is in +- // the right order and consistent. +- if (feedback.coveringExpressionOffsets !=3D null) { +- coveringExpressionOffsets.addAll(feedback.coveringExpressionOff= sets); +- } +- if (feedback.coveringExpressionLengths !=3D null) { +- coveringExpressionLengths.addAll(feedback.coveringExpressionLen= gths); +- } +- for (String name in feedback.names) { +- if (!names.contains(name)) { +- names.add(name); +- } +- } +- offsets.addAll(feedback.offsets); +- lengths.addAll(feedback.lengths); +- } +- return new ExtractLocalVariableFeedback(names.toList(), offsets, le= ngths, +- coveringExpressionOffsets: (coveringExpressionOffsets.isEmpty +- ? null +- : coveringExpressionOffsets), +- coveringExpressionLengths: (coveringExpressionLengths.isEmpty +- ? null +- : coveringExpressionLengths)); +- } else if (first is ExtractMethodFeedback) { +- int offset =3D first.offset; +- int length =3D first.length; +- String returnType =3D first.returnType; +- List names =3D first.names.toList(); +- bool canCreateGetter =3D first.canCreateGetter; +- List parameters =3D first.parameters; +- List offsets =3D first.offsets.toList(); +- List lengths =3D first.lengths.toList(); +- for (int i =3D 1; i < count; i++) { +- ExtractMethodFeedback feedback =3D feedbacks[i]; +- if (returnType.isEmpty) { +- returnType =3D feedback.returnType; +- } +- for (String name in feedback.names) { +- if (!names.contains(name)) { +- names.add(name); +- } +- } +- canCreateGetter =3D canCreateGetter && feedback.canCreateGetter; +- // TODO(brianwilkerson) This doesn't allow plugins to add paramet= ers. +- // TODO(brianwilkerson) This doesn't check for duplicate offsets. +- offsets.addAll(feedback.offsets); +- lengths.addAll(feedback.lengths); +- } +- return new ExtractMethodFeedback(offset, length, returnType, +- names.toList(), canCreateGetter, parameters, offsets, lengths); +- } else if (first is InlineLocalVariableFeedback) { +- int occurrences =3D first.occurrences; +- for (int i =3D 1; i < count; i++) { +- occurrences +=3D +- (feedbacks[i] as InlineLocalVariableFeedback).occurrences; +- } +- return new InlineLocalVariableFeedback(first.name, occurrences); +- } else if (first is InlineMethodFeedback) { +- // There is nothing in the feedback that can reasonably be extended= or +- // modified by other plugins. +- return first; +- } else if (first is MoveFileFeedback) { +- // The feedbacks are empty, so there's nothing to merge. +- return first; +- } else if (first is RenameFeedback) { +- // There is nothing in the feedback that can reasonably be extended= or +- // modified by other plugins. +- return first; +- } +- throw new StateError( +- 'Unsupported class of refactoring feedback: ${first.runtimeType}'= ); +- } +- +- /** +- * Return a list of refactoring kinds composed by merging the lists of +- * refactoring kinds in the [partialResultList]. +- * +- * The resulting list will contain all of the refactoring kinds from al= l of +- * the plugins, but will not contain duplicate elements. +- */ +- List mergeRefactoringKinds( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- Set mergedKinds =3D new HashSet(); +- for (List partialResults in partialResultList) { +- mergedKinds.addAll(partialResults); +- } +- return mergedKinds.toList(); +- } +- +- /** +- * Return the result for a getRefactorings request composed by merging = the +- * results in the [partialResultList]. +- * +- * The returned result will contain the concatenation of the initial, o= ptions, +- * and final problems. If two or more plugins produce the same problem,= then +- * the resulting list of problems will contain duplications. +- * +- * The returned result will contain a merged list of refactoring feedba= cks (as +- * defined by [mergeRefactoringFeedbacks]) and a merged list of source = changes +- * (as defined by [mergeChanges]). +- * +- * The returned result will contain the concatenation of the potential = edits. +- * If two or more plugins produce the same potential edit, then the res= ulting +- * list of potential edits will contain duplications. +- */ +- EditGetRefactoringResult mergeRefactorings( +- List partialResultList) { +- /** +- * Return the result of merging the given list of source [changes] in= to a +- * single source change. +- * +- * The resulting change will have the first non-null message and the = first +- * non-null selection. The linked edit groups will be a concatenation= of all +- * of the individual linked edit groups because there's no way to det= ermine +- * when two such groups should be merged. The resulting list of edits= will +- * be merged at the level of the file being edited, but will be a +- * concatenation of the individual edits within each file, even if mu= ltiple +- * plugins contribute duplicate or conflicting edits. +- */ +- SourceChange mergeChanges(List changes) { +- int count =3D changes.length; +- if (count =3D=3D 0) { +- return null; +- } else if (count =3D=3D 1) { +- return changes[0]; +- } +- SourceChange first =3D changes[0]; +- String message =3D first.message; +- Map editMap =3D {}; +- for (SourceFileEdit edit in first.edits) { +- editMap[edit.file] =3D edit; +- } +- List linkedEditGroups =3D first.linkedEditGroups.t= oList(); +- Position selection =3D first.selection; +- for (int i =3D 1; i < count; i++) { +- SourceChange change =3D changes[i]; +- for (SourceFileEdit edit in change.edits) { +- SourceFileEdit mergedEdit =3D editMap[edit.file]; +- if (mergedEdit =3D=3D null) { +- editMap[edit.file] =3D edit; +- } else { +- // This doesn't detect if multiple plugins contribute the sam= e (or +- // conflicting) edits. +- List edits =3D mergedEdit.edits.toList(); +- edits.addAll(edit.edits); +- editMap[edit.file] =3D new SourceFileEdit( +- mergedEdit.file, mergedEdit.fileStamp, +- edits: edits); +- } +- } +- linkedEditGroups.addAll(change.linkedEditGroups); +- message ??=3D change.message; +- selection ??=3D change.selection; +- } +- return new SourceChange(message, +- edits: editMap.values.toList(), +- linkedEditGroups: linkedEditGroups, +- selection: selection); +- } +- +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return null; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- EditGetRefactoringResult result =3D partialResultList[0]; +- List initialProblems =3D result.initialProblems.t= oList(); +- List optionsProblems =3D result.optionsProblems.t= oList(); +- List finalProblems =3D result.finalProblems.toLis= t(); +- List feedbacks =3D []; +- if (result.feedback !=3D null) { +- feedbacks.add(result.feedback); +- } +- List changes =3D []; +- if (result.change !=3D null) { +- changes.add(result.change); +- } +- List potentialEdits =3D result.potentialEdits.toList(); +- for (int i =3D 1; i < count; i++) { +- EditGetRefactoringResult result =3D partialResultList[1]; +- initialProblems.addAll(result.initialProblems); +- optionsProblems.addAll(result.optionsProblems); +- finalProblems.addAll(result.finalProblems); +- if (result.feedback !=3D null) { +- feedbacks.add(result.feedback); +- } +- if (result.change !=3D null) { +- changes.add(result.change); +- } +- potentialEdits.addAll(result.potentialEdits); +- } +- return new EditGetRefactoringResult( +- initialProblems, optionsProblems, finalProblems, +- feedback: mergeRefactoringFeedbacks(feedbacks), +- change: mergeChanges(changes), +- potentialEdits: potentialEdits); +- } +- +- /** +- * Return a list of source changes composed by merging the lists of sou= rce +- * changes in the [partialResultList]. +- * +- * The resulting list will contain all of the source changes from all o= f the +- * plugins. If two or more plugins contribute the same source change the +- * resulting list will contain duplications. +- */ +- List mergeSourceChanges( +- List> partialResultList) { +- int count =3D partialResultList.length; +- if (count =3D=3D 0) { +- return []; +- } else if (count =3D=3D 1) { +- return partialResultList[0]; +- } +- List mergedChanges =3D []; +- for (List partialResults in partialResultList) { +- mergedChanges.addAll(partialResults); +- } +- return mergedChanges; +- } +- +- /** +- * Return `true` if a region extending from [leftStart] (inclusive) to +- * [leftEnd] (exclusive) overlaps a region extending from [rightStart] +- * (inclusive) to [rightEnd] (exclusive). If [allowNesting] is `true`, = then +- * the regions are allowed to overlap as long as one region is complete= ly +- * nested within the other region. +- */ +- @visibleForTesting +- bool overlaps(int leftStart, int leftEnd, int rightStart, int rightEnd, +- {bool allowNesting: false}) { +- if (leftEnd < rightStart || leftStart > rightEnd) { +- return false; +- } +- if (!allowNesting) { +- return true; +- } +- return !((leftStart <=3D rightStart && rightEnd <=3D leftEnd) || +- (rightStart <=3D leftStart && leftEnd <=3D rightEnd)); +- } +-} +diff --git a/pkg/analysis_server/lib/src/protocol/protocol_internal.dart b= /pkg/analysis_server/lib/src/protocol/protocol_internal.dart +deleted file mode 100644 +index 4fe30315517..00000000000 +--- a/pkg/analysis_server/lib/src/protocol/protocol_internal.dart ++++ /dev/null +@@ -1,336 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:collection'; +-import 'dart:convert' hide JsonDecoder; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart' +- show JsonDecoder; +- +-export 'package:analyzer_plugin/src/protocol/protocol_internal.dart' +- show JsonDecoder; +- +-final Map REQUEST_ID_REFACTORING_KINDS =3D +- new HashMap(); +- +-/** +- * Adds the given [sourceEdits] to the list in [sourceFileEdit]. +- */ +-void addAllEditsForSource( +- SourceFileEdit sourceFileEdit, Iterable edits) { +- edits.forEach(sourceFileEdit.add); +-} +- +-/** +- * Adds the given [sourceEdit] to the list in [sourceFileEdit]. +- */ +-void addEditForSource(SourceFileEdit sourceFileEdit, SourceEdit sourceEdi= t) { +- List edits =3D sourceFileEdit.edits; +- int index =3D 0; +- while (index < edits.length && edits[index].offset > sourceEdit.offset)= { +- index++; +- } +- edits.insert(index, sourceEdit); +-} +- +-/** +- * Adds [edit] to the [FileEdit] for the given [file]. +- */ +-void addEditToSourceChange( +- SourceChange change, String file, int fileStamp, SourceEdit edit) { +- SourceFileEdit fileEdit =3D change.getFileEdit(file); +- if (fileEdit =3D=3D null) { +- fileEdit =3D new SourceFileEdit(file, fileStamp); +- change.addFileEdit(fileEdit); +- } +- fileEdit.add(edit); +-} +- +-/** +- * Get the result of applying the edit to the given [code]. Access via +- * SourceEdit.apply(). +- */ +-String applyEdit(String code, SourceEdit edit) { +- if (edit.length < 0) { +- throw new RangeError('length is negative'); +- } +- return code.replaceRange(edit.offset, edit.end, edit.replacement); +-} +- +-/** +- * Get the result of applying a set of [edits] to the given [code]. Edits +- * are applied in the order they appear in [edits]. Access via +- * SourceEdit.applySequence(). +- */ +-String applySequenceOfEdits(String code, Iterable edits) { +- edits.forEach((SourceEdit edit) { +- code =3D edit.apply(code); +- }); +- return code; +-} +- +-/** +- * Returns the [FileEdit] for the given [file], maybe `null`. +- */ +-SourceFileEdit getChangeFileEdit(SourceChange change, String file) { +- for (SourceFileEdit fileEdit in change.edits) { +- if (fileEdit.file =3D=3D file) { +- return fileEdit; +- } +- } +- return null; +-} +- +-/** +- * Compare the lists [listA] and [listB], using [itemEqual] to compare +- * list elements. +- */ +-bool listEqual( +- List listA, List listB, bool itemEqual(T1 a, T2 b)) { +- if (listA =3D=3D null) { +- return listB =3D=3D null; +- } +- if (listB =3D=3D null) { +- return false; +- } +- if (listA.length !=3D listB.length) { +- return false; +- } +- for (int i =3D 0; i < listA.length; i++) { +- if (!itemEqual(listA[i], listB[i])) { +- return false; +- } +- } +- return true; +-} +- +-/** +- * Compare the maps [mapA] and [mapB], using [valueEqual] to compare map +- * values. +- */ +-bool mapEqual(Map mapA, Map mapB, bool valueEqual(V a, = V b)) { +- if (mapA =3D=3D null) { +- return mapB =3D=3D null; +- } +- if (mapB =3D=3D null) { +- return false; +- } +- if (mapA.length !=3D mapB.length) { +- return false; +- } +- for (var key in mapA.keys) { +- if (!mapB.containsKey(key)) { +- return false; +- } +- if (!valueEqual(mapA[key], mapB[key])) { +- return false; +- } +- } +- return true; +-} +- +-/** +- * Translate the input [map], applying [keyCallback] to all its keys, and +- * [valueCallback] to all its values. +- */ +-Map mapMap(Map map, +- {KR keyCallback(KP key), VR valueCallback(VP value)}) { +- Map result =3D new HashMap(); +- map.forEach((key, value) { +- KR resultKey; +- VR resultValue; +- if (keyCallback !=3D null) { +- resultKey =3D keyCallback(key); +- } else { +- resultKey =3D key as KR; +- } +- if (valueCallback !=3D null) { +- resultValue =3D valueCallback(value); +- } else { +- resultValue =3D value as VR; +- } +- result[resultKey] =3D resultValue; +- }); +- return result; +-} +- +-RefactoringProblemSeverity maxRefactoringProblemSeverity( +- RefactoringProblemSeverity a, RefactoringProblemSeverity b) { +- if (b =3D=3D null) { +- return a; +- } +- if (a =3D=3D null) { +- return b; +- } else if (a =3D=3D RefactoringProblemSeverity.INFO) { +- return b; +- } else if (a =3D=3D RefactoringProblemSeverity.WARNING) { +- if (b =3D=3D RefactoringProblemSeverity.ERROR || +- b =3D=3D RefactoringProblemSeverity.FATAL) { +- return b; +- } +- } else if (a =3D=3D RefactoringProblemSeverity.ERROR) { +- if (b =3D=3D RefactoringProblemSeverity.FATAL) { +- return b; +- } +- } +- return a; +-} +- +-/** +- * Create a [RefactoringFeedback] corresponding the given [kind]. +- */ +-RefactoringFeedback refactoringFeedbackFromJson( +- JsonDecoder jsonDecoder, String jsonPath, Object json, Map feedbackJs= on) { +- RefactoringKind kind =3D jsonDecoder.refactoringKind; +- if (kind =3D=3D RefactoringKind.EXTRACT_LOCAL_VARIABLE) { +- return new ExtractLocalVariableFeedback.fromJson( +- jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.EXTRACT_METHOD) { +- return new ExtractMethodFeedback.fromJson(jsonDecoder, jsonPath, json= ); +- } +- if (kind =3D=3D RefactoringKind.INLINE_LOCAL_VARIABLE) { +- return new InlineLocalVariableFeedback.fromJson( +- jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.INLINE_METHOD) { +- return new InlineMethodFeedback.fromJson(jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.RENAME) { +- return new RenameFeedback.fromJson(jsonDecoder, jsonPath, json); +- } +- return null; +-} +- +-/** +- * Create a [RefactoringOptions] corresponding the given [kind]. +- */ +-RefactoringOptions refactoringOptionsFromJson(JsonDecoder jsonDecoder, +- String jsonPath, Object json, RefactoringKind kind) { +- if (kind =3D=3D RefactoringKind.EXTRACT_LOCAL_VARIABLE) { +- return new ExtractLocalVariableOptions.fromJson( +- jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.EXTRACT_METHOD) { +- return new ExtractMethodOptions.fromJson(jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.INLINE_METHOD) { +- return new InlineMethodOptions.fromJson(jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.MOVE_FILE) { +- return new MoveFileOptions.fromJson(jsonDecoder, jsonPath, json); +- } +- if (kind =3D=3D RefactoringKind.RENAME) { +- return new RenameOptions.fromJson(jsonDecoder, jsonPath, json); +- } +- return null; +-} +- +-/** +- * Type of callbacks used to decode parts of JSON objects. [jsonPath] is= a +- * string describing the part of the JSON object being decoded, and [valu= e] is +- * the part to decode. +- */ +-typedef E JsonDecoderCallback(String jsonPath, Object value); +- +-/** +- * Instances of the class [HasToJson] implement [toJson] method that retu= rns +- * a JSON presentation. +- */ +-abstract class HasToJson { +- /** +- * Returns a JSON presentation of the object. +- */ +- Map toJson(); +-} +- +-/** +- * JsonDecoder for decoding requests. Errors are reporting by throwing a +- * [RequestFailure]. +- */ +-class RequestDecoder extends JsonDecoder { +- /** +- * The request being deserialized. +- */ +- final Request _request; +- +- RequestDecoder(this._request); +- +- RefactoringKind get refactoringKind { +- // Refactoring feedback objects should never appear in requests. +- return null; +- } +- +- @override +- dynamic mismatch(String jsonPath, String expected, [Object actual]) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write('Expected to be '); +- buffer.write(expected); +- if (actual !=3D null) { +- buffer.write('; found "'); +- buffer.write(JSON.encode(actual)); +- buffer.write('"'); +- } +- return new RequestFailure( +- new Response.invalidParameter(_request, jsonPath, buffer.toString= ())); +- } +- +- @override +- dynamic missingKey(String jsonPath, String key) { +- return new RequestFailure(new Response.invalidParameter( +- _request, jsonPath, 'Expected to contain key ${JSON.encode(key)}'= )); +- } +-} +- +-abstract class RequestParams implements HasToJson { +- /** +- * Return a request whose parameters are taken from this object and tha= t has +- * the given [id]. +- */ +- Request toRequest(String id); +-} +- +-/** +- * JsonDecoder for decoding responses from the server. This is intended = to be +- * used only for testing. Errors are reported using bare [Exception] obj= ects. +- */ +-class ResponseDecoder extends JsonDecoder { +- final RefactoringKind refactoringKind; +- +- ResponseDecoder(this.refactoringKind); +- +- @override +- dynamic mismatch(String jsonPath, String expected, [Object actual]) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write('Expected '); +- buffer.write(expected); +- if (actual !=3D null) { +- buffer.write(' found "'); +- buffer.write(JSON.encode(actual)); +- buffer.write('"'); +- } +- buffer.write(' at '); +- buffer.write(jsonPath); +- return new Exception(buffer.toString()); +- } +- +- @override +- dynamic missingKey(String jsonPath, String key) { +- return new Exception('Missing key $key at $jsonPath'); +- } +-} +- +-/** +- * The result data associated with a response. +- */ +-abstract class ResponseResult implements HasToJson { +- /** +- * Return a response whose result data is this object for the request w= ith the +- * given [id]. +- */ +- Response toResponse(String id); +-} +diff --git a/pkg/analysis_server/lib/src/protocol_server.dart b/pkg/analys= is_server/lib/src/protocol_server.dart +deleted file mode 100644 +index a84b950cbe6..00000000000 +--- a/pkg/analysis_server/lib/src/protocol_server.dart ++++ /dev/null +@@ -1,283 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/plugin/protocol/protocol_dart.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/services/correction/fix.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart' +- as engine; +-import 'package:analyzer/dart/ast/ast.dart' as engine; +-import 'package:analyzer/dart/ast/visitor.dart' as engine; +-import 'package:analyzer/dart/element/element.dart' as engine; +-import 'package:analyzer/dart/element/type.dart' as engine; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/source/error_processor.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart' as engine; +-import 'package:analyzer/src/error/codes.dart' as engine; +-import 'package:analyzer/src/generated/engine.dart' as engine; +-import 'package:analyzer/src/generated/source.dart' as engine; +-import 'package:analyzer/src/generated/utilities_dart.dart' as engine; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-export 'package:analysis_server/plugin/protocol/protocol_dart.dart'; +-export 'package:analysis_server/protocol/protocol.dart'; +-export 'package:analysis_server/protocol/protocol_generated.dart'; +-export 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * Returns a list of AnalysisErrors corresponding to the given list of En= gine +- * errors. +- */ +-List doAnalysisError_listFromEngine( +- engine.AnalysisOptions analysisOptions, +- engine.LineInfo lineInfo, +- List errors) { +- List serverErrors =3D []; +- for (engine.AnalysisError error in errors) { +- ErrorProcessor processor =3D +- ErrorProcessor.getProcessor(analysisOptions, error); +- if (processor !=3D null) { +- engine.ErrorSeverity severity =3D processor.severity; +- // Errors with null severity are filtered out. +- if (severity !=3D null) { +- // Specified severities override. +- serverErrors +- .add(newAnalysisError_fromEngine(lineInfo, error, severity)); +- } +- } else { +- serverErrors.add(newAnalysisError_fromEngine(lineInfo, error)); +- } +- } +- return serverErrors; +-} +- +-/** +- * Adds [edit] to the file containing the given [element]. +- */ +-void doSourceChange_addElementEdit( +- SourceChange change, engine.Element element, SourceEdit edit) { +- engine.Source source =3D element.source; +- doSourceChange_addSourceEdit(change, source, edit); +-} +- +-/** +- * Adds [edit] for the given [source] to the [change]. +- */ +-void doSourceChange_addSourceEdit( +- SourceChange change, engine.Source source, SourceEdit edit, +- {bool isNewFile: false}) { +- String file =3D source.fullName; +- change.addEdit(file, isNewFile ? -1 : 0, edit); +-} +- +-String getReturnTypeString(engine.Element element) { +- if (element is engine.ExecutableElement) { +- if (element.kind =3D=3D engine.ElementKind.SETTER) { +- return null; +- } else { +- return element.returnType?.toString(); +- } +- } else if (element is engine.VariableElement) { +- engine.DartType type =3D element.type; +- return type !=3D null ? type.displayName : 'dynamic'; +- } else if (element is engine.FunctionTypeAliasElement) { +- return element.returnType.toString(); +- } else { +- return null; +- } +-} +- +-/** +- * Construct based on error information from the analyzer engine. +- * +- * If an [errorSeverity] is specified, it will override the one in [error= ]. +- */ +-AnalysisError newAnalysisError_fromEngine( +- engine.LineInfo lineInfo, engine.AnalysisError error, +- [engine.ErrorSeverity errorSeverity]) { +- engine.ErrorCode errorCode =3D error.errorCode; +- // prepare location +- Location location; +- { +- String file =3D error.source.fullName; +- int offset =3D error.offset; +- int length =3D error.length; +- int startLine =3D -1; +- int startColumn =3D -1; +- if (lineInfo !=3D null) { +- engine.LineInfo_Location lineLocation =3D lineInfo.getLocation(offs= et); +- if (lineLocation !=3D null) { +- startLine =3D lineLocation.lineNumber; +- startColumn =3D lineLocation.columnNumber; +- } +- } +- location =3D new Location(file, offset, length, startLine, startColum= n); +- } +- +- // Default to the error's severity if none is specified. +- errorSeverity ??=3D errorCode.errorSeverity; +- +- // done +- var severity =3D new AnalysisErrorSeverity(errorSeverity.name); +- var type =3D new AnalysisErrorType(errorCode.type.name); +- String message =3D error.message; +- String code =3D errorCode.name.toLowerCase(); +- String correction =3D error.correction; +- bool fix =3D hasFix(error.errorCode); +- return new AnalysisError(severity, type, location, message, code, +- correction: correction, hasFix: fix); +-} +- +-/** +- * Create a Location based on an [engine.Element]. +- */ +-Location newLocation_fromElement(engine.Element element) { +- if (element =3D=3D null || element.source =3D=3D null) { +- return null; +- } +- int offset =3D element.nameOffset; +- int length =3D element.nameLength; +- if (element is engine.CompilationUnitElement || +- (element is engine.LibraryElement && offset < 0)) { +- offset =3D 0; +- length =3D 0; +- } +- engine.CompilationUnitElement unitElement =3D _getUnitElement(element); +- engine.SourceRange range =3D new engine.SourceRange(offset, length); +- return _locationForArgs(unitElement, range); +-} +- +-/** +- * Create a Location based on an [engine.SearchMatch]. +- */ +-Location newLocation_fromMatch(engine.SearchMatch match) { +- engine.CompilationUnitElement unitElement =3D _getUnitElement(match.ele= ment); +- return _locationForArgs(unitElement, match.sourceRange); +-} +- +-/** +- * Create a Location based on an [engine.AstNode]. +- */ +-Location newLocation_fromNode(engine.AstNode node) { +- engine.CompilationUnit unit =3D +- node.getAncestor((node) =3D> node is engine.CompilationUnit); +- engine.CompilationUnitElement unitElement =3D unit.element; +- engine.SourceRange range =3D new engine.SourceRange(node.offset, node.l= ength); +- return _locationForArgs(unitElement, range); +-} +- +-/** +- * Create a Location based on an [engine.CompilationUnit]. +- */ +-Location newLocation_fromUnit( +- engine.CompilationUnit unit, engine.SourceRange range) { +- return _locationForArgs(unit.element, range); +-} +- +-/** +- * Construct based on an element from the analyzer engine. +- */ +-OverriddenMember newOverriddenMember_fromEngine(engine.Element member) { +- Element element =3D convertElement(member); +- String className =3D member.enclosingElement.displayName; +- return new OverriddenMember(element, className); +-} +- +-/** +- * Construct based on a value from the search engine. +- */ +-SearchResult newSearchResult_fromMatch(engine.SearchMatch match) { +- SearchResultKind kind =3D newSearchResultKind_fromEngine(match.kind); +- Location location =3D newLocation_fromMatch(match); +- List path =3D _computePath(match.element); +- return new SearchResult(location, kind, !match.isResolved, path); +-} +- +-/** +- * Construct based on a value from the search engine. +- */ +-SearchResultKind newSearchResultKind_fromEngine(engine.MatchKind kind) { +- if (kind =3D=3D engine.MatchKind.DECLARATION) { +- return SearchResultKind.DECLARATION; +- } +- if (kind =3D=3D engine.MatchKind.READ) { +- return SearchResultKind.READ; +- } +- if (kind =3D=3D engine.MatchKind.READ_WRITE) { +- return SearchResultKind.READ_WRITE; +- } +- if (kind =3D=3D engine.MatchKind.WRITE) { +- return SearchResultKind.WRITE; +- } +- if (kind =3D=3D engine.MatchKind.INVOCATION) { +- return SearchResultKind.INVOCATION; +- } +- if (kind =3D=3D engine.MatchKind.REFERENCE) { +- return SearchResultKind.REFERENCE; +- } +- return SearchResultKind.UNKNOWN; +-} +- +-/** +- * Construct based on a SourceRange. +- */ +-SourceEdit newSourceEdit_range(engine.SourceRange range, String replaceme= nt, +- {String id}) { +- return new SourceEdit(range.offset, range.length, replacement, id: id); +-} +- +-List _computePath(engine.Element element) { +- List path =3D []; +- while (element !=3D null) { +- path.add(convertElement(element)); +- // go up +- if (element is engine.PrefixElement) { +- // imports are library children, but they are physically in the unit +- engine.LibraryElement library =3D element.enclosingElement; +- element =3D library.definingCompilationUnit; +- } else { +- element =3D element.enclosingElement; +- } +- } +- return path; +-} +- +-engine.CompilationUnitElement _getUnitElement(engine.Element element) { +- if (element is engine.CompilationUnitElement) { +- return element; +- } +- if (element?.enclosingElement is engine.LibraryElement) { +- element =3D element.enclosingElement; +- } +- if (element is engine.LibraryElement) { +- return element.definingCompilationUnit; +- } +- for (; element !=3D null; element =3D element.enclosingElement) { +- if (element is engine.CompilationUnitElement) { +- return element; +- } +- } +- return null; +-} +- +-/** +- * Creates a new [Location]. +- */ +-Location _locationForArgs( +- engine.CompilationUnitElement unitElement, engine.SourceRange range) { +- int startLine =3D 0; +- int startColumn =3D 0; +- try { +- engine.LineInfo lineInfo =3D unitElement.lineInfo; +- if (lineInfo !=3D null) { +- engine.LineInfo_Location offsetLocation =3D +- lineInfo.getLocation(range.offset); +- startLine =3D offsetLocation.lineNumber; +- startColumn =3D offsetLocation.columnNumber; +- } +- } on AnalysisException {} +- return new Location(unitElement.source.fullName, range.offset, range.le= ngth, +- startLine, startColumn); +-} +diff --git a/pkg/analysis_server/lib/src/provisional/completion/completion= _core.dart b/pkg/analysis_server/lib/src/provisional/completion/completion_= core.dart +deleted file mode 100644 +index 9934390413e..00000000000 +--- a/pkg/analysis_server/lib/src/provisional/completion/completion_core.d= art ++++ /dev/null +@@ -1,86 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * An empty list returned by [CompletionContributor]s +- * when they have no suggestions to contribute. +- */ +-const EMPTY_LIST =3D const []; +- +-/** +- * An object used to instantiate a [CompletionContributor] instance +- * for each 'completion.getSuggestions' request. +- * Contributors should *not* be cached between requests. +- */ +-typedef CompletionContributor CompletionContributorFactory(); +- +-/** +- * [AbortCompletion] is thrown when the current completion request +- * should be aborted because either +- * the source changed since the request was made, or +- * a new completion request was received. +- */ +-class AbortCompletion {} +- +-/** +- * An object used to produce completions at a specific location within a = file. +- * +- * Clients may implement this class when implementing plugins. +- */ +-abstract class CompletionContributor { +- /** +- * Return a [Future] that completes with a list of suggestions +- * for the given completion [request]. This will +- * throw [AbortCompletion] if the completion request has been aborted. +- */ +- Future> computeSuggestions( +- CompletionRequest request); +-} +- +-/** +- * The information about a requested list of completions. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class CompletionRequest { +- /** +- * Return the offset within the source at which the completion is being +- * requested. +- */ +- int get offset; +- +- /** +- * Return the resource provider associated with this request. +- */ +- ResourceProvider get resourceProvider; +- +- /** +- * The analysis result for the file in which the completion is being +- * requested. +- */ +- AnalysisResult get result; +- +- /** +- * Return the source in which the completion is being requested. +- */ +- Source get source; +- +- /** +- * Return the content of the [source] in which the completion is being +- * requested, or `null` if the content could not be accessed. +- */ +- String get sourceContents; +- +- /** +- * Throw [AbortCompletion] if the completion request has been aborted. +- */ +- void checkAborted(); +-} +diff --git a/pkg/analysis_server/lib/src/provisional/completion/dart/compl= etion_dart.dart b/pkg/analysis_server/lib/src/provisional/completion/dart/c= ompletion_dart.dart +deleted file mode 100644 +index 093c2da1c66..00000000000 +--- a/pkg/analysis_server/lib/src/provisional/completion/dart/completion_d= art.dart ++++ /dev/null +@@ -1,97 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/completion_targe= t.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-export 'package:analysis_server/src/provisional/completion/completion_cor= e.dart' +- show EMPTY_LIST; +-export 'package:analyzer_plugin/utilities/completion/relevance.dart'; +- +-/** +- * An object used to instantiate a [DartCompletionContributor] instance +- * for each 'completion.getSuggestions' request. +- * Contributors should *not* be cached between requests. +- */ +-typedef DartCompletionContributor DartCompletionContributorFactory(); +- +-/** +- * An object used to produce completions +- * at a specific location within a Dart file. +- * +- * Clients may implement this class when implementing plugins. +- */ +-abstract class DartCompletionContributor { +- /** +- * Return a [Future] that completes with a list of suggestions +- * for the given completion [request]. +- */ +- Future> computeSuggestions( +- DartCompletionRequest request); +-} +- +-/** +- * The information about a requested list of completions within a Dart fi= le. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class DartCompletionRequest extends CompletionRequest { +- /** +- * Return the expression to the right of the "dot" or "dot dot", +- * or `null` if this is not a "dot" completion (e.g. `foo.b`). +- */ +- Expression get dotTarget; +- +- /** +- * Return `true` if free standing identifiers should be suggested +- */ +- bool get includeIdentifiers; +- +- /** +- * Return the library element which contains the unit in which the comp= letion +- * is occurring. This may return `null` if the library cannot be determ= ined +- * (e.g. unlinked part file). +- */ +- LibraryElement get libraryElement; +- +- /** +- * The source for the library containing the completion request. +- * This may be different from the source in which the completion is req= uested +- * if the completion is being requested in a part file. +- * This may be `null` if the library for a part file cannot be determin= ed. +- */ +- Source get librarySource; +- +- /** +- * Answer the [DartType] for Object in dart:core +- */ +- DartType get objectType; +- +- /** +- * The [OpType] which describes which types of suggestions would fit the +- * request. +- */ +- OpType get opType; +- +- /** +- * Return the [SourceFactory] of the request. +- */ +- SourceFactory get sourceFactory; +- +- /** +- * Return the completion target. This determines what part of the pars= e tree +- * will receive the newly inserted text. +- * At a minimum, all declarations in the completion scope in [target.un= it] +- * will be resolved if they can be resolved. +- */ +- CompletionTarget get target; +-} +diff --git a/pkg/analysis_server/lib/src/search/element_references.dart b/= pkg/analysis_server/lib/src/search/element_references.dart +deleted file mode 100644 +index 4b53584b495..00000000000 +--- a/pkg/analysis_server/lib/src/search/element_references.dart ++++ /dev/null +@@ -1,93 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show SearchResult, newSearchResult_fromMatch; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-/** +- * A computer for `search.findElementReferences` request results. +- */ +-class ElementReferencesComputer { +- final SearchEngine searchEngine; +- +- ElementReferencesComputer(this.searchEngine); +- +- /** +- * Computes [SearchResult]s for [element] references. +- */ +- Future> compute( +- Element element, bool withPotential) async { +- List results =3D []; +- +- // Add element references. +- results.addAll(await _findElementsReferences(element)); +- +- // Add potential references. +- if (withPotential && _isMemberElement(element)) { +- String name =3D element.displayName; +- List matches =3D +- await searchEngine.searchMemberReferences(name); +- matches =3D SearchMatch.withNotNullElement(matches); +- results.addAll(matches.where((match) =3D> !match.isResolved).map(to= Result)); +- } +- +- return results; +- } +- +- /** +- * Returns a [Future] completing with a [List] of references to [elemen= t] or +- * to the corresponding hierarchy [Element]s. +- */ +- Future> _findElementsReferences(Element element) asy= nc { +- List allResults =3D []; +- Iterable refElements =3D await _getRefElements(element); +- for (Element refElement in refElements) { +- List elementResults =3D +- await _findSingleElementReferences(refElement); +- allResults.addAll(elementResults); +- } +- return allResults; +- } +- +- /** +- * Returns a [Future] completing with a [List] of references to [elemen= t]. +- */ +- Future> _findSingleElementReferences( +- Element element) async { +- List matches =3D await searchEngine.searchReferences(ele= ment); +- matches =3D SearchMatch.withNotNullElement(matches); +- return matches.map(toResult).toList(); +- } +- +- /** +- * Returns a [Future] completing with [Element]s to search references t= o. +- * +- * If a [ClassMemberElement] is given, each corresponding [Element] in = the +- * hierarchy is returned. +- * +- * Otherwise, only references to [element] should be searched. +- */ +- Future> _getRefElements(Element element) { +- if (element is ClassMemberElement) { +- return getHierarchyMembers(searchEngine, element); +- } +- return new Future.value([element]); +- } +- +- static SearchResult toResult(SearchMatch match) { +- return newSearchResult_fromMatch(match); +- } +- +- static bool _isMemberElement(Element element) { +- if (element is ConstructorElement) { +- return false; +- } +- return element.enclosingElement is ClassElement; +- } +-} +diff --git a/pkg/analysis_server/lib/src/search/search_domain.dart b/pkg/a= nalysis_server/lib/src/search/search_domain.dart +deleted file mode 100644 +index cb7f02fb53e..00000000000 +--- a/pkg/analysis_server/lib/src/search/search_domain.dart ++++ /dev/null +@@ -1,211 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analysis_server/src/search/element_references.dart'; +-import 'package:analysis_server/src/search/type_hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-/** +- * Instances of the class [SearchDomainHandler] implement a [RequestHandl= er] +- * that handles requests in the search domain. +- */ +-class SearchDomainHandler implements protocol.RequestHandler { +- /** +- * The analysis server that is using this handler to process requests. +- */ +- final AnalysisServer server; +- +- /** +- * The [SearchEngine] for this server. +- */ +- final SearchEngine searchEngine; +- +- /** +- * The next search response id. +- */ +- int _nextSearchId =3D 0; +- +- /** +- * Initialize a newly created handler to handle requests for the given = [server]. +- */ +- SearchDomainHandler(AnalysisServer server) +- : server =3D server, +- searchEngine =3D server.searchEngine; +- +- Future findElementReferences(protocol.Request request) async { +- var params =3D +- new protocol.SearchFindElementReferencesParams.fromRequest(reques= t); +- String file =3D params.file; +- // prepare element +- Element element =3D await server.getElementAtOffset(file, params.offs= et); +- if (element is ImportElement) { +- element =3D (element as ImportElement).prefix; +- } +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- if (element is PropertyAccessorElement) { +- element =3D (element as PropertyAccessorElement).variable; +- } +- // respond +- String searchId =3D (_nextSearchId++).toString(); +- var result =3D new protocol.SearchFindElementReferencesResult(); +- if (element !=3D null) { +- result.id =3D searchId; +- result.element =3D protocol.convertElement(element); +- } +- _sendSearchResult(request, result); +- // search elements +- if (element !=3D null) { +- var computer =3D new ElementReferencesComputer(searchEngine); +- List results =3D +- await computer.compute(element, params.includePotential); +- _sendSearchNotification(searchId, true, results); +- } +- } +- +- Future findMemberDeclarations(protocol.Request request) async { +- var params =3D +- new protocol.SearchFindMemberDeclarationsParams.fromRequest(reque= st); +- await server.onAnalysisComplete; +- // respond +- String searchId =3D (_nextSearchId++).toString(); +- _sendSearchResult( +- request, new protocol.SearchFindMemberDeclarationsResult(searchId= )); +- // search +- List matches =3D +- await searchEngine.searchMemberDeclarations(params.name); +- matches =3D SearchMatch.withNotNullElement(matches); +- _sendSearchNotification(searchId, true, matches.map(toResult)); +- } +- +- Future findMemberReferences(protocol.Request request) async { +- var params =3D +- new protocol.SearchFindMemberReferencesParams.fromRequest(request= ); +- await server.onAnalysisComplete; +- // respond +- String searchId =3D (_nextSearchId++).toString(); +- _sendSearchResult( +- request, new protocol.SearchFindMemberReferencesResult(searchId)); +- // search +- List matches =3D +- await searchEngine.searchMemberReferences(params.name); +- matches =3D SearchMatch.withNotNullElement(matches); +- _sendSearchNotification(searchId, true, matches.map(toResult)); +- } +- +- Future findTopLevelDeclarations(protocol.Request request) async { +- var params =3D +- new protocol.SearchFindTopLevelDeclarationsParams.fromRequest(req= uest); +- try { +- // validate the regex +- new RegExp(params.pattern); +- } on FormatException catch (exception) { +- server.sendResponse(new protocol.Response.invalidParameter( +- request, 'pattern', exception.message)); +- return; +- } +- +- await server.onAnalysisComplete; +- // respond +- String searchId =3D (_nextSearchId++).toString(); +- _sendSearchResult( +- request, new protocol.SearchFindTopLevelDeclarationsResult(search= Id)); +- // search +- List matches =3D +- await searchEngine.searchTopLevelDeclarations(params.pattern); +- matches =3D SearchMatch.withNotNullElement(matches); +- _sendSearchNotification(searchId, true, matches.map(toResult)); +- } +- +- /** +- * Implement the `search.getTypeHierarchy` request. +- */ +- Future getTypeHierarchy(protocol.Request request) async { +- var params =3D new protocol.SearchGetTypeHierarchyParams.fromRequest(= request); +- String file =3D params.file; +- // prepare element +- Element element =3D await server.getElementAtOffset(file, params.offs= et); +- if (element =3D=3D null) { +- _sendTypeHierarchyNull(request); +- return; +- } +- // maybe supertype hierarchy only +- if (params.superOnly =3D=3D true) { +- TypeHierarchyComputer computer =3D +- new TypeHierarchyComputer(searchEngine, element); +- List items =3D computer.computeSuper(); +- protocol.Response response =3D +- new protocol.SearchGetTypeHierarchyResult(hierarchyItems: items) +- .toResponse(request.id); +- server.sendResponse(response); +- return; +- } +- // prepare type hierarchy +- TypeHierarchyComputer computer =3D +- new TypeHierarchyComputer(searchEngine, element); +- List items =3D await computer.compute(); +- protocol.Response response =3D +- new protocol.SearchGetTypeHierarchyResult(hierarchyItems: items) +- .toResponse(request.id); +- server.sendResponse(response); +- } +- +- @override +- protocol.Response handleRequest(protocol.Request request) { +- try { +- String requestName =3D request.method; +- if (requestName =3D=3D SEARCH_REQUEST_FIND_ELEMENT_REFERENCES) { +- findElementReferences(request); +- return protocol.Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D SEARCH_REQUEST_FIND_MEMBER_DECLARATIO= NS) { +- findMemberDeclarations(request); +- return protocol.Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D SEARCH_REQUEST_FIND_MEMBER_REFERENCES= ) { +- findMemberReferences(request); +- return protocol.Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D SEARCH_REQUEST_FIND_TOP_LEVEL_DECLARA= TIONS) { +- findTopLevelDeclarations(request); +- return protocol.Response.DELAYED_RESPONSE; +- } else if (requestName =3D=3D SEARCH_REQUEST_GET_TYPE_HIERARCHY) { +- getTypeHierarchy(request); +- return protocol.Response.DELAYED_RESPONSE; +- } +- } on protocol.RequestFailure catch (exception) { +- return exception.response; +- } +- return null; +- } +- +- void _sendSearchNotification( +- String searchId, bool isLast, Iterable resul= ts) { +- server.sendNotification( +- new protocol.SearchResultsParams(searchId, results.toList(), isLa= st) +- .toNotification()); +- } +- +- /** +- * Send a search response with the given [result] to the given [request= ]. +- */ +- void _sendSearchResult(protocol.Request request, result) { +- protocol.Response response =3D result.toResponse(request.id); +- server.sendResponse(response); +- } +- +- void _sendTypeHierarchyNull(protocol.Request request) { +- protocol.Response response =3D +- new protocol.SearchGetTypeHierarchyResult().toResponse(request.id= ); +- server.sendResponse(response); +- } +- +- static protocol.SearchResult toResult(SearchMatch match) { +- return protocol.newSearchResult_fromMatch(match); +- } +-} +diff --git a/pkg/analysis_server/lib/src/search/type_hierarchy.dart b/pkg/= analysis_server/lib/src/search/type_hierarchy.dart +deleted file mode 100644 +index 841e291ec82..00000000000 +--- a/pkg/analysis_server/lib/src/search/type_hierarchy.dart ++++ /dev/null +@@ -1,202 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show TypeHierarchyItem, convertElement; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +- +-/** +- * A computer for a type hierarchy of an [Element]. +- */ +-class TypeHierarchyComputer { +- final SearchEngine _searchEngine; +- +- Element _pivotElement; +- LibraryElement _pivotLibrary; +- ElementKind _pivotKind; +- String _pivotName; +- bool _pivotFieldFinal; +- ClassElement _pivotClass; +- +- final List _items =3D []; +- final List _itemClassElements =3D []; +- final Map _elementItemMap =3D +- new HashMap(); +- +- TypeHierarchyComputer(this._searchEngine, this._pivotElement) { +- _pivotLibrary =3D _pivotElement.library; +- _pivotKind =3D _pivotElement.kind; +- _pivotName =3D _pivotElement.name; +- // try to find enclosing ClassElement +- Element element =3D _pivotElement; +- if (_pivotElement is FieldElement) { +- _pivotFieldFinal =3D (_pivotElement as FieldElement).isFinal; +- element =3D _pivotElement.enclosingElement; +- } +- if (_pivotElement is ExecutableElement) { +- element =3D _pivotElement.enclosingElement; +- } +- if (element is ClassElement) { +- _pivotClass =3D element; +- } +- } +- +- /** +- * Returns the computed type hierarchy, maybe `null`. +- */ +- Future> compute() async { +- if (_pivotClass !=3D null) { +- InterfaceType type =3D _pivotClass.type; +- _createSuperItem(type); +- await _createSubclasses(_items[0], 0, type); +- return _items; +- } +- return null; +- } +- +- /** +- * Returns the computed super type only type hierarchy, maybe `null`. +- */ +- List computeSuper() { +- if (_pivotClass !=3D null) { +- InterfaceType type =3D _pivotClass.type; +- _createSuperItem(type); +- return _items; +- } +- return null; +- } +- +- Future _createSubclasses( +- TypeHierarchyItem item, int itemId, InterfaceType type) async { +- Set subElements =3D +- await getDirectSubClasses(_searchEngine, type.element); +- List subItemIds =3D []; +- for (ClassElement subElement in subElements) { +- // check for recursion +- TypeHierarchyItem subItem =3D _elementItemMap[subElement]; +- if (subItem !=3D null) { +- int id =3D _items.indexOf(subItem); +- item.subclasses.add(id); +- continue; +- } +- // create a subclass item +- ExecutableElement subMemberElement =3D _findMemberElement(subElemen= t); +- subItem =3D new TypeHierarchyItem(convertElement(subElement), +- memberElement: subMemberElement !=3D null +- ? convertElement(subMemberElement) +- : null, +- superclass: itemId); +- int subItemId =3D _items.length; +- // remember +- _elementItemMap[subElement] =3D subItem; +- _items.add(subItem); +- _itemClassElements.add(subElement); +- // add to hierarchy +- item.subclasses.add(subItemId); +- subItemIds.add(subItemId); +- } +- // compute subclasses of subclasses +- for (int subItemId in subItemIds) { +- TypeHierarchyItem subItem =3D _items[subItemId]; +- ClassElement subItemElement =3D _itemClassElements[subItemId]; +- InterfaceType subType =3D subItemElement.type; +- await _createSubclasses(subItem, subItemId, subType); +- } +- } +- +- int _createSuperItem(InterfaceType type) { +- // check for recursion +- TypeHierarchyItem item =3D _elementItemMap[type.element]; +- if (item !=3D null) { +- return _items.indexOf(item); +- } +- // create an empty item now +- int itemId; +- { +- String displayName =3D null; +- if (type.typeArguments.isNotEmpty) { +- displayName =3D type.toString(); +- } +- ClassElement classElement =3D type.element; +- ExecutableElement memberElement =3D _findMemberElement(classElement= ); +- item =3D new TypeHierarchyItem(convertElement(classElement), +- displayName: displayName, +- memberElement: +- memberElement !=3D null ? convertElement(memberElement) : n= ull); +- _elementItemMap[classElement] =3D item; +- itemId =3D _items.length; +- _items.add(item); +- _itemClassElements.add(classElement); +- } +- // superclass +- { +- InterfaceType superType =3D type.superclass; +- if (superType !=3D null) { +- item.superclass =3D _createSuperItem(superType); +- } +- } +- // mixins +- type.mixins.forEach((InterfaceType type) { +- int id =3D _createSuperItem(type); +- item.mixins.add(id); +- }); +- // interfaces +- type.interfaces.forEach((InterfaceType type) { +- int id =3D _createSuperItem(type); +- item.interfaces.add(id); +- }); +- // done +- return itemId; +- } +- +- ExecutableElement _findMemberElement(ClassElement clazz) { +- ExecutableElement result; +- // try to find in the class itself +- if (_pivotKind =3D=3D ElementKind.METHOD) { +- result =3D clazz.getMethod(_pivotName); +- } else if (_pivotKind =3D=3D ElementKind.GETTER) { +- result =3D clazz.getGetter(_pivotName); +- } else if (_pivotKind =3D=3D ElementKind.SETTER) { +- result =3D clazz.getSetter(_pivotName); +- } else if (_pivotKind =3D=3D ElementKind.FIELD) { +- result =3D clazz.getGetter(_pivotName); +- if (result =3D=3D null && !_pivotFieldFinal) { +- result =3D clazz.getSetter(_pivotName); +- } +- } +- if (result !=3D null && result.isAccessibleIn(_pivotLibrary)) { +- return result; +- } +- // try to find in the class mixin +- for (InterfaceType mixin in clazz.mixins.reversed) { +- ClassElement mixinElement =3D mixin.element; +- if (_pivotKind =3D=3D ElementKind.METHOD) { +- result =3D mixinElement.lookUpMethod(_pivotName, _pivotLibrary); +- } else if (_pivotKind =3D=3D ElementKind.GETTER) { +- result =3D mixinElement.lookUpGetter(_pivotName, _pivotLibrary); +- } else if (_pivotKind =3D=3D ElementKind.SETTER) { +- result =3D mixinElement.lookUpSetter(_pivotName, _pivotLibrary); +- } else if (_pivotKind =3D=3D ElementKind.FIELD) { +- result =3D mixinElement.lookUpGetter(_pivotName, _pivotLibrary); +- if (result =3D=3D null && !_pivotFieldFinal) { +- result =3D mixinElement.lookUpSetter(_pivotName, _pivotLibrary); +- } +- } +- if (result =3D=3D _pivotElement) { +- return null; +- } +- if (result !=3D null) { +- return result; +- } +- } +- // not found +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/server/diagnostic_server.dart b/p= kg/analysis_server/lib/src/server/diagnostic_server.dart +deleted file mode 100644 +index b147a43ed55..00000000000 +--- a/pkg/analysis_server/lib/src/server/diagnostic_server.dart ++++ /dev/null +@@ -1,16 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-/** +- * A handle to start, and return the current port of, a diagnostic server. +- */ +-abstract class DiagnosticServer { +- /** +- * Return the port of the diagnostic web server. If the server is not r= unning +- * this call will start the server. +- */ +- Future getServerPort(); +-} +diff --git a/pkg/analysis_server/lib/src/server/driver.dart b/pkg/analysis= _server/lib/src/server/driver.dart +deleted file mode 100644 +index 039d508bd01..00000000000 +--- a/pkg/analysis_server/lib/src/server/driver.dart ++++ /dev/null +@@ -1,640 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +-import 'dart:math'; +- +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/server/diagnostic_server.dart'; +-import 'package:analysis_server/src/server/http_server.dart'; +-import 'package:analysis_server/src/server/stdio_server.dart'; +-import 'package:analysis_server/src/services/completion/dart/uri_contribu= tor.dart' +- show UriContributor; +-import 'package:analysis_server/src/socket_server.dart'; +-import 'package:analysis_server/starter.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer/instrumentation/file_instrumentation.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/plugin/resolver_provider.dart'; +-import 'package:analyzer/src/context/builder.dart'; +-import 'package:analyzer/src/dart/sdk/sdk.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:args/args.dart'; +-import 'package:linter/src/rules.dart' as linter; +-import 'package:plugin/manager.dart'; +-import 'package:telemetry/crash_reporting.dart'; +-import 'package:telemetry/telemetry.dart' as telemetry; +- +-/// Commandline argument parser. (Copied from analyzer/lib/options.dart) +-/// TODO(pquitslund): replaces with a simple [ArgParser] instance +-/// when the args package supports ignoring unrecognized +-/// options/flags (https://github.com/dart-lang/args/issues/9). +-class CommandLineParser { +- final List _knownFlags; +- final bool _alwaysIgnoreUnrecognized; +- final ArgParser _parser; +- +- /// Creates a new command line parser +- CommandLineParser({bool alwaysIgnoreUnrecognized: false}) +- : _knownFlags =3D [], +- _alwaysIgnoreUnrecognized =3D alwaysIgnoreUnrecognized, +- _parser =3D new ArgParser(allowTrailingOptions: true); +- +- ArgParser get parser =3D> _parser; +- +- /// Defines a flag. +- /// See [ArgParser.addFlag()]. +- void addFlag(String name, +- {String abbr, +- String help, +- bool defaultsTo: false, +- bool negatable: true, +- void callback(bool value), +- bool hide: false}) { +- _knownFlags.add(name); +- _parser.addFlag(name, +- abbr: abbr, +- help: help, +- defaultsTo: defaultsTo, +- negatable: negatable, +- callback: callback, +- hide: hide); +- } +- +- /// Defines a value-taking option. +- /// See [ArgParser.addOption()]. +- void addOption(String name, +- {String abbr, +- String help, +- List allowed, +- Map allowedHelp, +- String defaultsTo, +- void callback(value), +- bool allowMultiple: false}) { +- _knownFlags.add(name); +- _parser.addOption(name, +- abbr: abbr, +- help: help, +- allowed: allowed, +- allowedHelp: allowedHelp, +- defaultsTo: defaultsTo, +- callback: callback, +- allowMultiple: allowMultiple); +- } +- +- /// Generates a string displaying usage information for the defined opt= ions. +- /// See [ArgParser.usage]. +- String getUsage() =3D> _parser.usage; +- +- /// Parses [args], a list of command-line arguments, matches them again= st the +- /// flags and options defined by this parser, and returns the result. T= he +- /// values of any defined variables are captured in the given map. +- /// See [ArgParser]. +- ArgResults parse(List args, Map definedVariable= s) =3D> +- _parser.parse( +- _filterUnknowns(parseDefinedVariables(args, definedVariables))); +- +- List parseDefinedVariables( +- List args, Map definedVariables) { +- int count =3D args.length; +- List remainingArgs =3D []; +- for (int i =3D 0; i < count; i++) { +- String arg =3D args[i]; +- if (arg =3D=3D '--') { +- while (i < count) { +- remainingArgs.add(args[i++]); +- } +- } else if (arg.startsWith("-D")) { +- definedVariables[arg.substring(2)] =3D args[++i]; +- } else { +- remainingArgs.add(arg); +- } +- } +- return remainingArgs; +- } +- +- List _filterUnknowns(List args) { +- // Only filter args if the ignore flag is specified, or if +- // _alwaysIgnoreUnrecognized was set to true +- if (_alwaysIgnoreUnrecognized || +- args.contains('--ignore-unrecognized-flags')) { +- // Filter all unrecognized flags and options. +- List filtered =3D []; +- for (int i =3D 0; i < args.length; ++i) { +- String arg =3D args[i]; +- if (arg.startsWith('--') && arg.length > 2) { +- String option =3D arg.substring(2); +- // remove any leading 'no-' +- if (option.startsWith('no-')) { +- option =3D option.substring(3); +- } +- // strip the last '=3Dvalue' +- int equalsOffset =3D option.lastIndexOf('=3D'); +- if (equalsOffset !=3D -1) { +- option =3D option.substring(0, equalsOffset); +- } +- // check the option +- if (!_knownFlags.contains(option)) { +- //"eat" params by advancing to the next flag/option +- i =3D _getNextFlagIndex(args, i); +- } else { +- filtered.add(arg); +- } +- } else { +- filtered.add(arg); +- } +- } +- +- return filtered; +- } else { +- return args; +- } +- } +- +- _getNextFlagIndex(args, i) { +- for (; i < args.length; ++i) { +- if (args[i].startsWith('--')) { +- return i; +- } +- } +- return i; +- } +-} +- +-/** +- * The [Driver] class represents a single running instance of the analysis +- * server application. It is responsible for parsing command line options +- * and starting the HTTP and/or stdio servers. +- */ +-class Driver implements ServerStarter { +- /** +- * The name of the application that is used to start a server. +- */ +- static const BINARY_NAME =3D "server"; +- +- /** +- * The name of the option used to set the identifier for the client. +- */ +- static const String CLIENT_ID =3D "client-id"; +- +- /** +- * The name of the option used to set the version for the client. +- */ +- static const String CLIENT_VERSION =3D "client-version"; +- +- /** +- * The name of the option used to enable DartPad specific functionality. +- */ +- static const String DARTPAD_OPTION =3D "dartpad"; +- +- /** +- * The name of the option used to enable instrumentation. +- */ +- static const String ENABLE_INSTRUMENTATION_OPTION =3D "enable-instrumen= tation"; +- +- /** +- * The name of the option used to set the file read mode. +- */ +- static const String FILE_READ_MODE =3D "file-read-mode"; +- +- /** +- * The name of the flag used when analyzing the flutter repository. +- * See comments in source for `flutter analyze --watch`. +- */ +- static const FLUTTER_REPO =3D "flutter-repo"; +- +- /** +- * The name of the option used to print usage information. +- */ +- static const String HELP_OPTION =3D "help"; +- +- /** +- * The name of the flag used to configure reporting analytics. +- */ +- static const String ANALYTICS_FLAG =3D "analytics"; +- +- /** +- * Suppress analytics for this session. +- */ +- static const String SUPPRESS_ANALYTICS_FLAG =3D "suppress-analytics"; +- +- /** +- * The name of the option used to cause instrumentation to also be writ= ten to +- * a local file. +- */ +- static const String INSTRUMENTATION_LOG_FILE =3D "instrumentation-log-f= ile"; +- +- /** +- * The name of the option used to specify if [print] should print to the +- * console instead of being intercepted. +- */ +- static const String INTERNAL_PRINT_TO_CONSOLE =3D "internal-print-to-co= nsole"; +- +- /** +- * The name of the option used to describe the new analysis driver logg= er. +- */ +- static const String NEW_ANALYSIS_DRIVER_LOG =3D 'new-analysis-driver-lo= g'; +- +- /** +- * The name of the flag used to enable version 2 of semantic highlight +- * notification. +- */ +- static const String USE_ANALYSIS_HIGHLIGHT2 =3D "useAnalysisHighlight2"; +- +- /** +- * The option for specifying the http diagnostic port. +- * If specified, users can review server status and performance informa= tion +- * by opening a web browser on http://localhost: +- */ +- static const String PORT_OPTION =3D "port"; +- +- /** +- * The path to the SDK. +- */ +- static const String SDK_OPTION =3D "sdk"; +- +- /** +- * The path to the data cache. +- */ +- static const String CACHE_FOLDER =3D "cache"; +- +- /** +- * Whether to enable the Dart 2.0 Front End. +- */ +- static const String PREVIEW_DART2 =3D "preview-dart-2"; +- +- /** +- * The instrumentation server that is to be used by the analysis server. +- */ +- InstrumentationServer instrumentationServer; +- +- /** +- * The file resolver provider used to override the way file URI's are +- * resolved in some contexts. +- */ +- ResolverProvider fileResolverProvider; +- +- /** +- * The package resolver provider used to override the way package URI's= are +- * resolved in some contexts. +- */ +- ResolverProvider packageResolverProvider; +- +- SocketServer socketServer; +- +- HttpAnalysisServer httpServer; +- +- StdioAnalysisServer stdioServer; +- +- Driver(); +- +- /** +- * Use the given command-line [arguments] to start this server. +- * +- * At least temporarily returns AnalysisServer so that consumers of the +- * starter API can then use the server, this is done as a stopgap for t= he +- * angular plugin until the official plugin API is finished. +- */ +- AnalysisServer start(List arguments) { +- CommandLineParser parser =3D _createArgParser(); +- ArgResults results =3D parser.parse(arguments, {}); +- +- AnalysisServerOptions analysisServerOptions =3D new AnalysisServerOpt= ions(); +- analysisServerOptions.useAnalysisHighlight2 =3D +- results[USE_ANALYSIS_HIGHLIGHT2]; +- analysisServerOptions.fileReadMode =3D results[FILE_READ_MODE]; +- analysisServerOptions.newAnalysisDriverLog =3D +- results[NEW_ANALYSIS_DRIVER_LOG]; +- analysisServerOptions.clientId =3D results[CLIENT_ID]; +- analysisServerOptions.clientVersion =3D results[CLIENT_VERSION]; +- analysisServerOptions.cacheFolder =3D results[CACHE_FOLDER]; +- analysisServerOptions.previewDart2 =3D results[PREVIEW_DART2]; +- +- ContextBuilderOptions.flutterRepo =3D results[FLUTTER_REPO]; +- +- telemetry.Analytics analytics =3D telemetry.createAnalyticsInstance( +- 'UA-26406144-29', 'analysis-server', +- disableForSession: results[SUPPRESS_ANALYTICS_FLAG]); +- analysisServerOptions.analytics =3D analytics; +- +- if (analysisServerOptions.clientId !=3D null) { +- // Record the client name as the application installer ID. +- analytics.setSessionValue('aiid', analysisServerOptions.clientId); +- } +- if (analysisServerOptions.clientVersion !=3D null) { +- analytics.setSessionValue('cd1', analysisServerOptions.clientVersio= n); +- } +- +- // TODO(devoncarew): Replace with the real crash product ID. +- analysisServerOptions.crashReportSender =3D +- new CrashReportSender('Dart_analysis_server', analytics); +- +- if (telemetry.SHOW_ANALYTICS_UI) { +- if (results.wasParsed(ANALYTICS_FLAG)) { +- analytics.enabled =3D results[ANALYTICS_FLAG]; +- print(telemetry.createAnalyticsStatusMessage(analytics.enabled)); +- return null; +- } +- } +- +- if (results[DARTPAD_OPTION]) { +- UriContributor.suggestFilePaths =3D false; +- } +- +- if (results[HELP_OPTION]) { +- _printUsage(parser.parser, analytics, fromHelp: true); +- return null; +- } +- +- int port; +- bool serve_http =3D false; +- if (results[PORT_OPTION] !=3D null) { +- try { +- port =3D int.parse(results[PORT_OPTION]); +- serve_http =3D true; +- } on FormatException { +- print('Invalid port number: ${results[PORT_OPTION]}'); +- print(''); +- _printUsage(parser.parser, analytics); +- exitCode =3D 1; +- return null; +- } +- } +- +- // +- // Process all of the plugins so that extensions are registered. +- // +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- linter.registerLintRules(); +- +- String defaultSdkPath; +- if (results[SDK_OPTION] !=3D null) { +- defaultSdkPath =3D results[SDK_OPTION]; +- } else { +- // No path to the SDK was provided. +- // Use FolderBasedDartSdk.defaultSdkDirectory, which will make a gu= ess. +- defaultSdkPath =3D FolderBasedDartSdk +- .defaultSdkDirectory(PhysicalResourceProvider.INSTANCE) +- .path; +- } +- // TODO(brianwilkerson) It would be nice to avoid creating an SDK that +- // cannot be re-used, but the SDK is needed to create a package map p= rovider +- // in the case where we need to run `pub` in order to get the package= map. +- DartSdk defaultSdk =3D _createDefaultSdk(defaultSdkPath, true); +- // +- // Initialize the instrumentation service. +- // +- String logFilePath =3D results[INSTRUMENTATION_LOG_FILE]; +- if (logFilePath !=3D null) { +- _rollLogFiles(logFilePath, 5); +- FileInstrumentationServer fileBasedServer =3D +- new FileInstrumentationServer(logFilePath); +- instrumentationServer =3D instrumentationServer !=3D null +- ? new MulticastInstrumentationServer( +- [instrumentationServer, fileBasedServer]) +- : fileBasedServer; +- } +- InstrumentationService instrumentationService =3D +- new InstrumentationService(instrumentationServer); +- instrumentationService.logVersion( +- _readUuid(instrumentationService), +- analysisServerOptions.clientId, +- analysisServerOptions.clientVersion, +- AnalysisServer.VERSION, +- defaultSdk.sdkVersion); +- AnalysisEngine.instance.instrumentationService =3D instrumentationSer= vice; +- +- _DiagnosticServerImpl diagnosticServer =3D new _DiagnosticServerImpl(= ); +- +- // Ping analytics with our initial call. +- analytics.sendScreenView('home'); +- +- // +- // Create the sockets and start listening for requests. +- // +- socketServer =3D new SocketServer( +- analysisServerOptions, +- new DartSdkManager(defaultSdkPath, true), +- defaultSdk, +- instrumentationService, +- diagnosticServer, +- fileResolverProvider, +- packageResolverProvider); +- httpServer =3D new HttpAnalysisServer(socketServer); +- stdioServer =3D new StdioAnalysisServer(socketServer); +- +- diagnosticServer.httpServer =3D httpServer; +- if (serve_http) { +- diagnosticServer.startOnPort(port); +- } +- +- _captureExceptions(instrumentationService, () { +- stdioServer.serveStdio().then((_) async { +- if (serve_http) { +- httpServer.close(); +- } +- await instrumentationService.shutdown(); +- exit(0); +- }); +- }, +- print: +- results[INTERNAL_PRINT_TO_CONSOLE] ? null : httpServer.record= Print); +- +- return socketServer.analysisServer; +- } +- +- /** +- * Execute the given [callback] within a zone that will capture any unh= andled +- * exceptions and both report them to the client and send them to the g= iven +- * instrumentation [service]. If a [print] function is provided, then a= lso +- * capture any data printed by the callback and redirect it to the func= tion. +- */ +- dynamic _captureExceptions(InstrumentationService service, dynamic call= back(), +- {void print(String line)}) { +- void errorFunction(Zone self, ZoneDelegate parent, Zone zone, +- dynamic exception, StackTrace stackTrace) { +- service.logPriorityException(exception, stackTrace); +- AnalysisServer analysisServer =3D socketServer.analysisServer; +- analysisServer.sendServerErrorNotification( +- 'Captured exception', exception, stackTrace); +- throw exception; +- } +- +- var printFunction =3D print =3D=3D null +- ? null +- : (Zone self, ZoneDelegate parent, Zone zone, String line) { +- // Note: we don't pass the line on to stdout, because that is +- // reserved for communication to the client. +- print(line); +- }; +- ZoneSpecification zoneSpecification =3D new ZoneSpecification( +- handleUncaughtError: errorFunction, print: printFunction); +- return runZoned(callback, zoneSpecification: zoneSpecification); +- } +- +- /** +- * Create and return the parser used to parse the command-line argument= s. +- */ +- CommandLineParser _createArgParser() { +- CommandLineParser parser =3D +- new CommandLineParser(alwaysIgnoreUnrecognized: true); +- parser.addOption(CLIENT_ID, +- help: "an identifier used to identify the client"); +- parser.addOption(CLIENT_VERSION, help: "the version of the client"); +- parser.addFlag(DARTPAD_OPTION, +- help: 'enable DartPad specific functionality', +- defaultsTo: false, +- hide: true); +- parser.addFlag(ENABLE_INSTRUMENTATION_OPTION, +- help: "enable sending instrumentation information to a server", +- defaultsTo: false, +- negatable: false); +- parser.addFlag(FLUTTER_REPO, +- help: 'used by "flutter analyze" to enable specific lints' +- ' when analyzing the flutter repository', +- hide: false); +- parser.addFlag(HELP_OPTION, +- help: "print this help message without starting a server", +- abbr: 'h', +- defaultsTo: false, +- negatable: false); +- parser.addOption(INSTRUMENTATION_LOG_FILE, +- help: "write instrumentation data to the given file"); +- parser.addFlag(INTERNAL_PRINT_TO_CONSOLE, +- help: "enable sending `print` output to the console", +- defaultsTo: false, +- negatable: false); +- parser.addOption(NEW_ANALYSIS_DRIVER_LOG, +- help: "set a destination for the new analysis driver's log"); +- if (telemetry.SHOW_ANALYTICS_UI) { +- parser.addFlag(ANALYTICS_FLAG, +- help: 'enable or disable sending analytics information to Googl= e'); +- } +- parser.addFlag(SUPPRESS_ANALYTICS_FLAG, +- negatable: false, help: 'suppress analytics for this session'); +- parser.addOption(PORT_OPTION, +- help: "the http diagnostic port on which the server provides" +- " status and performance information"); +- parser.addOption(SDK_OPTION, help: "[path] the path to the sdk"); +- parser.addFlag(USE_ANALYSIS_HIGHLIGHT2, +- help: "enable version 2 of semantic highlight", +- defaultsTo: false, +- negatable: false); +- parser.addOption(FILE_READ_MODE, +- help: "an option for reading files (some clients normalize eol " +- "characters, which make the file offset and range information= " +- "incorrect)", +- allowed: ["as-is", "normalize-eol-always"], +- allowedHelp: { +- "as-is": "file contents are read as-is", +- "normalize-eol-always": +- r"eol characters normalized to the single character new lin= e ('\n')" +- }, +- defaultsTo: "as-is"); +- parser.addOption(CACHE_FOLDER, +- help: "[path] path to the location where to cache data"); +- parser.addFlag(PREVIEW_DART2, +- help: "Enable the Dart 2.0 Front End implementation."); +- +- return parser; +- } +- +- DartSdk _createDefaultSdk(String defaultSdkPath, bool useSummaries) { +- PhysicalResourceProvider resourceProvider =3D +- PhysicalResourceProvider.INSTANCE; +- FolderBasedDartSdk sdk =3D new FolderBasedDartSdk( +- resourceProvider, resourceProvider.getFolder(defaultSdkPath)); +- sdk.useSummary =3D useSummaries; +- return sdk; +- } +- +- /** +- * Print information about how to use the server. +- */ +- void _printUsage(ArgParser parser, telemetry.Analytics analytics, +- {bool fromHelp: false}) { +- print('Usage: $BINARY_NAME [flags]'); +- print(''); +- print('Supported flags are:'); +- print(parser.usage); +- +- if (telemetry.SHOW_ANALYTICS_UI) { +- // Print analytics status and information. +- if (fromHelp) { +- print(''); +- print(telemetry.analyticsNotice); +- } +- print(''); +- print(telemetry.createAnalyticsStatusMessage(analytics.enabled, +- command: ANALYTICS_FLAG)); +- } +- } +- +- /** +- * Read the UUID from disk, generating and storing a new one if necessa= ry. +- */ +- String _readUuid(InstrumentationService service) { +- File uuidFile =3D new File(PhysicalResourceProvider.INSTANCE +- .getStateLocation('.instrumentation') +- .getChild('uuid.txt') +- .path); +- try { +- if (uuidFile.existsSync()) { +- String uuid =3D uuidFile.readAsStringSync(); +- if (uuid !=3D null && uuid.length > 5) { +- return uuid; +- } +- } +- } catch (exception, stackTrace) { +- service.logPriorityException(exception, stackTrace); +- } +- int millisecondsSinceEpoch =3D new DateTime.now().millisecondsSinceEp= och; +- int random =3D new Random().nextInt(0x3fffffff); +- String uuid =3D '$millisecondsSinceEpoch$random'; +- try { +- uuidFile.parent.createSync(recursive: true); +- uuidFile.writeAsStringSync(uuid); +- } catch (exception, stackTrace) { +- service.logPriorityException(exception, stackTrace); +- // Slightly alter the uuid to indicate it was not persisted +- uuid =3D 'temp-$uuid'; +- } +- return uuid; +- } +- +- /** +- * Perform log files rolling. +- * +- * Rename existing files with names `[path].(x)` to `[path].(x+1)`. +- * Keep at most [numOld] files. +- * Rename the file with the given [path] to `[path].1`. +- */ +- static void _rollLogFiles(String path, int numOld) { +- for (int i =3D numOld - 1; i >=3D 0; i--) { +- try { +- String oldPath =3D i =3D=3D 0 ? path : '$path.$i'; +- new File(oldPath).renameSync('$path.${i+1}'); +- } catch (e) {} +- } +- } +-} +- +-/** +- * Implements the [DiagnosticServer] class by wrapping an [HttpAnalysisSe= rver]. +- */ +-class _DiagnosticServerImpl extends DiagnosticServer { +- HttpAnalysisServer httpServer; +- +- _DiagnosticServerImpl(); +- +- @override +- Future getServerPort() =3D> httpServer.serveHttp(); +- +- Future startOnPort(int port) { +- return httpServer.serveHttp(port); +- } +-} +diff --git a/pkg/analysis_server/lib/src/server/http_server.dart b/pkg/ana= lysis_server/lib/src/server/http_server.dart +deleted file mode 100644 +index 131d00a2b7c..00000000000 +--- a/pkg/analysis_server/lib/src/server/http_server.dart ++++ /dev/null +@@ -1,169 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analysis_server/src/socket_server.dart'; +-import 'package:analysis_server/src/status/diagnostics.dart'; +- +-/** +- * Instances of the class [AbstractGetHandler] handle GET requests. +- */ +-abstract class AbstractGetHandler { +- /** +- * Handle a GET request received by the HTTP server. +- */ +- void handleGetRequest(HttpRequest request); +-} +- +-/** +- * An [AbstractGetHandler] that always returns the given error message. +- */ +-class ErrorGetHandler extends AbstractGetHandler { +- final String message; +- +- ErrorGetHandler(this.message); +- +- @override +- void handleGetRequest(HttpRequest request) { +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.NOT_FOUND; +- response.headers.contentType =3D ContentType.TEXT; +- response.write(message); +- response.close(); +- } +-} +- +-/** +- * Instances of the class [HttpServer] implement a simple HTTP server. The +- * server: +- * +- * - listens for an UPGRADE request in order to start an analysis server +- * - serves diagnostic information as html pages +- */ +-class HttpAnalysisServer { +- /** +- * Number of lines of print output to capture. +- */ +- static const int MAX_PRINT_BUFFER_LENGTH =3D 1000; +- +- /** +- * An object that can handle either a WebSocket connection or a connect= ion +- * to the client over stdio. +- */ +- SocketServer socketServer; +- +- /** +- * An object that can handle GET requests. +- */ +- AbstractGetHandler getHandler; +- +- /** +- * Future that is completed with the HTTP server once it is running. +- */ +- Future _serverFuture; +- +- /** +- * Last PRINT_BUFFER_LENGTH lines printed. +- */ +- List _printBuffer =3D []; +- +- /** +- * Initialize a newly created HTTP server. +- */ +- HttpAnalysisServer(this.socketServer); +- +- /** +- * Return the port this server is bound to. +- */ +- Future get boundPort async =3D> (await _serverFuture)?.port; +- +- void close() { +- _serverFuture?.then((HttpServer server) { +- server.close(); +- }); +- } +- +- /** +- * Record that the given line was printed out by the analysis server. +- */ +- void recordPrint(String line) { +- _printBuffer.add(line); +- if (_printBuffer.length > MAX_PRINT_BUFFER_LENGTH) { +- _printBuffer.removeRange( +- 0, _printBuffer.length - MAX_PRINT_BUFFER_LENGTH); +- } +- } +- +- /** +- * Begin serving HTTP requests over the given port. +- */ +- Future serveHttp([int initialPort]) async { +- if (_serverFuture !=3D null) { +- return boundPort; +- } +- +- try { +- _serverFuture =3D +- HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, initialPort ?? = 0); +- +- HttpServer server =3D await _serverFuture; +- _handleServer(server); +- return server.port; +- } catch (ignore) { +- // If we can't bind to the specified port, don't remember the broken +- // server. +- _serverFuture =3D null; +- +- return null; +- } +- } +- +- /** +- * Handle a GET request received by the HTTP server. +- */ +- Future _handleGetRequest(HttpRequest request) async { +- if (getHandler =3D=3D null) { +- getHandler =3D new DiagnosticsSite(socketServer, _printBuffer); +- } +- await getHandler.handleGetRequest(request); +- } +- +- /** +- * Attach a listener to a newly created HTTP server. +- */ +- void _handleServer(HttpServer httpServer) { +- httpServer.listen((HttpRequest request) async { +- List updateValues =3D request.headers[HttpHeaders.UPGRADE]; +- if (request.method =3D=3D 'GET') { +- await _handleGetRequest(request); +- } else if (updateValues !=3D null && +- updateValues.indexOf('websocket') >=3D 0) { +- // We no longer support serving analysis server communications ov= er +- // WebSocket connections. +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.NOT_FOUND; +- response.headers.contentType =3D ContentType.TEXT; +- response.write( +- 'WebSocket connections not supported (${request.uri.path}).'); +- response.close(); +- } else { +- _returnUnknownRequest(request); +- } +- }); +- } +- +- /** +- * Return an error in response to an unrecognized request received by t= he HTTP +- * server. +- */ +- void _returnUnknownRequest(HttpRequest request) { +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.NOT_FOUND; +- response.headers.contentType =3D ContentType.TEXT; +- response.write('Not found'); +- response.close(); +- } +-} +diff --git a/pkg/analysis_server/lib/src/server/stdio_server.dart b/pkg/an= alysis_server/lib/src/server/stdio_server.dart +deleted file mode 100644 +index 18954447cbe..00000000000 +--- a/pkg/analysis_server/lib/src/server/stdio_server.dart ++++ /dev/null +@@ -1,40 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analysis_server/src/channel/byte_stream_channel.dart'; +-import 'package:analysis_server/src/socket_server.dart'; +- +-/** +- * Instances of the class [StdioServer] implement a simple server operati= ng +- * over standard input and output. The primary responsibility of this ser= ver +- * is to split incoming messages on newlines and pass them along to the +- * analysis server. +- */ +-class StdioAnalysisServer { +- /** +- * An object that can handle either a WebSocket connection or a connect= ion +- * to the client over stdio. +- */ +- SocketServer socketServer; +- +- /** +- * Initialize a newly created stdio server. +- */ +- StdioAnalysisServer(this.socketServer); +- +- /** +- * Begin serving requests over stdio. +- * +- * Return a future that will be completed when stdin closes. +- */ +- Future serveStdio() { +- ByteStreamServerChannel serverChannel =3D new ByteStreamServerChannel( +- stdin, stdout, socketServer.instrumentationService); +- socketServer.createAnalysisServer(serverChannel); +- return serverChannel.closed; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/completion_co= re.dart b/pkg/analysis_server/lib/src/services/completion/completion_core.d= art +deleted file mode 100644 +index 9d15c203812..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/completion_core.dart ++++ /dev/null +@@ -1,75 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart'; +-import 'package:analysis_server/src/services/completion/completion_perfor= mance.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * The information about a requested list of completions. +- */ +-class CompletionRequestImpl implements CompletionRequest { +- @override +- final AnalysisResult result; +- +- @override +- final Source source; +- +- @override +- final int offset; +- +- /** +- * The offset of the start of the text to be replaced. +- * This will be different than the [offset] used to request the complet= ion +- * suggestions if there was a portion of an identifier before the origi= nal +- * [offset]. In particular, the [replacementOffset] will be the offset = of the +- * beginning of said identifier. +- */ +- int replacementOffset; +- +- /** +- * The length of the text to be replaced if the remainder of the identi= fier +- * containing the cursor is to be replaced when the suggestion is appli= ed +- * (that is, the number of characters in the existing identifier). +- * This will be different than the [replacementOffset] - [offset] +- * if the [offset] is in the middle of an existing identifier. +- */ +- int replacementLength; +- +- @override +- final ResourceProvider resourceProvider; +- +- bool _aborted =3D false; +- +- final CompletionPerformance performance; +- +- /** +- * Initialize a newly created completion request based on the given arg= uments. +- */ +- CompletionRequestImpl(this.result, this.resourceProvider, Source source, +- int offset, this.performance) +- : this.source =3D source, +- this.offset =3D offset, +- replacementOffset =3D offset, +- replacementLength =3D 0; +- +- @override +- String get sourceContents =3D> result?.content; +- +- /** +- * Abort the current completion request. +- */ +- void abort() { +- _aborted =3D true; +- } +- +- @override +- void checkAborted() { +- if (_aborted) { +- throw new AbortCompletion(); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/completion_pe= rformance.dart b/pkg/analysis_server/lib/src/services/completion/completion= _performance.dart +deleted file mode 100644 +index fab1435d9ca..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/completion_performan= ce.dart ++++ /dev/null +@@ -1,117 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * Overall performance of a code completion operation. +- */ +-class CompletionPerformance { +- final DateTime start =3D new DateTime.now(); +- final Map _startTimes =3D new Map(); +- final Stopwatch _stopwatch =3D new Stopwatch(); +- final List operations =3D [= ]; +- +- Source source; +- String snippet =3D ''; +- int notificationCount =3D -1; +- int suggestionCountFirst =3D -1; +- int suggestionCountLast =3D -1; +- Duration _firstNotification; +- +- CompletionPerformance() { +- _stopwatch.start(); +- } +- +- int get elapsedInMilliseconds =3D> +- operations.length > 0 ? operations.last.elapsed.inMilliseconds : 0; +- +- int get firstNotificationInMilliseconds =3D> +- _firstNotification !=3D null ? _firstNotification.inMilliseconds : = 0; +- +- String get startTimeAndMs =3D> '${start.millisecondsSinceEpoch} - $star= t'; +- +- String get suggestionCount { +- if (notificationCount < 1) return ''; +- if (notificationCount =3D=3D 1) return '$suggestionCountFirst'; +- return '$suggestionCountFirst, $suggestionCountLast'; +- } +- +- void complete([String tag =3D null]) { +- _stopwatch.stop(); +- _logDuration(tag ?? 'total time', _stopwatch.elapsed); +- } +- +- void logElapseTime(String tag) { +- Duration end =3D _stopwatch.elapsed; +- Duration start =3D _startTimes[tag]; +- if (start =3D=3D null) { +- _logDuration(tag, null); +- return null; +- } +- _logDuration(tag, end - start); +- } +- +- void logFirstNotificationComplete(String tag) { +- _firstNotification =3D _stopwatch.elapsed; +- _logDuration(tag, _firstNotification); +- } +- +- void logStartTime(String tag) { +- _startTimes[tag] =3D _stopwatch.elapsed; +- } +- +- void setContentsAndOffset(String contents, int offset) { +- snippet =3D _computeSnippet(contents, offset); +- } +- +- void _logDuration(String tag, Duration elapsed) { +- operations.add(new OperationPerformance(tag, elapsed)); +- } +- +- static String _computeSnippet(String contents, int offset) { +- if (contents =3D=3D null || +- offset =3D=3D null || +- offset < 0 || +- contents.length < offset) { +- return '???'; +- } +- int start =3D offset; +- while (start > 0) { +- String ch =3D contents[start - 1]; +- if (ch =3D=3D '\r' || ch =3D=3D '\n') { +- break; +- } +- --start; +- } +- int end =3D offset; +- while (end < contents.length) { +- String ch =3D contents[end]; +- if (ch =3D=3D '\r' || ch =3D=3D '\n') { +- break; +- } +- ++end; +- } +- String prefix =3D contents.substring(start, offset); +- String suffix =3D contents.substring(offset, end); +- return '$prefix^$suffix'; +- } +-} +- +-/** +- * The performance of an operation when computing code completion. +- */ +-class OperationPerformance { +- /** +- * The name of the operation +- */ +- final String name; +- +- /** +- * The elapse time or `null` if undefined. +- */ +- final Duration elapsed; +- +- OperationPerformance(this.name, this.elapsed); +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/arglist_= contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/arg= list_contributor.dart +deleted file mode 100644 +index 010164a1cea..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/arglist_contrib= utor.dart ++++ /dev/null +@@ -1,340 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- hide Element, ElementKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/utilities.da= rt'; +-import 'package:analysis_server/src/utilities/documentation.dart'; +-import 'package:analysis_server/src/utilities/flutter.dart' as flutter; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/utilities_dart.dart'; +- +-/** +- * Determine the number of arguments. +- */ +-int _argCount(DartCompletionRequest request) { +- AstNode node =3D request.target.containingNode; +- if (node is ArgumentList) { +- if (request.target.entity =3D=3D node.rightParenthesis) { +- // Parser ignores trailing commas +- if (node.rightParenthesis.previous?.lexeme =3D=3D ',') { +- return node.arguments.length + 1; +- } +- } +- return node.arguments.length; +- } +- return 0; +-} +- +-/** +- * If the containing [node] is an argument list +- * or named expression in an argument list +- * then return the simple identifier for the method, constructor, or anno= tation +- * to which the argument list is associated +- */ +-SimpleIdentifier _getTargetId(AstNode node) { +- if (node is NamedExpression) { +- return _getTargetId(node.parent); +- } +- if (node is ArgumentList) { +- AstNode parent =3D node.parent; +- if (parent is MethodInvocation) { +- return parent.methodName; +- } +- if (parent is InstanceCreationExpression) { +- ConstructorName constructorName =3D parent.constructorName; +- if (constructorName !=3D null) { +- if (constructorName.name !=3D null) { +- return constructorName.name; +- } +- Identifier typeName =3D constructorName.type.name; +- if (typeName is SimpleIdentifier) { +- return typeName; +- } +- if (typeName is PrefixedIdentifier) { +- return typeName.identifier; +- } +- } +- } +- if (parent is Annotation) { +- return parent.constructorName ?? parent.name; +- } +- } +- return null; +-} +- +-/** +- * Determine if the completion target is at the end of the list of argume= nts. +- */ +-bool _isAppendingToArgList(DartCompletionRequest request) { +- AstNode node =3D request.target.containingNode; +- if (node is ArgumentList) { +- var entity =3D request.target.entity; +- if (entity =3D=3D node.rightParenthesis) { +- return true; +- } +- if (node.arguments.length > 0 && node.arguments.last =3D=3D entity) { +- return entity is SimpleIdentifier; +- } +- } +- return false; +-} +- +-/** +- * Determine if the completion target is the label for a named argument. +- */ +-bool _isEditingNamedArgLabel(DartCompletionRequest request) { +- AstNode node =3D request.target.containingNode; +- if (node is ArgumentList) { +- var entity =3D request.target.entity; +- if (entity is NamedExpression) { +- int offset =3D request.offset; +- if (entity.offset < offset && offset < entity.end) { +- return true; +- } +- } +- } +- return false; +-} +- +-/** +- * Return `true` if the [request] is inside of a [NamedExpression] name. +- */ +-bool _isInNamedExpression(DartCompletionRequest request) { +- Object entity =3D request.target.entity; +- if (entity is NamedExpression) { +- Label name =3D entity.name; +- return name.offset < request.offset && request.offset < name.end; +- } +- return false; +-} +- +-/** +- * Determine if the completion target is in the middle or beginning of th= e list +- * of named parameters and is not preceded by a comma. This method assume= s that +- * _isAppendingToArgList has been called and is false. +- */ +-bool _isInsertingToArgListWithNoSynthetic(DartCompletionRequest request) { +- AstNode node =3D request.target.containingNode; +- if (node is ArgumentList) { +- var entity =3D request.target.entity; +- return entity is NamedExpression; +- } +- return false; +-} +- +-/** +- * Determine if the completion target is in the middle or beginning of th= e list +- * of named parameters and is preceded by a comma. This method assumes th= at +- * _isAppendingToArgList and _isInsertingToArgListWithNoSynthetic have be= en +- * called and both return false. +- */ +-bool _isInsertingToArgListWithSynthetic(DartCompletionRequest request) { +- AstNode node =3D request.target.containingNode; +- if (node is ArgumentList) { +- var entity =3D request.target.entity; +- if (entity is SimpleIdentifier) { +- int argIndex =3D request.target.argIndex; +- // if the next argument is a NamedExpression, then we are in the na= med +- // parameter list, guard first against end of list +- if (node.arguments.length =3D=3D argIndex + 1 || +- node.arguments.getRange(argIndex + 1, argIndex + 2).first +- is NamedExpression) { +- return true; +- } +- } +- } +- return false; +-} +- +-/** +- * Return a collection of currently specified named arguments +- */ +-Iterable _namedArgs(DartCompletionRequest request) { +- AstNode node =3D request.target.containingNode; +- List namedArgs =3D new List(); +- if (node is ArgumentList) { +- for (Expression arg in node.arguments) { +- if (arg is NamedExpression) { +- namedArgs.add(arg.name.label.name); +- } +- } +- } +- return namedArgs; +-} +- +-/** +- * A contributor for calculating `completion.getSuggestions` request resu= lts +- * when the cursor position is inside the arguments to a method call. +- */ +-class ArgListContributor extends DartCompletionContributor { +- DartCompletionRequest request; +- List suggestions; +- +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- this.request =3D request; +- this.suggestions =3D []; +- +- // Determine if the target is in an argument list +- // for a method or a constructor or an annotation +- SimpleIdentifier targetId =3D _getTargetId(request.target.containingN= ode); +- if (targetId =3D=3D null) { +- return EMPTY_LIST; +- } +- Element elem =3D targetId.bestElement; +- if (elem =3D=3D null) { +- return EMPTY_LIST; +- } +- +- // Generate argument list suggestion based upon the type of element +- if (elem is ClassElement) { +- _addSuggestions(elem.unnamedConstructor?.parameters); +- return suggestions; +- } +- if (elem is ConstructorElement) { +- _addSuggestions(elem.parameters); +- return suggestions; +- } +- if (elem is FunctionElement) { +- _addSuggestions(elem.parameters); +- return suggestions; +- } +- if (elem is MethodElement) { +- _addSuggestions(elem.parameters); +- return suggestions; +- } +- return EMPTY_LIST; +- } +- +- void _addDefaultParamSuggestions(Iterable parameters, +- [bool appendComma =3D false]) { +- bool appendColon =3D !_isInNamedExpression(request); +- Iterable namedArgs =3D _namedArgs(request); +- for (ParameterElement parameter in parameters) { +- if (parameter.parameterKind =3D=3D ParameterKind.NAMED) { +- _addNamedParameterSuggestion( +- namedArgs, parameter, appendColon, appendComma); +- } +- } +- } +- +- void _addNamedParameterSuggestion(List namedArgs, +- ParameterElement parameter, bool appendColon, bool appendComma) { +- String name =3D parameter.name; +- String type =3D parameter.type?.displayName; +- if (name !=3D null && name.length > 0 && !namedArgs.contains(name)) { +- String completion =3D name; +- if (appendColon) { +- completion +=3D ': '; +- } +- int selectionOffset =3D completion.length; +- +- // Optionally add Flutter child widget details. +- Element element =3D parameter.enclosingElement; +- if (element is ConstructorElement) { +- if (flutter.isWidget(element.enclosingElement) && +- parameter.name =3D=3D 'children') { +- String value =3D getDefaultStringParameterValue(parameter); +- if (value !=3D null) { +- completion +=3D value; +- // children: [] +- selectionOffset =3D completion.length - 1; // before closing = ']' +- } +- } +- } +- +- if (appendComma) { +- completion +=3D ','; +- } +- +- final int relevance =3D parameter.isRequired +- ? DART_RELEVANCE_NAMED_PARAMETER_REQUIRED +- : DART_RELEVANCE_NAMED_PARAMETER; +- +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance, +- completion, +- selectionOffset, +- 0, +- false, +- false, +- parameterName: name, +- parameterType: type); +- if (parameter is FieldFormalParameterElement) { +- _setDocumentation(suggestion, parameter.field?.documentationComme= nt); +- suggestion.element =3D convertElement(parameter); +- } +- +- suggestions.add(suggestion); +- } +- } +- +- void _addSuggestions(Iterable parameters) { +- if (parameters =3D=3D null || parameters.length =3D=3D 0) { +- return; +- } +- Iterable requiredParam =3D parameters.where( +- (ParameterElement p) =3D> p.parameterKind =3D=3D ParameterKind.RE= QUIRED); +- int requiredCount =3D requiredParam.length; +- // TODO (jwren) _isAppendingToArgList can be split into two cases (wi= th and +- // without preceded), then _isAppendingToArgList, +- // _isInsertingToArgListWithNoSynthetic and +- // _isInsertingToArgListWithSynthetic could be formatted into a single +- // method which returns some enum with 5+ cases. +- if (_isEditingNamedArgLabel(request) || _isAppendingToArgList(request= )) { +- if (requiredCount =3D=3D 0 || requiredCount < _argCount(request)) { +- bool addTrailingComma =3D +- !_isFollowedByAComma(request) && _isInFlutterCreation(request= ); +- _addDefaultParamSuggestions(parameters, addTrailingComma); +- } +- } else if (_isInsertingToArgListWithNoSynthetic(request)) { +- _addDefaultParamSuggestions(parameters, true); +- } else if (_isInsertingToArgListWithSynthetic(request)) { +- _addDefaultParamSuggestions(parameters, !_isFollowedByAComma(reques= t)); +- } +- } +- +- bool _isFollowedByAComma(DartCompletionRequest request) { +- // new A(^); NO +- // new A(one: 1, ^); NO +- // new A(^ , one: 1); YES +- // new A(^), ... NO +- +- var containingNode =3D request.target.containingNode; +- var entity =3D request.target.entity; +- Token token =3D +- entity is AstNode ? entity.endToken : entity is Token ? entity : = null; +- return (token !=3D containingNode?.endToken) && +- token?.next?.type =3D=3D TokenType.COMMA; +- } +- +- bool _isInFlutterCreation(DartCompletionRequest request) { +- AstNode containingNode =3D request?.target?.containingNode; +- InstanceCreationExpression newExpr =3D containingNode !=3D null +- ? flutter.identifyNewExpression(containingNode.parent) +- : null; +- return newExpr !=3D null && flutter.isWidgetCreation(newExpr); +- } +- +- /** +- * If the given [comment] is not `null`, fill the [suggestion] document= ation +- * fields. +- */ +- static void _setDocumentation( +- CompletionSuggestion suggestion, String comment) { +- if (comment !=3D null) { +- String doc =3D removeDartDocDelimiters(comment); +- suggestion.docComplete =3D doc; +- suggestion.docSummary =3D getDartDocSummary(doc); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/combinat= or_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/= combinator_contributor.dart +deleted file mode 100644 +index 4d30f30eb5f..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/combinator_cont= ributor.dart ++++ /dev/null +@@ -1,41 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- hide Element, ElementKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-/** +- * A contributor for calculating `completion.getSuggestions` request resu= lts +- * for the import combinators show and hide. +- */ +-class CombinatorContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- AstNode node =3D request.target.containingNode; +- if (node is! Combinator) { +- return EMPTY_LIST; +- } +- +- // Build list of suggestions +- var directive =3D node.getAncestor((parent) =3D> parent is NamespaceD= irective); +- if (directive is NamespaceDirective) { +- LibraryElement library =3D directive.uriElement; +- if (library !=3D null) { +- LibraryElementSuggestionBuilder builder =3D +- new LibraryElementSuggestionBuilder(request.libraryElement, +- CompletionSuggestionKind.IDENTIFIER, false, false); +- library.visitChildren(builder); +- return builder.suggestions; +- } +- } +- return EMPTY_LIST; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/common_u= sage_sorter.dart b/pkg/analysis_server/lib/src/services/completion/dart/com= mon_usage_sorter.dart +deleted file mode 100644 +index a515bedff80..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/common_usage_so= rter.dart ++++ /dev/null +@@ -1,127 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library services.completion.dart.sorter.common; +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/contribution= _sorter.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/completion_targe= t.dart'; +- +-part 'common_usage_sorter.g.dart'; +- +-/** +- * A computer for adjusting the relevance of completions computed by othe= rs +- * based upon common Dart usage patterns. This is a long-lived object +- * that should not maintain state between calls to it's [sort] method. +- */ +-class CommonUsageSorter implements DartContributionSorter { +- /** +- * A map of . to an ordered list of method names, +- * field names, getter names, and named constructors. +- * The names are ordered from most relevant to least relevant. +- * Names not listed are considered equally less relevant than those lis= ted. +- */ +- Map> selectorRelevance; +- +- CommonUsageSorter([this.selectorRelevance =3D defaultSelectorRelevance]= ); +- +- @override +- Future sort(DartCompletionRequest request, +- Iterable suggestions) { +- _update(request, suggestions); +- return new Future.value(); +- } +- +- CompletionTarget _getCompletionTarget(CompletionRequest request) =3D> +- new CompletionTarget.forOffset(request.result.unit, request.offset); +- +- /** +- * Adjusts the relevance based on the given completion context. +- * The compilation unit and completion node +- * in the given completion context may not be resolved. +- */ +- void _update( +- CompletionRequest request, Iterable suggestio= ns) { +- var target =3D _getCompletionTarget(request); +- if (target !=3D null) { +- var visitor =3D new _BestTypeVisitor(target.entity); +- DartType type =3D target.containingNode.accept(visitor); +- if (type !=3D null) { +- Element typeElem =3D type.element; +- if (typeElem !=3D null) { +- LibraryElement libElem =3D typeElem.library; +- if (libElem !=3D null) { +- _updateInvocationRelevance(type, libElem, suggestions); +- } +- } +- } +- } +- } +- +- /** +- * Adjusts the relevance of all method suggestions based upon the given +- * target type and library. +- */ +- void _updateInvocationRelevance(DartType type, LibraryElement libElem, +- Iterable suggestions) { +- String typeName =3D type.name; +- List selectors =3D selectorRelevance['${libElem.name}.$typeNa= me']; +- if (selectors !=3D null) { +- for (CompletionSuggestion suggestion in suggestions) { +- protocol.Element element =3D suggestion.element; +- if (element !=3D null && +- (element.kind =3D=3D protocol.ElementKind.CONSTRUCTOR || +- element.kind =3D=3D protocol.ElementKind.FIELD || +- element.kind =3D=3D protocol.ElementKind.GETTER || +- element.kind =3D=3D protocol.ElementKind.METHOD || +- element.kind =3D=3D protocol.ElementKind.SETTER) && +- suggestion.kind =3D=3D CompletionSuggestionKind.INVOCATION && +- suggestion.declaringType =3D=3D typeName) { +- int index =3D selectors.indexOf(suggestion.completion); +- if (index !=3D -1) { +- suggestion.relevance =3D DART_RELEVANCE_COMMON_USAGE - index; +- } +- } +- } +- } +- } +-} +- +-/** +- * An [AstVisitor] used to determine the best defining type of a node. +- */ +-class _BestTypeVisitor extends GeneralizingAstVisitor { +- /** +- * The entity which the completed text will replace (or which will be +- * displaced once the completed text is inserted). This may be an AstN= ode or +- * a Token, or it may be null if the cursor is after all tokens in the = file. +- * See field of the same name in [CompletionTarget]. +- */ +- final Object entity; +- +- _BestTypeVisitor(this.entity); +- +- DartType visitConstructorName(ConstructorName node) =3D> +- node.period !=3D null && node.name =3D=3D entity ? node.type?.type = : null; +- +- DartType visitNode(AstNode node) { +- return null; +- } +- +- DartType visitPrefixedIdentifier(PrefixedIdentifier node) =3D> +- node.identifier =3D=3D entity ? node.prefix?.bestType : null; +- +- DartType visitPropertyAccess(PropertyAccess node) =3D> +- node.propertyName =3D=3D entity ? node.realTarget?.bestType : null; +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/common_u= sage_sorter.g.dart b/pkg/analysis_server/lib/src/services/completion/dart/c= ommon_usage_sorter.g.dart +deleted file mode 100644 +index f065701d986..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/common_usage_so= rter.g.dart ++++ /dev/null +@@ -1,427 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-part of services.completion.dart.sorter.common; +- +-// Auto-generated, please do not edit. +- +-/** +- * A map of . to an ordered list of method names, +- * field names, getter names, and named constructors. +- * The names are ordered from most relevant to least relevant. +- * Names not listed are considered equally less relevant than those liste= d. +- */ +-const Map> defaultSelectorRelevance =3D const { +-'dart.core.Comparable': const ['compareTo','compare',], +-'dart.math.Random': const ['nextInt','nextDouble','nextBool',], +-'dart.core.List': const ['add','map','length','removeLast','addAll','join= ','forEach','contains','removeAt','where','last','clear','setRange','sort',= 'insert','remove','sublist','indexOf','isEmpty','any','insertAll','first','= removeRange','replaceRange','take','getRange','skip','toList','retainWhere'= ,'fillRange','removeWhere','expand','fold','reversed','firstWhere','every',= 'setAll','asMap','isNotEmpty','lastIndexOf','singleWhere','lastWhere','shuf= fle','takeWhile','iterator','toString','toSet','single','reduce','elementAt= ','skipWhile','insertRange','filter','push','mappedBy','addLast','some','sl= ice','retainMatching','firstMatching','removeAll','retainAll','removeMatchi= ng','min','lastMatching','singleMatching','max','get','toArray','runtimeTyp= e','reverse','addd','asByteArray',], +-'dart.core.Iterable': const ['toList','map','join','toSet','where','forEa= ch','expand','fold','every','any','contains','firstWhere','length','element= At','skipWhile','reduce','iterator','take','skip','toString','singleWhere',= 'lastWhere','takeWhile','isEmpty','first','single','last','isNotEmpty','add= All','indexOf','add','sort','toArray','mappedBy','filter',], +-'dart.core.Set': const ['add','contains','remove','addAll','clear','diffe= rence','map','containsAll','union','removeWhere','removeAll','intersection'= ,'retainAll','retainWhere','forEach','toSet','every','lookup','any','toStri= ng','toList','where','length','join','skip','firstWhere','isEmpty','first',= 'iterator','singleWhere','expand','elementAt','fold','reduce','single','las= tWhere','isNotEmpty','take','takeWhile','skipWhile','last','findBy','toArra= y','filter',], +-'dart.collection.Queue': const ['add','removeFirst','clear','removeLast',= 'remove','addAll','addLast','addFirst','removeWhere','retainWhere','length'= ,'toList','where','contains','forEach','map','isNotEmpty','first','isEmpty'= ,'fold','skip','any','elementAt',], +-'dart.core.Map': const ['containsKey','forEach','remove','putIfAbsent','c= lear','addAll','length','keys','values','containsValue','toString','isNotEm= pty','isEmpty','get','getKeys','put','getValues','clone','keySet','hashCode= ','runtimeType',], +-'dart.core.Iterator': const ['moveNext','current','next','hasNext',], +-'dart.pkg.collection.equality.Equality': const ['hash','equals','isValidK= ey',], +-'dart.pkg.collection.equality.SetEquality': const ['equals','hash',], +-'dart.pkg.collection.equality.MapEquality': const ['equals','hash',], +-'dart.pkg.collection.equality.ListEquality': const ['equals','hash',], +-'dart.pkg.collection.equality.IterableEquality': const ['hash','equals',], +-'dart.pkg.collection.equality.UnorderedIterableEquality': const ['hash','= equals',], +-'dart.async.StreamSubscription': const ['cancel','pause','onDone','resume= ','onError','asFuture','onData','isPaused',], +-'dart.async.StreamController': const ['add','close','addError','addStream= ','stream','hasListener','signalError','sink','done',], +-'dart.async.Stream': const ['listen','transform','pipe','first','toList',= 'forEach','firstWhere','where','join','fold','asyncMap','map','isEmpty','as= BroadcastStream','handleError','capture','asyncExpand','take','single','exp= and','onFile','skip','any','timeout','add','last','runtimeType','isBroadcas= t','drain','elementAt','skipWhile','distinct','singleWhere','lastWhere','co= ntains','every','takeWhile','emit','onDir','onError','onDone','onData','len= gth',], +-'dart.async.Future': const ['then','catchError','wait','whenComplete','fo= rEach','asStream','timeout','map','packages','where','firstWhere','chain','= transform','doWhile','onError','onResponse','onRequest','handleException',], +-'dart.core.String': const ['substring','codeUnitAt','startsWith','replace= All','split','contains','indexOf','toLowerCase','trim','length','endsWith',= 'lastIndexOf','compareTo','isEmpty','toUpperCase','replaceFirst','toString'= ,'replaceAllMapped','allMatches','padLeft','codeUnits','hashCode','splitMap= Join','isNotEmpty','runes','charCodeAt','charCodes','trimRight','padRight',= 'concat','equalsIgnoreCase','splitChars','trimLeft','matchAsPrefix','equals= ','map','toLoweCase','match','slice','getBytes','toCharArray','runtimeType'= ,'charAt','valueOf',], +-'dart.core.StringBuffer': const ['write','toString','writeln','writeCharC= ode','clear','writeAll','add','addAll','addCharCode','isEmpty',], +-'dart.core.RegExp': const ['firstMatch','hasMatch','allMatches','matchAsP= refix','pattern','stringMatch','toString','exec',], +-'dart.core.double': const ['parse','toInt','compareTo','floor','toString'= ,'abs','round','toStringAsPrecision','toDouble','floorToDouble','ceil','tru= ncate','toStringAsFixed','roundToDouble','clamp','isNaN','isFinite','toStri= ngAsExponential','ceilToDouble','truncateToDouble','isNan','isNegative','is= Infinite','hashCode',], +-'dart.core.Type': const ['toString','hashCode','runtimeType',], +-'dart.mirrors.InstanceMirror': const ['reflectee','getField','type','invo= ke','setField','delegate','function','then','apply','hasReflectee',], +-'dart.collection.IterableBase': const ['iterableToFullString',], +-'dart.pkg.collection.utils.Pair': const ['last',], +-'dart.collection.Maps': const ['mapToString','length','putIfAbsent','clea= r','containsKey','getValues','forEach','containsValue','isNotEmpty','isEmpt= y',], +-'dart.collection.SplayTreeSet': const ['add','addAll','where',], +-'dart.core.StackTrace': const ['toString','frames',], +-'dart.convert.JsonCodec': const ['encode','decode','fuse',], +-'dart.mirrors.MirrorSystem': const ['getName','libraries','findLibrary','= isolate','dynamicType','getSymbol','voidType',], +-'dart.mirrors.ClassMirror': const ['newInstance','isSubtypeOf','reflected= Type','qualifiedName','metadata','getField','owner','declarations','supercl= ass','simpleName','isSubclassOf','invoke','instanceMembers','mixin','isAbst= ract','originalDeclaration','typeVariables','setField','isOriginalDeclarati= on','superinterfaces','isAssignableTo','owners',], +-'dart.io.Process': const ['start','runSync','run','kill','exitCode',], +-'dart.core.int': const ['parse','toDouble','toString','toInt','compareTo'= ,'toRadixString','abs','remainder','toUnsigned','toSigned','clamp','round',= 'floor','substr','ceil','isEven','id','append','truncate','hashCode','toStr= ingAsFixed','ceilToDouble','roundToDouble','floorToDouble','truncateToDoubl= e','isNegative','length','isNaN','isInfinite','runtimeType','bitLength',], +-'dart.core.Sink': const ['add','close',], +-'dart.async.EventSink': const ['close','add','addError',], +-'dart.async.Completer': const ['complete','completeError','future','isCom= pleted','completeException','then',], +-'dart.io.FileStat': const ['mode','stat','type','statSync','changed','mod= ified','size',], +-'dart.io.Link': const ['existsSync','createSync','resolveSymbolicLinksSyn= c','exists','delete','targetSync','deleteSync','target','create','updateSyn= c',], +-'dart.io.FileSystemEntityType': const ['toString','NOT_FOUND','DIRECTORY'= ,'FILE',], +-'dart.io.Directory': const ['existsSync','list','listSync','watch','path'= ,'exists','createSync','create','deleteSync','delete','createTemp','createT= empSync','renameSync','parent','absolute','stat','current','createRecursive= lySync','resolveSymbolicLinksSync','rename','statSync',], +-'dart.io.File': const ['existsSync','readAsStringSync','openRead','writeA= sStringSync','readAsString','openWrite','lastModifiedSync','exists','resolv= eSymbolicLinksSync','writeAsString','path','resolveSymbolicLinks','statSync= ','deleteSync','createSync','delete','openSync','parent','readAsBytesSync',= 'copy','open','absolute','fullPathSync','length','writeAsBytesSync','lastMo= dified','writeAsBytes','readAsLinesSync','fullPath','readAsBytes','copySync= ','create','lengthSync','readAsLines','isFileSync','isFile','rename','openO= utputStream','openInputStream','stat','renameSync','watch','directorySync',= 'isAbsolute','directory',], +-'dart.io.Stdout': const ['writeln','close','write','flush','addStream','w= riteString','add','writeCharCode','addString',], +-'dart.io.IOSink': const ['write','close','writeln','flush','add','addStre= am','writeAll','writeCharCode','encoding','addError','done',], +-'dart.mirrors.LibraryMirror': const ['uri','getField','declarations','inv= oke','topLevelMembers','setField','classes','first',], +-'dart.core.Match': const ['group','end','start','groups','toString',], +-'dart.isolate.SendPort': const ['send','call','hashCode',], +-'dart.core.DateTime': const ['parse','toIso8601String','millisecondsSince= Epoch','difference','toUtc','add','day','year','month','isAfter','toString'= ,'compareTo','subtract','isBefore','millisecond','toLocal','timeZoneName','= timeZoneOffset','isUtc','weekday','isAtSameMomentAs','second','hour','minut= e','hashCode','now','runtimeType',], +-'dart.core.Duration': const ['inMilliseconds','toString','inSeconds','inM= icroseconds','inHours','inMinutes','inDays','isNegative','compareTo',], +-'dart.core.Uri': const ['parse','toString','toFilePath','path','resolve',= 'decodeComponent','encodeFull','decodeQueryComponent','scheme','encodeCompo= nent','resolveUri','encodeQueryComponent','query','decodeFull','pathSegment= s','queryParameters','origin','authority','splitQueryString','replace','hos= t','isAbsolute','port','fragment','hasAuthority','userInfo','parseIPv4Addre= ss','parseIPv6Address','hasQuery','endsWith','startsWith',], +-'dart.typed_data.Uint32List': const ['sublist','setAll','fillRange','setR= ange','removeRange','removeLast','clear','addAll','add',], +-'dart.typed_data.TypedData': const ['buffer',], +-'dart.io.BytesBuilder': const ['takeBytes','addByte','add','clear','toByt= es',], +-'dart.isolate.ReceivePort': const ['close','transform','listen','receive'= ,'toSendPort','takeWhile','sendPort','asBroadcastStream',], +-'dart.convert.Encoding': const ['decode','encode','getByName','decodeStre= am','name',], +-'dart.convert.Utf8Codec': const ['encode','decode','decoder','decodeStrea= m',], +-'dart.core.Stopwatch': const ['start','stop','reset','elapsedMicroseconds= ','elapsedMilliseconds','elapsed','elapsedInMs',], +-'dart.async.ZoneDelegate': const ['handleUncaughtError','registerUnaryCal= lback','registerCallback','registerBinaryCallback','runBinary','errorCallba= ck','scheduleMicrotask','run','createTimer',], +-'dart.async.Zone': const ['handleUncaughtError','run','fork','inSameError= Zone','runGuarded','bindUnaryCallback','bindBinaryCallback','runUnary','bin= dCallback','scheduleMicrotask','createTimer',], +-'dart.dom.html.BodyElement': const ['innerHtml','children','nodes','appen= d','style','onContextMenu','onMouseDown','onMouseWheel','scrollTop','onMous= eUp','onClick','scrollLeft','clientHeight','clientWidth','onBlur','onFocus'= ,'onDoubleClick','scrollHeight','onMouseMove','elements','createFragment','= classes','ownerDocument','query','onKeyDown','querySelector','offsetWidth',= 'scrollWidth','offsetHeight','setInnerHtml','childNodes','requestFullscreen= ','offsetTop',], +-'dart.dom.html.Location': const ['hash','search','reload','pathname','toS= tring','href','host','assign','replace','protocol','hostname','port','origi= n',], +-'dart.convert.HtmlEscape': const ['convert',], +-'dart.dom.html.Window': const ['postMessage','btoa','lookupPort','documen= t','requestAnimationFrame','alert','navigator','devicePixelRatio','pageYOff= set','pageXOffset','onAnimationEnd','innerWidth','onResize','getSelection',= 'cancelAnimationFrame','animationEndEvent','innerHeight','registerPort','di= spatchEvent','onAnimationStart','onMouseUp','onMouseMove','open','screen','= indexedDB','setTimeout','scrollX','scrollY','onScroll','openDatabase','conf= irm','getContainer','location','onKeyUp','atob','scrollTo','localStorage','= scrollBy','setInterval','setImmediate','requestLayoutFrame','requestFileSys= tem','onHashChange','close','console','onError','onMessage','animationFrame= ',], +-'dart.core.Function': const ['apply','toString','call','bind',], +-'dart.async.Timer': const ['cancel','run',], +-'dart.dom.html.HeadElement': const ['append','querySelector','query','chi= ldren','style','elements','querySelectorAll','nodes','id','insertBefore','t= ext',], +-'dart.dom.html.ElementStream': const ['listen','where','first','matches',= 'forEach','map',], +-'dart.dom.html.Element': const ['query','onClick','innerHtml','style','qu= erySelector','nodes','children','remove','append','querySelectorAll','class= es','attributes','setInnerHtml','getComputedStyle','onChange','parent','mat= ches','getBoundingClientRect','focus','dispatchEvent','addEventListener','i= nsertAllBefore','clone','getAttribute','blur','createShadowRoot','contains'= ,'text','setAttribute','insertAdjacentElement','appendText','scrollIntoView= ','shadowRoot','getNamespacedAttributes','removeEventListener','insertBefor= e','appendHtml','click','offsetWidth','insertAdjacentHtml','insertAdjacentT= ext','getClientRects','getElementsByClassName','replaceWith','scrollByLines= ','scrollByPages','hasChildNodes','requestFullscreen','requestPointerLock',= 'queryAll','setAttributeNS','getAttributeNS','dataset','offsetHeight','on',= 'createFragment','offsetTo','getDestinationInsertionPoints','matchesWithAnc= estors','attributeChanged','onMouseDown','nextElementSibling','getRegionFlo= wRanges','onContextMenu','animate','onTouchStart','scrollTop','offsetTop','= onTouchMove','onTouchEnd','onMouseWheel','clientWidth','scrollLeft','client= Height','isTagSupported','parentNode','onMouseUp','bind','onKeyDown','owner= Document','unbind','unbindAll','init','createInstance','render','update','o= nKeyUp','onMouseMove','xtag','offsetLeft','tabIndex','client','requestFullS= creen','getInputContext','borderEdge','clearModel','id','disabled','value',= 'getContext','lastChild','firstChild','nextNode','innerHTML','onMouseEnter'= ,'onMouseLeave','contentEdge','elements','matchesSelector','webkitRequestPo= interLock','tagName','childNodes','webkitRequestFullscreen','webkitRequestF= ullScreen','marginEdge','paddingEdge','outerHtml','onMouseOver','onMouseOut= ','onDragEnd','boolean','scrollHeight','hidden','onDragStart','onDoubleClic= k','nodeType','hashCode','onDrag','onInput','selectionStart','selectionEnd'= ,'onDrop','onDragLeave','hideOrShowNavigation','onDragOver','model','scroll= Event','onDragEnter','previousElementSibling','className','namespaceUri','o= nSubmit','selection','setItemSelected','runtimeType','apply','createBinding= ','values','onBlur','onTouchCancel','show','insertAdjacentHTML','nodeName',= 'selected','contentEditable','localName','number','draggable','src','addTex= t','addHTML','select','clear','str','clearSelection',], +-'dart.dom.html.HtmlElement': const ['querySelector','query','append','cla= sses','style','getComputedStyle','remove','getBoundingClientRect','querySel= ectorAll','clone','attributes','focus','tabIndex','onClick','parent','onMou= seLeave','replaceWith','onContextMenu','onMouseEnter','onKeyDown','blur','s= etInnerText','scrollTop','appendHtml','dataset','lastChild','onSelectStart'= ,'onDrop','onDragOver','onDragLeave','onDragEnter','onDragEnd','onDragStart= ','onDrag','onDoubleClick','children','onScroll','getAttribute','nodes','ou= terHtml','click','createShadowRoot',], +-'dart.dom.html.ElementList': const ['forEach','length','contains','last',= 'style','addAll','first','where','onMouseLeave','onMouseEnter','toList','so= me','onClick','map','classes','indexOf',], +-'dart.dom.html.HtmlDocument': const ['query','querySelectorAll','querySel= ector','queryAll','createElement','body','title','createElementUpgrader','d= ocumentElement','timeline','onKeyDown','getElementById','registerElement','= onClick','addEventListener','onMouseUp','onMouseMove','activeElement','crea= teElementNS','createDocumentFragment','createRange','adoptNode','getElement= sByTagName','onKeyUp','elementFromPoint','contains','getElementsByName','he= ad','exitFullscreen','onMouseWheel','register',], +-'dart.collection.LinkedHashMap': const ['containsKey','forEach','remove',= 'putIfAbsent','keys','length','clear','values','isNotEmpty',], +-'dart.dom.html.Navigator': const ['userAgent','language','appVersion','ap= pName','geolocation','vendor','appCodeName','dartEnabled','getUserMedia','o= nLine','platform','storageQuota',], +-'dart.dom.html.CssStyleDeclaration': const ['display','width','height','t= op','setProperty','left','position','zIndex','cssText','right','maxHeight',= 'visibility','bottom','background','removeProperty','cursor','overflow','ge= tPropertyValue','opacity','backgroundColor','float','transform','padding','= border','borderRadius','paddingBottom','transition','paddingTop','overflowY= ','color','outline','backgroundImage','transformStyle','pointerEvents','mar= ginLeft','textAlign','backgroundPosition','boxSizing','paddingLeft','backgr= oundSize','margin','fontFamily','userSelect','fontSize','lineHeight','willC= hange','fontWeight','getProperty','marginRight','whiteSpace','overflowX','t= extDecoration','perspective','perspectiveOrigin','appearance','borderLeftWi= dth','paddingRight','borderColor','borderBottomWidth','borderTopWidth','web= kitOverflowScrolling','borderRightWidth','marginBottom','transitionProperty= ','transitionTimingFunction','transitionDuration','animation','animationDel= ay','animationFillMode','animationDirection','animationIterationCount','ani= mationTimingFunction','animationDuration','animationName','verticalAlign','= marginTop','boxShadow','getPropertyPriority','textStrokeColor','borderBotto= m','font','supportsProperty','textShadow','maxWidth','minWidth','minHeight'= ,'outlineColor','filter','borderWidth','animationPlayState','fontStyle','bo= rderRight','borderLeft','borderTop',], +-'dart.io.ProcessResult': const ['stdout','exitCode',], +-'dart.io.FileSystemEvent': const ['path','isDirectory','type','MODIFY','C= REATE','DELETE',], +-'dart.collection.HashSet': const ['add','contains','remove','clear','addA= ll','retainAll','length','isEmpty','toList','removeAll','any','forEach','ma= p',], +-'dart.collection.HashMap': const ['remove','containsKey','forEach','clear= ','keys','putIfAbsent','addAll','values',], +-'dart.io.FileSystemEntity': const ['isDirectorySync','path','typeSync','e= xistsSync','isDirectory','identicalSync','isFileSync','type','isFile','stat= Sync','deleteSync','isLinkSync','parentOf','renameSync','isLink','readAsStr= ingSync','identical','rename','toString','delete','exists','parent','stat',= ], +-'dart.io.OSError': const ['errorCode','toString',], +-'dart.async.StreamTransformer': const ['bind',], +-'dart.core.Runes': const ['toList','any','elementAt','iterator','single',= 'first','forEach','last',], +-'dart.core.Object': const ['toString','toJson','hashCode','discardListCha= ges','reverse','map','lightDom','getName','where','add','containsKey','form= at','setTable','getClass','getNamespace','getId','getCell','getSize','setNa= mespace','equals','setColumn','getColumnName','getForeignTableName','setDat= abase','setAttribute','setId','getChild','body','setPrevious','getIndex','g= etParent','getChildAt','getChildCount','getValue','getRoot','POST','GET','g= etPackage','setSchema','clone','getType','then','isInheritance','isVisible'= ,'getDartName','getPlatform','setPosition','setPackage','requiresTransactio= nInPostgres','setAppData','getSchema','getBuildProperty','getPrevious','get= Terminal','n','replaceWith','setChild','setPlatform','run','removeItem','ge= tAllItems','bytes','compareTo','getAttribute','setPreviousIndex','isEmpty',= 'getEdgeAt','isVertex','writeExternal','isEdge','getEdgeCount','isConnectab= le','setValue','isCollapsed','getStyles','setRoot','getStyle','getGeometry'= ,'noSuchMethod','contains','elementAt','e',], +-'dart.core.StringSink': const ['write','writeln','writeCharCode','toStrin= g','writeAll',], +-'dart.io.Stdin': const ['pipe','readLineSync','transform','listen',], +-'dart.io.HttpServer': const ['bind','listen','close','connectionsInfo','b= indSecure','address','port','idleTimeout','serverHeader','autoCompress','as= BroadcastStream','transform','addRequestHandler','listenOn','on',], +-'dart.io.HttpResponse': const ['close','write','statusCode','headers','ad= d','done','redirect','addStream','detachSocket','reasonPhrase','writeln','a= ddError','writeCharCode','writeAll','flush','toString','when','cookies','co= ntentLength','addString','getLogs','listen','persistentConnection','deadlin= e',], +-'dart.io.HttpRequest': const ['listen','uri','session','drain','transform= ','response','toString','cookies','method','fold','connectionInfo','pipe','= asBroadcastStream','toList','timeout','takeWhile','take','skipWhile','singl= eWhere','map','lastWhere','join','handleError','skip','firstWhere','expand'= ,'every','elementAt','distinct','asyncMap','asyncExpand','any','toSet','con= tains','where','reduce','forEach','headers','path',], +-'dart.collection.SplayTreeMap': const ['forEach','containsKey','remove','= keys','values','firstKeyAfter','lastKeyBefore','clear','length',], +-'dart.io.HttpClient': const ['post','getUrl','openUrl','close','postUrl',= 'get','open','addCredentials','patchUrl','shutdown','put','delete','addProx= yCredentials','findProxyFromEnvironment',], +-'dart.io.HttpClientRequest': const ['close','add','write','addStream','co= okies',], +-'dart.io.Platform': const ['isWindows','script','environment','operatingS= ystem','pathSeparator',], +-'dart.collection.LinkedHashSet': const ['add','map','contains','toList','= addAll','remove',], +-'dart.io.RandomAccessFile': const ['lengthSync','readIntoSync','close','c= loseSync','writeStringSync','writeString','writeFromSync','length','readInt= o','read','readSync','writeFrom','readListSync','flushSync','positionSync',= 'setPosition','writeListSync','setPositionSync','unlock','lock','unlockSync= ','readList','lockSync','readByteSync','position','writeList','writeByteSyn= c',], +-'dart.core.num': const ['round','toDouble','toInt','floor','abs','toStrin= g','parse','ceil','toStringAsFixed','isNaN','compareTo','roundToDouble','re= mainder','hashCode','clamp','isInfinite','isNegative','truncate','toStringA= sPrecision','toStringAsExponential','isFinite','truncateToDouble','toRadixS= tring',], +-'dart.dom.html.HttpRequest': const ['send','open','getString','abort','se= tRequestHeader','request','getAllResponseHeaders','overrideMimeType','reque= stCrossOrigin','getResponseHeader','postFormData','onLoadEnd','onError','on= Load','DONE','withCredentials','onReadyStateChange','onLoadStart',], +-'dart.dom.html.Event': const ['preventDefault','toString','stopImmediateP= ropagation','stopPropagation','target','currentTarget',], +-'dart.dom.html.FileReader': const ['readAsArrayBuffer','readAsDataUrl','r= eadAsText','onError','onLoadEnd','result',], +-'dart.core.Pattern': const ['allMatches','matchAsPrefix','toString','firs= tMatch','pattern','codeUnitAt',], +-'dart.io.ContentType': const ['parse','toString','charset','mimeType','va= lue','parameters','subType','primaryType',], +-'dart.io.HttpHeaders': const ['set','contentType','ifModifiedSince','valu= e','add','host','forEach','date','removeAll','clear','remove','noFolding','= contentLength','port','expires','chunkedTransferEncoding','persistentConnec= tion','toString','CONTENT_TYPE','data',], +-'dart.typed_data.Uint8List': const ['setRange','sublist','fillRange','set= All','length','buffer','toString','toList','lastIndexOf','indexOf','join','= removeRange','removeLast','clear','addAll','add',], +-'dart.async.StreamSink': const ['close','addStream','add','addError',], +-'dart.typed_data.ByteData': const ['getUint32','setUint32','getUint8','se= tUint64','getInt32','getUint16','getUint64','setUint16','getInt16','setInt6= 4','setInt32','setInt16','setFloat64','getInt64','setInt8','getFloat64','ge= tFloat32','setFloat32','getInt8','setUint8',], +-'dart.io.HttpClientResponse': const ['listen','toList','transform','drain= ','fold','pipe','detachSocket',], +-'dart.core.BidirectionalIterator': const ['moveNext','movePrevious',], +-'dart.mirrors.ClosureMirror': const ['invoke','apply','function',], +-'dart.typed_data.Int32x4': const ['x','signMask','select',], +-'dart.js.JsObject': const ['callMethod','hasProperty','toString','deleteP= roperty','instanceof',], +-'dart.dom.html.Node': const ['remove','ELEMENT_NODE','insertBefore','repl= aceWith','insertAllBefore','querySelector','localName','text','append','set= MenubarOrientation','getElementsByTagName','getElementsByClassName','nodes'= ,'parentNode','getElementById','firstChild','parent','contains','tagName','= value','toString','name','querySelectorAll','clone','attributes','nextNode'= ,'nodeType','click','bind','outerHtml','dispatchEvent','on','childNodes',], +-'dart.core.RuneIterator': const ['moveNext','reset',], +-'dart.mirrors.DeclarationMirror': const ['isPrivate','simpleName','metada= ta','isSubclassOf','qualifiedName','parameters','invoke',], +-'dart.dom.html.History': const ['pushState','back','replaceState','length= ',], +-'dart.dom.html.CssClassSet': const ['add','remove','toggle','clear','cont= ains','addAll','removeAll','toString','firstWhere','first','toggleAll','len= gth','containsAll',], +-'dart.dom.html.Document': const ['querySelector','querySelectorAll','docu= mentElement','createElement','title','body','removeEventListener','addEvent= Listener','getElementsByTagName','createElementNS','query','window','queryA= ll',], +-'dart.mirrors.IsolateMirror': const ['rootLibrary',], +-'dart.mirrors.ObjectMirror': const ['invoke','getField','setField',], +-'dart.dom.html.DivElement': const ['append','classes','style','setInnerHt= ml','remove','querySelector','id','getComputedStyle','appendText','text','q= uerySelectorAll','onDragEnd','onDrag','onDragStart','draggable','innerHtml'= ,'insertAdjacentElement','appendHtml','className','children','focus','query= ','nodes','createShadowRoot','clone','attributes','queryAll','click','onMou= seDown','onClick','hidden','addEventListener','onMouseMove','scrollIntoView= ','onKeyDown','title','getBoundingClientRect','onMouseUp','dispatchEvent','= insertAdjacentText','contentEditable','scrollTop','scrollByLines','bind','i= nsertBefore','xtag','insertAdjacentHtml','matches','setAttribute','on','onK= eyUp','getElementsByClassName',], +-'dart.dom.html.NodeValidatorBuilder': const ['allowNavigation','allowElem= ent','allowHtml5','allowSvg','allowInlineStyles','allowTextElements','allow= Templating','allowCustomElement','allowTagExtension','allowImages',], +-'dart.dom.html.Console': const ['timeEnd','time','timeStamp','warn','log'= ,'error','groupEnd','info','debug','groupCollapsed','group','dir',], +-'dart.dom.html.ElementUpgrader': const ['upgrade',], +-'dart.async.StreamIterator': const ['moveNext','cancel',], +-'dart.io.SystemEncoding': const ['decode',], +-'dart.collection.UnmodifiableListView': const ['where','contains','any','= length','join','firstWhere',], +-'dart.core.Error': const ['safeToString','toString',], +-'dart.convert.Utf8Encoder': const ['bind','convert','startChunkedConversi= on',], +-'dart.dom.html.DomImplementation': const ['createHtmlDocument',], +-'dart.dom.html.DocumentFragment': const ['querySelectorAll','append','clo= ne','nodes','children','setInnerHtml','querySelector','queryAll','query','r= emove','ownerDocument',], +-'dart.dom.html.ShadowRoot': const ['querySelector','querySelectorAll','ho= st','children','append','contains','query','activeElement','supported','nod= es','firstChild','getElementsByTagName','text','innerHtml','olderShadowRoot= ',], +-'dart.mirrors.TypeMirror': const ['qualifiedName','isSubtypeOf','reflecte= dType','newInstance','isAssignableTo','simpleName','typeArguments','origina= lDeclaration','toString','referent','hasReflectedType','isPrivate','typeVar= iables','owner','invoke','isOriginalDeclaration',], +-'dart.io.ServerSocket': const ['bind','close','listen',], +-'dart.dom.html.PerformanceNavigation': const ['type','redirectCount',], +-'dart.dom.html.Performance': const ['now','timing','navigation',], +-'dart.dom.html.PerformanceTiming': const ['navigationStart',], +-'dart.typed_data.ByteBuffer': const ['asUint8List','asUint32List','asInt3= 2List','asByteData','asFloat64x2List','asInt32x4List','asFloat32x4List','as= Float64List','asFloat32List','asUint64List','asInt64List','asUint16List','a= sInt16List','asUint8ClampedList','asInt8List',], +-'dart.io.WebSocket': const ['add','listen','close','connect','where','map= ','send',], +-'dart.convert.JsonEncoder': const ['convert','startChunkedConversion',], +-'dart.convert.JsonDecoder': const ['convert','startChunkedConversion',], +-'dart.core.bool': const ['toString','should','hashCode','isAssignableFrom= ','parse','containsKey',], +-'dart.core.FormatException': const ['toString',], +-'dart.dom.html.WindowBase': const ['postMessage','navigator','close','ale= rt',], +-'dart.dom.html.ButtonElement': const ['text','onClick','classes','attribu= tes','style','append','type','setInnerHtml','children','onMouseOut','onMous= eOver','click','disabled','dataset','appendText',], +-'dart.core.Exception': const ['toString','printStackTrace',], +-'dart.dom.html.DataTransfer': const ['setData','setDragImage','types','ef= fectAllowed','dropEffect','getData','files',], +-'dart.math.Point': const ['x','y','distanceTo','magnitude',], +-'dart.dom.html.LIElement': const ['classes','append','style','text','quer= ySelector','innerHtml','dispatchEvent','children','dataset','className','no= des','remove','value',], +-'dart.dom.html.CanvasRenderingContext2D': const ['lineTo','beginPath','fi= llRect','moveTo','stroke','drawImage','closePath','restore','translate','sa= ve','scale','fill','getImageData','clearRect','setTransform','strokeRect','= rotate','putImageData','fillStyle','arc','transform','fillText','strokeStyl= e','createImageData','createPatternFromImage','clip','lineWidth','drawImage= ToRect','strokeText','font','rect','drawImageScaledFromSource','setFillColo= rRgb','createLinearGradient','bezierCurveTo','drawImageScaled','measureText= ','setLineDash','shadowBlur','shadowOffsetX','shadowOffsetY','shadowColor',= 'quadraticCurveTo','imageSmoothingEnabled','textAlign','createRadialGradien= t','textBaseline','globalAlpha','lineCap',], +-'dart.io.HeaderValue': const ['parse',], +-'dart.dom.html.ScriptElement': const ['src','type','async','remove','text= ',], +-'dart.dom.html.MouseEvent': const ['preventDefault','stopPropagation','ta= rget','dataTransfer','page','client','ctrlKey','stopImmediatePropagation','= metaKey','shiftKey',], +-'dart.io.RawSocket': const ['write','listen','close','connect','read','av= ailable','shutdown','setOption',], +-'dart.io.RawSecureSocket': const ['secure','connect','shutdown','listen',= 'secureServer','write','read',], +-'dart.dom.web_sql.SqlDatabase': const ['transaction','supported',], +-'dart.dom.web_sql.SqlTransaction': const ['executeSql',], +-'dart.dom.web_sql.SqlResultSetRowList': const ['length','elementAt','isNo= tEmpty','item','forEach',], +-'dart.convert.AsciiCodec': const ['encode','decode',], +-'dart.dom.html.EventStreamProvider': const ['forTarget','forElement',], +-'dart.dom.html.MutationObserver': const ['observe','disconnect','takeReco= rds',], +-'dart.dom.html.UListElement': const ['queryAll','append','style','id','ch= ildren','remove','query','insertBefore','classes',], +-'dart.dom.html.VideoElement': const ['canPlayType','load','pause','play',= 'autoplay','remove','src',], +-'dart.dom.html.MediaError': const ['code',], +-'dart.dom.html.TimeRanges': const ['start','end',], +-'dart.dom.html.SourceElement': const ['remove',], +-'dart.dom.html.ObjectElement': const ['remove','getAttribute',], +-'dart.dom.html.OptionElement': const ['value','text','selected','label','= appendText',], +-'dart.dom.html.SpanElement': const ['classes','text','style','append','ap= pendText','onMouseOut','onMouseOver','onClick','attributes','remove','dragg= able','id','outerHtml','innerHtml','setAttribute','querySelector','scrollIn= toView',], +-'dart.dom.html.Geolocation': const ['getCurrentPosition','watchPosition',= ], +-'dart.dom.html.Coordinates': const ['accuracy','longitude','latitude','sp= eed','heading','altitudeAccuracy','altitude',], +-'dart.dom.html.ImageElement': const ['remove','width','height','onLoad','= src','style','crossOrigin','classes','className','id','onDragStart',], +-'dart.mirrors.MethodMirror': const ['parameters','isGetter','isConstructo= r','returnType','owner','simpleName','location','source','isStatic',], +-'dart.dom.html.Storage': const ['containsKey','clear','remove','length','= keys','containsValue',], +-'dart.convert.ChunkedConversionSink': const ['add','close','specialI',], +-'dart.collection.ListQueue': const ['add','removeFirst','addAll','addLast= ','removeLast','forEach','toList','removeWhere','addFirst',], +-'dart.dom.html.CanvasElement': const ['getContext','style','width','heigh= t','context2D','toDataUrl','getContext3d','onMouseUp','onMouseDown','getBou= ndingClientRect','onMouseMove','onClick','onMouseOut','className','onMouseO= ver','setAttribute','remove','context2d','focus',], +-'dart.dom.html.KeyboardEvent': const ['preventDefault','which','stopPropa= gation','ctrlKey','keyCode','stopImmediatePropagation','metaKey','altKey','= shiftKey','getModifierState',], +-'dart.dom.html.WebSocket': const ['send','close','onMessage','onClose','o= nError','onOpen','readyState','url','sendTypedData','binaryType',], +-'dart.io.WebSocketTransformer': const ['upgrade','isUpgradeRequest',], +-'dart.core.Symbol': const ['toString','length',], +-'dart.js.JsFunction': const ['apply',], +-'dart.io.InternetAddress': const ['address','host','lookup','toString','i= sLoopback',], +-'dart.convert.Latin1Codec': const ['decode',], +-'dart.dom.html.ElementEvents': const ['click','load','change','keyPress',= 'drop','dragOver','dragEnter','input','keyDown','dragLeave','dragEnd','drag= Start','mouseOut','mouseMove','keyUp','loadedMetadata',], +-'dart.dom.html.TableCellElement': const ['setInnerHtml','style','append',= 'text','insertAdjacentElement','colSpan','setAttribute','innerHtml','cellIn= dex',], +-'dart.dom.html.TableRowElement': const ['append','attributes','classes','= onClick','children','onMouseOut','onMouseOver','remove','insertCell','cells= ','createFragment','addCell','query','outerHtml',], +-'dart.convert.Converter': const ['convert','startChunkedConversion',], +-'dart.dom.html.FormData': const ['append','appendBlob',], +-'dart.io.ProcessException': const ['toString',], +-'dart.dom.html.Text': const ['remove','text','toString',], +-'dart.dom.html.AnchorElement': const ['href','text','onClick','id','class= es','append','dispatchEvent','replaceWith','download','click','setAttribute= ','appendText',], +-'dart.dom.svg.LineElement': const ['setAttribute',], +-'dart.dom.svg.RectElement': const ['setAttribute','attributes',], +-'dart.dom.svg.EllipseElement': const ['setAttribute',], +-'dart.dom.svg.PolylineElement': const ['attributes',], +-'dart.dom.svg.CircleElement': const ['setAttribute',], +-'dart.dom.svg.PathElement': const ['setAttribute','createSvgPathSegLineto= Abs','createSvgPathSegMovetoAbs',], +-'dart.dom.html.HeadingElement': const ['text','classes','appendText','app= end','id',], +-'dart.dom.html.TableElement': const ['insertRow','createFragment','append= ','children','createTBody','deleteRow','addRow','query','querySelector',], +-'dart.io.HttpConnectionInfo': const ['remoteAddress','remotePort','localP= ort','remoteHost',], +-'dart.dom.html.FormElement': const ['append','submit','children','remove'= ,], +-'dart.io.Cookie': const ['value','toString','path',], +-'dart.dom.html.InputElement': const ['focus','select','value','remove','t= ype','checkValidity','dataset','onKeyDown','setSelectionRange','dispatchEve= nt','selectionStart','selectionEnd','setAttribute','bind','checked','attrib= utes','blur','setRangeText','click','onChange','placeholder','id','onKeyUp'= ,'onBlur','onKeyPress','autocomplete','onPaste','defaultChecked','onFocus',= 'disabled',], +-'dart.io.Socket': const ['close','connect','transform','destroy','add','l= isten','write','addStream','pipe','address','read','writeList','setOption',= 'flush','map','readList','available',], +-'dart.mirrors.ParameterMirror': const ['type','isOptional','defaultValue'= ,], +-'dart.convert.Codec': const ['fuse','encode','decode',], +-'dart.dom.indexed_db.Database': const ['transaction','createObjectStore',= 'close',], +-'dart.dom.indexed_db.Transaction': const ['objectStore','onAbort','onErro= r','onComplete',], +-'dart.dom.indexed_db.ObjectStore': const ['put','delete','createIndex','g= etObject','index','openCursor','clear',], +-'dart.dom.svg.SvgSvgElement': const ['append','setAttribute','createFragm= ent','createSvgPoint','getScreenCtm','onMouseUp','onMouseMove',], +-'dart.dom.svg.Point': const ['matrixTransform',], +-'dart.dom.svg.Matrix': const ['inverse',], +-'dart.dom.html.WheelEvent': const ['preventDefault','stopPropagation',], +-'dart.dom.svg.AnimatedRect': const ['baseVal',], +-'dart.dom.html.SelectElement': const ['append','focus','remove','classes'= ,'tabIndex','options','selectedIndex','querySelectorAll','multiple','value'= ,], +-'dart.dom.html.LabelElement': const ['query','text','append','htmlFor','s= tyle','appendText','classes',], +-'dart.io.HttpSession': const ['id','destroy','clear','containsKey','isNew= ','remove','onTimeout',], +-'dart.dom.indexed_db.IdbFactory': const ['open','deleteDatabase','support= ed','supportsDatabaseNames','getDatabaseNames',], +-'dart.dom.indexed_db.Request': const ['result',], +-'dart.dom.indexed_db.Index': const ['openCursor',], +-'dart.dom.indexed_db.KeyRange': const ['upperBound_','bound_','lowerBound= _','only_',], +-'dart.dom.indexed_db.CursorWithValue': const ['delete',], +-'dart.core.NoSuchMethodError': const ['toString',], +-'dart.isolate.Isolate': const ['spawn','spawnUri','resume','addOnExitList= ener','removeErrorListener','addErrorListener','kill','ping','pause','setEr= rorsFatal',], +-'dart.dom.html.TemplateElement': const ['decorate','content',], +-'dart.dom.html.TreeWalker': const ['nextNode',], +-'dart.dom.html.StyleElement': const ['remove','appendText','text','sheet'= ,'attributes','type','appendHtml','dataset','append','innerHtml',], +-'dart.dom.html.EventTarget': const ['error','result','matchesWithAncestor= s','nodeName','matches','classes','dispatchEvent','removeEventListener','ad= dEventListener','status','parent','value','hashCode',], +-'dart.collection_helpers.equality.Equality': const ['hash','equals','isVa= lidKey',], +-'dart.collection_helpers.equality.SetEquality': const ['hash','equals',], +-'dart.collection_helpers.equality.MapEquality': const ['hash','equals',], +-'dart.collection_helpers.equality.ListEquality': const ['hash','equals',], +-'dart.collection_helpers.equality.IterableEquality': const ['hash','equal= s',], +-'dart.collection_helpers.equality.UnorderedIterableEquality': const ['has= h','equals',], +-'dart.io.SecureSocket': const ['initialize','close','connect','listen','w= rite','add','fold','writeln','secure','transform',], +-'dart.io.HttpDate': const ['parse','format',], +-'dart.math.Rectangle': const ['top','left','containsPoint','height','widt= h','topLeft','intersection','topRight','intersects','containsRectangle','bo= undingBox','snap',], +-'dart.dom.html.ContentElement': const ['getDistributedNodes',], +-'dart.io.SocketException': const ['toString',], +-'dart.dom.html.TextAreaElement': const ['style','focus','select','rows','= attributes','setSelectionRange','value','appendText','remove',], +-'dart.dom.html.LinkElement': const ['href','replaceWith','rel',], +-'dart.dom.html.ParagraphElement': const ['text','appendHtml','classes','a= ddHtml','hidden',], +-'dart.typed_data.Int32List': const ['setRange','indexOf','sublist','remov= eRange','removeLast','clear','addAll','add','setAll',], +-'dart.dom.web_gl.RenderingContext': const ['ARRAY_BUFFER','texParameteri'= ,'bindBuffer','bindFramebuffer','TEXTURE_2D','enable','deleteShader','getUn= iformLocation','bindTexture','clear','createTexture','detachShader','attach= Shader','getAttribLocation','createBuffer','enableVertexAttribArray','verte= xAttribPointer','FLOAT','STATIC_DRAW','createShader','shaderSource','compil= eShader','viewport','useProgram','clearColor','bufferDataTyped','getShaderP= arameter','uniformMatrix4fv','getShaderInfoLog','bindRenderbuffer','deleteT= exture','deleteProgram','RGBA','linkProgram','createProgram','disableVertex= AttribArray','disable','getProgramParameter','blendFunc','drawArrays','getP= rogramInfoLog','TRIANGLES','lineWidth','COMPILE_STATUS','texImage2DTyped','= NEAREST','createFramebuffer','getExtension','framebufferTexture2D','framebu= fferRenderbuffer','renderbufferStorage','createRenderbuffer','ELEMENT_ARRAY= _BUFFER','uniformMatrix3fv','uniform2f','UNSIGNED_BYTE','deleteFramebuffer'= ,'deleteRenderbuffer','TEXTURE_MIN_FILTER','TEXTURE_MAG_FILTER','CLAMP_TO_E= DGE','DEPTH_TEST','DEPTH_BUFFER_BIT','texImage2DImage','COLOR_BUFFER_BIT','= LINK_STATUS','FRAGMENT_SHADER','VERTEX_SHADER','bufferData','TEXTURE_WRAP_S= ','TEXTURE_WRAP_T','texImage2DCanvas','LINEAR','UNSIGNED_SHORT','texImage2D= ','drawElements','pixelStorei','colorMask','depthFunc','TRIANGLE_STRIP','ac= tiveTexture','TEXTURE0','depthMask','FRAMEBUFFER','UNPACK_FLIP_Y_WEBGL','ge= nerateMipmap','uniform1i',], +-'dart.typed_data.Float32List': const ['sublist','indexOf','buffer','setRa= nge','length',], +-'dart.dom.html.DirectoryEntry': const ['getFile','createDirectory','creat= eFile','createReader','getDirectory','removeRecursively','toUrl','fullPath'= ,'toString',], +-'dart.dom.html.Entry': const ['moveTo','isFile','copyTo','isDirectory','f= ullPath','name','remove','getMetadata','createWriter','file','getParent','t= oUrl',], +-'dart.dom.html.DirectoryReader': const ['readEntries',], +-'dart.dom.html.KeyCode': const ['DOWN','RIGHT','LEFT','TAB','UP','ESC','E= NTER','isCharacterKey','SPACE','NUM_SOUTH','NUM_NORTH','NUM_EAST','NUM_WEST= ','NUM_NORTH_EAST','NUM_SOUTH_EAST','R',], +-'dart.pkg.collection.iterable_zip.IterableZip': const ['map','toList',], +-'dart.convert.LineSplitter': const ['convert',], +-'dart.dom.html.HttpRequestUpload': const ['onProgress','onError','onTimeo= ut',], +-'dart.dom.html.File': const ['name','slice','readAsBytesSync','existsSync= ',], +-'dart.dom.html.Events': const ['error','message','load','hashChange','pop= State','resize','loadEnd',], +-'dart.dom.html.Url': const ['createObjectUrl','revokeObjectUrl','createOb= jectUrlFromBlob','createObjectUrlFromStream',], +-'dart.dom.html.RtcIceCandidate': const ['candidate','sdpMLineIndex',], +-'dart.dom.html.RtcPeerConnection': const ['setLocalDescription','createDa= taChannel','createOffer','createAnswer',], +-'dart.io.RawDatagramSocket': const ['bind','close','receive','send','list= en',], +-'dart.pkg.collection.equality.DeepCollectionEquality': const ['equals','h= ash',], +-'dart.pkg.collection.priority_queue.PriorityQueue': const ['addAll','cont= ains','removeFirst','add','removeAll',], +-'dart.convert.StringConversionSink': const ['add','asUtf8Sink','close','a= sStringSink','addSlice',], +-'dart.dom.html.ImageData': const ['data',], +-'dart.dom.html.PreElement': const ['appendText','text','append','classes'= ,], +-'dart.dom.html.MediaStream': const ['stop',], +-'dart.dom.html.DomParser': const ['parseFromString',], +-'dart.dom.html.CustomEvent': const ['stopImmediatePropagation','preventDe= fault','stopPropagation',], +-'dart.typed_data.Uint16List': const ['buffer','sublist','setRange','remov= eRange','removeLast','clear','addAll','add','length',], +-'dart.dom.html.CanvasGradient': const ['addColorStop',], +-'dart.dom.html.Notification': const ['requestPermission',], +-'dart.dom.svg.Length': const ['value','valueAsString',], +-'dart.dom.svg.AnimatedLength': const ['baseVal',], +-'dart.dom.svg.PointList': const ['getItem',], +-'dart.mirrors.SourceLocation': const ['line',], +-'dart.DartGrammarDefinition': const ['build',], +-'dart.dom.html.TextMetrics': const ['width',], +-'dart.dom.html.CssRect': const ['width','height','top','left','topLeft',], +-'dart.dom.html.KeyboardEventStream': const ['onKeyDown',], +-'dart.dom.html.CssRule': const ['selectorText',], +-'dart.dom.html.CssStyleRule': const ['style','selectorText',], +-'dart.dom.html.Selection': const ['removeAllRanges','collapse','getRangeA= t',], +-'dart.dom.html.CheckboxInputElement': const ['checked','attributes','clas= ses','value',], +-'dart.dom.html.TextInputElement': const ['classes','value','focus','selec= t','className','onKeyDown','style',], +-'dart.dom.html.DateInputElement': const ['classes',], +-'dart.dom.html.RangeInputElement': const ['style','attributes','onChange'= ,'value','step','max','min',], +-'dart.dom.html.AnimationTimeline': const ['play',], +-'dart.dom.html.AnimationPlayer': const ['play',], +-'dart.dom.html.GlobalEventHandlers': const ['clickEvent',], +-'dart.dom.html.TouchEvent': const ['preventDefault','supported','stopProp= agation',], +-'dart.dom.html.AudioElement': const ['canPlayType','load','append','play'= ,'pause','remove',], +-'dart.io.ProcessSignal': const ['watch',], +-'dart.convert.Utf8Decoder': const ['convert','startChunkedConversion',], +-'dart.dom.html.AnimationEvent': const ['preventDefault','stopImmediatePro= pagation',], +-'dart.dom.html.FocusEvent': const ['stopImmediatePropagation',], +-'dart.dom.html.Touch': const ['page','client',], +-'dart.async.DeferredLibrary': const ['load',], +-'dart.dom.html.TableSectionElement': const ['append','innerHtml','rows','= createFragment','addRow',], +-'dart.mirrors.Mirror': const ['methods','invoke','type','delegate','membe= rs',], +-'dart.core.StateError': const ['toString',], +-'dart.io.FileMode': const ['APPEND','READ','WRITE',], +-'dart.dom.html.CssStyleDeclarationBase': const ['display','backgroundColo= r','opacity','borderLeftWidth',], +-'dart.dom.html.IFrameElement': const ['style','src',], +-'dart.io.FileSystemException': const ['toString',], +-'dart.dom.html.Screen': const ['width','height','pixelDepth',], +-'dart.core.ArgumentError': const ['toString',], +-'dart.dom.html.Blob': const ['slice',], +-'dart.dom.svg.PatternElement': const ['setAttribute','append',], +-'dart.dom.svg.DefsElement': const ['append',], +-'dart.dom.svg.PathSegList': const ['appendItem','clear','length','getItem= ',], +-'dart.dom.html.FileList': const ['length','item',], +-'dart.dom.html.FileError': const ['NOT_FOUND_ERR','code',], +-'dart.mirrors.VariableMirror': const ['type','isFinal','isStatic',], +-'dart.io.HttpStatus': const ['NOT_FOUND',], +-'dart.typed_data.Float64List': const ['sublist','indexOf','setRange',], +-'dart.typed_data.Float32x4': const ['shuffle','shuffleMix','scale','signM= ask','clamp','withX','withY','w','z','y','x',], +-'dart.pkg.typed_data.typed_buffers.Int32x4Buffer': const ['add',], +-'dart.dom.html.NumberInputElement': const ['step','max','min','valueAsNum= ber',], +-'dart.dom.html.ValidityState': const ['valid',], +-'dart.dom.html.CssStyleSheet': const ['ownerNode','insertRule','addRule',= ], +-'dart.io.ZLibCodec': const ['decode',], +-'dart.collection.HasNextIterator': const ['next',], +-'dart.isolate.RawReceivePort': const ['close',], +-'dart.mirrors.TypeVariableMirror': const ['simpleName','isSubtypeOf','isA= ssignableTo','owner',], +-'dart.typed_data.implementation.NativeByteBuffer': const ['asFloat64List'= ,'asFloat32List','asInt32List',], +-'dart.typed_data.implementation.NativeFloat32x4List': const ['length',], +-'dart.typed_data.implementation.NativeFloat32List': const ['sublist',], +-'dart.typed_data.implementation.NativeInt32x4List': const ['length',], +-'dart.typed_data.implementation.NativeFloat64x2List': const ['length',], +-'dart.typed_data.implementation.NativeFloat64List': const ['sublist',], +-'dart.typed_data.implementation.NativeTypedArray': const ['length',], +-'dart.typed_data.implementation.NativeTypedArrayOfDouble': const ['setRan= ge',], +-'dart.typed_data.implementation.NativeTypedArrayOfInt': const ['setRange'= ,], +-'dart.typed_data.implementation.NativeInt32x4': const ['w','z','y','x',], +-'dart.dom.svg.SvgElement': const ['isTagSupported','clone','setAttribute'= ,'children','setInnerHtml','attributes',], +-'dart.dom.svg.GElement': const ['append','querySelector','id',], +-'dart.dom.html.ProgressEvent': const ['toString',], +-'dart.core.RangeError': const ['toString','checkValidRange','checkNotNega= tive','checkValueInInterval','checkValidIndex',], +-'dart.dom.html.TouchList': const ['length','first','isEmpty','isNotEmpty'= ,], +-'dart.dom.html.FieldSetElement': const ['append','querySelector',], +-'dart.dom.html.ShadowElement': const ['getDistributedNodes',], +-'dart.dom.html.KeyEvent': const ['keyCode','type','preventDefault',], +-'dart.dom.html.NodeList': const ['length','add',], +-'dart.dom.html.DomStringList': const ['length',], +-'dart.dom.html.HtmlCollection': const ['length','forEach','contains',], +-'dart.dom.html.Range': const ['createContextualFragment','selectNodeConte= nts','insertNode','setEndAfter',], +-'dart.dom.html.NodeTreeSanitizer': const ['sanitizeTree',], +-'dart.dom.html.MimeTypeArray': const ['length',], +-'dart.dom.html.PluginArray': const ['length',], +-'dart.dom.html.SourceBufferList': const ['length',], +-'dart.dom.html.SpeechGrammarList': const ['length',], +-'dart.dom.html.TextTrackCueList': const ['length',], +-'dart.dom.html.TextTrackList': const ['length',], +-'dart.dom.html.Dimension': const ['value','toString',], +-'dart.dom.html.UriPolicy': const ['allowsUri',], +-'dart.dom.html.NodeValidator': const ['allowsAttribute','allowsElement',], +-'dart.dom.html.Worker': const ['terminate',], +-'dart.typed_data.Int16List': const ['sublist','buffer','contains','setRan= ge','removeRange','removeLast','clear','addAll','add',], +-'dart.dom.indexed_db.Cursor': const ['next',], +-'dart.dom.svg.LengthList': const ['length','getItem',], +-'dart.dom.svg.NumberList': const ['length','getItem',], +-'dart.dom.svg.StringList': const ['length','getItem',], +-'dart.dom.svg.TransformList': const ['length','getItem',], +-'dart.js.JsArray': const ['length','addAll','insert','removeRange','remov= eAt','add','setRange','removeLast',], +-'dart.dom.html.ApplicationCache': const ['swapCache',], +-'dart.dom.web_audio.AudioContext': const ['createBufferSource','createOsc= illator','destination','createPanner','createGain',], +-'dart.dom.html.FileUploadInputElement': const ['click',], +-'dart.dom.html.DomRectReadOnly': const ['top','left','height','width',], +-'dart.typed_data.Int8List': const ['sublist','setRange','removeRange','re= moveLast','clear','addAll','add','buffer',], +-'dart.dom.web_audio.AudioBufferSourceNode': const ['connectNode','start',= 'stop',], +-'dart.dom.html.FileEntry': const ['file','getParent','toUrl','getMetadata= ',], +-'dart.dom.html.CustomStream': const ['listen',], +-'dart.dom.html.TrackElement': const ['defaultValue',], +-'dart.dom.web_audio.OscillatorNode': const ['connectNode',], +-'dart.dom.html.StorageQuota': const ['queryInfo',], +-'dart.collection.DoubleLinkedQueue': const ['add',], +-'dart.core.TypeError': const ['toString',], +-'dart.core.AssertionError': const ['toString',], +-'dart.profiler.Metrics': const ['register',], +-'dart.collection.LinkedList': const ['remove','addFirst','clear','add',], +-'dart.typed_data.Uint8ClampedList': const ['sublist',], +-'dart.typed_data.Float64x2': const ['y','x','withX',], +-'dart.convert.ByteConversionSink': const ['close','add','addSlice',], +-'dart.convert.ClosableStringSink': const ['close','write',], +-'dart.mirrors.TypedefMirror': const ['isSubtypeOf','isAssignableTo','refe= rent',], +-'dart.mirrors.FunctionTypeMirror': const ['isSubtypeOf','isAssignableTo',= 'returnType','parameters','isOriginalDeclaration',], +-'dart.mirrors.LibraryDependencyMirror': const ['metadata',], +-'dart.test.stream_from_iterable.IterableTest': const ['run',], +-'dart.io.SecureServerSocket': const ['bind','close','listen',], +-'dart.io.RawServerSocket': const ['bind','listen','close',], +-'dart.typed_data.Uint64List': const ['sublist','setRange','removeRange','= removeLast','clear','addAll','add',], +-'dart.typed_data.Int64List': const ['sublist','setRange','removeRange','r= emoveLast','clear','addAll','add',], +-'dart.io.StdioType': const ['name',], +-'dart.io.HttpConnectionsInfo': const ['total','idle','active',], +-'dart.io.RawSecureServerSocket': const ['bind','close','listen',], +-'dart.io.ServerSocketReference': const ['create',], +-'dart.io.NetworkInterface': const ['list',], +-'dart.io.ZLibDecoder': const ['convert',], +-'dart.io.ZLibEncoder': const ['convert',], +-'dart.pkg.async.results.ValueResult': const ['value',], +-'dart.pkg.async.stream_zip.StreamZip': const ['toList',], +-'dart.pkg.async.results.Result': const ['flatten','release',], +-'dart.pkg.async.results.ErrorResult': const ['stackTrace','error',], +-'dart.dom.html.OptGroupElement': const ['append',], +-'dart.dom.html.UnknownElement': const ['query',], +-'dart.dom.web_audio.AudioParam': const ['value','setValueAtTime',], +-'dart.dom.html.RadioButtonInputElement': const ['checked',], +-'dart.dom.web_audio.BiquadFilterNode': const ['connectNode',], +-'dart.async.StreamConsumer': const ['addStream','close',], +-'dart.dom.html.FileSystem': const ['root',], +-'dart.dom.html.FileWriter': const ['write','abort',], +-'dart.dom.html.OutputElement': const ['scrollIntoView',], +-'dart.dom.html.Css': const ['supports',], +-'dart.io.IOException': const ['toString',], +-'dart.dom.html.ButtonInputElement': const ['value','onClick',], +-}; +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/completi= on_manager.dart b/pkg/analysis_server/lib/src/services/completion/dart/comp= letion_manager.dart +deleted file mode 100644 +index 7cba4580f7e..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/completion_mana= ger.dart ++++ /dev/null +@@ -1,278 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart' +- show CompletionContributor, CompletionRequest; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/completion_core.d= art'; +-import 'package:analysis_server/src/services/completion/completion_perfor= mance.dart'; +-import 'package:analysis_server/src/services/completion/dart/arglist_cont= ributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/combinator_c= ontributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/common_usage= _sorter.dart'; +-import 'package:analysis_server/src/services/completion/dart/contribution= _sorter.dart'; +-import 'package:analysis_server/src/services/completion/dart/field_formal= _contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/imported_ref= erence_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/inherited_re= ference_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/keyword_cont= ributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/label_contri= butor.dart'; +-import 'package:analysis_server/src/services/completion/dart/library_memb= er_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/library_pref= ix_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_constr= uctor_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_librar= y_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_refere= nce_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/named_constr= uctor_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/static_membe= r_contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/type_member_= contributor.dart'; +-import 'package:analysis_server/src/services/completion/dart/uri_contribu= tor.dart'; +-import 'package:analysis_server/src/services/completion/dart/variable_nam= e_contributor.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/engine.dart' hide AnalysisResult; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/task/model.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/completion_targe= t.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-/** +- * [DartCompletionManager] determines if a completion request is Dart spe= cific +- * and forwards those requests to all [DartCompletionContributor]s. +- */ +-class DartCompletionManager implements CompletionContributor { +- /** +- * The [contributionSorter] is a long-lived object that isn't allowed +- * to maintain state between calls to [DartContributionSorter#sort(...)= ]. +- */ +- static DartContributionSorter contributionSorter =3D new CommonUsageSor= ter(); +- +- @override +- Future> computeSuggestions( +- CompletionRequest request) async { +- request.checkAborted(); +- if (!AnalysisEngine.isDartFileName(request.source.shortName)) { +- return EMPTY_LIST; +- } +- +- CompletionPerformance performance =3D +- (request as CompletionRequestImpl).performance; +- DartCompletionRequestImpl dartRequest =3D +- await DartCompletionRequestImpl.from(request); +- +- // Don't suggest in comments. +- if (dartRequest.target.isCommentText) { +- return EMPTY_LIST; +- } +- +- SourceRange range =3D +- dartRequest.target.computeReplacementRange(dartRequest.offset); +- (request as CompletionRequestImpl) +- ..replacementOffset =3D range.offset +- ..replacementLength =3D range.length; +- +- // Request Dart specific completions from each contributor +- Map suggestionMap =3D +- {}; +- List contributors =3D [ +- new ArgListContributor(), +- new CombinatorContributor(), +- new FieldFormalContributor(), +- new ImportedReferenceContributor(), +- new InheritedReferenceContributor(), +- new KeywordContributor(), +- new LabelContributor(), +- new LibraryMemberContributor(), +- new LibraryPrefixContributor(), +- new LocalConstructorContributor(), +- new LocalLibraryContributor(), +- new LocalReferenceContributor(), +- new NamedConstructorContributor(), +- // Revisit this contributor and these tests +- // once DartChangeBuilder API has solidified. +- // new OverrideContributor(), +- new StaticMemberContributor(), +- new TypeMemberContributor(), +- new UriContributor(), +- new VariableNameContributor() +- ]; +- for (DartCompletionContributor contributor in contributors) { +- String contributorTag =3D +- 'DartCompletionManager - ${contributor.runtimeType}'; +- performance.logStartTime(contributorTag); +- List contributorSuggestions =3D +- await contributor.computeSuggestions(dartRequest); +- performance.logElapseTime(contributorTag); +- request.checkAborted(); +- +- for (CompletionSuggestion newSuggestion in contributorSuggestions) { +- var oldSuggestion =3D suggestionMap.putIfAbsent( +- newSuggestion.completion, () =3D> newSuggestion); +- if (newSuggestion !=3D oldSuggestion && +- newSuggestion.relevance > oldSuggestion.relevance) { +- suggestionMap[newSuggestion.completion] =3D newSuggestion; +- } +- } +- } +- +- // Adjust suggestion relevance before returning +- List suggestions =3D suggestionMap.values.toLis= t(); +- const SORT_TAG =3D 'DartCompletionManager - sort'; +- performance.logStartTime(SORT_TAG); +- await contributionSorter.sort(dartRequest, suggestions); +- performance.logElapseTime(SORT_TAG); +- request.checkAborted(); +- return suggestions; +- } +-} +- +-/** +- * The information about a requested list of completions within a Dart fi= le. +- */ +-class DartCompletionRequestImpl implements DartCompletionRequest { +- @override +- final AnalysisResult result; +- +- @override +- final ResourceProvider resourceProvider; +- +- @override +- final InterfaceType objectType; +- +- @override +- final Source source; +- +- @override +- final int offset; +- +- @override +- Expression dotTarget; +- +- @override +- Source librarySource; +- +- @override +- CompletionTarget target; +- +- OpType _opType; +- +- final CompletionRequest _originalRequest; +- +- final CompletionPerformance performance; +- +- DartCompletionRequestImpl._( +- this.result, +- this.resourceProvider, +- this.objectType, +- this.librarySource, +- this.source, +- this.offset, +- CompilationUnit unit, +- this._originalRequest, +- this.performance) { +- _updateTargets(unit); +- } +- +- @override +- bool get includeIdentifiers { +- return opType.includeIdentifiers; +- } +- +- @override +- LibraryElement get libraryElement { +- //TODO(danrubel) build the library element rather than all the declar= ations +- CompilationUnit unit =3D target.unit; +- if (unit !=3D null) { +- CompilationUnitElement elem =3D unit.element; +- if (elem !=3D null) { +- return elem.library; +- } +- } +- return null; +- } +- +- OpType get opType { +- if (_opType =3D=3D null) { +- _opType =3D new OpType.forCompletion(target, offset); +- } +- return _opType; +- } +- +- @override +- String get sourceContents =3D> result.content; +- +- @override +- SourceFactory get sourceFactory =3D> result.sourceFactory; +- +- /** +- * Throw [AbortCompletion] if the completion request has been aborted. +- */ +- void checkAborted() { +- _originalRequest.checkAborted(); +- } +- +- /** +- * Update the completion [target] and [dotTarget] based on the given [u= nit]. +- */ +- void _updateTargets(CompilationUnit unit) { +- _opType =3D null; +- dotTarget =3D null; +- target =3D new CompletionTarget.forOffset(unit, offset); +- AstNode node =3D target.containingNode; +- if (node is MethodInvocation) { +- if (identical(node.methodName, target.entity)) { +- dotTarget =3D node.realTarget; +- } else if (node.isCascaded && node.operator.offset + 1 =3D=3D targe= t.offset) { +- dotTarget =3D node.realTarget; +- } +- } +- if (node is PropertyAccess) { +- if (identical(node.propertyName, target.entity)) { +- dotTarget =3D node.realTarget; +- } else if (node.isCascaded && node.operator.offset + 1 =3D=3D targe= t.offset) { +- dotTarget =3D node.realTarget; +- } +- } +- if (node is PrefixedIdentifier) { +- if (identical(node.identifier, target.entity)) { +- dotTarget =3D node.prefix; +- } +- } +- } +- +- /** +- * Return a [Future] that completes with a newly created completion req= uest +- * based on the given [request]. This method will throw [AbortCompletio= n] +- * if the completion request has been aborted. +- */ +- static Future from(CompletionRequest request, +- {ResultDescriptor resultDescriptor}) async { +- request.checkAborted(); +- CompletionPerformance performance =3D +- (request as CompletionRequestImpl).performance; +- const BUILD_REQUEST_TAG =3D 'build DartCompletionRequest'; +- performance.logStartTime(BUILD_REQUEST_TAG); +- +- CompilationUnit unit =3D request.result.unit; +- Source libSource =3D unit.element.library.source; +- InterfaceType objectType =3D request.result.typeProvider.objectType; +- +- DartCompletionRequestImpl dartRequest =3D new DartCompletionRequestIm= pl._( +- request.result, +- request.resourceProvider, +- objectType, +- libSource, +- request.source, +- request.offset, +- unit, +- request, +- performance); +- +- performance.logElapseTime(BUILD_REQUEST_TAG); +- return dartRequest; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/contribu= tion_sorter.dart b/pkg/analysis_server/lib/src/services/completion/dart/con= tribution_sorter.dart +deleted file mode 100644 +index 6dfbf6fb881..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/contribution_so= rter.dart ++++ /dev/null +@@ -1,24 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * The abstract class [DartContributionSorter] defines the behavior of ob= jects +- * that are used to adjust the relevance of an existing list of suggestio= ns. +- * This is a long-lived object that should not maintain state between +- * calls to it's [sort] method. +- */ +-abstract class DartContributionSorter { +- /** +- * After [CompletionSuggestion]s have been computed, +- * this method is called to adjust the relevance of those suggestions. +- * Return a [Future] that completes when the suggestions have been upda= ted. +- */ +- Future sort(DartCompletionRequest request, +- Iterable suggestions); +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/field_fo= rmal_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dar= t/field_formal_contributor.dart +deleted file mode 100644 +index 94f43188f5f..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/field_formal_co= ntributor.dart ++++ /dev/null +@@ -1,78 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- hide Element, ElementKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +- +-/** +- * A contributor for calculating invocation / access suggestions +- * `completion.getSuggestions` request results. +- */ +-class FieldFormalContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- AstNode node =3D request.target.containingNode; +- if (node is! FieldFormalParameter) { +- return EMPTY_LIST; +- } +- +- // If this is a constructor declaration +- // then compute fields already referenced +- ConstructorDeclaration constructorDecl =3D +- node.getAncestor((p) =3D> p is ConstructorDeclaration); +- if (constructorDecl =3D=3D null) { +- return EMPTY_LIST; +- } +- +- // Compute the list of fields already referenced in the constructor +- List referencedFields =3D new List(); +- for (FormalParameter param in constructorDecl.parameters.parameters) { +- if (param is DefaultFormalParameter && +- param.parameter is FieldFormalParameter) { +- param =3D (param as DefaultFormalParameter).parameter; +- } +- if (param is FieldFormalParameter) { +- SimpleIdentifier fieldId =3D param.identifier; +- if (fieldId !=3D null && fieldId !=3D request.target.entity) { +- String fieldName =3D fieldId.name; +- if (fieldName !=3D null && fieldName.length > 0) { +- referencedFields.add(fieldName); +- } +- } +- } +- } +- +- // Add suggestions for fields that are not already referenced +- ClassDeclaration classDecl =3D +- constructorDecl.getAncestor((p) =3D> p is ClassDeclaration); +- List suggestions =3D []; +- for (ClassMember member in classDecl.members) { +- if (member is FieldDeclaration && !member.isStatic) { +- for (VariableDeclaration varDecl in member.fields.variables) { +- SimpleIdentifier fieldId =3D varDecl.name; +- if (fieldId !=3D null) { +- String fieldName =3D fieldId.name; +- if (fieldName !=3D null && fieldName.length > 0) { +- if (!referencedFields.contains(fieldName)) { +- CompletionSuggestion suggestion =3D createSuggestion( +- fieldId.bestElement, +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- if (suggestion !=3D null) { +- suggestions.add(suggestion); +- } +- } +- } +- } +- } +- } +- } +- return suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/imported= _reference_contributor.dart b/pkg/analysis_server/lib/src/services/completi= on/dart/imported_reference_contributor.dart +deleted file mode 100644 +index e182fdfb7b2..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/imported_refere= nce_contributor.dart ++++ /dev/null +@@ -1,86 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_librar= y_contributor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/resolver.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-import '../../../protocol_server.dart' show CompletionSuggestion; +- +-List hiddenNamesIn(ImportElement importElem) { +- for (NamespaceCombinator combinator in importElem.combinators) { +- if (combinator is HideElementCombinator) { +- return combinator.hiddenNames; +- } +- } +- return null; +-} +- +-List showNamesIn(ImportElement importElem) { +- for (NamespaceCombinator combinator in importElem.combinators) { +- if (combinator is ShowElementCombinator) { +- return combinator.shownNames; +- } +- } +- return null; +-} +- +-/** +- * A contributor for calculating suggestions for imported top level membe= rs. +- */ +-class ImportedReferenceContributor extends DartCompletionContributor { +- DartCompletionRequest request; +- OpType optype; +- +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- if (!request.includeIdentifiers) { +- return EMPTY_LIST; +- } +- +- List imports =3D request.libraryElement.imports; +- if (imports =3D=3D null) { +- return EMPTY_LIST; +- } +- +- this.request =3D request; +- this.optype =3D (request as DartCompletionRequestImpl).opType; +- List suggestions =3D []; +- +- // Traverse imports including dart:core +- for (ImportElement importElem in imports) { +- LibraryElement libElem =3D importElem?.importedLibrary; +- if (libElem !=3D null) { +- suggestions.addAll(_buildSuggestions(libElem.exportNamespace, +- prefix: importElem.prefix?.name, +- showNames: showNamesIn(importElem), +- hiddenNames: hiddenNamesIn(importElem))); +- } +- } +- +- return suggestions; +- } +- +- List _buildSuggestions(Namespace namespace, +- {String prefix, List showNames, List hiddenNames}) { +- LibraryElementSuggestionBuilder visitor =3D +- new LibraryElementSuggestionBuilder(request, optype, prefix); +- for (Element elem in namespace.definedNames.values) { +- if (showNames !=3D null && !showNames.contains(elem.name)) { +- continue; +- } +- if (hiddenNames !=3D null && hiddenNames.contains(elem.name)) { +- continue; +- } +- elem.accept(visitor); +- } +- return visitor.suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/inherite= d_reference_contributor.dart b/pkg/analysis_server/lib/src/services/complet= ion/dart/inherited_reference_contributor.dart +deleted file mode 100644 +index 315b49c64f3..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/inherited_refer= ence_contributor.dart ++++ /dev/null +@@ -1,134 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/completion_targe= t.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-import '../../../protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +- +-/** +- * Return the class containing the target +- * or `null` if the target is in a static method or field +- * or not in a class. +- */ +-ClassDeclaration _enclosingClass(CompletionTarget target) { +- AstNode node =3D target.containingNode; +- while (node !=3D null) { +- if (node is ClassDeclaration) { +- return node; +- } +- if (node is MethodDeclaration) { +- if (node.isStatic) { +- return null; +- } +- } +- if (node is FieldDeclaration) { +- if (node.isStatic) { +- return null; +- } +- } +- node =3D node.parent; +- } +- return null; +-} +- +-/** +- * A contributor for calculating suggestions for inherited references. +- */ +-class InheritedReferenceContributor extends DartCompletionContributor +- with ElementSuggestionBuilder { +- @override +- LibraryElement containingLibrary; +- +- @override +- CompletionSuggestionKind kind; +- +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- if (!request.includeIdentifiers) { +- return EMPTY_LIST; +- } +- +- ClassDeclaration classDecl =3D _enclosingClass(request.target); +- if (classDecl =3D=3D null || classDecl.element =3D=3D null) { +- return EMPTY_LIST; +- } +- containingLibrary =3D request.libraryElement; +- return _computeSuggestionsForClass2( +- resolutionMap.elementDeclaredByClassDeclaration(classDecl), reque= st); +- } +- +- List computeSuggestionsForClass( +- ClassElement classElement, DartCompletionRequest request, +- {bool skipChildClass: true}) { +- if (!request.includeIdentifiers) { +- return EMPTY_LIST; +- } +- containingLibrary =3D request.libraryElement; +- +- return _computeSuggestionsForClass2(classElement, request, +- skipChildClass: skipChildClass); +- } +- +- _addSuggestionsForType(InterfaceType type, OpType optype, +- {bool isFunctionalArgument: false}) { +- if (!isFunctionalArgument) { +- for (PropertyAccessorElement elem in type.accessors) { +- if (elem.isGetter) { +- if (optype.includeReturnValueSuggestions) { +- addSuggestion(elem); +- } +- } else { +- if (optype.includeVoidReturnSuggestions) { +- addSuggestion(elem); +- } +- } +- } +- } +- for (MethodElement elem in type.methods) { +- if (elem.returnType =3D=3D null) { +- addSuggestion(elem); +- } else if (!elem.returnType.isVoid) { +- if (optype.includeReturnValueSuggestions) { +- addSuggestion(elem); +- } +- } else { +- if (optype.includeVoidReturnSuggestions) { +- addSuggestion(elem); +- } +- } +- } +- } +- +- List _computeSuggestionsForClass2( +- ClassElement classElement, DartCompletionRequest request, +- {bool skipChildClass: true}) { +- bool isFunctionalArgument =3D request.target.isFunctionalArgument(); +- kind =3D isFunctionalArgument +- ? CompletionSuggestionKind.IDENTIFIER +- : CompletionSuggestionKind.INVOCATION; +- OpType optype =3D request.opType; +- +- if (!skipChildClass) { +- _addSuggestionsForType(classElement.type, optype, +- isFunctionalArgument: isFunctionalArgument); +- } +- +- for (InterfaceType type in classElement.allSupertypes) { +- _addSuggestionsForType(type, optype, +- isFunctionalArgument: isFunctionalArgument); +- } +- return suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/keyword_= contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/key= word_contributor.dart +deleted file mode 100644 +index 8803b5a2e97..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/keyword_contrib= utor.dart ++++ /dev/null +@@ -1,706 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/src/dart/ast/token.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-const ASYNC_STAR =3D 'async*'; +-const DEFERRED_AS =3D 'deferred as'; +-const EXPORT_STATEMENT =3D "export '';"; +-const IMPORT_STATEMENT =3D "import '';"; +-const PART_STATEMENT =3D "part '';"; +-const SYNC_STAR =3D 'sync*'; +-const YIELD_STAR =3D 'yield*'; +- +-/** +- * A contributor for calculating `completion.getSuggestions` request resu= lts +- * for the local library in which the completion is requested. +- */ +-class KeywordContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- List suggestions =3D []; +- request.target.containingNode +- .accept(new _KeywordVisitor(request, suggestions)); +- return suggestions; +- } +-} +- +-/** +- * A visitor for generating keyword suggestions. +- */ +-class _KeywordVisitor extends GeneralizingAstVisitor { +- final DartCompletionRequest request; +- final Object entity; +- final List suggestions; +- +- _KeywordVisitor(DartCompletionRequest request, this.suggestions) +- : this.request =3D request, +- this.entity =3D request.target.entity; +- +- @override +- visitArgumentList(ArgumentList node) { +- if (request is DartCompletionRequestImpl) { +- //TODO(danrubel) consider adding opType to the API then remove this= cast +- OpType opType =3D (request as DartCompletionRequestImpl).opType; +- if (opType.includeOnlyNamedArgumentSuggestions) { +- return; +- } +- } +- if (entity =3D=3D node.rightParenthesis) { +- _addExpressionKeywords(node); +- Token previous =3D (entity as Token).previous; +- if (previous.isSynthetic) { +- previous =3D previous.previous; +- } +- if (previous.lexeme =3D=3D ')') { +- _addSuggestion(Keyword.ASYNC); +- _addSuggestion2(ASYNC_STAR); +- _addSuggestion2(SYNC_STAR); +- } +- } +- if (entity is SimpleIdentifier && node.arguments.contains(entity)) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitAsExpression(AsExpression node) { +- if (identical(entity, node.asOperator) && +- node.expression is ParenthesizedExpression) { +- _addSuggestion(Keyword.ASYNC, DART_RELEVANCE_HIGH); +- _addSuggestion2(ASYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- _addSuggestion2(SYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- } +- } +- +- @override +- visitBlock(Block node) { +- Statement prevStmt =3D OpType.getPreviousStatement(node, entity); +- if (prevStmt is TryStatement) { +- if (prevStmt.finallyBlock =3D=3D null) { +- _addSuggestion(Keyword.ON); +- _addSuggestion(Keyword.CATCH); +- _addSuggestion(Keyword.FINALLY); +- if (prevStmt.catchClauses.isEmpty) { +- // If try statement with no catch, on, or finally +- // then only suggest these keywords +- return; +- } +- } +- } +- +- if (entity is ExpressionStatement) { +- Expression expression =3D (entity as ExpressionStatement).expressio= n; +- if (expression is SimpleIdentifier) { +- Token token =3D expression.token; +- Token previous =3D token.previous; +- if (previous.isSynthetic) { +- previous =3D previous.previous; +- } +- Token next =3D token.next; +- if (next.isSynthetic) { +- next =3D next.next; +- } +- if (previous.type =3D=3D TokenType.CLOSE_PAREN && +- next.type =3D=3D TokenType.OPEN_CURLY_BRACKET) { +- _addSuggestion(Keyword.ASYNC); +- _addSuggestion2(ASYNC_STAR); +- _addSuggestion2(SYNC_STAR); +- } +- } +- } +- _addStatementKeywords(node); +- if (_inCatchClause(node)) { +- _addSuggestion(Keyword.RETHROW, DART_RELEVANCE_KEYWORD - 1); +- } +- } +- +- @override +- visitClassDeclaration(ClassDeclaration node) { +- // Don't suggest class name +- if (entity =3D=3D node.name) { +- return; +- } +- if (entity =3D=3D node.rightBracket) { +- _addClassBodyKeywords(); +- } else if (entity is ClassMember) { +- _addClassBodyKeywords(); +- int index =3D node.members.indexOf(entity); +- ClassMember previous =3D index > 0 ? node.members[index - 1] : null; +- if (previous is MethodDeclaration && previous.body is EmptyFunction= Body) { +- _addSuggestion(Keyword.ASYNC); +- _addSuggestion2(ASYNC_STAR); +- _addSuggestion2(SYNC_STAR); +- } +- } else { +- _addClassDeclarationKeywords(node); +- } +- } +- +- @override +- visitCompilationUnit(CompilationUnit node) { +- var previousMember =3D null; +- for (var member in node.childEntities) { +- if (entity =3D=3D member) { +- break; +- } +- previousMember =3D member; +- } +- if (previousMember is ClassDeclaration) { +- if (previousMember.leftBracket =3D=3D null || +- previousMember.leftBracket.isSynthetic) { +- // If the prior member is an unfinished class declaration +- // then the user is probably finishing that +- _addClassDeclarationKeywords(previousMember); +- return; +- } +- } +- if (previousMember is ImportDirective) { +- if (previousMember.semicolon =3D=3D null || +- previousMember.semicolon.isSynthetic) { +- // If the prior member is an unfinished import directive +- // then the user is probably finishing that +- _addImportDirectiveKeywords(previousMember); +- return; +- } +- } +- if (previousMember =3D=3D null || previousMember is Directive) { +- if (previousMember =3D=3D null && +- !node.directives.any((d) =3D> d is LibraryDirective)) { +- _addSuggestions([Keyword.LIBRARY], DART_RELEVANCE_HIGH); +- } +- _addSuggestion2(IMPORT_STATEMENT, +- offset: 8, relevance: DART_RELEVANCE_HIGH); +- _addSuggestion2(EXPORT_STATEMENT, +- offset: 8, relevance: DART_RELEVANCE_HIGH); +- _addSuggestion2(PART_STATEMENT, +- offset: 6, relevance: DART_RELEVANCE_HIGH); +- } +- if (entity =3D=3D null || entity is Declaration) { +- if (previousMember is FunctionDeclaration && +- previousMember.functionExpression is FunctionExpression && +- previousMember.functionExpression.body is EmptyFunctionBody) { +- _addSuggestion(Keyword.ASYNC, DART_RELEVANCE_HIGH); +- _addSuggestion2(ASYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- _addSuggestion2(SYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- } +- _addCompilationUnitKeywords(); +- } +- } +- +- @override +- visitConstructorDeclaration(ConstructorDeclaration node) { +- if (node.initializers.isNotEmpty && node.initializers.last =3D=3D ent= ity) { +- _addSuggestion(Keyword.SUPER); +- } +- } +- +- @override +- visitDefaultFormalParameter(DefaultFormalParameter node) { +- if (entity =3D=3D node.defaultValue) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitExpression(Expression node) { +- _addExpressionKeywords(node); +- } +- +- @override +- visitExpressionFunctionBody(ExpressionFunctionBody node) { +- if (entity =3D=3D node.expression) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitFieldDeclaration(FieldDeclaration node) { +- VariableDeclarationList fields =3D node.fields; +- NodeList variables =3D fields.variables; +- if (variables.length !=3D 1 || +- !variables[0].name.isSynthetic || +- fields.type =3D=3D null) { +- return; +- } +- if (entity !=3D fields) { +- return; +- } +- List keywords =3D [Keyword.CONST, Keyword.FINAL]; +- if (!node.isStatic) { +- keywords.add(Keyword.STATIC); +- } +- _addSuggestions(keywords); +- } +- +- @override +- visitForEachStatement(ForEachStatement node) { +- if (entity =3D=3D node.inKeyword) { +- Token previous =3D node.inKeyword.previous; +- if (previous is SyntheticStringToken && previous.lexeme =3D=3D 'in'= ) { +- previous =3D previous.previous; +- } +- if (previous !=3D null && previous.type =3D=3D TokenType.EQ) { +- _addSuggestions([ +- Keyword.CONST, +- Keyword.FALSE, +- Keyword.NEW, +- Keyword.NULL, +- Keyword.TRUE +- ]); +- } else { +- _addSuggestion(Keyword.IN, DART_RELEVANCE_HIGH); +- } +- } +- } +- +- @override +- visitFormalParameterList(FormalParameterList node) { +- AstNode constructorDeclaration =3D +- node.getAncestor((p) =3D> p is ConstructorDeclaration); +- if (constructorDeclaration !=3D null) { +- _addSuggestions([Keyword.THIS]); +- } +- if (entity is Token && (entity as Token).type =3D=3D TokenType.CLOSE_= PAREN) { +- _addSuggestion(Keyword.COVARIANT); +- } else if (entity is FormalParameter) { +- Token beginToken =3D (entity as FormalParameter).beginToken; +- if (beginToken !=3D null && request.target.offset =3D=3D beginToken= .end) { +- _addSuggestion(Keyword.COVARIANT); +- } +- } +- } +- +- @override +- visitForStatement(ForStatement node) { +- // Actual: for (va^) +- // Parsed: for (va^; ;) +- if (node.initialization =3D=3D entity && entity is SimpleIdentifier) { +- if (_isNextTokenSynthetic(entity, TokenType.SEMICOLON)) { +- _addSuggestion(Keyword.VAR, DART_RELEVANCE_HIGH); +- } +- } +- // Actual: for (int x i^) +- // Parsed: for (int x; i^;) +- // Handle the degenerate case while typing - for (int x i^) +- if (node.condition =3D=3D entity && +- entity is SimpleIdentifier && +- node.variables !=3D null) { +- if (_isPreviousTokenSynthetic(entity, TokenType.SEMICOLON)) { +- _addSuggestion(Keyword.IN, DART_RELEVANCE_HIGH); +- } +- } +- } +- +- @override +- visitFunctionExpression(FunctionExpression node) { +- if (entity =3D=3D node.body) { +- FunctionBody body =3D node.body; +- if (!body.isAsynchronous) { +- _addSuggestion(Keyword.ASYNC, DART_RELEVANCE_HIGH); +- if (body is! ExpressionFunctionBody) { +- _addSuggestion2(ASYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- _addSuggestion2(SYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- } +- } +- if (node.body is EmptyFunctionBody && +- node.parent is FunctionDeclaration && +- node.parent.parent is CompilationUnit) { +- _addCompilationUnitKeywords(); +- } +- } +- } +- +- @override +- visitIfStatement(IfStatement node) { +- if (_isPreviousTokenSynthetic(entity, TokenType.CLOSE_PAREN)) { +- // Actual: if (x i^) +- // Parsed: if (x) i^ +- _addSuggestion(Keyword.IS, DART_RELEVANCE_HIGH); +- } else if (entity =3D=3D node.thenStatement || entity =3D=3D node.els= eStatement) { +- _addStatementKeywords(node); +- } else if (entity =3D=3D node.condition) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitImportDirective(ImportDirective node) { +- if (entity =3D=3D node.asKeyword) { +- if (node.deferredKeyword =3D=3D null) { +- _addSuggestion(Keyword.DEFERRED, DART_RELEVANCE_HIGH); +- } +- } +- // Handle degenerate case where import statement does not have a semi= colon +- // and the cursor is in the uri string +- if ((entity =3D=3D node.semicolon && +- node.uri !=3D null && +- node.uri.offset + 1 !=3D request.offset) || +- node.combinators.contains(entity)) { +- _addImportDirectiveKeywords(node); +- } +- } +- +- @override +- visitInstanceCreationExpression(InstanceCreationExpression node) { +- if (entity =3D=3D node.constructorName) { +- // no keywords in 'new ^' expression +- } else { +- super.visitInstanceCreationExpression(node); +- } +- } +- +- @override +- visitIsExpression(IsExpression node) { +- if (entity =3D=3D node.isOperator) { +- _addSuggestion(Keyword.IS, DART_RELEVANCE_HIGH); +- } else { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitLibraryIdentifier(LibraryIdentifier node) { +- // no suggestions +- } +- +- @override +- visitMethodDeclaration(MethodDeclaration node) { +- if (entity =3D=3D node.body) { +- if (node.body is EmptyFunctionBody) { +- _addClassBodyKeywords(); +- _addSuggestion(Keyword.ASYNC); +- _addSuggestion2(ASYNC_STAR); +- _addSuggestion2(SYNC_STAR); +- } else { +- _addSuggestion(Keyword.ASYNC, DART_RELEVANCE_HIGH); +- if (node.body is! ExpressionFunctionBody) { +- _addSuggestion2(ASYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- _addSuggestion2(SYNC_STAR, relevance: DART_RELEVANCE_HIGH); +- } +- } +- } +- } +- +- @override +- visitMethodInvocation(MethodInvocation node) { +- if (entity =3D=3D node.methodName) { +- // no keywords in '.' expression +- } else { +- super.visitMethodInvocation(node); +- } +- } +- +- @override +- visitNamedExpression(NamedExpression node) { +- if (entity is SimpleIdentifier && entity =3D=3D node.expression) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitNode(AstNode node) { +- // ignored +- } +- +- @override +- visitPrefixedIdentifier(PrefixedIdentifier node) { +- if (entity !=3D node.identifier) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitPropertyAccess(PropertyAccess node) { +- // suggestions before '.' but not after +- if (entity !=3D node.propertyName) { +- super.visitPropertyAccess(node); +- } +- } +- +- @override +- visitReturnStatement(ReturnStatement node) { +- if (entity =3D=3D node.expression) { +- _addExpressionKeywords(node); +- } +- } +- +- @override +- visitStringLiteral(StringLiteral node) { +- // ignored +- } +- +- @override +- visitSwitchStatement(SwitchStatement node) { +- if (entity =3D=3D node.expression) { +- _addExpressionKeywords(node); +- } else if (entity =3D=3D node.rightBracket) { +- if (node.members.isEmpty) { +- _addSuggestions([Keyword.CASE, Keyword.DEFAULT], DART_RELEVANCE_H= IGH); +- } else { +- _addSuggestions([Keyword.CASE, Keyword.DEFAULT]); +- _addStatementKeywords(node); +- } +- } +- if (node.members.contains(entity)) { +- if (entity =3D=3D node.members.first) { +- _addSuggestions([Keyword.CASE, Keyword.DEFAULT], DART_RELEVANCE_H= IGH); +- } else { +- _addSuggestions([Keyword.CASE, Keyword.DEFAULT]); +- _addStatementKeywords(node); +- } +- } +- } +- +- @override +- visitTryStatement(TryStatement node) { +- var obj =3D entity; +- if (obj is CatchClause || +- (obj is KeywordToken && obj.value() =3D=3D Keyword.FINALLY)) { +- _addSuggestion(Keyword.ON); +- _addSuggestion(Keyword.CATCH); +- return null; +- } +- return visitStatement(node); +- } +- +- @override +- visitVariableDeclaration(VariableDeclaration node) { +- if (entity =3D=3D node.initializer) { +- _addExpressionKeywords(node); +- } +- } +- +- void _addClassBodyKeywords() { +- _addSuggestions([ +- Keyword.CONST, +- Keyword.DYNAMIC, +- Keyword.FACTORY, +- Keyword.FINAL, +- Keyword.GET, +- Keyword.OPERATOR, +- Keyword.SET, +- Keyword.STATIC, +- Keyword.VAR, +- Keyword.VOID +- ]); +- } +- +- void _addClassDeclarationKeywords(ClassDeclaration node) { +- // Very simplistic suggestion because analyzer will warn if +- // the extends / with / implements keywords are out of order +- if (node.extendsClause =3D=3D null) { +- _addSuggestion(Keyword.EXTENDS, DART_RELEVANCE_HIGH); +- } else if (node.withClause =3D=3D null) { +- _addSuggestion(Keyword.WITH, DART_RELEVANCE_HIGH); +- } +- if (node.implementsClause =3D=3D null) { +- _addSuggestion(Keyword.IMPLEMENTS, DART_RELEVANCE_HIGH); +- } +- } +- +- void _addCompilationUnitKeywords() { +- _addSuggestions([ +- Keyword.ABSTRACT, +- Keyword.CLASS, +- Keyword.CONST, +- Keyword.DYNAMIC, +- Keyword.FINAL, +- Keyword.TYPEDEF, +- Keyword.VAR, +- Keyword.VOID +- ], DART_RELEVANCE_HIGH); +- } +- +- void _addExpressionKeywords(AstNode node) { +- _addSuggestions([ +- Keyword.CONST, +- Keyword.FALSE, +- Keyword.NEW, +- Keyword.NULL, +- Keyword.TRUE, +- ]); +- if (_inClassMemberBody(node)) { +- _addSuggestions([Keyword.SUPER, Keyword.THIS]); +- } +- if (_inAsyncMethodOrFunction(node)) { +- _addSuggestion(Keyword.AWAIT); +- } +- } +- +- void _addImportDirectiveKeywords(ImportDirective node) { +- bool hasDeferredKeyword =3D node.deferredKeyword !=3D null; +- bool hasAsKeyword =3D node.asKeyword !=3D null; +- if (!hasAsKeyword) { +- _addSuggestion(Keyword.AS, DART_RELEVANCE_HIGH); +- } +- if (!hasDeferredKeyword) { +- if (!hasAsKeyword) { +- _addSuggestion2(DEFERRED_AS, relevance: DART_RELEVANCE_HIGH); +- } else if (entity =3D=3D node.asKeyword) { +- _addSuggestion(Keyword.DEFERRED, DART_RELEVANCE_HIGH); +- } +- } +- if (!hasDeferredKeyword || hasAsKeyword) { +- if (node.combinators.isEmpty) { +- _addSuggestion(Keyword.SHOW, DART_RELEVANCE_HIGH); +- _addSuggestion(Keyword.HIDE, DART_RELEVANCE_HIGH); +- } +- } +- } +- +- void _addStatementKeywords(AstNode node) { +- if (_inClassMemberBody(node)) { +- _addSuggestions([Keyword.SUPER, Keyword.THIS]); +- } +- if (_inAsyncMethodOrFunction(node)) { +- _addSuggestion(Keyword.AWAIT); +- } else if (_inAsyncStarOrSyncStarMethodOrFunction(node)) { +- _addSuggestion(Keyword.AWAIT); +- _addSuggestion(Keyword.YIELD); +- _addSuggestion2(YIELD_STAR); +- } +- if (_inLoop(node)) { +- _addSuggestions([Keyword.BREAK, Keyword.CONTINUE]); +- } +- if (_inSwitch(node)) { +- _addSuggestions([Keyword.BREAK]); +- } +- if (_isEntityAfterIfWithoutElse(node)) { +- _addSuggestions([Keyword.ELSE]); +- } +- _addSuggestions([ +- Keyword.ASSERT, +- Keyword.CONST, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SWITCH, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]); +- } +- +- void _addSuggestion(Keyword keyword, +- [int relevance =3D DART_RELEVANCE_KEYWORD]) { +- _addSuggestion2(keyword.lexeme, relevance: relevance); +- } +- +- void _addSuggestion2(String completion, +- {int offset, int relevance: DART_RELEVANCE_KEYWORD}) { +- if (offset =3D=3D null) { +- offset =3D completion.length; +- } +- suggestions.add(new CompletionSuggestion(CompletionSuggestionKind.KEY= WORD, +- relevance, completion, offset, 0, false, false)); +- } +- +- void _addSuggestions(List keywords, +- [int relevance =3D DART_RELEVANCE_KEYWORD]) { +- keywords.forEach((Keyword keyword) { +- _addSuggestion(keyword, relevance); +- }); +- } +- +- bool _inAsyncMethodOrFunction(AstNode node) { +- FunctionBody body =3D node.getAncestor((n) =3D> n is FunctionBody); +- return body !=3D null && body.isAsynchronous && body.star =3D=3D null; +- } +- +- bool _inAsyncStarOrSyncStarMethodOrFunction(AstNode node) { +- FunctionBody body =3D node.getAncestor((n) =3D> n is FunctionBody); +- return body !=3D null && body.keyword !=3D null && body.star !=3D nul= l; +- } +- +- bool _inCatchClause(Block node) =3D> +- node.getAncestor((p) =3D> p is CatchClause) !=3D null; +- +- bool _inClassMemberBody(AstNode node) { +- while (true) { +- AstNode body =3D node.getAncestor((n) =3D> n is FunctionBody); +- if (body =3D=3D null) { +- return false; +- } +- AstNode parent =3D body.parent; +- if (parent is ConstructorDeclaration || parent is MethodDeclaration= ) { +- return true; +- } +- node =3D parent; +- } +- } +- +- bool _inDoLoop(AstNode node) =3D> +- node.getAncestor((p) =3D> p is DoStatement) !=3D null; +- +- bool _inForLoop(AstNode node) =3D> +- node.getAncestor((p) =3D> p is ForStatement || p is ForEachStatemen= t) !=3D +- null; +- +- bool _inLoop(AstNode node) =3D> +- _inDoLoop(node) || _inForLoop(node) || _inWhileLoop(node); +- +- bool _inSwitch(AstNode node) =3D> +- node.getAncestor((p) =3D> p is SwitchStatement) !=3D null; +- +- bool _inWhileLoop(AstNode node) =3D> +- node.getAncestor((p) =3D> p is WhileStatement) !=3D null; +- +- bool _isEntityAfterIfWithoutElse(AstNode node) { +- Block block =3D node?.getAncestor((n) =3D> n is Block); +- if (block =3D=3D null) { +- return false; +- } +- Object entity =3D this.entity; +- if (entity is Statement) { +- int entityIndex =3D block.statements.indexOf(entity); +- if (entityIndex > 0) { +- Statement prevStatement =3D block.statements[entityIndex - 1]; +- return prevStatement is IfStatement && +- prevStatement.elseStatement =3D=3D null; +- } +- } +- if (entity is Token) { +- for (Statement statement in block.statements) { +- if (statement.endToken.next =3D=3D entity) { +- return statement is IfStatement && statement.elseStatement =3D= =3D null; +- } +- } +- } +- return false; +- } +- +- static bool _isNextTokenSynthetic(Object entity, TokenType type) { +- if (entity is AstNode) { +- Token token =3D entity.beginToken; +- Token nextToken =3D token.next; +- return nextToken.isSynthetic && nextToken.type =3D=3D type; +- } +- return false; +- } +- +- static bool _isPreviousTokenSynthetic(Object entity, TokenType type) { +- if (entity is AstNode) { +- Token token =3D entity.beginToken; +- Token previousToken =3D token.previous; +- return previousToken.isSynthetic && previousToken.type =3D=3D type; +- } +- return false; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/label_co= ntributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/label= _contributor.dart +deleted file mode 100644 +index 1e8c52095bc..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/label_contribut= or.dart ++++ /dev/null +@@ -1,156 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart' +- show DartCompletionRequestImpl; +-import 'package:analysis_server/src/services/completion/dart/utilities.da= rt'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' as protocol +- show ElementKind; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +-import 'package:analyzer_plugin/src/utilities/visitors/local_declaration_= visitor.dart' +- show LocalDeclarationVisitor; +- +-/** +- * A contributor for calculating label suggestions. +- */ +-class LabelContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- OpType optype =3D (request as DartCompletionRequestImpl).opType; +- +- // Collect suggestions from the specific child [AstNode] that contains +- // the completion offset and all of its parents recursively. +- List suggestions =3D []; +- if (!optype.isPrefixed) { +- if (optype.includeStatementLabelSuggestions || +- optype.includeCaseLabelSuggestions) { +- new _LabelVisitor(request, optype.includeStatementLabelSuggestion= s, +- optype.includeCaseLabelSuggestions, suggestions) +- .visit(request.target.containingNode); +- } +- } +- return suggestions; +- } +-} +- +-/** +- * A visitor for collecting suggestions for break and continue labels. +- */ +-class _LabelVisitor extends LocalDeclarationVisitor { +- final DartCompletionRequest request; +- final List suggestions; +- +- /** +- * True if statement labels should be included as suggestions. +- */ +- final bool includeStatementLabels; +- +- /** +- * True if case labels should be included as suggestions. +- */ +- final bool includeCaseLabels; +- +- _LabelVisitor(DartCompletionRequest request, this.includeStatementLabel= s, +- this.includeCaseLabels, this.suggestions) +- : request =3D request, +- super(request.offset); +- +- @override +- void declaredClass(ClassDeclaration declaration) { +- // ignored +- } +- +- @override +- void declaredClassTypeAlias(ClassTypeAlias declaration) { +- // ignored +- } +- +- @override +- void declaredField(FieldDeclaration fieldDecl, VariableDeclaration varD= ecl) { +- // ignored +- } +- +- @override +- void declaredFunction(FunctionDeclaration declaration) { +- // ignored +- } +- +- @override +- void declaredFunctionTypeAlias(FunctionTypeAlias declaration) { +- // ignored +- } +- +- @override +- void declaredLabel(Label label, bool isCaseLabel) { +- if (isCaseLabel ? includeCaseLabels : includeStatementLabels) { +- CompletionSuggestion suggestion =3D _addSuggestion(label.label); +- if (suggestion !=3D null) { +- suggestion.element =3D createLocalElement( +- request.source, protocol.ElementKind.LABEL, label.label, +- returnType: NO_RETURN_TYPE); +- } +- } +- } +- +- @override +- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) { +- // ignored +- } +- +- @override +- void declaredMethod(MethodDeclaration declaration) { +- // ignored +- } +- +- @override +- void declaredParam(SimpleIdentifier name, TypeAnnotation type) { +- // ignored +- } +- +- @override +- void declaredTopLevelVar( +- VariableDeclarationList varList, VariableDeclaration varDecl) { +- // ignored +- } +- +- @override +- void visitFunctionExpression(FunctionExpression node) { +- // Labels are only accessible within the local function, so stop visi= ting +- // once we reach a function boundary. +- finished(); +- } +- +- @override +- void visitMethodDeclaration(MethodDeclaration node) { +- // Labels are only accessible within the local function, so stop visi= ting +- // once we reach a function boundary. +- finished(); +- } +- +- CompletionSuggestion _addSuggestion(SimpleIdentifier id) { +- if (id !=3D null) { +- String completion =3D id.name; +- if (completion !=3D null && completion.length > 0 && completion != =3D '_') { +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- CompletionSuggestionKind.IDENTIFIER, +- DART_RELEVANCE_DEFAULT, +- completion, +- completion.length, +- 0, +- false, +- false); +- suggestions.add(suggestion); +- return suggestion; +- } +- } +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/library_= member_contributor.dart b/pkg/analysis_server/lib/src/services/completion/d= art/library_member_contributor.dart +deleted file mode 100644 +index 078959a84b1..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/library_member_= contributor.dart ++++ /dev/null +@@ -1,73 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-import '../../../protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +- +-/** +- * A contributor for calculating prefixed import library member suggestio= ns +- * `completion.getSuggestions` request results. +- */ +-class LibraryMemberContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- // Determine if the target looks like a library prefix +- Expression targetId =3D request.dotTarget; +- if (targetId is SimpleIdentifier && !request.target.isCascade) { +- Element elem =3D targetId.bestElement; +- if (elem is PrefixElement && !elem.isSynthetic) { +- LibraryElement containingLibrary =3D request.libraryElement; +- // Gracefully degrade if the library or directives +- // could not be determined (e.g. detached part file or source cha= nge) +- if (containingLibrary !=3D null) { +- List imports =3D containingLibrary.imports; +- if (imports !=3D null) { +- return _buildSuggestions(request, elem, containingLibrary, im= ports); +- } +- } +- } +- } +- return EMPTY_LIST; +- } +- +- List _buildSuggestions( +- DartCompletionRequest request, +- PrefixElement elem, +- LibraryElement containingLibrary, +- List imports) { +- List suggestions =3D []; +- for (ImportElement importElem in imports) { +- if (importElem.prefix?.name =3D=3D elem.name) { +- LibraryElement library =3D importElem.importedLibrary; +- if (library !=3D null) { +- // Suggest elements from the imported library +- AstNode parent =3D request.target.containingNode.parent; +- bool isConstructor =3D parent.parent is ConstructorName; +- bool typesOnly =3D parent is TypeName; +- bool instCreation =3D typesOnly && isConstructor; +- LibraryElementSuggestionBuilder builder =3D +- new LibraryElementSuggestionBuilder(containingLibrary, +- CompletionSuggestionKind.INVOCATION, typesOnly, instCre= ation); +- library.visitChildren(builder); +- suggestions.addAll(builder.suggestions); +- +- // If the import is 'deferred' then suggest 'loadLibrary' +- if (importElem.isDeferred) { +- FunctionElement loadLibFunct =3D library.loadLibraryFunction; +- suggestions.add(createSuggestion(loadLibFunct)); +- } +- } +- } +- } +- return suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/library_= prefix_contributor.dart b/pkg/analysis_server/lib/src/services/completion/d= art/library_prefix_contributor.dart +deleted file mode 100644 +index 9ba62c4463c..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/library_prefix_= contributor.dart ++++ /dev/null +@@ -1,48 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-import '../../../protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +- +-/** +- * A contributor for calculating prefixed import library member suggestio= ns +- * `completion.getSuggestions` request results. +- */ +-class LibraryPrefixContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- if (!request.includeIdentifiers) { +- return EMPTY_LIST; +- } +- +- List imports =3D request.libraryElement.imports; +- if (imports =3D=3D null) { +- return EMPTY_LIST; +- } +- +- List suggestions =3D []; +- for (ImportElement element in imports) { +- String completion =3D element.prefix?.name; +- if (completion !=3D null && completion.length > 0) { +- LibraryElement libElem =3D element.importedLibrary; +- if (libElem !=3D null) { +- CompletionSuggestion suggestion =3D createSuggestion(libElem, +- completion: completion, +- kind: CompletionSuggestionKind.IDENTIFIER); +- if (suggestion !=3D null) { +- suggestions.add(suggestion); +- } +- } +- } +- } +- return suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/local_co= nstructor_contributor.dart b/pkg/analysis_server/lib/src/services/completio= n/dart/local_constructor_contributor.dart +deleted file mode 100644 +index 17fc0c59bbe..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/local_construct= or_contributor.dart ++++ /dev/null +@@ -1,161 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart' +- show DartCompletionRequestImpl; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analysis_server/src/services/completion/dart/utilities.da= rt'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' as protocol +- show Element, ElementKind; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +-import 'package:analyzer_plugin/src/utilities/visitors/local_declaration_= visitor.dart' +- show LocalDeclarationVisitor; +- +-/** +- * A contributor for calculating constructor suggestions +- * for declarations in the local file. +- */ +-class LocalConstructorContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- OpType optype =3D (request as DartCompletionRequestImpl).opType; +- +- // Collect suggestions from the specific child [AstNode] that contains +- // the completion offset and all of its parents recursively. +- List suggestions =3D []; +- if (!optype.isPrefixed) { +- if (optype.includeConstructorSuggestions) { +- new _Visitor(request, suggestions, optype) +- .visit(request.target.containingNode); +- } +- } +- return suggestions; +- } +-} +- +-/** +- * A visitor for collecting constructor suggestions. +- */ +-class _Visitor extends LocalDeclarationVisitor { +- final DartCompletionRequest request; +- final OpType optype; +- final List suggestions; +- +- _Visitor(DartCompletionRequest request, this.suggestions, this.optype) +- : request =3D request, +- super(request.offset); +- +- @override +- void declaredClass(ClassDeclaration declaration) { +- bool found =3D false; +- for (ClassMember member in declaration.members) { +- if (member is ConstructorDeclaration) { +- found =3D true; +- _addSuggestion(declaration, member); +- } +- } +- if (!found) { +- _addSuggestion(declaration, null); +- } +- } +- +- @override +- void declaredClassTypeAlias(ClassTypeAlias declaration) {} +- +- @override +- void declaredField(FieldDeclaration fieldDecl, VariableDeclaration varD= ecl) {} +- +- @override +- void declaredFunction(FunctionDeclaration declaration) {} +- +- @override +- void declaredFunctionTypeAlias(FunctionTypeAlias declaration) {} +- +- @override +- void declaredLabel(Label label, bool isCaseLabel) {} +- +- @override +- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) {} +- +- @override +- void declaredMethod(MethodDeclaration declaration) {} +- +- @override +- void declaredParam(SimpleIdentifier name, TypeAnnotation type) {} +- +- @override +- void declaredTopLevelVar( +- VariableDeclarationList varList, VariableDeclaration varDecl) {} +- +- /** +- * For the given class and constructor, +- * add a suggestion of the form B(...) or B.name(...). +- * If the given constructor is `null` +- * then add a default constructor suggestion. +- */ +- void _addSuggestion( +- ClassDeclaration classDecl, ConstructorDeclaration constructorDecl)= { +- String completion =3D classDecl.name.name; +- SimpleIdentifier elemId; +- +- ClassElement classElement =3D +- resolutionMap.elementDeclaredByClassDeclaration(classDecl); +- int relevance =3D optype.constructorSuggestionsFilter( +- classElement?.type, DART_RELEVANCE_DEFAULT); +- if (relevance =3D=3D null) { +- return; +- } +- +- // Build a suggestion for explicitly declared constructor +- if (constructorDecl !=3D null) { +- elemId =3D constructorDecl.name; +- ConstructorElement elem =3D constructorDecl.element; +- if (elemId !=3D null) { +- String name =3D elemId.name; +- if (name !=3D null && name.length > 0) { +- completion =3D '$completion.$name'; +- } +- } +- if (elem !=3D null) { +- CompletionSuggestion suggestion =3D createSuggestion(elem, +- completion: completion, relevance: relevance); +- if (suggestion !=3D null) { +- suggestions.add(suggestion); +- } +- } +- } +- +- // Build a suggestion for an implicit constructor +- else { +- protocol.Element element =3D createLocalElement( +- request.source, protocol.ElementKind.CONSTRUCTOR, elemId, +- parameters: '()'); +- element.returnType =3D classDecl.name.name; +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- CompletionSuggestionKind.INVOCATION, +- relevance, +- completion, +- completion.length, +- 0, +- false, +- false, +- declaringType: classDecl.name.name, +- element: element, +- parameterNames: [], +- parameterTypes: [], +- requiredParameterCount: 0, +- hasNamedParameters: false); +- suggestions.add(suggestion); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/local_li= brary_contributor.dart b/pkg/analysis_server/lib/src/services/completion/da= rt/local_library_contributor.dart +deleted file mode 100644 +index e54e3fb3b25..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/local_library_c= ontributor.dart ++++ /dev/null +@@ -1,197 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart' +- show createSuggestion, ElementSuggestionBuilder; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-import '../../../protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +- +-/** +- * A visitor for building suggestions based upon the elements defined by +- * a source file contained in the same library but not the same as +- * the source in which the completions are being requested. +- */ +-class LibraryElementSuggestionBuilder extends GeneralizingElementVisitor +- with ElementSuggestionBuilder { +- final DartCompletionRequest request; +- final OpType optype; +- CompletionSuggestionKind kind; +- final String prefix; +- List showNames; +- List hiddenNames; +- +- /** +- * The set of libraries that have been, or are currently being, visited. +- */ +- final Set visitedLibraries =3D new Set(= ); +- +- LibraryElementSuggestionBuilder(this.request, this.optype, [this.prefix= ]) { +- this.kind =3D request.target.isFunctionalArgument() +- ? CompletionSuggestionKind.IDENTIFIER +- : optype.suggestKind; +- } +- +- @override +- LibraryElement get containingLibrary =3D> request.libraryElement; +- +- @override +- void visitClassElement(ClassElement element) { +- if (optype.includeTypeNameSuggestions) { +- // if includeTypeNameSuggestions, then use the filter +- int relevance =3D optype.typeNameSuggestionsFilter( +- element.type, DART_RELEVANCE_DEFAULT); +- if (relevance !=3D null) { +- addSuggestion(element, prefix: prefix, relevance: relevance); +- } +- } +- if (optype.includeConstructorSuggestions) { +- int relevance =3D optype.constructorSuggestionsFilter( +- element.type, DART_RELEVANCE_DEFAULT); +- if (relevance !=3D null) { +- _addConstructorSuggestions(element, relevance); +- } +- } +- } +- +- @override +- void visitCompilationUnitElement(CompilationUnitElement element) { +- element.visitChildren(this); +- } +- +- @override +- void visitElement(Element element) { +- // ignored +- } +- +- @override +- void visitFunctionElement(FunctionElement element) { +- // Do not suggest operators or local functions +- if (element.isOperator) { +- return; +- } +- if (element.enclosingElement is! CompilationUnitElement) { +- return; +- } +- int relevance =3D element.library =3D=3D containingLibrary +- ? DART_RELEVANCE_LOCAL_FUNCTION +- : DART_RELEVANCE_DEFAULT; +- DartType returnType =3D element.returnType; +- if (returnType !=3D null && returnType.isVoid) { +- if (optype.includeVoidReturnSuggestions) { +- addSuggestion(element, prefix: prefix, relevance: relevance); +- } +- } else { +- if (optype.includeReturnValueSuggestions) { +- addSuggestion(element, prefix: prefix, relevance: relevance); +- } +- } +- } +- +- @override +- void visitFunctionTypeAliasElement(FunctionTypeAliasElement element) { +- if (optype.includeTypeNameSuggestions) { +- int relevance =3D element.library =3D=3D containingLibrary +- ? DART_RELEVANCE_LOCAL_FUNCTION +- : DART_RELEVANCE_DEFAULT; +- addSuggestion(element, prefix: prefix, relevance: relevance); +- } +- } +- +- @override +- void visitLibraryElement(LibraryElement element) { +- if (visitedLibraries.add(element)) { +- element.visitChildren(this); +- } +- } +- +- @override +- void visitPropertyAccessorElement(PropertyAccessorElement element) { +- if (optype.includeReturnValueSuggestions) { +- int relevance; +- if (element.library =3D=3D containingLibrary) { +- if (element.enclosingElement is ClassElement) { +- relevance =3D DART_RELEVANCE_LOCAL_FIELD; +- } else { +- relevance =3D DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE; +- } +- } else { +- relevance =3D DART_RELEVANCE_DEFAULT; +- } +- addSuggestion(element, prefix: prefix, relevance: relevance); +- } +- } +- +- @override +- void visitTopLevelVariableElement(TopLevelVariableElement element) { +- if (optype.includeReturnValueSuggestions) { +- int relevance =3D element.library =3D=3D containingLibrary +- ? DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE +- : DART_RELEVANCE_DEFAULT; +- addSuggestion(element, prefix: prefix, relevance: relevance); +- } +- } +- +- /** +- * Add constructor suggestions for the given class. +- */ +- void _addConstructorSuggestions(ClassElement classElem, int relevance) { +- String className =3D classElem.name; +- for (ConstructorElement constructor in classElem.constructors) { +- if (!constructor.isPrivate) { +- CompletionSuggestion suggestion =3D +- createSuggestion(constructor, relevance: relevance); +- if (suggestion !=3D null) { +- String name =3D suggestion.completion; +- name =3D name.length > 0 ? '$className.$name' : className; +- if (prefix !=3D null && prefix.length > 0) { +- name =3D '$prefix.$name'; +- } +- suggestion.completion =3D name; +- suggestion.selectionOffset =3D suggestion.completion.length; +- suggestions.add(suggestion); +- } +- } +- } +- } +-} +- +-/** +- * A contributor for calculating suggestions for top level members +- * in the library in which the completion is requested +- * but outside the file in which the completion is requested. +- */ +-class LocalLibraryContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- if (!request.includeIdentifiers) { +- return EMPTY_LIST; +- } +- +- List libraryUnits =3D +- request.result.unit.element.library.units; +- if (libraryUnits =3D=3D null) { +- return EMPTY_LIST; +- } +- +- OpType optype =3D (request as DartCompletionRequestImpl).opType; +- LibraryElementSuggestionBuilder visitor =3D +- new LibraryElementSuggestionBuilder(request, optype); +- for (CompilationUnitElement unit in libraryUnits) { +- if (unit !=3D null && unit.source !=3D request.source) { +- unit.accept(visitor); +- } +- } +- return visitor.suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/local_re= ference_contributor.dart b/pkg/analysis_server/lib/src/services/completion/= dart/local_reference_contributor.dart +deleted file mode 100644 +index 3ae01206584..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/local_reference= _contributor.dart ++++ /dev/null +@@ -1,517 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind, Location; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart' +- show DartCompletionRequestImpl; +-import 'package:analysis_server/src/services/completion/dart/utilities.da= rt'; +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analysis_server/src/utilities/documentation.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/generated/utilities_dart.dart' show Paramete= rKind; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' as protocol +- show Element, ElementKind; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +-import 'package:analyzer_plugin/src/utilities/visitors/local_declaration_= visitor.dart' +- show LocalDeclarationVisitor; +- +-/** +- * A contributor for calculating suggestions for declarations in the local +- * file and containing library. +- */ +-class LocalReferenceContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- OpType optype =3D (request as DartCompletionRequestImpl).opType; +- AstNode node =3D request.target.containingNode; +- +- // Suggest local fields for constructor initializers +- bool suggestLocalFields =3D node is ConstructorDeclaration && +- node.initializers.contains(request.target.entity); +- +- // Collect suggestions from the specific child [AstNode] that contains +- // the completion offset and all of its parents recursively. +- if (!optype.isPrefixed) { +- if (optype.includeReturnValueSuggestions || +- optype.includeTypeNameSuggestions || +- optype.includeVoidReturnSuggestions || +- suggestLocalFields) { +- // Do not suggest local vars within the current expression +- while (node is Expression) { +- node =3D node.parent; +- } +- +- // Do not suggest loop variable of a ForEachStatement +- // when completing the expression of the ForEachStatement +- if (node is ForEachStatement) { +- node =3D node.parent; +- } +- +- _LocalVisitor visitor =3D new _LocalVisitor( +- request, request.offset, optype, +- suggestLocalFields: suggestLocalFields); +- visitor.visit(node); +- return visitor.suggestions; +- } +- } +- return EMPTY_LIST; +- } +-} +- +-/** +- * A visitor for collecting suggestions from the most specific child [Ast= Node] +- * that contains the completion offset to the [CompilationUnit]. +- */ +-class _LocalVisitor extends LocalDeclarationVisitor { +- final DartCompletionRequest request; +- final OpType optype; +- final bool suggestLocalFields; +- final Map suggestionMap =3D +- {}; +- int privateMemberRelevance =3D DART_RELEVANCE_DEFAULT; +- bool targetIsFunctionalArgument; +- +- _LocalVisitor(this.request, int offset, this.optype, +- {this.suggestLocalFields}) +- : super(offset) { +- // Suggestions for inherited members provided by InheritedReferenceCo= ntributor +- targetIsFunctionalArgument =3D request.target.isFunctionalArgument(); +- +- // If user typed identifier starting with '_' +- // then do not suppress the relevance of private members +- var data =3D request.result !=3D null +- ? request.result.content +- : request.sourceContents; +- int offset =3D request.offset; +- if (data !=3D null && 0 < offset && offset <=3D data.length) { +- bool isIdentifierChar(int index) { +- int code =3D data.codeUnitAt(index); +- return isLetterOrDigit(code) || code =3D=3D CHAR_UNDERSCORE; +- } +- +- if (isIdentifierChar(offset - 1)) { +- while (offset > 0 && isIdentifierChar(offset - 1)) { +- --offset; +- } +- if (data.codeUnitAt(offset) =3D=3D CHAR_UNDERSCORE) { +- privateMemberRelevance =3D null; +- } +- } +- } +- } +- +- List get suggestions =3D> suggestionMap.values.to= List(); +- +- @override +- void declaredClass(ClassDeclaration declaration) { +- if (optype.includeTypeNameSuggestions) { +- _addLocalSuggestion_includeTypeNameSuggestions( +- declaration.documentationComment, +- declaration.name, +- NO_RETURN_TYPE, +- protocol.ElementKind.CLASS, +- isAbstract: declaration.isAbstract, +- isDeprecated: isDeprecated(declaration)); +- } +- } +- +- @override +- void declaredClassTypeAlias(ClassTypeAlias declaration) { +- if (optype.includeTypeNameSuggestions) { +- _addLocalSuggestion_includeTypeNameSuggestions( +- declaration.documentationComment, +- declaration.name, +- NO_RETURN_TYPE, +- protocol.ElementKind.CLASS_TYPE_ALIAS, +- isAbstract: true, +- isDeprecated: isDeprecated(declaration)); +- } +- } +- +- @override +- void declaredEnum(EnumDeclaration declaration) { +- if (optype.includeTypeNameSuggestions) { +- _addLocalSuggestion_includeTypeNameSuggestions( +- declaration.documentationComment, +- declaration.name, +- NO_RETURN_TYPE, +- protocol.ElementKind.ENUM, +- isDeprecated: isDeprecated(declaration)); +- for (EnumConstantDeclaration enumConstant in declaration.constants)= { +- if (!enumConstant.isSynthetic) { +- _addLocalSuggestion_includeReturnValueSuggestions_enumConstant( +- enumConstant, declaration, +- isDeprecated: isDeprecated(declaration)); +- } +- } +- } +- } +- +- @override +- void declaredField(FieldDeclaration fieldDecl, VariableDeclaration varD= ecl) { +- if ((optype.includeReturnValueSuggestions && +- (!optype.inStaticMethodBody || fieldDecl.isStatic)) || +- suggestLocalFields) { +- bool deprecated =3D isDeprecated(fieldDecl) || isDeprecated(varDecl= ); +- TypeAnnotation typeName =3D fieldDecl.fields.type; +- _addLocalSuggestion_includeReturnValueSuggestions( +- fieldDecl.documentationComment, +- varDecl.name, +- typeName, +- protocol.ElementKind.FIELD, +- isDeprecated: deprecated, +- relevance: DART_RELEVANCE_LOCAL_FIELD, +- classDecl: fieldDecl.parent); +- } +- } +- +- @override +- void declaredFunction(FunctionDeclaration declaration) { +- if (optype.includeReturnValueSuggestions || +- optype.includeVoidReturnSuggestions) { +- TypeAnnotation typeName =3D declaration.returnType; +- protocol.ElementKind elemKind; +- int relevance =3D DART_RELEVANCE_DEFAULT; +- if (declaration.isGetter) { +- elemKind =3D protocol.ElementKind.GETTER; +- relevance =3D DART_RELEVANCE_LOCAL_ACCESSOR; +- } else if (declaration.isSetter) { +- if (!optype.includeVoidReturnSuggestions) { +- return; +- } +- elemKind =3D protocol.ElementKind.SETTER; +- typeName =3D NO_RETURN_TYPE; +- relevance =3D DART_RELEVANCE_LOCAL_ACCESSOR; +- } else { +- if (!optype.includeVoidReturnSuggestions && _isVoid(typeName)) { +- return; +- } +- elemKind =3D protocol.ElementKind.FUNCTION; +- relevance =3D DART_RELEVANCE_LOCAL_FUNCTION; +- } +- _addLocalSuggestion_includeReturnValueSuggestions( +- declaration.documentationComment, +- declaration.name, +- typeName, +- elemKind, +- isDeprecated: isDeprecated(declaration), +- param: declaration.functionExpression.parameters, +- relevance: relevance); +- } +- } +- +- @override +- void declaredFunctionTypeAlias(FunctionTypeAlias declaration) { +- if (optype.includeTypeNameSuggestions) { +- // TODO (danrubel) determine parameters and return type +- _addLocalSuggestion_includeTypeNameSuggestions( +- declaration.documentationComment, +- declaration.name, +- declaration.returnType, +- protocol.ElementKind.FUNCTION_TYPE_ALIAS, +- isAbstract: true, +- isDeprecated: isDeprecated(declaration)); +- } +- } +- +- @override +- void declaredLabel(Label label, bool isCaseLabel) { +- // ignored +- } +- +- @override +- void declaredLocalVar(SimpleIdentifier id, TypeAnnotation typeName) { +- if (optype.includeReturnValueSuggestions) { +- _addLocalSuggestion_includeReturnValueSuggestions( +- null, id, typeName, protocol.ElementKind.LOCAL_VARIABLE, +- relevance: DART_RELEVANCE_LOCAL_VARIABLE); +- } +- } +- +- @override +- void declaredMethod(MethodDeclaration declaration) { +- if ((optype.includeReturnValueSuggestions || +- optype.includeVoidReturnSuggestions) && +- (!optype.inStaticMethodBody || declaration.isStatic)) { +- protocol.ElementKind elemKind; +- FormalParameterList param; +- TypeAnnotation typeName =3D declaration.returnType; +- int relevance =3D DART_RELEVANCE_DEFAULT; +- if (declaration.isGetter) { +- elemKind =3D protocol.ElementKind.GETTER; +- param =3D null; +- relevance =3D DART_RELEVANCE_LOCAL_ACCESSOR; +- } else if (declaration.isSetter) { +- if (!optype.includeVoidReturnSuggestions) { +- return; +- } +- elemKind =3D protocol.ElementKind.SETTER; +- typeName =3D NO_RETURN_TYPE; +- relevance =3D DART_RELEVANCE_LOCAL_ACCESSOR; +- } else { +- if (!optype.includeVoidReturnSuggestions && _isVoid(typeName)) { +- return; +- } +- elemKind =3D protocol.ElementKind.METHOD; +- param =3D declaration.parameters; +- relevance =3D DART_RELEVANCE_LOCAL_METHOD; +- } +- _addLocalSuggestion_includeReturnValueSuggestions( +- declaration.documentationComment, +- declaration.name, +- typeName, +- elemKind, +- isAbstract: declaration.isAbstract, +- isDeprecated: isDeprecated(declaration), +- classDecl: declaration.parent, +- param: param, +- relevance: relevance); +- } +- } +- +- @override +- void declaredParam(SimpleIdentifier id, TypeAnnotation typeName) { +- if (optype.includeReturnValueSuggestions) { +- _addLocalSuggestion_includeReturnValueSuggestions( +- null, id, typeName, protocol.ElementKind.PARAMETER, +- relevance: DART_RELEVANCE_PARAMETER); +- } +- } +- +- @override +- void declaredTopLevelVar( +- VariableDeclarationList varList, VariableDeclaration varDecl) { +- if (optype.includeReturnValueSuggestions) { +- _addLocalSuggestion_includeReturnValueSuggestions( +- varDecl.documentationComment, +- varDecl.name, +- varList.type, +- protocol.ElementKind.TOP_LEVEL_VARIABLE, +- isDeprecated: isDeprecated(varList) || isDeprecated(varDecl), +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- } +- } +- +- void _addLocalSuggestion(Comment documentationComment, SimpleIdentifier= id, +- TypeAnnotation typeName, protocol.ElementKind elemKind, +- {bool isAbstract: false, +- bool isDeprecated: false, +- ClassDeclaration classDecl, +- FormalParameterList param, +- int relevance: DART_RELEVANCE_DEFAULT}) { +- CompletionSuggestionKind kind =3D targetIsFunctionalArgument +- ? CompletionSuggestionKind.IDENTIFIER +- : optype.suggestKind; +- CompletionSuggestion suggestion =3D createLocalSuggestion( +- id, isDeprecated, relevance, typeName, +- classDecl: classDecl, kind: kind); +- if (suggestion !=3D null) { +- _setDocumentation(suggestion, documentationComment); +- if (privateMemberRelevance !=3D null && +- suggestion.completion.startsWith('_')) { +- suggestion.relevance =3D privateMemberRelevance; +- } +- suggestionMap.putIfAbsent(suggestion.completion, () =3D> suggestion= ); +- suggestion.element =3D createLocalElement(request.source, elemKind,= id, +- isAbstract: isAbstract, +- isDeprecated: isDeprecated, +- parameters: param?.toSource(), +- returnType: typeName); +- if ((elemKind =3D=3D protocol.ElementKind.METHOD || +- elemKind =3D=3D protocol.ElementKind.FUNCTION) && +- param !=3D null) { +- _addParameterInfo(suggestion, param); +- } +- } +- } +- +- void _addLocalSuggestion_enumConstant( +- EnumConstantDeclaration constantDeclaration, +- EnumDeclaration enumDeclaration, +- {bool isAbstract: false, +- bool isDeprecated: false, +- int relevance: DART_RELEVANCE_DEFAULT}) { +- String completion =3D +- '${enumDeclaration.name.name}.${constantDeclaration.name.name}'; +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- CompletionSuggestionKind.INVOCATION, +- isDeprecated ? DART_RELEVANCE_LOW : relevance, +- completion, +- completion.length, +- 0, +- isDeprecated, +- false, +- returnType: enumDeclaration.name.name); +- +- suggestionMap.putIfAbsent(suggestion.completion, () =3D> suggestion); +- int flags =3D protocol.Element.makeFlags( +- isAbstract: isAbstract, +- isDeprecated: isDeprecated, +- isPrivate: Identifier.isPrivateName(constantDeclaration.name.name= )); +- suggestion.element =3D new protocol.Element( +- protocol.ElementKind.ENUM_CONSTANT, +- constantDeclaration.name.name, +- flags, +- location: new Location( +- request.source.fullName, +- constantDeclaration.name.offset, +- constantDeclaration.name.length, +- 0, +- 0)); +- } +- +- void _addLocalSuggestion_includeReturnValueSuggestions( +- Comment documentationComment, +- SimpleIdentifier id, +- TypeAnnotation typeName, +- protocol.ElementKind elemKind, +- {bool isAbstract: false, +- bool isDeprecated: false, +- ClassDeclaration classDecl, +- FormalParameterList param, +- int relevance: DART_RELEVANCE_DEFAULT}) { +- relevance =3D optype.returnValueSuggestionsFilter( +- _staticTypeOfIdentifier(id), relevance); +- if (relevance !=3D null) { +- _addLocalSuggestion(documentationComment, id, typeName, elemKind, +- isAbstract: isAbstract, +- isDeprecated: isDeprecated, +- classDecl: classDecl, +- param: param, +- relevance: relevance); +- } +- } +- +- void _addLocalSuggestion_includeReturnValueSuggestions_enumConstant( +- EnumConstantDeclaration constantDeclaration, +- EnumDeclaration enumDeclaration, +- {bool isAbstract: false, +- bool isDeprecated: false, +- int relevance: DART_RELEVANCE_DEFAULT}) { +- ClassElement classElement =3D +- resolutionMap.elementDeclaredByEnumDeclaration(enumDeclaration); +- relevance =3D +- optype.returnValueSuggestionsFilter(classElement?.type, relevance= ); +- if (relevance !=3D null) { +- _addLocalSuggestion_enumConstant(constantDeclaration, enumDeclarati= on, +- isAbstract: isAbstract, +- isDeprecated: isDeprecated, +- relevance: relevance); +- } +- } +- +- void _addLocalSuggestion_includeTypeNameSuggestions( +- Comment documentationComment, +- SimpleIdentifier id, +- TypeAnnotation typeName, +- protocol.ElementKind elemKind, +- {bool isAbstract: false, +- bool isDeprecated: false, +- ClassDeclaration classDecl, +- FormalParameterList param, +- int relevance: DART_RELEVANCE_DEFAULT}) { +- relevance =3D optype.typeNameSuggestionsFilter( +- _staticTypeOfIdentifier(id), relevance); +- if (relevance !=3D null) { +- _addLocalSuggestion(documentationComment, id, typeName, elemKind, +- isAbstract: isAbstract, +- isDeprecated: isDeprecated, +- classDecl: classDecl, +- param: param, +- relevance: relevance); +- } +- } +- +- void _addParameterInfo( +- CompletionSuggestion suggestion, FormalParameterList parameters) { +- var paramList =3D parameters.parameters; +- suggestion.parameterNames =3D paramList +- .map((FormalParameter param) =3D> param.identifier.name) +- .toList(); +- suggestion.parameterTypes =3D paramList.map((FormalParameter param) { +- TypeAnnotation type =3D null; +- if (param is DefaultFormalParameter) { +- NormalFormalParameter child =3D param.parameter; +- if (child is SimpleFormalParameter) { +- type =3D child.type; +- } else if (child is FieldFormalParameter) { +- type =3D child.type; +- } +- } +- if (param is SimpleFormalParameter) { +- type =3D param.type; +- } else if (param is FieldFormalParameter) { +- type =3D param.type; +- } +- if (type =3D=3D null) { +- return 'dynamic'; +- } +- if (type is TypeName) { +- Identifier typeId =3D type.name; +- if (typeId =3D=3D null) { +- return 'dynamic'; +- } +- return typeId.name; +- } +- // TODO(brianwilkerson) Support function types. +- return 'dynamic'; +- }).toList(); +- +- Iterable requiredParameters =3D paramList +- .where((FormalParameter param) =3D> param.kind =3D=3D ParameterKi= nd.REQUIRED) +- .map((p) =3D> p.element); +- suggestion.requiredParameterCount =3D requiredParameters.length; +- +- Iterable namedParameters =3D paramList +- .where((FormalParameter param) =3D> param.kind =3D=3D ParameterKi= nd.NAMED) +- .map((p) =3D> p.element); +- suggestion.hasNamedParameters =3D namedParameters.isNotEmpty; +- +- addDefaultArgDetails(suggestion, null, requiredParameters, namedParam= eters); +- } +- +- bool _isVoid(TypeAnnotation returnType) { +- if (returnType is TypeName) { +- Identifier id =3D returnType.name; +- if (id !=3D null && id.name =3D=3D 'void') { +- return true; +- } +- } +- return false; +- } +- +- DartType _staticTypeOfIdentifier(Identifier id) { +- if (id.staticElement is ClassElement) { +- return (id.staticElement as ClassElement).type; +- } else { +- return id.staticType; +- } +- } +- +- /** +- * If the given [documentationComment] is not `null`, fill the [suggest= ion] +- * documentation fields. +- */ +- static void _setDocumentation( +- CompletionSuggestion suggestion, Comment documentationComment) { +- if (documentationComment !=3D null) { +- String text =3D documentationComment.tokens +- .map((Token t) =3D> t.toString()) +- .join('\n') +- .replaceAll('\r\n', '\n'); +- String doc =3D removeDartDocDelimiters(text); +- suggestion.docComplete =3D doc; +- suggestion.docSummary =3D getDartDocSummary(doc); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/named_co= nstructor_contributor.dart b/pkg/analysis_server/lib/src/services/completio= n/dart/named_constructor_contributor.dart +deleted file mode 100644 +index 5874ac51648..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/named_construct= or_contributor.dart ++++ /dev/null +@@ -1,61 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +- +-/** +- * A contributor for calculating named constructor suggestions +- * such as suggesting `bar` in `new Foo.bar()`. +- */ +-class NamedConstructorContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- AstNode node =3D request.target.containingNode; +- LibraryElement libElem =3D request.libraryElement; +- if (libElem =3D=3D null) { +- return EMPTY_LIST; +- } +- +- // Build the list of suggestions +- if (node is ConstructorName) { +- TypeName typeName =3D node.type; +- if (typeName !=3D null) { +- DartType type =3D typeName.type; +- if (type !=3D null) { +- Element classElem =3D type.element; +- if (classElem is ClassElement) { +- return _buildSuggestions(libElem, classElem); +- } +- } +- } +- } +- return EMPTY_LIST; +- } +- +- List _buildSuggestions( +- LibraryElement libElem, ClassElement classElem) { +- bool isLocalClassDecl =3D classElem.library =3D=3D libElem; +- List suggestions =3D []; +- for (ConstructorElement elem in classElem.constructors) { +- if (isLocalClassDecl || !elem.isPrivate) { +- String name =3D elem.name; +- if (name !=3D null) { +- CompletionSuggestion s =3D createSuggestion(elem, completion: n= ame); +- if (s !=3D null) { +- suggestions.add(s); +- } +- } +- } +- } +- return suggestions; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/override= _contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/ov= erride_contributor.dart +deleted file mode 100644 +index 492567f6f66..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/override_contri= butor.dart ++++ /dev/null +@@ -1,150 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/protocol_server.dart' as protocol +- hide CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/resolver/inheritance_manager.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/completion_targe= t.dart'; +- +-/** +- * A completion contributor used to suggest replacing partial identifiers= inside +- * a class declaration with templates for inherited members. +- */ +-class OverrideContributor implements DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- SimpleIdentifier targetId =3D _getTargetId(request.target); +- if (targetId =3D=3D null) { +- return EMPTY_LIST; +- } +- ClassDeclaration classDecl =3D +- targetId.getAncestor((p) =3D> p is ClassDeclaration); +- if (classDecl =3D=3D null) { +- return EMPTY_LIST; +- } +- +- // Generate a collection of inherited members +- ClassElement classElem =3D classDecl.element; +- InheritanceManager manager =3D new InheritanceManager(classElem.libra= ry); +- Map map =3D +- manager.getMembersInheritedFromInterfaces(classElem); +- List memberNames =3D _computeMemberNames(map, classElem); +- +- // Build suggestions +- List suggestions =3D []; +- for (String memberName in memberNames) { +- ExecutableElement element =3D map[memberName]; +- // Gracefully degrade if the overridden element has not been resolv= ed. +- if (element.returnType !=3D null) { +- CompletionSuggestion suggestion =3D +- _buildSuggestion(request, targetId, element); +- if (suggestion !=3D null) { +- suggestions.add(suggestion); +- } +- } +- } +- return suggestions; +- } +- +- /** +- * Return a template for an override of the given [element] in the given +- * [source]. If selected, the template will replace [targetId]. +- */ +- String _buildRepacementText(Source source, SimpleIdentifier targetId, +- CompilationUnit unit, ExecutableElement element) { +- // AnalysisContext context =3D element.context; +- // Inject partially resolved unit for use by change builder +- // DartChangeBuilder builder =3D new DartChangeBuilder(context, unit); +- // builder.addFileEdit(source, context.getModificationStamp(source), +- // (DartFileEditBuilder builder) { +- // builder.addReplacement(targetId.offset, targetId.length, +- // (DartEditBuilder builder) { +- // builder.writeOverrideOfInheritedMember(element); +- // }); +- // }); +- // return builder.sourceChange.edits[0].edits[0].replacement.trim(); +- return ''; +- } +- +- /** +- * Build a suggestion to replace [targetId] in the given [unit] +- * with an override of the given [element]. +- */ +- CompletionSuggestion _buildSuggestion(DartCompletionRequest request, +- SimpleIdentifier targetId, ExecutableElement element) { +- String completion =3D _buildRepacementText( +- request.source, targetId, request.target.unit, element); +- if (completion =3D=3D null || completion.length =3D=3D 0) { +- return null; +- } +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- CompletionSuggestionKind.IDENTIFIER, +- DART_RELEVANCE_HIGH, +- completion, +- targetId.offset, +- 0, +- element.isDeprecated, +- false); +- suggestion.element =3D protocol.convertElement(element); +- return suggestion; +- } +- +- /** +- * Return a list containing the names of all of the inherited but not +- * implemented members of the class represented by the given [element]. +- * The [map] is used to find all of the members that are inherited. +- */ +- List _computeMemberNames( +- Map map, ClassElement element) { +- List memberNames =3D []; +- for (String memberName in map.keys) { +- if (!_hasMember(element, memberName)) { +- memberNames.add(memberName); +- } +- } +- return memberNames; +- } +- +- /** +- * If the target looks like a partial identifier inside a class declara= tion +- * then return that identifier, otherwise return `null`. +- */ +- SimpleIdentifier _getTargetId(CompletionTarget target) { +- AstNode node =3D target.containingNode; +- if (node is ClassDeclaration) { +- Object entity =3D target.entity; +- if (entity is FieldDeclaration) { +- NodeList variables =3D entity.fields.variabl= es; +- if (variables.length =3D=3D 1) { +- SimpleIdentifier targetId =3D variables[0].name; +- if (targetId.name.isEmpty) { +- return targetId; +- } +- } +- } +- } +- return null; +- } +- +- /** +- * Return `true` if the given [classElement] directly declares a member= with +- * the given [memberName]. +- */ +- bool _hasMember(ClassElement classElement, String memberName) { +- return classElement.getField(memberName) !=3D null || +- classElement.getGetter(memberName) !=3D null || +- classElement.getMethod(memberName) !=3D null || +- classElement.getSetter(memberName) !=3D null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/static_m= ember_contributor.dart b/pkg/analysis_server/lib/src/services/completion/da= rt/static_member_contributor.dart +deleted file mode 100644 +index 8239f37c20d..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/static_member_c= ontributor.dart ++++ /dev/null +@@ -1,131 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +- +-import '../../../protocol_server.dart' show CompletionSuggestion; +- +-/** +- * A contributor for calculating static member invocation / access sugges= tions +- * `completion.getSuggestions` request results. +- */ +-class StaticMemberContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- Expression targetId =3D request.dotTarget; +- if (targetId is Identifier && !request.target.isCascade) { +- Element elem =3D targetId.bestElement; +- if (elem is ClassElement) { +- LibraryElement containingLibrary =3D request.libraryElement; +- // Gracefully degrade if the library could not be determined +- // e.g. detached part file or source change +- if (containingLibrary =3D=3D null) { +- return EMPTY_LIST; +- } +- +- _SuggestionBuilder builder =3D new _SuggestionBuilder(containingL= ibrary); +- elem.accept(builder); +- return builder.suggestions; +- } +- } +- return EMPTY_LIST; +- } +-} +- +-/** +- * This class visits elements in a class and provides suggestions based u= pon +- * the visible static members in that class. +- */ +-class _SuggestionBuilder extends GeneralizingElementVisitor { +- /** +- * The library containing the unit in which the completion is requested. +- */ +- final LibraryElement containingLibrary; +- +- /** +- * A collection of completion suggestions. +- */ +- final List suggestions =3D = []; +- +- _SuggestionBuilder(this.containingLibrary); +- +- @override +- visitClassElement(ClassElement element) { +- element.visitChildren(this); +- } +- +- @override +- visitElement(Element element) { +- // ignored +- } +- +- @override +- visitFieldElement(FieldElement element) { +- if (element.isStatic) { +- _addSuggestion(element); +- } +- } +- +- @override +- visitMethodElement(MethodElement element) { +- if (element.isStatic && !element.isOperator) { +- _addSuggestion(element); +- } +- } +- +- @override +- visitPropertyAccessorElement(PropertyAccessorElement element) { +- if (element.isStatic) { +- _addSuggestion(element); +- } +- } +- +- /** +- * Add a suggestion based upon the given element. +- */ +- void _addSuggestion(Element element) { +- if (element.isPrivate) { +- if (element.library !=3D containingLibrary) { +- // Do not suggest private members for imported libraries +- return; +- } +- } +- if (element.isSynthetic) { +- if ((element is PropertyAccessorElement) || +- element is FieldElement && !_isSpecialEnumField(element)) { +- return; +- } +- } +- String completion =3D element.displayName; +- if (completion =3D=3D null || completion.length <=3D 0) { +- return; +- } +- CompletionSuggestion suggestion =3D +- createSuggestion(element, completion: completion); +- if (suggestion !=3D null) { +- suggestions.add(suggestion); +- } +- } +- +- /** +- * Determine if the given element is one of the synthetic enum access= ors +- * for which we should generate a suggestion. +- */ +- bool _isSpecialEnumField(FieldElement element) { +- Element parent =3D element.enclosingElement; +- if (parent is ClassElement && parent.isEnum) { +- if (element.name =3D=3D 'values') { +- return true; +- } +- } +- return false; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/suggesti= on_builder.dart b/pkg/analysis_server/lib/src/services/completion/dart/sugg= estion_builder.dart +deleted file mode 100644 +index 83347c9fece..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/suggestion_buil= der.dart ++++ /dev/null +@@ -1,302 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart' as protocol; +-import 'package:analysis_server/src/protocol_server.dart' +- hide Element, ElementKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/utilities.da= rt'; +-import 'package:analysis_server/src/utilities/documentation.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/utilities_dart.dart'; +-import 'package:path/path.dart' as path; +- +-const String DYNAMIC =3D 'dynamic'; +- +-/** +- * Return a suggestion based upon the given element +- * or `null` if a suggestion is not appropriate for the given element. +- * If the suggestion is not currently in scope, then specify +- * importForSource as the source to which an import should be added. +- */ +-CompletionSuggestion createSuggestion(Element element, +- {String completion, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- int relevance: DART_RELEVANCE_DEFAULT, +- Source importForSource}) { +- if (element =3D=3D null) { +- return null; +- } +- if (element is ExecutableElement && element.isOperator) { +- // Do not include operators in suggestions +- return null; +- } +- if (completion =3D=3D null) { +- completion =3D element.displayName; +- } +- bool isDeprecated =3D element.isDeprecated; +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- kind, +- isDeprecated ? DART_RELEVANCE_LOW : relevance, +- completion, +- completion.length, +- 0, +- isDeprecated, +- false); +- +- // Attach docs. +- String doc =3D removeDartDocDelimiters(element.documentationComment); +- suggestion.docComplete =3D doc; +- suggestion.docSummary =3D getDartDocSummary(doc); +- +- suggestion.element =3D protocol.convertElement(element); +- Element enclosingElement =3D element.enclosingElement; +- if (enclosingElement is ClassElement) { +- suggestion.declaringType =3D enclosingElement.displayName; +- } +- suggestion.returnType =3D getReturnTypeString(element); +- if (element is ExecutableElement && element is! PropertyAccessorElement= ) { +- suggestion.parameterNames =3D element.parameters +- .map((ParameterElement parameter) =3D> parameter.name) +- .toList(); +- suggestion.parameterTypes =3D +- element.parameters.map((ParameterElement parameter) { +- DartType paramType =3D parameter.type; +- // Gracefully degrade if type not resolved yet +- return paramType !=3D null ? paramType.displayName : 'var'; +- }).toList(); +- +- Iterable requiredParameters =3D element.parameters.= where( +- (ParameterElement param) =3D> +- param.parameterKind =3D=3D ParameterKind.REQUIRED); +- suggestion.requiredParameterCount =3D requiredParameters.length; +- +- Iterable namedParameters =3D element.parameters.whe= re( +- (ParameterElement param) =3D> param.parameterKind =3D=3D Paramete= rKind.NAMED); +- suggestion.hasNamedParameters =3D namedParameters.isNotEmpty; +- +- addDefaultArgDetails( +- suggestion, element, requiredParameters, namedParameters); +- } +- if (importForSource !=3D null) { +- String srcPath =3D path.dirname(importForSource.fullName); +- LibraryElement libElem =3D element.library; +- if (libElem !=3D null) { +- Source libSource =3D libElem.source; +- if (libSource !=3D null) { +- UriKind uriKind =3D libSource.uriKind; +- if (uriKind =3D=3D UriKind.DART_URI) { +- suggestion.importUri =3D libSource.uri.toString(); +- } else if (uriKind =3D=3D UriKind.PACKAGE_URI) { +- suggestion.importUri =3D libSource.uri.toString(); +- } else if (uriKind =3D=3D UriKind.FILE_URI && +- element.source.uriKind =3D=3D UriKind.FILE_URI) { +- try { +- suggestion.importUri =3D +- path.relative(libSource.fullName, from: srcPath); +- } catch (_) { +- // ignored +- } +- } +- } +- } +- if (suggestion.importUri =3D=3D null) { +- // Do not include out of scope suggestions +- // for which we cannot determine an import +- return null; +- } +- } +- return suggestion; +-} +- +-/** +- * Common mixin for sharing behavior +- */ +-abstract class ElementSuggestionBuilder { +- /** +- * A collection of completion suggestions. +- */ +- final List suggestions =3D = []; +- +- /** +- * A set of existing completions used to prevent duplicate suggestions. +- */ +- final Set _completions =3D new Set(); +- +- /** +- * A map of element names to suggestions for synthetic getters and sett= ers. +- */ +- final Map _syntheticMap =3D +- {}; +- +- /** +- * Return the library in which the completion is requested. +- */ +- LibraryElement get containingLibrary; +- +- /** +- * Return the kind of suggestions that should be built. +- */ +- CompletionSuggestionKind get kind; +- +- /** +- * Add a suggestion based upon the given element. +- */ +- void addSuggestion(Element element, +- {String prefix, int relevance: DART_RELEVANCE_DEFAULT}) { +- if (element.isPrivate) { +- if (element.library !=3D containingLibrary) { +- return; +- } +- } +- String completion =3D element.displayName; +- if (prefix !=3D null && prefix.length > 0) { +- if (completion =3D=3D null || completion.length <=3D 0) { +- completion =3D prefix; +- } else { +- completion =3D '$prefix.$completion'; +- } +- } +- if (completion =3D=3D null || completion.length <=3D 0) { +- return; +- } +- CompletionSuggestion suggestion =3D createSuggestion(element, +- completion: completion, kind: kind, relevance: relevance); +- if (suggestion !=3D null) { +- if (element.isSynthetic && element is PropertyAccessorElement) { +- String cacheKey; +- if (element.isGetter) { +- cacheKey =3D element.name; +- } +- if (element.isSetter) { +- cacheKey =3D element.name; +- cacheKey =3D cacheKey.substring(0, cacheKey.length - 1); +- } +- if (cacheKey !=3D null) { +- CompletionSuggestion existingSuggestion =3D _syntheticMap[cache= Key]; +- +- // Pair getter/setter by updating the existing suggestion +- if (existingSuggestion !=3D null) { +- CompletionSuggestion getter =3D +- element.isGetter ? suggestion : existingSuggestion; +- protocol.ElementKind elemKind =3D +- element.enclosingElement is ClassElement +- ? protocol.ElementKind.FIELD +- : protocol.ElementKind.TOP_LEVEL_VARIABLE; +- existingSuggestion.element =3D new protocol.Element( +- elemKind, +- existingSuggestion.element.name, +- existingSuggestion.element.flags, +- location: getter.element.location, +- typeParameters: getter.element.typeParameters, +- parameters: null, +- returnType: getter.returnType); +- return; +- } +- +- // Cache lone getter/setter so that it can be paired +- _syntheticMap[cacheKey] =3D suggestion; +- } +- } +- if (_completions.add(suggestion.completion)) { +- suggestions.add(suggestion); +- } +- } +- } +-} +- +-/** +- * This class visits elements in a library and provides suggestions based= upon +- * the visible members in that library. +- */ +-class LibraryElementSuggestionBuilder extends GeneralizingElementVisitor +- with ElementSuggestionBuilder { +- final LibraryElement containingLibrary; +- final CompletionSuggestionKind kind; +- final bool typesOnly; +- final bool instCreation; +- +- /** +- * The set of libraries that have been, or are currently being, visited. +- */ +- final Set visitedLibraries =3D new Set(= ); +- +- LibraryElementSuggestionBuilder( +- this.containingLibrary, this.kind, this.typesOnly, this.instCreatio= n); +- +- @override +- visitClassElement(ClassElement element) { +- if (instCreation) { +- element.visitChildren(this); +- } else { +- addSuggestion(element); +- } +- } +- +- @override +- visitCompilationUnitElement(CompilationUnitElement element) { +- element.visitChildren(this); +- LibraryElement containingLibrary =3D element.library; +- if (containingLibrary !=3D null) { +- for (var lib in containingLibrary.exportedLibraries) { +- lib.accept(this); +- } +- } +- } +- +- @override +- visitConstructorElement(ConstructorElement element) { +- if (instCreation) { +- ClassElement classElem =3D element.enclosingElement; +- if (classElem !=3D null) { +- String prefix =3D classElem.name; +- if (prefix !=3D null && prefix.length > 0) { +- addSuggestion(element, prefix: prefix); +- } +- } +- } +- } +- +- @override +- visitElement(Element element) { +- // ignored +- } +- +- @override +- visitFunctionElement(FunctionElement element) { +- if (!typesOnly) { +- int relevance =3D element.library =3D=3D containingLibrary +- ? DART_RELEVANCE_LOCAL_FUNCTION +- : DART_RELEVANCE_DEFAULT; +- addSuggestion(element, relevance: relevance); +- } +- } +- +- @override +- visitFunctionTypeAliasElement(FunctionTypeAliasElement element) { +- if (!instCreation) { +- addSuggestion(element); +- } +- } +- +- @override +- visitLibraryElement(LibraryElement element) { +- if (visitedLibraries.add(element)) { +- element.visitChildren(this); +- } +- } +- +- @override +- visitTopLevelVariableElement(TopLevelVariableElement element) { +- if (!typesOnly) { +- int relevance =3D element.library =3D=3D containingLibrary +- ? DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE +- : DART_RELEVANCE_DEFAULT; +- addSuggestion(element, relevance: relevance); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/type_mem= ber_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart= /type_member_contributor.dart +deleted file mode 100644 +index e49bdab5ddb..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/type_member_con= tributor.dart ++++ /dev/null +@@ -1,411 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/suggestion_b= uilder.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/src/utilities/visitors/local_declaration_= visitor.dart'; +- +-import '../../../protocol_server.dart' show CompletionSuggestion; +- +-/** +- * A contributor for calculating instance invocation / access suggestions +- * `completion.getSuggestions` request results. +- */ +-class TypeMemberContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- LibraryElement containingLibrary =3D request.libraryElement; +- // Gracefully degrade if the library element is not resolved +- // e.g. detached part file or source change +- if (containingLibrary =3D=3D null) { +- return EMPTY_LIST; +- } +- +- // Recompute the target since resolution may have changed it +- Expression expression =3D request.dotTarget; +- if (expression =3D=3D null || expression.isSynthetic) { +- return EMPTY_LIST; +- } +- if (expression is Identifier) { +- Element elem =3D expression.bestElement; +- if (elem is ClassElement) { +- // Suggestions provided by StaticMemberContributor +- return EMPTY_LIST; +- } +- if (elem is PrefixElement) { +- // Suggestions provided by LibraryMemberContributor +- return EMPTY_LIST; +- } +- } +- +- // Determine the target expression's type +- DartType type =3D expression.bestType; +- if (type.isDynamic) { +- // If the expression does not provide a good type +- // then attempt to get a better type from the element +- if (expression is Identifier) { +- Element elem =3D expression.bestElement; +- if (elem is FunctionTypedElement) { +- type =3D elem.returnType; +- } else if (elem is ParameterElement) { +- type =3D elem.type; +- } else if (elem is LocalVariableElement) { +- type =3D elem.type; +- } +- if ((type =3D=3D null || type.isDynamic) && +- expression is SimpleIdentifier) { +- // If the element does not provide a good type +- // then attempt to get a better type from a local declaration +- _LocalBestTypeVisitor visitor =3D +- new _LocalBestTypeVisitor(expression.name, request.offset); +- if (visitor.visit(expression) && visitor.typeFound !=3D null) { +- type =3D visitor.typeFound; +- } +- } +- } +- } +- String containingMethodName; +- if (expression is SuperExpression && type is InterfaceType) { +- // Suggest members from superclass if target is "super" +- type =3D (type as InterfaceType).superclass; +- // Determine the name of the containing method because +- // the most likely completion is a super expression with same name +- MethodDeclaration containingMethod =3D +- expression.getAncestor((p) =3D> p is MethodDeclaration); +- if (containingMethod !=3D null) { +- SimpleIdentifier id =3D containingMethod.name; +- if (id !=3D null) { +- containingMethodName =3D id.name; +- } +- } +- } +- if (type.isDynamic) { +- // Suggest members from object if target is "dynamic" +- type =3D request.objectType; +- } +- +- // Build the suggestions +- if (type is InterfaceType) { +- _SuggestionBuilder builder =3D new _SuggestionBuilder(containingLib= rary); +- builder.buildSuggestions(type, containingMethodName); +- return builder.suggestions.toList(); +- } +- return EMPTY_LIST; +- } +-} +- +-/** +- * An [AstVisitor] which looks for a declaration with the given name +- * and if found, tries to determine a type for that declaration. +- */ +-class _LocalBestTypeVisitor extends LocalDeclarationVisitor { +- /** +- * The name for the declaration to be found. +- */ +- final String targetName; +- +- /** +- * The best type for the found declaration, +- * or `null` if no declaration found or failed to determine a type. +- */ +- DartType typeFound; +- +- /** +- * Construct a new instance to search for a declaration +- */ +- _LocalBestTypeVisitor(this.targetName, int offset) : super(offset); +- +- @override +- void declaredClass(ClassDeclaration declaration) { +- if (declaration.name.name =3D=3D targetName) { +- // no type +- finished(); +- } +- } +- +- @override +- void declaredClassTypeAlias(ClassTypeAlias declaration) { +- if (declaration.name.name =3D=3D targetName) { +- // no type +- finished(); +- } +- } +- +- @override +- void declaredField(FieldDeclaration fieldDecl, VariableDeclaration varD= ecl) { +- if (varDecl.name.name =3D=3D targetName) { +- // Type provided by the element in computeFull above +- finished(); +- } +- } +- +- @override +- void declaredFunction(FunctionDeclaration declaration) { +- if (declaration.name.name =3D=3D targetName) { +- TypeAnnotation typeName =3D declaration.returnType; +- if (typeName !=3D null) { +- typeFound =3D typeName.type; +- } +- finished(); +- } +- } +- +- @override +- void declaredFunctionTypeAlias(FunctionTypeAlias declaration) { +- if (declaration.name.name =3D=3D targetName) { +- TypeAnnotation typeName =3D declaration.returnType; +- if (typeName !=3D null) { +- typeFound =3D typeName.type; +- } +- finished(); +- } +- } +- +- @override +- void declaredLabel(Label label, bool isCaseLabel) { +- if (label.label.name =3D=3D targetName) { +- // no type +- finished(); +- } +- } +- +- @override +- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) { +- if (name.name =3D=3D targetName) { +- typeFound =3D name.bestType; +- finished(); +- } +- } +- +- @override +- void declaredMethod(MethodDeclaration declaration) { +- if (declaration.name.name =3D=3D targetName) { +- TypeAnnotation typeName =3D declaration.returnType; +- if (typeName !=3D null) { +- typeFound =3D typeName.type; +- } +- finished(); +- } +- } +- +- @override +- void declaredParam(SimpleIdentifier name, TypeAnnotation type) { +- if (name.name =3D=3D targetName) { +- // Type provided by the element in computeFull above +- finished(); +- } +- } +- +- @override +- void declaredTopLevelVar( +- VariableDeclarationList varList, VariableDeclaration varDecl) { +- if (varDecl.name.name =3D=3D targetName) { +- // Type provided by the element in computeFull above +- finished(); +- } +- } +-} +- +-/** +- * This class provides suggestions based upon the visible instance member= s in +- * an interface type. +- */ +-class _SuggestionBuilder { +- /** +- * Enumerated value indicating that we have not generated any completio= ns for +- * a given identifier yet. +- */ +- static const int _COMPLETION_TYPE_NONE =3D 0; +- +- /** +- * Enumerated value indicating that we have generated a completion for a +- * getter. +- */ +- static const int _COMPLETION_TYPE_GETTER =3D 1; +- +- /** +- * Enumerated value indicating that we have generated a completion for a +- * setter. +- */ +- static const int _COMPLETION_TYPE_SETTER =3D 2; +- +- /** +- * Enumerated value indicating that we have generated a completion for a +- * field, a method, or a getter/setter pair. +- */ +- static const int _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET =3D 3; +- +- /** +- * The library containing the unit in which the completion is requested. +- */ +- final LibraryElement containingLibrary; +- +- /** +- * Map indicating, for each possible completion identifier, whether we = have +- * already generated completions for a getter, setter, or both. The "b= oth" +- * case also handles the case where have generated a completion for a m= ethod +- * or a field. +- * +- * Note: the enumerated values stored in this map are intended to be bi= twise +- * compared. +- */ +- Map _completionTypesGenerated =3D new HashMap= (); +- +- /** +- * Map from completion identifier to completion suggestion +- */ +- Map _suggestionMap =3D +- {}; +- +- _SuggestionBuilder(this.containingLibrary); +- +- Iterable get suggestions =3D> _suggestionMap.valu= es; +- +- /** +- * Return completion suggestions for 'dot' completions on the given [ty= pe]. +- * If the 'dot' completion is a super expression, then [containingMetho= dName] +- * is the name of the method in which the completion is requested. +- */ +- void buildSuggestions(InterfaceType type, String containingMethodName) { +- // Visit all of the types in the class hierarchy, collecting possible +- // completions. If multiple elements are found that complete to the = same +- // identifier, addSuggestion will discard all but the first (with a f= ew +- // exceptions to handle getter/setter pairs). +- List types =3D _getTypeOrdering(type); +- for (InterfaceType targetType in types) { +- for (MethodElement method in targetType.methods) { +- // Exclude static methods when completion on an instance +- if (!method.isStatic) { +- // Boost the relevance of a super expression +- // calling a method of the same name as the containing method +- _addSuggestion(method, +- relevance: method.name =3D=3D containingMethodName +- ? DART_RELEVANCE_HIGH +- : DART_RELEVANCE_DEFAULT); +- } +- } +- for (PropertyAccessorElement propertyAccessor in targetType.accesso= rs) { +- if (!propertyAccessor.isStatic) { +- if (propertyAccessor.isSynthetic) { +- // Avoid visiting a field twice +- if (propertyAccessor.isGetter) { +- _addSuggestion(propertyAccessor.variable); +- } +- } else { +- _addSuggestion(propertyAccessor); +- } +- } +- } +- } +- } +- +- /** +- * Add a suggestion based upon the given element, provided that it is n= ot +- * shadowed by a previously added suggestion. +- */ +- void _addSuggestion(Element element, +- {int relevance: DART_RELEVANCE_DEFAULT}) { +- if (element.isPrivate) { +- if (element.library !=3D containingLibrary) { +- // Do not suggest private members for imported libraries +- return; +- } +- } +- String identifier =3D element.displayName; +- +- if (relevance =3D=3D DART_RELEVANCE_DEFAULT && identifier !=3D null) { +- // Decrease relevance of suggestions starting with $ +- // https://github.com/dart-lang/sdk/issues/27303 +- if (identifier.startsWith(r'$')) { +- relevance =3D DART_RELEVANCE_LOW; +- } +- } +- +- int alreadyGenerated =3D _completionTypesGenerated.putIfAbsent( +- identifier, () =3D> _COMPLETION_TYPE_NONE); +- if (element is MethodElement) { +- // Anything shadows a method. +- if (alreadyGenerated !=3D _COMPLETION_TYPE_NONE) { +- return; +- } +- _completionTypesGenerated[identifier] =3D +- _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET; +- } else if (element is PropertyAccessorElement) { +- if (element.isGetter) { +- // Getters, fields, and methods shadow a getter. +- if ((alreadyGenerated & _COMPLETION_TYPE_GETTER) !=3D 0) { +- return; +- } +- _completionTypesGenerated[identifier] |=3D _COMPLETION_TYPE_GETTE= R; +- } else { +- // Setters, fields, and methods shadow a setter. +- if ((alreadyGenerated & _COMPLETION_TYPE_SETTER) !=3D 0) { +- return; +- } +- _completionTypesGenerated[identifier] |=3D _COMPLETION_TYPE_SETTE= R; +- } +- } else if (element is FieldElement) { +- // Fields and methods shadow a field. A getter/setter pair shadows= a +- // field, but a getter or setter by itself doesn't. +- if (alreadyGenerated =3D=3D _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GET= SET) { +- return; +- } +- _completionTypesGenerated[identifier] =3D +- _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET; +- } else { +- // Unexpected element type; skip it. +- assert(false); +- return; +- } +- CompletionSuggestion suggestion =3D +- createSuggestion(element, relevance: relevance); +- if (suggestion !=3D null) { +- _suggestionMap[suggestion.completion] =3D suggestion; +- } +- } +- +- /** +- * Get a list of [InterfaceType]s that should be searched to find the +- * possible completions for an object having type [type]. +- */ +- List _getTypeOrdering(InterfaceType type) { +- // Candidate completions can come from [type] as well as any types ab= ove it +- // in the class hierarchy (including mixins, superclasses, and interf= aces). +- // If a given completion identifier shows up in multiple types, we sh= ould +- // use the element that is nearest in the superclass chain, so we will +- // visit [type] first, then its mixins, then its superclass, then its +- // superclass's mixins, etc., and only afterwards visit interfaces. +- // +- // We short-circuit loops in the class hierarchy by keeping track of = the +- // classes seen (not the interfaces) so that we won't be fooled by no= nsense +- // like "class C extends C> {}" +- List result =3D []; +- Set classesSeen =3D new HashSet(); +- List typesToVisit =3D [type]; +- while (typesToVisit.isNotEmpty) { +- InterfaceType nextType =3D typesToVisit.removeLast(); +- if (!classesSeen.add(nextType.element)) { +- // Class had already been seen, so ignore this type. +- continue; +- } +- result.add(nextType); +- // typesToVisit is a stack, so push on the interfaces first, then t= he +- // superclass, then the mixins. This will ensure that they are vis= ited +- // in the reverse order. +- typesToVisit.addAll(nextType.interfaces); +- if (nextType.superclass !=3D null) { +- typesToVisit.add(nextType.superclass); +- } +- typesToVisit.addAll(nextType.mixins); +- } +- return result; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/uri_cont= ributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/uri_con= tributor.dart +deleted file mode 100644 +index 59c0f2befbe..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor= .dart ++++ /dev/null +@@ -1,242 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:core'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:path/path.dart' show posix; +-import 'package:path/src/context.dart'; +- +-/** +- * A contributor for calculating uri suggestions +- * for import and part directives. +- */ +-class UriContributor extends DartCompletionContributor { +- _UriSuggestionBuilder builder; +- +- /** +- * A flag indicating whether file: and package: URI suggestions should +- * be included in the list of completion suggestions. +- */ +- // TODO(danrubel): remove this flag and related functionality +- // once the UriContributor limits file: and package: URI suggestions +- // to only those paths within context roots. +- static bool suggestFilePaths =3D true; +- +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- builder =3D new _UriSuggestionBuilder(request); +- request.target.containingNode.accept(builder); +- return builder.suggestions; +- } +-} +- +-class _UriSuggestionBuilder extends SimpleAstVisitor { +- final DartCompletionRequest request; +- final List suggestions =3D = []; +- +- _UriSuggestionBuilder(this.request); +- +- @override +- visitExportDirective(ExportDirective node) { +- visitNamespaceDirective(node); +- } +- +- @override +- visitImportDirective(ImportDirective node) { +- visitNamespaceDirective(node); +- } +- +- visitNamespaceDirective(NamespaceDirective node) { +- StringLiteral uri =3D node.uri; +- if (uri is SimpleStringLiteral) { +- int offset =3D request.offset; +- int start =3D uri.offset; +- int end =3D uri.end; +- if (offset > start) { +- if (offset < end) { +- // Quoted non-empty string +- visitSimpleStringLiteral(uri); +- } else if (offset =3D=3D end) { +- if (end =3D=3D start + 1) { +- // Quoted empty string +- visitSimpleStringLiteral(uri); +- } else { +- String data =3D request.sourceContents; +- if (end =3D=3D data.length) { +- String ch =3D data[end - 1]; +- if (ch !=3D '"' && ch !=3D "'") { +- // Insertion point at end of file +- // and missing closing quote on non-empty string +- visitSimpleStringLiteral(uri); +- } +- } +- } +- } +- } else if (offset =3D=3D start && offset =3D=3D end) { +- String data =3D request.sourceContents; +- if (end =3D=3D data.length) { +- String ch =3D data[end - 1]; +- if (ch =3D=3D '"' || ch =3D=3D "'") { +- // Insertion point at end of file +- // and missing closing quote on empty string +- visitSimpleStringLiteral(uri); +- } +- } +- } +- } +- } +- +- @override +- visitSimpleStringLiteral(SimpleStringLiteral node) { +- AstNode parent =3D node.parent; +- if (parent is NamespaceDirective && parent.uri =3D=3D node) { +- String partialUri =3D _extractPartialUri(node); +- if (partialUri !=3D null) { +- _addDartSuggestions(); +- if (UriContributor.suggestFilePaths) { +- _addPackageSuggestions(partialUri); +- _addFileSuggestions(partialUri); +- } +- } +- } else if (parent is PartDirective && parent.uri =3D=3D node) { +- String partialUri =3D _extractPartialUri(node); +- if (partialUri !=3D null) { +- if (UriContributor.suggestFilePaths) { +- _addFileSuggestions(partialUri); +- } +- } +- } +- } +- +- void _addDartSuggestions() { +- _addSuggestion('dart:'); +- SourceFactory factory =3D request.sourceFactory; +- for (SdkLibrary lib in factory.dartSdk.sdkLibraries) { +- if (!lib.isInternal && !lib.isImplementation) { +- if (!lib.shortName.startsWith('dart:_')) { +- _addSuggestion(lib.shortName, +- relevance: lib.shortName =3D=3D 'dart:core' +- ? DART_RELEVANCE_LOW +- : DART_RELEVANCE_DEFAULT); +- } +- } +- } +- } +- +- void _addFileSuggestions(String partialUri) { +- ResourceProvider resProvider =3D request.resourceProvider; +- Context resContext =3D resProvider.pathContext; +- Source source =3D request.source; +- +- String parentUri; +- if ((partialUri.endsWith('/'))) { +- parentUri =3D partialUri; +- } else { +- parentUri =3D posix.dirname(partialUri); +- if (parentUri !=3D '.' && !parentUri.endsWith('/')) { +- parentUri =3D '$parentUri/'; +- } +- } +- String uriPrefix =3D parentUri =3D=3D '.' ? '' : parentUri; +- +- String dirPath =3D resContext.normalize(parentUri); +- if (resContext.isRelative(dirPath)) { +- String sourceDirPath =3D resContext.dirname(source.fullName); +- if (resContext.isAbsolute(sourceDirPath)) { +- dirPath =3D resContext.normalize(resContext.join(sourceDirPath, d= irPath)); +- } else { +- return; +- } +- // Do not suggest relative paths reaching outside the 'lib' directo= ry. +- bool srcInLib =3D resContext.split(sourceDirPath).contains('lib'); +- bool dstInLib =3D resContext.split(dirPath).contains('lib'); +- if (srcInLib && !dstInLib) { +- return; +- } +- } +- if (dirPath.endsWith('\\.')) { +- dirPath =3D dirPath.substring(0, dirPath.length - 1); +- } +- +- Resource dir =3D resProvider.getResource(dirPath); +- if (dir is Folder) { +- try { +- for (Resource child in dir.getChildren()) { +- String completion; +- if (child is Folder) { +- completion =3D '$uriPrefix${child.shortName}/'; +- } else { +- completion =3D '$uriPrefix${child.shortName}'; +- } +- if (completion !=3D source.shortName) { +- _addSuggestion(completion); +- } +- } +- } on FileSystemException { +- // Guard against I/O exceptions. +- } +- } +- } +- +- void _addPackageFolderSuggestions( +- String partial, String prefix, Folder folder) { +- try { +- for (Resource child in folder.getChildren()) { +- if (child is Folder) { +- String childPrefix =3D '$prefix${child.shortName}/'; +- _addSuggestion(childPrefix); +- if (partial.startsWith(childPrefix)) { +- _addPackageFolderSuggestions(partial, childPrefix, child); +- } +- } else { +- _addSuggestion('$prefix${child.shortName}'); +- } +- } +- } on FileSystemException { +- // Guard against I/O exceptions. +- return; +- } +- } +- +- void _addPackageSuggestions(String partial) { +- SourceFactory factory =3D request.sourceFactory; +- Map> packageMap =3D factory.packageMap; +- if (packageMap !=3D null) { +- _addSuggestion('package:'); +- packageMap.forEach((String pkgName, List folders) { +- String prefix =3D 'package:$pkgName/'; +- _addSuggestion(prefix); +- for (Folder folder in folders) { +- if (folder.exists) { +- _addPackageFolderSuggestions(partial, prefix, folder); +- } +- } +- }); +- } +- } +- +- void _addSuggestion(String completion, +- {int relevance: DART_RELEVANCE_DEFAULT}) { +- suggestions.add(new CompletionSuggestion(CompletionSuggestionKind.IMP= ORT, +- relevance, completion, completion.length, 0, false, false)); +- } +- +- String _extractPartialUri(SimpleStringLiteral node) { +- if (request.offset < node.contentsOffset) { +- return null; +- } +- return node.literal.lexeme.substring( +- node.contentsOffset - node.offset, request.offset - node.offset); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/utilitie= s.dart b/pkg/analysis_server/lib/src/services/completion/dart/utilities.dart +deleted file mode 100644 +index baf199e6cd3..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/utilities.dart ++++ /dev/null +@@ -1,237 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * A collection of utility methods used by completion contributors. +- */ +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind, Location; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_ast_factory.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/dart/ast/token.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' as protocol +- show Element, ElementKind; +- +-/** +- * The name of the type `dynamic`; +- */ +-const DYNAMIC =3D 'dynamic'; +- +-/** +- * A marker used in place of `null` when a function has no return type. +- */ +-final TypeName NO_RETURN_TYPE =3D astFactory.typeName( +- astFactory.simpleIdentifier(new StringToken(TokenType.IDENTIFIER, '',= 0)), +- null); +- +-/** +- * Add default argument list text and ranges based on the given [required= Params] +- * and [namedParams]. +- */ +-void addDefaultArgDetails( +- CompletionSuggestion suggestion, +- Element element, +- Iterable requiredParams, +- Iterable namedParams) { +- StringBuffer sb =3D new StringBuffer(); +- List ranges =3D []; +- +- int offset; +- +- for (ParameterElement param in requiredParams) { +- if (sb.isNotEmpty) { +- sb.write(', '); +- } +- offset =3D sb.length; +- String name =3D param.name; +- sb.write(name); +- ranges.addAll([offset, name.length]); +- } +- +- for (ParameterElement param in namedParams) { +- if (param.isRequired) { +- if (sb.isNotEmpty) { +- sb.write(', '); +- } +- String name =3D param.name; +- sb.write('$name: '); +- offset =3D sb.length; +- String defaultValue =3D _getDefaultValue(param); +- sb.write(defaultValue); +- ranges.addAll([offset, defaultValue.length]); +- } +- } +- +- suggestion.defaultArgumentListString =3D sb.isNotEmpty ? sb.toString() = : null; +- suggestion.defaultArgumentListTextRanges =3D ranges.isNotEmpty ? ranges= : null; +-} +- +-/** +- * Create a new protocol Element for inclusion in a completion suggestion. +- */ +-protocol.Element createLocalElement( +- Source source, protocol.ElementKind kind, SimpleIdentifier id, +- {String parameters, +- TypeAnnotation returnType, +- bool isAbstract: false, +- bool isDeprecated: false}) { +- String name; +- Location location; +- if (id !=3D null) { +- name =3D id.name; +- // TODO(danrubel) use lineInfo to determine startLine and startColumn +- location =3D new Location(source.fullName, id.offset, id.length, 0, 0= ); +- } else { +- name =3D ''; +- location =3D new Location(source.fullName, -1, 0, 1, 0); +- } +- int flags =3D protocol.Element.makeFlags( +- isAbstract: isAbstract, +- isDeprecated: isDeprecated, +- isPrivate: Identifier.isPrivateName(name)); +- return new protocol.Element(kind, name, flags, +- location: location, +- parameters: parameters, +- returnType: nameForType(returnType)); +-} +- +-/** +- * Create a new suggestion for the given [fieldDecl]. Return the new sugg= estion +- * or `null` if it could not be created. +- */ +-CompletionSuggestion createLocalFieldSuggestion( +- Source source, FieldDeclaration fieldDecl, VariableDeclaration varDec= l) { +- bool deprecated =3D isDeprecated(fieldDecl) || isDeprecated(varDecl); +- TypeAnnotation type =3D fieldDecl.fields.type; +- return createLocalSuggestion( +- varDecl.name, deprecated, DART_RELEVANCE_LOCAL_FIELD, type, +- classDecl: fieldDecl.parent, +- element: createLocalElement( +- source, protocol.ElementKind.FIELD, varDecl.name, +- returnType: type, isDeprecated: deprecated)); +-} +- +-/** +- * Create a new suggestion based upon the given information. Return the n= ew +- * suggestion or `null` if it could not be created. +- */ +-CompletionSuggestion createLocalSuggestion(SimpleIdentifier id, +- bool isDeprecated, int defaultRelevance, TypeAnnotation returnType, +- {ClassDeclaration classDecl, +- CompletionSuggestionKind kind =3D CompletionSuggestionKind.INVOCATION, +- protocol.Element element}) { +- if (id =3D=3D null) { +- return null; +- } +- String completion =3D id.name; +- if (completion =3D=3D null || completion.length <=3D 0 || completion = =3D=3D '_') { +- return null; +- } +- CompletionSuggestion suggestion =3D new CompletionSuggestion( +- kind, +- isDeprecated ? DART_RELEVANCE_LOW : defaultRelevance, +- completion, +- completion.length, +- 0, +- isDeprecated, +- false, +- returnType: nameForType(returnType), +- element: element); +- if (classDecl !=3D null) { +- SimpleIdentifier classId =3D classDecl.name; +- if (classId !=3D null) { +- String className =3D classId.name; +- if (className !=3D null && className.length > 0) { +- suggestion.declaringType =3D className; +- } +- } +- } +- return suggestion; +-} +- +-String getDefaultStringParameterValue(ParameterElement param) { +- if (param !=3D null) { +- DartType type =3D param.type; +- if (type is InterfaceType && isDartList(type)) { +- List typeArguments =3D type.typeArguments; +- if (typeArguments.length =3D=3D 1) { +- DartType typeArg =3D typeArguments.first; +- String typeInfo =3D !typeArg.isDynamic ? '<${typeArg.name}>' : ''; +- return '$typeInfo[]'; +- } +- } +- if (type is FunctionType) { +- String params =3D type.parameters +- .map((p) =3D> '${getTypeString(p.type)}${p.name}') +- .join(', '); +- //TODO(pq): consider adding a `TODO:` message in generated stub +- return '($params) {}'; +- } +- //TODO(pq): support map literals +- } +- return null; +-} +- +-String getTypeString(DartType type) =3D> type.isDynamic ? '' : '${type.na= me} '; +- +-bool isDartList(DartType type) { +- ClassElement element =3D type.element; +- if (element !=3D null) { +- return element.name =3D=3D "List" && element.library.isDartCore; +- } +- return false; +-} +- +-/** +- * Return `true` if the @deprecated annotation is present on the given [n= ode]. +- */ +-bool isDeprecated(AnnotatedNode node) { +- if (node !=3D null) { +- NodeList metadata =3D node.metadata; +- if (metadata !=3D null) { +- return metadata.any((Annotation a) { +- return a.name is SimpleIdentifier && a.name.name =3D=3D 'deprecat= ed'; +- }); +- } +- } +- return false; +-} +- +-/** +- * Return the name for the given [type]. +- */ +-String nameForType(TypeAnnotation type) { +- if (type =3D=3D NO_RETURN_TYPE) { +- return null; +- } +- if (type =3D=3D null) { +- return DYNAMIC; +- } +- if (type is TypeName) { +- Identifier id =3D type.name; +- if (id =3D=3D null) { +- return DYNAMIC; +- } +- String name =3D id.name; +- if (name =3D=3D null || name.length <=3D 0) { +- return DYNAMIC; +- } +- TypeArgumentList typeArgs =3D type.typeArguments; +- if (typeArgs !=3D null) { +- //TODO (danrubel) include type arguments +- } +- return name; +- } else if (type is GenericFunctionType) { +- // TODO(brianwilkerson) Implement this. +- } +- return DYNAMIC; +-} +- +-//TODO(pq): fix to use getDefaultStringParameterValue() +-String _getDefaultValue(ParameterElement param) =3D> 'null'; +diff --git a/pkg/analysis_server/lib/src/services/completion/dart/variable= _name_contributor.dart b/pkg/analysis_server/lib/src/services/completion/da= rt/variable_name_contributor.dart +deleted file mode 100644 +index 92a8389e4c3..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/dart/variable_name_c= ontributor.dart ++++ /dev/null +@@ -1,99 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show CompletionSuggestion, CompletionSuggestionKind; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart' +- show DartCompletionRequestImpl; +-import 'package:analysis_server/src/services/correction/name_suggestion.d= art'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer_plugin/src/utilities/completion/optype.dart'; +- +-CompletionSuggestion _createNameSuggestion(String name) { +- if (name =3D=3D null || name.isEmpty) { +- return null; +- } +- return new CompletionSuggestion(CompletionSuggestionKind.IDENTIFIER, +- DART_RELEVANCE_DEFAULT, name, name.length, 0, false, false); +-} +- +-String _getStringName(Identifier id) { +- if (id =3D=3D null) { +- return null; +- } +- if (id is SimpleIdentifier) { +- return id.name; +- } else if (id is PrefixedIdentifier) { +- return id.identifier.name; +- } +- return id.name; +-} +- +-/** +- * A contributor for calculating suggestions for variable names. +- */ +-class VariableNameContributor extends DartCompletionContributor { +- @override +- Future> computeSuggestions( +- DartCompletionRequest request) async { +- OpType optype =3D (request as DartCompletionRequestImpl).opType; +- +- // Collect suggestions from the specific child [AstNode] that contains +- // the completion offset and all of its parents recursively. +- if (optype.includeVarNameSuggestions) { +- // Resolution not needed for this completion +- +- AstNode node =3D request.target.containingNode; +- String strName =3D null; +- if (node is ExpressionStatement) { +- if (node.expression is Identifier) { +- strName =3D _getStringName(node.expression as Identifier); +- } +- } else if (node is VariableDeclarationList) { +- TypeAnnotation typeAnnotation =3D node.type; +- if (typeAnnotation is TypeName) { +- strName =3D _getStringName(typeAnnotation.name); +- } +- } else if (node is TopLevelVariableDeclaration) { +- // The parser parses 'Foo ' and 'Foo ;' differently, resulting in= the +- // following. +- // 'Foo ': handled above +- // 'Foo ;': TopLevelVariableDeclaration with type null, and a fir= st +- // variable of 'Foo' +- VariableDeclarationList varDeclarationList =3D node.variables; +- TypeAnnotation typeAnnotation =3D varDeclarationList.type; +- if (typeAnnotation !=3D null) { +- if (typeAnnotation is TypeName) { +- strName =3D _getStringName(typeAnnotation.name); +- } +- } else { +- NodeList varDeclarations =3D +- varDeclarationList.variables; +- if (varDeclarations.length =3D=3D 1) { +- VariableDeclaration varDeclaration =3D varDeclarations.first; +- strName =3D _getStringName(varDeclaration.name); +- } +- } +- } +- if (strName =3D=3D null) { +- return EMPTY_LIST; +- } +- +- List variableNameSuggestions =3D getCamelWordCombinations(s= trName); +- variableNameSuggestions.remove(strName); +- List suggestions =3D []; +- for (String varName in variableNameSuggestions) { +- CompletionSuggestion suggestion =3D _createNameSuggestion(varName= ); +- if (suggestion !=3D null) { +- suggestions.add(suggestion); +- } +- } +- return suggestions; +- } +- return EMPTY_LIST; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/postfix/postf= ix_completion.dart b/pkg/analysis_server/lib/src/services/completion/postfi= x/postfix_completion.dart +deleted file mode 100644 +index 704ffdb26a4..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/postfix/postfix_comp= letion.dart ++++ /dev/null +@@ -1,567 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analyzer/dart/analysis/session.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/resolver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/change_builder/change_builder_d= art.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * An enumeration of possible postfix completion kinds. +- */ +-class DartPostfixCompletion { +- static const NO_TEMPLATE =3D +- const PostfixCompletionKind('', 'no change', null, null); +- static const ALL_TEMPLATES =3D const [ +- const PostfixCompletionKind("assert", "expr.assert -> assert(expr);", +- isAssertContext, expandAssert), +- const PostfixCompletionKind( +- "fori", +- "limit.fori -> for(var i =3D 0; i < limit; i++) {}", +- isIntContext, +- expandFori), +- const PostfixCompletionKind( +- "for", +- "values.for -> for(var value in values) {}", +- isIterableContext, +- expandFor), +- const PostfixCompletionKind( +- "iter", +- "values.iter -> for(var value in values) {}", +- isIterableContext, +- expandFor), +- const PostfixCompletionKind( +- "not", "bool.not -> !bool", isBoolContext, expandNegate), +- const PostfixCompletionKind( +- "!", "bool! -> !bool", isBoolContext, expandNegate), +- const PostfixCompletionKind( +- "else", "bool.else -> if (!bool) {}", isBoolContext, expandElse), +- const PostfixCompletionKind( +- "if", "bool.if -> if (bool) {}", isBoolContext, expandIf), +- const PostfixCompletionKind("nn", "expr.nn -> if (expr !=3D null) {}", +- isObjectContext, expandNotNull), +- const PostfixCompletionKind("notnull", +- "expr.notnull -> if (expr !=3D null) {}", isObjectContext, expand= NotNull), +- const PostfixCompletionKind("null", "expr.null -> if (expr =3D=3D nul= l) {}", +- isObjectContext, expandNull), +- const PostfixCompletionKind( +- "par", "expr.par -> (expr)", isObjectContext, expandParen), +- const PostfixCompletionKind( +- "return", "expr.return -> return expr", isObjectContext, expandRe= turn), +- const PostfixCompletionKind("switch", "expr.switch -> switch (expr) {= }", +- isSwitchContext, expandSwitch), +- const PostfixCompletionKind("try", "stmt.try -> try {stmt} catch (e,s= ) {}", +- isStatementContext, expandTry), +- const PostfixCompletionKind( +- "tryon", +- "stmt.try -> try {stmt} on Exception catch (e,s) {}", +- isStatementContext, +- expandTryon), +- const PostfixCompletionKind( +- "while", "expr.while -> while (expr) {}", isBoolContext, expandWh= ile), +- ]; +- +- static Future expandAssert( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findAssertExpression, (expr) { +- return "assert(${processor.utils.getNodeText(expr)});"; +- }, withBraces: false); +- } +- +- static Future expandElse( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findBoolExpression, +- (expr) =3D> "if (${processor.makeNegatedBoolExpr(expr)})"); +- } +- +- static Future expandFor( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findIterableExpression, (expr= ) { +- String value =3D processor.newVariable("value"); +- return "for (var $value in ${processor.utils.getNodeText(expr)})"; +- }); +- } +- +- static Future expandFori( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findIntExpression, (expr) { +- String index =3D processor.newVariable("i"); +- return "for (int $index =3D 0; $index < ${processor.utils.getNodeTe= xt( +- expr)}; $index++)"; +- }); +- } +- +- static Future expandIf( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findBoolExpression, +- (expr) =3D> "if (${processor.utils.getNodeText(expr)})"); +- } +- +- static Future expandNegate( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findBoolExpression, +- (expr) =3D> processor.makeNegatedBoolExpr(expr), +- withBraces: false); +- } +- +- static Future expandNotNull( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findObjectExpression, (expr) { +- return expr is NullLiteral +- ? "if (false)" +- : "if (${processor.utils.getNodeText(expr)} !=3D null)"; +- }); +- } +- +- static Future expandNull( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findObjectExpression, (expr) { +- return expr is NullLiteral +- ? "if (true)" +- : "if (${processor.utils.getNodeText(expr)} =3D=3D null)"; +- }); +- } +- +- static Future expandParen( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findObjectExpression, +- (expr) =3D> "(${processor.utils.getNodeText(expr)})", +- withBraces: false); +- } +- +- static Future expandReturn( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findObjectExpression, +- (expr) =3D> "return ${processor.utils.getNodeText(expr)};", +- withBraces: false); +- } +- +- static Future expandSwitch( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findObjectExpression, +- (expr) =3D> "switch (${processor.utils.getNodeText(expr)})"); +- } +- +- static Future expandTry( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expandTry(kind, processor.findStatement, withOn: fal= se); +- } +- +- static Future expandTryon( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expandTry(kind, processor.findStatement, withOn: tru= e); +- } +- +- static Future expandWhile( +- PostfixCompletionProcessor processor, PostfixCompletionKind kind) a= sync { +- return processor.expand(kind, processor.findBoolExpression, +- (expr) =3D> "while (${processor.utils.getNodeText(expr)})"); +- } +- +- static PostfixCompletionKind forKey(String key) =3D> +- ALL_TEMPLATES.firstWhere((kind) =3D> kind.key =3D=3D key, orElse: (= ) =3D> null); +- +- static bool isAssertContext(PostfixCompletionProcessor processor) { +- return processor.findAssertExpression() !=3D null; +- } +- +- static bool isBoolContext(PostfixCompletionProcessor processor) { +- return processor.findBoolExpression() !=3D null; +- } +- +- static bool isIntContext(PostfixCompletionProcessor processor) { +- return processor.findIntExpression() !=3D null; +- } +- +- static bool isIterableContext(PostfixCompletionProcessor processor) { +- return processor.findIterableExpression() !=3D null; +- } +- +- static bool isObjectContext(PostfixCompletionProcessor processor) { +- return processor.findObjectExpression() !=3D null; +- } +- +- static bool isStatementContext(PostfixCompletionProcessor processor) { +- return processor.findStatement() !=3D null; +- } +- +- static bool isSwitchContext(PostfixCompletionProcessor processor) { +- return processor.findObjectExpression() !=3D null; +- } +-} +- +-/** +- * A description of a postfix completion. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class PostfixCompletion { +- /** +- * A description of the assist being proposed. +- */ +- final PostfixCompletionKind kind; +- +- /** +- * The change to be made in order to apply the assist. +- */ +- final SourceChange change; +- +- /** +- * Initialize a newly created completion to have the given [kind] and [= change]. +- */ +- PostfixCompletion(this.kind, this.change); +-} +- +-/** +- * The context for computing a postfix completion. +- */ +-class PostfixCompletionContext { +- final String file; +- final LineInfo lineInfo; +- final int selectionOffset; +- final String key; +- final AnalysisDriver driver; +- final CompilationUnit unit; +- final CompilationUnitElement unitElement; +- final List errors; +- +- PostfixCompletionContext(this.file, this.lineInfo, this.selectionOffset, +- this.key, this.driver, this.unit, this.unitElement, this.errors) { +- if (unitElement.context =3D=3D null) { +- throw new Error(); // not reached +- } +- } +-} +- +-/** +- * A description of a template for postfix completion. Instances are inte= nded to +- * hold the functions required to determine applicability and expand the +- * template, in addition to its name and simple example. The example is s= hown +- * (in IntelliJ) in a code-completion menu, so must be quite short. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class PostfixCompletionKind { +- final String name, example; +- final Function selector; +- final Function computer; +- +- const PostfixCompletionKind( +- this.name, this.example, this.selector, this.computer); +- +- String get key =3D> name =3D=3D '!' ? name : '.$name'; +- +- String get message =3D> 'Expand $key'; +- +- @override +- String toString() =3D> name; +-} +- +-/** +- * The computer for Dart postfix completions. +- */ +-class PostfixCompletionProcessor { +- static final NO_COMPLETION =3D new PostfixCompletion( +- DartPostfixCompletion.NO_TEMPLATE, new SourceChange("", edits: [])); +- +- final PostfixCompletionContext completionContext; +- final CorrectionUtils utils; +- AstNode node; +- PostfixCompletion completion; +- SourceChange change =3D new SourceChange('postfix-completion'); +- final Map linkedPositionGroups =3D +- {}; +- Position exitPosition =3D null; +- TypeProvider _typeProvider; +- +- PostfixCompletionProcessor(this.completionContext) +- : utils =3D new CorrectionUtils(completionContext.unit); +- +- AnalysisDriver get driver =3D> completionContext.driver; +- +- String get eol =3D> utils.endOfLine; +- +- String get file =3D> completionContext.file; +- +- String get key =3D> completionContext.key; +- +- LineInfo get lineInfo =3D> completionContext.lineInfo; +- +- int get requestLine =3D> lineInfo.getLocation(selectionOffset).lineNumb= er; +- +- int get selectionOffset =3D> completionContext.selectionOffset; +- +- /** +- * Return the analysis session to be used to create the change builder. +- */ +- AnalysisSession get session =3D> driver.currentSession; +- +- Source get source =3D> completionContext.unitElement.source; +- +- TypeProvider get typeProvider { +- return _typeProvider ??=3D unitElement.context.typeProvider; +- } +- +- CompilationUnit get unit =3D> completionContext.unit; +- +- CompilationUnitElement get unitElement =3D> completionContext.unitEleme= nt; +- +- Future compute() async { +- node =3D _selectedNode(); +- if (node =3D=3D null) { +- return NO_COMPLETION; +- } +- PostfixCompletionKind completer =3D DartPostfixCompletion.forKey(key); +- return completer?.computer(this, completer) ?? NO_COMPLETION; +- } +- +- Future expand( +- PostfixCompletionKind kind, Function contexter, Function sourcer, +- {bool withBraces: true}) async { +- AstNode expr =3D contexter(); +- if (expr =3D=3D null) { +- return null; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(expr), (DartEditBuilder builder) { +- String newSrc =3D sourcer(expr); +- if (newSrc =3D=3D null) { +- return null; +- } +- builder.write(newSrc); +- if (withBraces) { +- builder.write(" {"); +- builder.write(eol); +- String indent =3D utils.getNodePrefix(expr); +- builder.write(indent); +- builder.write(utils.getIndent(1)); +- builder.selectHere(); +- builder.write(eol); +- builder.write(indent); +- builder.write("}"); +- } else { +- builder.selectHere(); +- } +- }); +- }); +- _setCompletionFromBuilder(changeBuilder, kind); +- return completion; +- } +- +- Future expandTry( +- PostfixCompletionKind kind, Function contexter, +- {bool withOn: false}) async { +- AstNode stmt =3D contexter(); +- if (stmt =3D=3D null) { +- return null; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- // Embed the full line(s) of the statement in the try block. +- var startLine =3D lineInfo.getLocation(stmt.offset).lineNumber - 1; +- var endLine =3D lineInfo.getLocation(stmt.end).lineNumber - 1; +- if (stmt is ExpressionStatement && !stmt.semicolon.isSynthetic) { +- endLine +=3D 1; +- } +- var startOffset =3D lineInfo.getOffsetOfLine(startLine); +- var endOffset =3D lineInfo.getOffsetOfLine(endLine); +- var src =3D utils.getText(startOffset, endOffset - startOffset); +- String indent =3D utils.getLinePrefix(stmt.offset); +- builder.addReplacement(range.startOffsetEndOffset(startOffset, endO= ffset), +- (DartEditBuilder builder) { +- builder.write(indent); +- builder.write('try {'); +- builder.write(eol); +- builder.write(src.replaceAll(new RegExp("^$indent", multiLine: tr= ue), +- "$indent${utils.getIndent(1)}")); +- builder.selectHere(); +- builder.write(indent); +- builder.write('}'); +- if (withOn) { +- builder.write(' on '); +- builder.addSimpleLinkedEdit('NAME', nameOfExceptionThrownBy(stm= t)); +- } +- builder.write(' catch (e, s) {'); +- builder.write(eol); +- builder.write(indent); +- builder.write(utils.getIndent(1)); +- builder.write('print(s);'); +- builder.write(eol); +- builder.write(indent); +- builder.write("}"); +- builder.write(eol); +- }); +- }); +- _setCompletionFromBuilder(changeBuilder, kind); +- return completion; +- } +- +- Expression findAssertExpression() { +- if (node is Expression) { +- Expression boolExpr =3D _findOuterExpression(node, typeProvider.boo= lType); +- if (boolExpr =3D=3D null) { +- return null; +- } +- if (boolExpr.parent is ExpressionFunctionBody && +- boolExpr.parent.parent is FunctionExpression) { +- FunctionExpression fnExpr =3D boolExpr.parent.parent; +- var type =3D fnExpr.bestType; +- if (type is! FunctionType) { +- return boolExpr; +- } +- FunctionType fnType =3D type; +- if (fnType.returnType =3D=3D typeProvider.boolType) { +- return fnExpr; +- } +- } +- if (boolExpr.bestType =3D=3D typeProvider.boolType) { +- return boolExpr; +- } +- } +- return null; +- } +- +- Expression findBoolExpression() =3D> +- _findOuterExpression(node, typeProvider.boolType); +- +- Expression findIntExpression() =3D> +- _findOuterExpression(node, typeProvider.intType); +- +- Expression findIterableExpression() =3D> +- _findOuterExpression(node, typeProvider.iterableType); +- +- Expression findObjectExpression() =3D> +- _findOuterExpression(node, typeProvider.objectType); +- +- AstNode findStatement() { +- var astNode =3D node; +- while (astNode !=3D null) { +- if (astNode is Statement && astNode is! Block) { +- // Disallow control-flow statements. +- if (astNode is DoStatement || +- astNode is IfStatement || +- astNode is ForEachStatement || +- astNode is ForStatement || +- astNode is SwitchStatement || +- astNode is TryStatement || +- astNode is WhileStatement) { +- return null; +- } +- return astNode; +- } +- astNode =3D astNode.parent; +- } +- return null; +- } +- +- Future isApplicable() async { +- node =3D _selectedNode(); +- if (node =3D=3D null) { +- return false; +- } +- PostfixCompletionKind completer =3D DartPostfixCompletion.forKey(key); +- return completer?.selector(this); +- } +- +- String makeNegatedBoolExpr(Expression expr) { +- String originalSrc =3D utils.getNodeText(expr); +- String newSrc =3D utils.invertCondition(expr); +- if (newSrc !=3D originalSrc) { +- return newSrc; +- } else { +- return "!${utils.getNodeText(expr)}"; +- } +- } +- +- String nameOfExceptionThrownBy(AstNode astNode) { +- if (astNode is ExpressionStatement) { +- astNode =3D (astNode as ExpressionStatement).expression; +- } +- if (astNode is ThrowExpression) { +- ThrowExpression expr =3D astNode; +- var type =3D expr.expression.bestType; +- return type.displayName; +- } +- return 'Exception'; +- } +- +- String newVariable(String base) { +- String name =3D base; +- int i =3D 1; +- Set vars =3D +- utils.findPossibleLocalVariableConflicts(selectionOffset); +- while (vars.contains(name)) { +- name =3D "$base${i++}"; +- } +- return name; +- } +- +- Expression _findOuterExpression(AstNode start, InterfaceType builtInTyp= e) { +- AstNode parent; +- if (start is Expression) { +- parent =3D start; +- } else if (start is ArgumentList) { +- parent =3D start.parent; +- } +- if (parent =3D=3D null) { +- return null; +- } +- var list =3D []; +- while (parent is Expression) { +- list.add(parent); +- parent =3D parent.parent; +- } +- Expression expr =3D list.firstWhere((expr) { +- DartType type =3D expr.bestType; +- if (type.isSubtypeOf(builtInType)) return true; +- Element element =3D type.element; +- if (element is TypeDefiningElement) { +- TypeDefiningElement typeDefElem =3D element; +- type =3D typeDefElem.type; +- if (type is ParameterizedType) { +- ParameterizedType pType =3D type; +- type =3D pType.instantiate(new List.filled( +- pType.typeParameters.length, typeProvider.dynamicType)); +- } +- } +- return type.isSubtypeOf(builtInType); +- }, orElse: () =3D> null); +- if (expr is SimpleIdentifier && expr.parent is PropertyAccess) { +- expr =3D expr.parent; +- } +- if (expr?.parent is CascadeExpression) { +- expr =3D expr.parent; +- } +- return expr; +- } +- +- AstNode _selectedNode({int at: null}) =3D> +- new NodeLocator(at =3D=3D null ? selectionOffset : at).searchWithin= (unit); +- +- void _setCompletionFromBuilder( +- DartChangeBuilder builder, PostfixCompletionKind kind, +- [List args]) { +- SourceChange change =3D builder.sourceChange; +- if (change.edits.isEmpty) { +- completion =3D null; +- return; +- } +- change.message =3D formatList(kind.message, args); +- completion =3D new PostfixCompletion(kind, change); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/completion/statement/des= ign_notes.md b/pkg/analysis_server/lib/src/services/completion/statement/de= sign_notes.md +deleted file mode 100644 +index 238c83c59f2..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/statement/design_not= es.md ++++ /dev/null +@@ -1,144 +0,0 @@ +-# Statement Completion +- +-### Mission Statement +- +-The purpose of this feature is to add required syntax to the current +-statement. The goal is to make the statement syntactically complete. +-That is not possible to do in all cases. A best-effort attempt is made +-when it cannot be done. +- +-### Current Statement +- +-The term _statement completion_ comes from IntelliJ. It is also called +-_smart enter_ there, which is a more general term. See the IntelliJ +-[documentation.](https://www.jetbrains.com/help/idea/2017.1/auto-completi= ng-code.html#statements_completion) +- +-Rather than restricting the functionality to statements, in the sense of = the grammar construct +-called _statement_, it is best to think of code constructs. Statement com= pletion +-can be used to add syntax to declarations, statements, and some expressio= ns. +-Generally, the syntax additions are punctuation marks, such as semicolons, +-parentheses, and braces. +- +-The _current statement_ then, is the code construct being written in the +-editor, as identified by the position of the editing cursor. The _cursor_= is the +-primary editing cursor of the active editor in IntelliJ. We ignore multip= le +-secondary cursors. +- +-If the _current statement_ is already syntactically complete then the fea= ture +-just adds a newline. This will be the case when the cursor follows the cl= osing +-brace of the body of a for-statement or while-statement, for example. The= model +-used is that the user is creating code going forward, and when the +-_smart enter_ keystroke is typed the user expects to see forward progress. +-The cursor should end up at the most likely place to continue editing, re= gardless +-of what errors may exist in previous code. It is as if the user said "I'm= done +-with this line. Finish it up and move me to the next line." +- +-## Code Constructs +- +-There are a number of cases where a matching right parenthesis could be a= dded +-if it is missing. This feature has not been considered a priority since t= he +-editor by default adds parenthesis in pairs. +- +-Generics are not currently handled. +- +-#### Declarations +- +-There is limited work to be done. +- +-- [x] Functions, methods, and classes can have a pair of braces added if = they do not already have a body defined. +-- [x] Functions and methods can have a closing parenthesis added to the p= arameter list. +-- [x] Variables can have a semicolon added to terminate them. +- +-#### Expressions +- +-Also limited. +- +-- [x] Unterminated strings can have appropriate string +-terminators added. +-- [x] Lists that have not been properly terminated can +-have closing brackets added (potentially with trailing commas). +-- [x] Maps are not currently handled. The parser error recovery +-gets confused by braces of code blocks too easily. +- +-#### Statements +- +-With actual statements, there are many more possibilities. +-Statements that start with a keyword must have at least the +-keyword in the partial statement in order for completion to +-happen. +- +-###### Do Statement +- +-This is one of the few cases where an actual word may be included. +-If the `while` keyword is missing it will be added. +-As long as the `do` keyword is present the braces for the body +-will be added. If the `while` keyword is present or can be added +-then the parentheses for the condition will be added, too. Finally, +-the terminating semicolon will be added. +- +-###### For Statement +- +-The parser cannot distinguish a for-statement from a for-each unless +-either at least one semicolon or the `in` keyword is present in the +-control parts. If neither is present then completion cannot do any +-more than possibly add braces for the body. +- +-Given that the statement is actually a for-statement then the control +-parts will be adjusted to ensure there are two semicolons. If the braces +-for the body are missing then they will be added. +- +-###### For-each Statement +- +-Braces for the body can be added if missing. +- +-###### If Statement +- +-The if-else-etc construct could get arbitrarily complex, so +-for simplicity the `else` keyword is ignored. Starting with nothing +-but the `if` keyword, the parentheses for the condition will be added +-and the braces for the body will be added. +- +-###### Switch Statement +- +-Given the `switch` keyword, parentheses for the selector will be added +-if absent and the braces for the body will be added. Also, for an +-individual case or default clause the terminating colon will be added +-if needed. To be clear, only the colon for the clause containing +-the cursor will be added. +- +-###### Try Statement +- +-If the statement is nothing more than the `try` keyword then the braces +-for the body will be added. No clauses (on, catch, or finally) will be ad= ded. +- +-An on-clause will be completed by adding braces for its body, if absent. +- +-A catch-clause will be completed by adding parentheses for its +-parameter list and braces for the body. +- +-A finally-clause will be completed by adding braces for its body. +- +-###### While Statement +- +-This is structurally identical to the if-statement and the implementation +-for both is shared. +- +-###### Expression Statements +- +-These include method and function invocations. +-- [x] Add closing parenthesis, if the expression is an invocation. +-- [x] Add terminating semicolon. +- +-###### Control-flow Blocks +- +-After finishing a `return` or `throw` in a block that is the +-body of a control-flow statement (do, for, for-each, if, while) +-then the cursor will be moved outside the block, ready to begin +-the next statement following the control-flow statement. +-```dart +-if (isFinished()) { +-releaseResources(); +-return; // invoke 'smart enter' here +-} +-// continue typing here +-``` +diff --git a/pkg/analysis_server/lib/src/services/completion/statement/sta= tement_completion.dart b/pkg/analysis_server/lib/src/services/completion/st= atement/statement_completion.dart +deleted file mode 100644 +index 2277f99ff2b..00000000000 +--- a/pkg/analysis_server/lib/src/services/completion/statement/statement_= completion.dart ++++ /dev/null +@@ -1,1237 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:math'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/source_buffer.dar= t'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/error/hint_codes.dart'; +-import 'package:analyzer/src/dart/error/syntactic_errors.dart'; +-import 'package:analyzer/src/error/codes.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * An enumeration of possible statement completion kinds. +- */ +-class DartStatementCompletion { +- static const NO_COMPLETION =3D +- const StatementCompletionKind('No_COMPLETION', 'No completion avail= able'); +- static const SIMPLE_ENTER =3D const StatementCompletionKind( +- 'SIMPLE_ENTER', "Insert a newline at the end of the current line"); +- static const SIMPLE_SEMICOLON =3D const StatementCompletionKind( +- 'SIMPLE_SEMICOLON', "Add a semicolon and newline"); +- static const COMPLETE_CLASS_DECLARATION =3D const StatementCompletionKi= nd( +- 'COMPLETE_CLASS_DECLARATION', "Complete class declaration"); +- static const COMPLETE_CONTROL_FLOW_BLOCK =3D const StatementCompletionK= ind( +- 'COMPLETE_CONTROL_FLOW_BLOCK', "Complete control flow block"); +- static const COMPLETE_DO_STMT =3D const StatementCompletionKind( +- 'COMPLETE_DO_STMT', "Complete do-statement"); +- static const COMPLETE_IF_STMT =3D const StatementCompletionKind( +- 'COMPLETE_IF_STMT', "Complete if-statement"); +- static const COMPLETE_FOR_STMT =3D const StatementCompletionKind( +- 'COMPLETE_FOR_STMT', "Complete for-statement"); +- static const COMPLETE_FOR_EACH_STMT =3D const StatementCompletionKind( +- 'COMPLETE_FOR_EACH_STMT', "Complete for-each-statement"); +- static const COMPLETE_FUNCTION_DECLARATION =3D const StatementCompletio= nKind( +- 'COMPLETE_FUNCTION_DECLARATION', "Complete function declaration"); +- static const COMPLETE_SWITCH_STMT =3D const StatementCompletionKind( +- 'COMPLETE_SWITCH_STMT', "Complete switch-statement"); +- static const COMPLETE_TRY_STMT =3D const StatementCompletionKind( +- 'COMPLETE_TRY_STMT', "Complete try-statement"); +- static const COMPLETE_VARIABLE_DECLARATION =3D const StatementCompletio= nKind( +- 'COMPLETE_VARIABLE_DECLARATION', "Complete variable declaration"); +- static const COMPLETE_WHILE_STMT =3D const StatementCompletionKind( +- 'COMPLETE_WHILE_STMT', "Complete while-statement"); +-} +- +-/** +- * A description of a statement completion. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class StatementCompletion { +- /** +- * A description of the assist being proposed. +- */ +- final StatementCompletionKind kind; +- +- /** +- * The change to be made in order to apply the assist. +- */ +- final SourceChange change; +- +- /** +- * Initialize a newly created completion to have the given [kind] and [= change]. +- */ +- StatementCompletion(this.kind, this.change); +-} +- +-/** +- * The context for computing a statement completion. +- */ +-class StatementCompletionContext { +- final String file; +- final LineInfo lineInfo; +- final int selectionOffset; +- final CompilationUnit unit; +- final CompilationUnitElement unitElement; +- final List errors; +- +- StatementCompletionContext(this.file, this.lineInfo, this.selectionOffs= et, +- this.unit, this.unitElement, this.errors) { +- if (unitElement.context =3D=3D null) { +- throw new Error(); // not reached; see getStatementCompletion() +- } +- } +-} +- +-/** +- * A description of a class of statement completions. Instances are inten= ded to +- * hold the information that is common across a number of completions and= to be +- * shared by those completions. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class StatementCompletionKind { +- /** +- * The name of this kind of statement completion, used for debugging. +- */ +- final String name; +- +- /** +- * A human-readable description of the changes that will be applied by = this +- * kind of statement completion. +- */ +- final String message; +- +- /** +- * Initialize a newly created kind of statement completion to have the = given +- * [name] and [message]. +- */ +- const StatementCompletionKind(this.name, this.message); +- +- @override +- String toString() =3D> name; +-} +- +-/** +- * The computer for Dart statement completions. +- */ +-class StatementCompletionProcessor { +- static final NO_COMPLETION =3D new StatementCompletion( +- DartStatementCompletion.NO_COMPLETION, new SourceChange("", edits: = [])); +- +- final StatementCompletionContext statementContext; +- final CorrectionUtils utils; +- AstNode node; +- StatementCompletion completion; +- SourceChange change =3D new SourceChange('statement-completion'); +- List errors =3D []; +- final Map linkedPositionGroups =3D +- {}; +- Position exitPosition =3D null; +- +- StatementCompletionProcessor(this.statementContext) +- : utils =3D new CorrectionUtils(statementContext.unit); +- +- String get eol =3D> utils.endOfLine; +- +- String get file =3D> statementContext.file; +- +- LineInfo get lineInfo =3D> statementContext.lineInfo; +- +- int get requestLine =3D> lineInfo.getLocation(selectionOffset).lineNumb= er; +- +- int get selectionOffset =3D> statementContext.selectionOffset; +- +- Source get source =3D> statementContext.unitElement.source; +- +- CompilationUnit get unit =3D> statementContext.unit; +- +- CompilationUnitElement get unitElement =3D> statementContext.unitElemen= t; +- +- Future compute() async { +- node =3D _selectedNode(); +- if (node =3D=3D null) { +- return NO_COMPLETION; +- } +- node =3D node +- .getAncestor((n) =3D> n is Statement || _isNonStatementDeclaratio= n(n)); +- if (node =3D=3D null) { +- return _complete_simpleEnter() ? completion : NO_COMPLETION; +- } +- if (node is Block) { +- Block blockNode =3D node; +- if (blockNode.statements.isNotEmpty) { +- node =3D blockNode.statements.last; +- } +- } +- if (_isEmptyStatement(node)) { +- node =3D node.parent; +- } +- for (engine.AnalysisError error in statementContext.errors) { +- if (error.offset >=3D node.offset && +- error.offset <=3D node.offset + node.length) { +- if (error.errorCode is! HintCode) { +- errors.add(error); +- } +- } +- } +- +- _checkExpressions(); +- if (node is Statement) { +- if (errors.isEmpty) { +- if (_complete_ifStatement() || +- _complete_forStatement() || +- _complete_forEachStatement() || +- _complete_whileStatement() || +- _complete_controlFlowBlock()) { +- return completion; +- } +- } else { +- if (_complete_ifStatement() || +- _complete_doStatement() || +- _complete_forStatement() || +- _complete_forEachStatement() || +- _complete_functionDeclarationStatement() || +- _complete_switchStatement() || +- _complete_tryStatement() || +- _complete_whileStatement() || +- _complete_controlFlowBlock() || +- _complete_simpleSemicolon() || +- _complete_methodCall()) { +- return completion; +- } +- } +- } else if (node is Declaration) { +- if (errors.isNotEmpty) { +- if (_complete_classDeclaration() || +- _complete_functionDeclaration() || +- _complete_variableDeclaration()) { +- return completion; +- } +- } +- } +- if (_complete_simpleEnter()) { +- return completion; +- } +- return NO_COMPLETION; +- } +- +- void _addInsertEdit(int offset, String text) { +- SourceEdit edit =3D new SourceEdit(offset, 0, text); +- doSourceChange_addElementEdit(change, unitElement, edit); +- } +- +- void _addReplaceEdit(SourceRange range, String text) { +- SourceEdit edit =3D new SourceEdit(range.offset, range.length, text); +- doSourceChange_addElementEdit(change, unitElement, edit); +- } +- +- void _appendEmptyBraces(SourceBuilder sb, [bool needsExitMark =3D false= ]) { +- sb.append('{'); +- sb.append(eol); +- String indent =3D utils.getLinePrefix(selectionOffset); +- sb.append(indent); +- sb.append(utils.getIndent(1)); +- if (needsExitMark && sb.exitOffset =3D=3D null) { +- sb.setExitOffset(); +- } +- sb.append(eol); +- sb.append(indent); +- sb.append('}'); +- } +- +- int _appendNewlinePlusIndent() { +- return _appendNewlinePlusIndentAt(selectionOffset); +- } +- +- int _appendNewlinePlusIndentAt(int offset) { +- // Append a newline plus proper indent and another newline. +- // Return the position before the second newline. +- String indent =3D utils.getLinePrefix(offset); +- int loc =3D utils.getLineNext(offset); +- _addInsertEdit(loc, indent + eol); +- return loc + indent.length; +- } +- +- String _baseNodeText(AstNode astNode) { +- String text =3D utils.getNodeText(astNode); +- if (text.endsWith(eol)) { +- text =3D text.substring(0, text.length - eol.length); +- } +- return text; +- } +- +- void _checkExpressions() { +- // Note: This may queue edits that have to be accounted for later. +- // See _lengthOfInsertions(). +- AstNode errorMatching(errorCode, {partialMatch =3D null}) { +- var error =3D _findError(errorCode, partialMatch: partialMatch); +- if (error =3D=3D null) { +- return null; +- } +- AstNode expr =3D _selectedNode(); +- return (expr.getAncestor((n) =3D> n is StringInterpolation) =3D=3D = null) +- ? expr +- : null; +- } +- +- var expr =3D errorMatching(ScannerErrorCode.UNTERMINATED_STRING_LITER= AL); +- if (expr !=3D null) { +- String source =3D utils.getNodeText(expr); +- String content =3D source; +- int char =3D content.codeUnitAt(0); +- if (char =3D=3D 'r'.codeUnitAt(0)) { +- content =3D source.substring(1); +- char =3D content.codeUnitAt(0); +- } +- String delimiter; +- int loc; +- if (content.length >=3D 3 && +- char =3D=3D content.codeUnitAt(1) && +- char =3D=3D content.codeUnitAt(2)) { +- // multi-line string +- delimiter =3D content.substring(0, 3); +- int newlineLoc =3D source.indexOf(eol, selectionOffset - expr.off= set); +- if (newlineLoc < 0) { +- newlineLoc =3D source.length; +- } +- loc =3D newlineLoc + expr.offset; +- } else { +- // add first char of src +- delimiter =3D content.substring(0, 1); +- loc =3D expr.offset + source.length; +- } +- _removeError(ScannerErrorCode.UNTERMINATED_STRING_LITERAL); +- _addInsertEdit(loc, delimiter); +- } +- expr =3D errorMatching(ParserErrorCode.EXPECTED_TOKEN, partialMatch: = "']'") ?? +- errorMatching(ScannerErrorCode.EXPECTED_TOKEN, partialMatch: "']'= "); +- if (expr !=3D null) { +- expr =3D expr.getAncestor((n) =3D> n is ListLiteral); +- if (expr !=3D null) { +- ListLiteral lit =3D expr; +- if (lit.rightBracket.isSynthetic) { +- String src =3D utils.getNodeText(expr).trim(); +- int loc =3D expr.offset + src.length; +- if (src.contains(eol)) { +- String indent =3D utils.getNodePrefix(node); +- _addInsertEdit(loc, ',' + eol + indent + ']'); +- } else { +- _addInsertEdit(loc, ']'); +- } +- _removeError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "']'= "); +- _removeError(ScannerErrorCode.EXPECTED_TOKEN, partialMatch: "']= '"); +- var ms =3D +- _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "'= ;'"); +- if (ms !=3D null) { +- // Ensure the semicolon gets inserted in the correct location. +- ms.offset =3D loc - 1; +- } +- } +- } +- } +- // The following code is similar to the code for ']' but does not wor= k well. +- // A closing brace is recognized as belong to the map even if it is i= ntended +- // to close a block of code. +- /* +- expr =3D errorMatching(ParserErrorCode.EXPECTED_TOKEN, partialMatch: = "'}'"); +- if (expr !=3D null) { +- expr =3D expr.getAncestor((n) =3D> n is MapLiteral); +- if (expr !=3D null) { +- MapLiteral lit =3D expr; +- String src =3D utils.getNodeText(expr).trim(); +- int loc =3D expr.offset + src.length; +- if (lit.entries.last.separator.isSynthetic) { +- _addInsertEdit(loc, ': '); +- } +- if (!src.endsWith('}')/*lit.rightBracket.isSynthetic*/) { +- _addInsertEdit(loc, '}'); +- } +- _removeError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "'}'"); +- var ms =3D +- _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "';'"); +- if (ms !=3D null) { +- // Ensure the semicolon gets inserted in the correct location. +- ms.offset =3D loc - 1; +- } +- } +- } +- */ +- } +- +- bool _complete_classDeclaration() { +- if (node is! ClassDeclaration) { +- return false; +- } +- ClassDeclaration decl =3D node; +- if (decl.leftBracket.isSynthetic && errors.length =3D=3D 1) { +- // The space before the left brace is assumed to exist, even if it = does not. +- SourceBuilder sb =3D new SourceBuilder(file, decl.end - 1); +- sb.append(' '); +- _appendEmptyBraces(sb, true); +- _insertBuilder(sb); +- _setCompletion(DartStatementCompletion.COMPLETE_CLASS_DECLARATION); +- return true; +- } +- return false; +- } +- +- bool _complete_controlFlowBlock() { +- Expression expr =3D (node is ExpressionStatement) +- ? (node as ExpressionStatement).expression +- : (node is ReturnStatement +- ? (node as ReturnStatement).expression +- : null); +- if (!(node is ReturnStatement || expr is ThrowExpression)) { +- return false; +- } +- if (node.parent is! Block) { +- return false; +- } +- AstNode outer =3D node.parent.parent; +- if (!(outer is DoStatement || +- outer is ForStatement || +- outer is ForEachStatement || +- outer is IfStatement || +- outer is WhileStatement)) { +- return false; +- } +- int previousInsertions =3D _lengthOfInsertions(); +- int delta =3D 0; +- if (errors.isNotEmpty) { +- var error =3D +- _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "';'"); +- if (error !=3D null) { +- int insertOffset; +- // Fasta scanner reports unterminated string literal errors +- // and generates a synthetic string token with non-zero length. +- // Because of this, check for length =3D=3D 0 rather than isSynth= etic. +- if (expr =3D=3D null || expr.length =3D=3D 0) { +- if (node is ReturnStatement) { +- insertOffset =3D (node as ReturnStatement).returnKeyword.end; +- } else if (node is ExpressionStatement) { +- insertOffset =3D +- ((node as ExpressionStatement).expression as ThrowExpress= ion) +- .throwKeyword +- .end; +- } else { +- insertOffset =3D node.end; // Not reached. +- } +- } else { +- insertOffset =3D expr.end; +- } +- //TODO(messick) Uncomment the following line when error location = is fixed. +- //insertOffset =3D error.offset + error.length; +- _addInsertEdit(insertOffset, ';'); +- delta =3D 1; +- } +- } +- int offset =3D _appendNewlinePlusIndentAt(node.parent.end); +- exitPosition =3D new Position(file, offset + delta + previousInsertio= ns); +- _setCompletion(DartStatementCompletion.COMPLETE_CONTROL_FLOW_BLOCK); +- return true; +- } +- +- bool _complete_doStatement() { +- if (node is! DoStatement) { +- return false; +- } +- DoStatement statement =3D node; +- SourceBuilder sb =3D _sourceBuilderAfterKeyword(statement.doKeyword); +- bool hasWhileKeyword =3D statement.whileKeyword.lexeme =3D=3D "while"; +- int exitDelta =3D 0; +- if (!_statementHasValidBody(statement.doKeyword, statement.body)) { +- String text =3D utils.getNodeText(statement.body); +- int delta =3D 0; +- if (text.startsWith(';')) { +- delta =3D 1; +- _addReplaceEdit(range.startLength(statement.body, delta), ''); +- if (hasWhileKeyword) { +- text =3D utils.getNodeText(statement); +- if (text.indexOf(new RegExp(r'do\s*;\s*while')) =3D=3D 0) { +- int end =3D text.indexOf('while'); +- int start =3D text.indexOf(';') + 1; +- delta +=3D end - start - 1; +- _addReplaceEdit( +- new SourceRange(start + statement.offset, end - start), '= '); +- } +- } +- sb =3D new SourceBuilder(file, sb.offset + delta); +- sb.append(' '); +- } +- _appendEmptyBraces(sb, +- !(hasWhileKeyword && _isSyntheticExpression(statement.condition= ))); +- if (delta !=3D 0) { +- exitDelta =3D sb.length - delta; +- } +- } else if (_isEmptyBlock(statement.body)) { +- sb =3D new SourceBuilder(sb.file, statement.body.end); +- } +- SourceBuilder sb2; +- if (hasWhileKeyword) { +- var stmt =3D new _KeywordConditionBlockStructure( +- statement.whileKeyword, +- statement.leftParenthesis, +- statement.condition, +- statement.rightParenthesis, +- null); +- sb2 =3D _complete_keywordCondition(stmt); +- if (sb2 =3D=3D null) { +- return false; +- } +- if (sb2.length =3D=3D 0) { +- // true if condition is '()' +- if (exitPosition !=3D null) { +- if (statement.semicolon.isSynthetic) { +- _insertBuilder(sb); +- sb =3D new SourceBuilder(file, exitPosition.offset + 1); +- sb.append(';'); +- } +- } +- } else { +- if (sb.exitOffset =3D=3D null && sb2?.exitOffset !=3D null) { +- _insertBuilder(sb); +- sb =3D sb2; +- sb.append(';'); +- } else { +- sb.append(sb2.toString()); +- } +- } +- } else { +- sb.append(" while ("); +- sb.setExitOffset(); +- sb.append(");"); +- } +- _insertBuilder(sb); +- if (exitDelta !=3D 0) { +- exitPosition =3D +- new Position(exitPosition.file, exitPosition.offset + exitDelta= ); +- } +- _setCompletion(DartStatementCompletion.COMPLETE_DO_STMT); +- return true; +- } +- +- bool _complete_forEachStatement() { +- if (node is! ForEachStatement) { +- return false; +- } +- ForEachStatement forNode =3D node; +- if (forNode.inKeyword.isSynthetic) { +- return false; // Can't happen -- would be parsed as a for-statement. +- } +- SourceBuilder sb =3D +- new SourceBuilder(file, forNode.rightParenthesis.offset + 1); +- AstNode name =3D forNode.identifier; +- name ??=3D forNode.loopVariable; +- String src =3D utils.getNodeText(forNode); +- if (name =3D=3D null) { +- exitPosition =3D new Position(file, forNode.leftParenthesis.offset = + 1); +- src =3D src.substring(forNode.leftParenthesis.offset - forNode.offs= et); +- if (src.startsWith(new RegExp(r'\(\s*in\s*\)'))) { +- _addReplaceEdit( +- range.startOffsetEndOffset(forNode.leftParenthesis.offset + 1, +- forNode.rightParenthesis.offset), +- ' in '); +- } else if (src.startsWith(new RegExp(r'\(\s*in'))) { +- _addReplaceEdit( +- range.startOffsetEndOffset( +- forNode.leftParenthesis.offset + 1, forNode.inKeyword.off= set), +- ' '); +- } +- } else if (_isSyntheticExpression(forNode.iterable)) { +- exitPosition =3D new Position(file, forNode.rightParenthesis.offset= + 1); +- src =3D src.substring(forNode.inKeyword.offset - forNode.offset); +- if (src.startsWith(new RegExp(r'in\s*\)'))) { +- _addReplaceEdit( +- range.startOffsetEndOffset( +- forNode.inKeyword.offset + forNode.inKeyword.length, +- forNode.rightParenthesis.offset), +- ' '); +- } +- } +- if (!_statementHasValidBody(forNode.forKeyword, forNode.body)) { +- sb.append(' '); +- _appendEmptyBraces(sb, exitPosition =3D=3D null); +- } +- _insertBuilder(sb); +- _setCompletion(DartStatementCompletion.COMPLETE_FOR_EACH_STMT); +- return true; +- } +- +- bool _complete_forStatement() { +- if (node is! ForStatement) { +- return false; +- } +- ForStatement forNode =3D node; +- SourceBuilder sb; +- int replacementLength =3D 0; +- if (forNode.leftParenthesis.isSynthetic) { +- if (!forNode.rightParenthesis.isSynthetic) { +- return false; +- } +- // keywordOnly (unit test name suffix that exercises this branch) +- sb =3D _sourceBuilderAfterKeyword(forNode.forKeyword); +- sb.append('('); +- sb.setExitOffset(); +- sb.append(')'); +- } else { +- if (!forNode.rightSeparator.isSynthetic) { +- // Fully-defined init, cond, updaters so nothing more needed here. +- // emptyParts, noError +- sb =3D new SourceBuilder(file, forNode.rightParenthesis.offset + = 1); +- } else if (!forNode.leftSeparator.isSynthetic) { +- if (_isSyntheticExpression(forNode.condition)) { +- String text =3D utils +- .getNodeText(forNode) +- .substring(forNode.leftSeparator.offset - forNode.offset); +- Match match =3D +- new RegExp(r';\s*(/\*.*\*/\s*)?\)[ \t]*').matchAsPrefix(tex= t); +- if (match !=3D null) { +- // emptyCondition, emptyInitializersEmptyCondition +- replacementLength =3D match.end - match.start; +- sb =3D new SourceBuilder(file, forNode.leftSeparator.offset); +- sb.append('; ${match.group(1) =3D=3D null ? '' : match.group(= 1)}; )'); +- String suffix =3D text.substring(match.end); +- if (suffix.trim().isNotEmpty) { +- sb.append(' '); +- sb.append(suffix.trim()); +- replacementLength +=3D suffix.length; +- if (suffix.endsWith(eol)) { +- // emptyCondition +- replacementLength -=3D eol.length; +- } +- } +- exitPosition =3D _newPosition(forNode.leftSeparator.offset + = 2); +- } else { +- return false; // Line comment in condition +- } +- } else { +- // emptyUpdaters +- sb =3D new SourceBuilder(file, forNode.rightParenthesis.offset); +- replacementLength =3D 1; +- sb.append('; )'); +- exitPosition =3D _newPosition(forNode.rightSeparator.offset + 2= ); +- } +- } else if (_isSyntheticExpression(forNode.initialization)) { +- // emptyInitializers +- exitPosition =3D _newPosition(forNode.rightParenthesis.offset); +- sb =3D new SourceBuilder(file, forNode.rightParenthesis.offset); +- } else { +- int start =3D forNode.condition.offset + forNode.condition.length; +- String text =3D +- utils.getNodeText(forNode).substring(start - forNode.offset); +- if (text.startsWith(new RegExp(r'\s*\)'))) { +- // missingLeftSeparator +- int end =3D text.indexOf(')'); +- sb =3D new SourceBuilder(file, start); +- _addReplaceEdit(new SourceRange(start, end), '; ; '); +- exitPosition =3D new Position(file, start - (end - '; '.length)= ); +- } else { +- // Not possible; any comment following init is attached to init. +- exitPosition =3D _newPosition(forNode.rightParenthesis.offset); +- sb =3D new SourceBuilder(file, forNode.rightParenthesis.offset); +- } +- } +- } +- if (!_statementHasValidBody(forNode.forKeyword, forNode.body)) { +- // keywordOnly, noError +- sb.append(' '); +- _appendEmptyBraces(sb, true /*exitPosition =3D=3D null*/); +- } else if (forNode.body is Block) { +- Block body =3D forNode.body; +- if (body.rightBracket.end <=3D selectionOffset) { +- // emptyInitializersAfterBody +- errors =3D []; // Ignore errors; they are for previous statement. +- return false; // If cursor is after closing brace just add newlin= e. +- } +- } +- _insertBuilder(sb, replacementLength); +- _setCompletion(DartStatementCompletion.COMPLETE_FOR_STMT); +- return true; +- } +- +- bool _complete_functionDeclaration() { +- if (node is! MethodDeclaration && node is! FunctionDeclaration) { +- return false; +- } +- bool needsParen =3D false; +- int computeExitPos(FormalParameterList parameters) { +- if (needsParen =3D parameters.rightParenthesis.isSynthetic) { +- var error =3D _findError(ParserErrorCode.MISSING_CLOSING_PARENTHE= SIS); +- if (error !=3D null) { +- return error.offset - 1; +- } +- } +- return node.end - 1; +- } +- +- int paramListEnd; +- if (node is FunctionDeclaration) { +- FunctionDeclaration func =3D node; +- paramListEnd =3D computeExitPos(func.functionExpression.parameters); +- } else { +- MethodDeclaration meth =3D node; +- paramListEnd =3D computeExitPos(meth.parameters); +- } +- SourceBuilder sb =3D new SourceBuilder(file, paramListEnd); +- if (needsParen) { +- sb.append(')'); +- } +- sb.append(' '); +- _appendEmptyBraces(sb, true); +- _insertBuilder(sb); +- _setCompletion(DartStatementCompletion.COMPLETE_FUNCTION_DECLARATION); +- return true; +- } +- +- bool _complete_functionDeclarationStatement() { +- if (node is! FunctionDeclarationStatement) { +- return false; +- } +- var error =3D _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch= : "';'"); +- if (error !=3D null) { +- FunctionDeclarationStatement stmt =3D node; +- String src =3D utils.getNodeText(stmt); +- int insertOffset =3D stmt.functionDeclaration.end - 1; +- if (stmt.functionDeclaration.functionExpression.body +- is ExpressionFunctionBody) { +- ExpressionFunctionBody fnb =3D +- stmt.functionDeclaration.functionExpression.body; +- int fnbOffset =3D fnb.functionDefinition.offset; +- String fnSrc =3D src.substring(fnbOffset - stmt.offset); +- if (!fnSrc.startsWith('=3D>')) { +- return false; +- } +- int delta =3D 0; +- if (fnb.expression.isSynthetic) { +- if (!fnSrc.startsWith('=3D> ')) { +- _addInsertEdit(insertOffset, ' '); +- delta =3D 1; +- } +- _addInsertEdit(insertOffset, ';'); +- _appendNewlinePlusIndentAt(insertOffset); +- } else { +- delta =3D 1; +- _addInsertEdit(insertOffset, ';'); +- insertOffset =3D _appendNewlinePlusIndent(); +- } +- _setCompletionAt( +- DartStatementCompletion.SIMPLE_SEMICOLON, insertOffset + delt= a); +- return true; +- } +- } +- return false; +- } +- +- bool _complete_ifOrWhileStatement( +- _KeywordConditionBlockStructure statement, StatementCompletionKind = kind) { +- if (_statementHasValidBody(statement.keyword, statement.block)) { +- return false; +- } +- SourceBuilder sb =3D _complete_keywordCondition(statement); +- if (sb =3D=3D null) { +- return false; +- } +- int overshoot =3D _lengthOfDeletions(); +- sb.append(' '); +- _appendEmptyBraces(sb, exitPosition =3D=3D null); +- _insertBuilder(sb); +- if (overshoot !=3D 0) { +- exitPosition =3D _newPosition(exitPosition.offset - overshoot); +- } +- _setCompletion(kind); +- return true; +- } +- +- bool _complete_ifStatement() { +- if (node is! IfStatement) { +- return false; +- } +- IfStatement ifNode =3D node; +- if (ifNode.elseKeyword !=3D null) { +- if (selectionOffset >=3D ifNode.elseKeyword.end && +- ifNode.elseStatement is EmptyStatement) { +- SourceBuilder sb =3D new SourceBuilder(file, selectionOffset); +- String src =3D utils.getNodeText(ifNode); +- if (!src +- .substring(ifNode.elseKeyword.end - node.offset) +- .startsWith(new RegExp(r'[ \t]'))) { +- sb.append(' '); +- } +- _appendEmptyBraces(sb, true); +- _insertBuilder(sb); +- _setCompletion(DartStatementCompletion.COMPLETE_IF_STMT); +- return true; +- } +- return false; +- } +- var stmt =3D new _KeywordConditionBlockStructure( +- ifNode.ifKeyword, +- ifNode.leftParenthesis, +- ifNode.condition, +- ifNode.rightParenthesis, +- ifNode.thenStatement); +- return _complete_ifOrWhileStatement( +- stmt, DartStatementCompletion.COMPLETE_IF_STMT); +- } +- +- SourceBuilder _complete_keywordCondition( +- _KeywordConditionBlockStructure statement) { +- SourceBuilder sb; +- if (statement.leftParenthesis.isSynthetic) { +- if (!statement.rightParenthesis.isSynthetic) { +- // Quite unlikely to see this so don't try to fix it. +- return null; +- } +- sb =3D _sourceBuilderAfterKeyword(statement.keyword); +- sb.append('('); +- sb.setExitOffset(); +- sb.append(')'); +- } else { +- if (_isSyntheticExpression(statement.condition)) { +- exitPosition =3D _newPosition(statement.leftParenthesis.offset + = 1); +- sb =3D new SourceBuilder(file, statement.rightParenthesis.offset = + 1); +- } else { +- int afterParen =3D statement.rightParenthesis.offset + 1; +- if (utils +- .getNodeText(node) +- .substring(afterParen - node.offset) +- .startsWith(new RegExp(r'[ \t]'))) { +- _addReplaceEdit(new SourceRange(afterParen, 1), ''); +- sb =3D new SourceBuilder(file, afterParen + 1); +- } else { +- sb =3D new SourceBuilder(file, afterParen); +- } +- } +- } +- return sb; +- } +- +- bool _complete_methodCall() { +- var parenError =3D +- _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "')'") ?? +- _findError(ScannerErrorCode.EXPECTED_TOKEN, partialMatch: "')= '"); +- if (parenError =3D=3D null) { +- return false; +- } +- AstNode argList =3D _selectedNode(at: selectionOffset) +- .getAncestor((n) =3D> n is ArgumentList); +- if (argList =3D=3D null) { +- argList =3D _selectedNode(at: parenError.offset) +- .getAncestor((n) =3D> n is ArgumentList); +- } +- if (argList?.getAncestor((n) =3D> n =3D=3D node) =3D=3D null) { +- return false; +- } +- int previousInsertions =3D _lengthOfInsertions(); +- int loc =3D min(selectionOffset, argList.end - 1); +- int delta =3D 1; +- var semicolonError =3D +- _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch: "';'"); +- if (semicolonError =3D=3D null) { +- loc +=3D 1; +- delta =3D 0; +- } +- _addInsertEdit(loc, ')'); +- if (semicolonError !=3D null) { +- _addInsertEdit(loc, ';'); +- } +- String indent =3D utils.getLinePrefix(selectionOffset); +- int exit =3D utils.getLineNext(selectionOffset); +- _addInsertEdit(exit, indent + eol); +- exit +=3D indent.length + eol.length + previousInsertions; +- +- _setCompletionAt(DartStatementCompletion.SIMPLE_ENTER, exit + delta); +- return true; +- } +- +- bool _complete_simpleEnter() { +- int offset; +- if (!errors.isEmpty) { +- offset =3D selectionOffset; +- } else { +- String indent =3D utils.getLinePrefix(selectionOffset); +- int loc =3D utils.getLineNext(selectionOffset); +- _addInsertEdit(loc, indent + eol); +- offset =3D loc + indent.length; +- } +- _setCompletionAt(DartStatementCompletion.SIMPLE_ENTER, offset); +- return true; +- } +- +- bool _complete_simpleSemicolon() { +- if (errors.length !=3D 1) { +- return false; +- } +- var error =3D _findError(ParserErrorCode.EXPECTED_TOKEN, partialMatch= : "';'"); +- if (error !=3D null) { +- int previousInsertions =3D _lengthOfInsertions(); +- // TODO(messick) Fix this to find the correct place in all cases. +- int insertOffset =3D error.offset + error.length; +- _addInsertEdit(insertOffset, ';'); +- int offset =3D _appendNewlinePlusIndent() + 1 /*';'*/ + previousIns= ertions; +- _setCompletionAt(DartStatementCompletion.SIMPLE_SEMICOLON, offset); +- return true; +- } +- return false; +- } +- +- bool _complete_switchStatement() { +- if (node is! SwitchStatement) { +- return false; +- } +- SourceBuilder sb; +- SwitchStatement switchNode =3D node; +- if (switchNode.leftParenthesis.isSynthetic && +- switchNode.rightParenthesis.isSynthetic) { +- exitPosition =3D new Position(file, switchNode.switchKeyword.end + = 2); +- String src =3D utils.getNodeText(switchNode); +- if (src +- .substring(switchNode.switchKeyword.end - switchNode.offset) +- .startsWith(new RegExp(r'[ \t]+'))) { +- sb =3D new SourceBuilder(file, switchNode.switchKeyword.end + 1); +- } else { +- sb =3D new SourceBuilder(file, switchNode.switchKeyword.end); +- sb.append(' '); +- } +- sb.append('()'); +- } else if (switchNode.leftParenthesis.isSynthetic || +- switchNode.rightParenthesis.isSynthetic) { +- return false; +- } else { +- sb =3D new SourceBuilder(file, switchNode.rightParenthesis.offset += 1); +- if (_isSyntheticExpression(switchNode.expression)) { +- exitPosition =3D +- new Position(file, switchNode.leftParenthesis.offset + 1); +- } +- } +- if (switchNode +- .leftBracket.isSynthetic /*&& switchNode.rightBracket.isSynthetic= */) { +- // See https://github.com/dart-lang/sdk/issues/29391 +- sb.append(' '); +- _appendEmptyBraces(sb, exitPosition =3D=3D null); +- } else { +- SwitchMember member =3D _findInvalidElement(switchNode.members); +- if (member !=3D null) { +- if (member.colon.isSynthetic) { +- int loc =3D +- member is SwitchCase ? member.expression.end : member.keywo= rd.end; +- sb =3D new SourceBuilder(file, loc); +- sb.append(': '); +- exitPosition =3D new Position(file, loc + 2); +- } +- } +- } +- _insertBuilder(sb); +- _setCompletion(DartStatementCompletion.COMPLETE_SWITCH_STMT); +- return true; +- } +- +- bool _complete_tryStatement() { +- if (node is! TryStatement) { +- return false; +- } +- TryStatement tryNode =3D node; +- SourceBuilder sb; +- CatchClause catchNode; +- bool addSpace =3D true; +- if (tryNode.body.leftBracket.isSynthetic) { +- String src =3D utils.getNodeText(tryNode); +- if (src +- .substring(tryNode.tryKeyword.end - tryNode.offset) +- .startsWith(new RegExp(r'[ \t]+'))) { +- // keywordSpace +- sb =3D new SourceBuilder(file, tryNode.tryKeyword.end + 1); +- } else { +- // keywordOnly +- sb =3D new SourceBuilder(file, tryNode.tryKeyword.end); +- sb.append(' '); +- } +- _appendEmptyBraces(sb, true); +- _insertBuilder(sb); +- sb =3D null; +- } else if ((catchNode =3D _findInvalidElement(tryNode.catchClauses)) = !=3D +- null) { +- if (catchNode.onKeyword !=3D null) { +- if (catchNode.exceptionType.length =3D=3D 0 || +- null !=3D +- _findError(StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE, +- partialMatch: "name 'catch")) { +- String src =3D utils.getNodeText(catchNode); +- if (src.startsWith(new RegExp(r'on[ \t]+'))) { +- if (src.startsWith(new RegExp(r'on[ \t][ \t]+'))) { +- // onSpaces +- exitPosition =3D new Position(file, catchNode.onKeyword.end= + 1); +- sb =3D new SourceBuilder(file, catchNode.onKeyword.end + 2); +- addSpace =3D false; +- } else { +- // onSpace +- sb =3D new SourceBuilder(file, catchNode.onKeyword.end + 1); +- sb.setExitOffset(); +- } +- } else { +- // onOnly +- sb =3D new SourceBuilder(file, catchNode.onKeyword.end); +- sb.append(' '); +- sb.setExitOffset(); +- } +- } else { +- // onType +- sb =3D new SourceBuilder(file, catchNode.exceptionType.end); +- } +- } +- if (catchNode.catchKeyword !=3D null) { +- // catchOnly +- var struct =3D new _KeywordConditionBlockStructure( +- catchNode.catchKeyword, +- catchNode.leftParenthesis, +- catchNode.exceptionParameter, +- catchNode.rightParenthesis, +- catchNode.body); +- if (sb !=3D null) { +- // onCatch +- _insertBuilder(sb); +- } +- sb =3D _complete_keywordCondition(struct); +- if (sb =3D=3D null) { +- return false; +- } +- } +- if (catchNode.body.leftBracket.isSynthetic) { +- // onOnly and others +- if (addSpace) { +- sb.append(' '); +- } +- _appendEmptyBraces(sb, exitPosition =3D=3D null); +- } +- _insertBuilder(sb); +- } else if (tryNode.finallyKeyword !=3D null) { +- if (tryNode.finallyBlock.leftBracket.isSynthetic) { +- // finallyOnly +- sb =3D new SourceBuilder(file, tryNode.finallyKeyword.end); +- sb.append(' '); +- _appendEmptyBraces(sb, true); +- _insertBuilder(sb); +- } +- } +- _setCompletion(DartStatementCompletion.COMPLETE_TRY_STMT); +- return true; +- } +- +- bool _complete_variableDeclaration() { +- if (node is! VariableDeclaration) { +- return false; +- } +- _addInsertEdit(node.end, ';'); +- exitPosition =3D new Position(file, _appendNewlinePlusIndentAt(node.e= nd) + 1); +- _setCompletion(DartStatementCompletion.COMPLETE_VARIABLE_DECLARATION); +- return true; +- } +- +- bool _complete_whileStatement() { +- if (node is! WhileStatement) { +- return false; +- } +- WhileStatement whileNode =3D node; +- if (whileNode !=3D null) { +- var stmt =3D new _KeywordConditionBlockStructure( +- whileNode.whileKeyword, +- whileNode.leftParenthesis, +- whileNode.condition, +- whileNode.rightParenthesis, +- whileNode.body); +- return _complete_ifOrWhileStatement( +- stmt, DartStatementCompletion.COMPLETE_WHILE_STMT); +- } +- return false; +- } +- +- engine.AnalysisError _findError(ErrorCode code, {partialMatch: null}) { +- return errors.firstWhere( +- (err) =3D> +- err.errorCode =3D=3D code && +- (partialMatch =3D=3D null ? true : err.message.contains(parti= alMatch)), +- orElse: () =3D> null); +- } +- +- T _findInvalidElement(NodeList list) { +- return list.firstWhere( +- (item) =3D> selectionOffset >=3D item.offset && selectionOffset <= =3D item.end, +- orElse: () =3D> null); +- } +- +- LinkedEditGroup _getLinkedPosition(String groupId) { +- LinkedEditGroup group =3D linkedPositionGroups[groupId]; +- if (group =3D=3D null) { +- group =3D new LinkedEditGroup.empty(); +- linkedPositionGroups[groupId] =3D group; +- } +- return group; +- } +- +- void _insertBuilder(SourceBuilder builder, [int length =3D 0]) { +- { +- SourceRange range =3D new SourceRange(builder.offset, length); +- String text =3D builder.toString(); +- _addReplaceEdit(range, text); +- } +- // add linked positions +- builder.linkedPositionGroups.forEach((String id, LinkedEditGroup grou= p) { +- LinkedEditGroup fixGroup =3D _getLinkedPosition(id); +- group.positions.forEach((Position position) { +- fixGroup.addPosition(position, group.length); +- }); +- group.suggestions.forEach((LinkedEditSuggestion suggestion) { +- fixGroup.addSuggestion(suggestion); +- }); +- }); +- // add exit position +- { +- int exitOffset =3D builder.exitOffset; +- if (exitOffset !=3D null) { +- exitPosition =3D _newPosition(exitOffset); +- } +- } +- } +- +- bool _isEmptyBlock(AstNode stmt) { +- return stmt is Block && stmt.statements.isEmpty; +- } +- +- bool _isEmptyStatement(AstNode stmt) { +- return stmt is EmptyStatement || _isEmptyBlock(stmt); +- } +- +- bool _isNonStatementDeclaration(AstNode n) { +- if (n is! Declaration) { +- return false; +- } +- if (n is! VariableDeclaration && n is! FunctionDeclaration) { +- return true; +- } +- AstNode p =3D n.parent; +- return p is! Statement && p?.parent is! Statement; +- } +- +- bool _isSyntheticExpression(Expression expr) { +- return expr is SimpleIdentifier && expr.isSynthetic; +- } +- +- int _lengthOfDeletions() { +- if (change.edits.isEmpty) { +- return 0; +- } +- int length =3D 0; +- for (SourceFileEdit edit in change.edits) { +- for (SourceEdit srcEdit in edit.edits) { +- if (srcEdit.length > 0) { +- length +=3D srcEdit.length - srcEdit.replacement.length; +- } +- } +- } +- return length; +- } +- +- int _lengthOfInsertions() { +- // Any _complete_*() that may follow changes made by _checkExpression= s() +- // must cache the result of this method and add that value to its +- // exit position. That's assuming all edits are done in increasing po= sition. +- // There are currently no editing sequences that produce both inserti= ons and +- // deletions, but if there were this approach would have to be genera= lized. +- if (change.edits.isEmpty) { +- return 0; +- } +- int length =3D 0; +- for (SourceFileEdit edit in change.edits) { +- for (SourceEdit srcEdit in edit.edits) { +- if (srcEdit.length =3D=3D 0) { +- length +=3D srcEdit.replacement.length; +- } +- } +- } +- return length; +- } +- +- Position _newPosition(int offset) { +- return new Position(file, offset); +- } +- +- void _removeError(errorCode, {partialMatch =3D null}) { +- var error =3D _findError(errorCode, partialMatch: partialMatch); +- if (error !=3D null) { +- errors.remove(error); +- } +- } +- +- AstNode _selectedNode({int at: null}) =3D> +- new NodeLocator(at =3D=3D null ? selectionOffset : at).searchWithin= (unit); +- +- void _setCompletion(StatementCompletionKind kind, [List args]) { +- assert(exitPosition !=3D null); +- change.selection =3D exitPosition; +- change.message =3D formatList(kind.message, args); +- linkedPositionGroups.values +- .forEach((group) =3D> change.addLinkedEditGroup(group)); +- completion =3D new StatementCompletion(kind, change); +- } +- +- void _setCompletionAt(StatementCompletionKind kind, int offset, [List a= rgs]) { +- exitPosition =3D _newPosition(offset); +- _setCompletion(kind, args); +- } +- +- SourceBuilder _sourceBuilderAfterKeyword(Token keyword) { +- SourceBuilder sb; +- String text =3D _baseNodeText(node); +- text =3D text.substring(keyword.offset - node.offset); +- int len =3D keyword.length; +- if (text.length =3D=3D len || // onCatchComment +- !text.substring(len, len + 1).contains(new RegExp(r'[ \t]'))) { +- sb =3D new SourceBuilder(file, keyword.offset + len); +- sb.append(' '); +- } else { +- sb =3D new SourceBuilder(file, keyword.offset + len + 1); +- } +- return sb; +- } +- +- bool _statementHasValidBody(Token keyword, Statement body) { +- // A "valid" body is either a non-synthetic block or a single stateme= nt +- // on the same line as the parent statement, similar to dart_style. +- if (body.isSynthetic) { +- return false; +- } +- if (body is Block) { +- Block block =3D body; +- return (!(block.leftBracket.isSynthetic)); +- } +- return (lineInfo.getLocation(keyword.offset) =3D=3D +- lineInfo.getLocation(body.offset)); +- } +-} +- +-// Encapsulate common structure of if-statement and while-statement. +-class _KeywordConditionBlockStructure { +- final Token keyword; +- final Token leftParenthesis, rightParenthesis; +- final Expression condition; +- final Statement block; +- +- _KeywordConditionBlockStructure(this.keyword, this.leftParenthesis, +- this.condition, this.rightParenthesis, this.block); +- +- int get offset =3D> keyword.offset; +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/assist.dart b= /pkg/analysis_server/lib/src/services/correction/assist.dart +deleted file mode 100644 +index 013e7cec40c..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/assist.dart ++++ /dev/null +@@ -1,126 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/plugin/edit/assist/assist_core.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/assist/assist.dart'; +- +-/** +- * The implementation of [AssistContext]. +- */ +-class AssistContextImpl implements AssistContext { +- @override +- final AnalysisDriver analysisDriver; +- +- @override +- final Source source; +- +- @override +- final int selectionOffset; +- +- @override +- final int selectionLength; +- +- AssistContextImpl(this.analysisDriver, this.source, this.selectionOffse= t, +- this.selectionLength); +-} +- +-/** +- * An enumeration of possible assist kinds. +- */ +-class DartAssistKind { +- static const ADD_PART_DIRECTIVE =3D +- const AssistKind('ADD_PART_DIRECTIVE', 30, "Add 'part' directive"); +- static const ADD_TYPE_ANNOTATION =3D +- const AssistKind('ADD_TYPE_ANNOTATION', 30, "Add type annotation"); +- static const ASSIGN_TO_LOCAL_VARIABLE =3D const AssistKind( +- 'ASSIGN_TO_LOCAL_VARIABLE', 30, "Assign value to new local variable= "); +- static const CONVERT_DOCUMENTATION_INTO_BLOCK =3D const AssistKind( +- 'CONVERT_DOCUMENTATION_INTO_BLOCK', +- 30, +- "Convert into block documentation comment"); +- static const CONVERT_DOCUMENTATION_INTO_LINE =3D const AssistKind( +- 'CONVERT_DOCUMENTATION_INTO_LINE', +- 30, +- "Convert into line documentation comment"); +- static const CONVERT_FLUTTER_CHILD =3D +- const AssistKind('CONVERT_FLUTTER_CHILD', 30, "Convert to children:= "); +- static const CONVERT_INTO_BLOCK_BODY =3D const AssistKind( +- 'CONVERT_INTO_BLOCK_BODY', 30, "Convert into block body"); +- static const CONVERT_INTO_EXPRESSION_BODY =3D const AssistKind( +- 'CONVERT_INTO_EXPRESSION_BODY', 30, "Convert into expression body"); +- static const CONVERT_INTO_FOR_INDEX =3D const AssistKind( +- 'CONVERT_INTO_FOR_INDEX', 30, "Convert into for-index loop"); +- static const CONVERT_INTO_FINAL_FIELD =3D const AssistKind( +- 'CONVERT_INTO_FINAL_FIELD', 30, "Convert into final field"); +- static const CONVERT_INTO_GETTER =3D +- const AssistKind('CONVERT_INTO_GETTER', 30, "Convert into getter"); +- static const CONVERT_INTO_IS_NOT =3D +- const AssistKind('CONVERT_INTO_IS_NOT', 30, "Convert into is!"); +- static const CONVERT_INTO_IS_NOT_EMPTY =3D const AssistKind( +- 'CONVERT_INTO_IS_NOT_EMPTY', 30, "Convert into 'isNotEmpty'"); +- static const CONVERT_PART_OF_TO_URI =3D +- const AssistKind('CONVERT_PART_OF_TO_URI', 30, "Convert to use a UR= I"); +- static const CONVERT_TO_FIELD_PARAMETER =3D const AssistKind( +- 'CONVERT_TO_FIELD_PARAMETER', 30, "Convert to field formal paramete= r"); +- static const CONVERT_TO_NORMAL_PARAMETER =3D const AssistKind( +- 'CONVERT_TO_NORMAL_PARAMETER', 30, "Convert to normal parameter"); +- static const ENCAPSULATE_FIELD =3D +- const AssistKind('ENCAPSULATE_FIELD', 30, "Encapsulate field"); +- static const EXCHANGE_OPERANDS =3D +- const AssistKind('EXCHANGE_OPERANDS', 30, "Exchange operands"); +- static const EXTRACT_CLASS =3D +- const AssistKind('EXTRACT_CLASS', 30, "Extract class into file '{0}= '"); +- static const IMPORT_ADD_SHOW =3D +- const AssistKind('IMPORT_ADD_SHOW', 30, "Add explicit 'show' combin= ator"); +- static const INTRODUCE_LOCAL_CAST_TYPE =3D const AssistKind( +- 'INTRODUCE_LOCAL_CAST_TYPE', 30, "Introduce new local with tested t= ype"); +- static const INVERT_IF_STATEMENT =3D +- const AssistKind('INVERT_IF_STATEMENT', 30, "Invert 'if' statement"= ); +- static const JOIN_IF_WITH_INNER =3D const AssistKind('JOIN_IF_WITH_INNE= R', 30, +- "Join 'if' statement with inner 'if' statement"); +- static const JOIN_IF_WITH_OUTER =3D const AssistKind('JOIN_IF_WITH_OUTE= R', 30, +- "Join 'if' statement with outer 'if' statement"); +- static const JOIN_VARIABLE_DECLARATION =3D const AssistKind( +- 'JOIN_VARIABLE_DECLARATION', 30, "Join variable declaration"); +- static const MOVE_FLUTTER_WIDGET_DOWN =3D +- const AssistKind("MOVE_FLUTTER_WIDGET_DOWN", 30, "Move widget down"= ); +- static const MOVE_FLUTTER_WIDGET_UP =3D +- const AssistKind("MOVE_FLUTTER_WIDGET_UP", 30, "Move widget up"); +- static const REPARENT_FLUTTER_LIST =3D +- const AssistKind("REPARENT_FLUTTER_LIST", 30, "Wrap with new widget= "); +- static const REPARENT_FLUTTER_WIDGET =3D +- const AssistKind("REPARENT_FLUTTER_WIDGET", 30, "Wrap with new widg= et"); +- static const REMOVE_TYPE_ANNOTATION =3D +- const AssistKind('REMOVE_TYPE_ANNOTATION', 29, "Remove type annotat= ion"); +- static const REPLACE_CONDITIONAL_WITH_IF_ELSE =3D const AssistKind( +- 'REPLACE_CONDITIONAL_WITH_IF_ELSE', +- 30, +- "Replace conditional with 'if-else'"); +- static const REPLACE_IF_ELSE_WITH_CONDITIONAL =3D const AssistKind( +- 'REPLACE_IF_ELSE_WITH_CONDITIONAL', +- 30, +- "Replace 'if-else' with conditional ('c ? x : y')"); +- static const SPLIT_AND_CONDITION =3D +- const AssistKind('SPLIT_AND_CONDITION', 30, "Split && condition"); +- static const SPLIT_VARIABLE_DECLARATION =3D const AssistKind( +- 'SPLIT_VARIABLE_DECLARATION', 30, "Split variable declaration"); +- static const SURROUND_WITH_BLOCK =3D +- const AssistKind('SURROUND_WITH_BLOCK', 30, "Surround with block"); +- static const SURROUND_WITH_DO_WHILE =3D const AssistKind( +- 'SURROUND_WITH_DO_WHILE', 30, "Surround with 'do-while'"); +- static const SURROUND_WITH_FOR =3D +- const AssistKind('SURROUND_WITH_FOR', 30, "Surround with 'for'"); +- static const SURROUND_WITH_FOR_IN =3D +- const AssistKind('SURROUND_WITH_FOR_IN', 30, "Surround with 'for-in= '"); +- static const SURROUND_WITH_IF =3D +- const AssistKind('SURROUND_WITH_IF', 30, "Surround with 'if'"); +- static const SURROUND_WITH_TRY_CATCH =3D const AssistKind( +- 'SURROUND_WITH_TRY_CATCH', 30, "Surround with 'try-catch'"); +- static const SURROUND_WITH_TRY_FINALLY =3D const AssistKind( +- 'SURROUND_WITH_TRY_FINALLY', 30, "Surround with 'try-finally'"); +- static const SURROUND_WITH_WHILE =3D +- const AssistKind('SURROUND_WITH_WHILE', 30, "Surround with 'while'"= ); +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/assist_intern= al.dart b/pkg/analysis_server/lib/src/services/correction/assist_internal.d= art +deleted file mode 100644 +index 4ca94bf1d18..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/assist_internal.dart ++++ /dev/null +@@ -1,2617 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analysis_server/plugin/edit/assist/assist_core.dart'; +-import 'package:analysis_server/plugin/edit/assist/assist_dart.dart'; +-import 'package:analysis_server/src/services/correction/assist.dart'; +-import 'package:analysis_server/src/services/correction/name_suggestion.d= art'; +-import 'package:analysis_server/src/services/correction/statement_analyze= r.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/utilities/flutter.dart' as flutter; +-import 'package:analyzer/dart/analysis/session.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/ast/token.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/resolver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +-import 'package:analyzer_plugin/utilities/assist/assist.dart' +- hide AssistContributor; +-import 'package:analyzer_plugin/utilities/change_builder/change_builder_d= art.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +-import 'package:path/path.dart'; +- +-typedef _SimpleIdentifierVisitor(SimpleIdentifier node); +- +-/** +- * The computer for Dart assists. +- */ +-class AssistProcessor { +- /** +- * The analysis driver being used to perform analysis. +- */ +- AnalysisDriver driver; +- +- Source source; +- String file; +- +- CompilationUnit unit; +- CompilationUnitElement unitElement; +- +- LibraryElement unitLibraryElement; +- String unitLibraryFile; +- String unitLibraryFolder; +- +- int selectionOffset; +- int selectionLength; +- int selectionEnd; +- +- final List assists =3D []; +- +- Position exitPosition =3D null; +- +- CorrectionUtils utils; +- +- AstNode node; +- +- TypeProvider _typeProvider; +- +- AssistProcessor(DartAssistContext dartContext) { +- driver =3D dartContext.analysisDriver; +- // source +- source =3D dartContext.source; +- file =3D dartContext.source.fullName; +- // unit +- unit =3D dartContext.unit; +- unitElement =3D dartContext.unit.element; +- // library +- unitLibraryElement =3D resolutionMap +- .elementDeclaredByCompilationUnit(dartContext.unit) +- .library; +- unitLibraryFile =3D unitLibraryElement.source.fullName; +- unitLibraryFolder =3D dirname(unitLibraryFile); +- // selection +- selectionOffset =3D dartContext.selectionOffset; +- selectionLength =3D dartContext.selectionLength; +- selectionEnd =3D selectionOffset + selectionLength; +- } +- +- /** +- * Returns the EOL to use for this [CompilationUnit]. +- */ +- String get eol =3D> utils.endOfLine; +- +- /** +- * Return the analysis session to be used to create the change builder. +- */ +- AnalysisSession get session =3D> driver.currentSession; +- +- TypeProvider get typeProvider { +- if (_typeProvider =3D=3D null) { +- _typeProvider =3D unitElement.context.typeProvider; +- } +- return _typeProvider; +- } +- +- Future> compute() async { +- try { +- utils =3D new CorrectionUtils(unit); +- } catch (e) { +- throw new CancelCorrectionException(exception: e); +- } +- +- node =3D new NodeLocator(selectionOffset, selectionEnd).searchWithin(= unit); +- if (node =3D=3D null) { +- return assists; +- } +- +- await _addProposal_addTypeAnnotation_DeclaredIdentifier(); +- await _addProposal_addTypeAnnotation_SimpleFormalParameter(); +- await _addProposal_addTypeAnnotation_VariableDeclaration(); +- await _addProposal_assignToLocalVariable(); +- await _addProposal_convertIntoFinalField(); +- await _addProposal_convertIntoGetter(); +- await _addProposal_convertDocumentationIntoBlock(); +- await _addProposal_convertDocumentationIntoLine(); +- await _addProposal_convertToBlockFunctionBody(); +- await _addProposal_convertToExpressionFunctionBody(); +- await _addProposal_convertFlutterChild(); +- await _addProposal_convertPartOfToUri(); +- await _addProposal_convertToForIndexLoop(); +- await _addProposal_convertToIsNot_onIs(); +- await _addProposal_convertToIsNot_onNot(); +- await _addProposal_convertToIsNotEmpty(); +- await _addProposal_convertToFieldParameter(); +- await _addProposal_convertToNormalParameter(); +- await _addProposal_encapsulateField(); +- await _addProposal_exchangeOperands(); +- await _addProposal_importAddShow(); +- await _addProposal_introduceLocalTestedType(); +- await _addProposal_invertIf(); +- await _addProposal_joinIfStatementInner(); +- await _addProposal_joinIfStatementOuter(); +- await _addProposal_joinVariableDeclaration_onAssignment(); +- await _addProposal_joinVariableDeclaration_onDeclaration(); +- await _addProposal_moveFlutterWidgetDown(); +- await _addProposal_moveFlutterWidgetUp(); +- await _addProposal_removeTypeAnnotation(); +- await _addProposal_reparentFlutterList(); +- await _addProposal_reparentFlutterWidget(); +- await _addProposal_replaceConditionalWithIfElse(); +- await _addProposal_replaceIfElseWithConditional(); +- await _addProposal_splitAndCondition(); +- await _addProposal_splitVariableDeclaration(); +- await _addProposal_surroundWith(); +- +- return assists; +- } +- +- FunctionBody getEnclosingFunctionBody() { +- { +- FunctionExpression function =3D +- node.getAncestor((node) =3D> node is FunctionExpression); +- if (function !=3D null) { +- return function.body; +- } +- } +- { +- FunctionDeclaration function =3D +- node.getAncestor((node) =3D> node is FunctionDeclaration); +- if (function !=3D null) { +- return function.functionExpression.body; +- } +- } +- { +- ConstructorDeclaration constructor =3D +- node.getAncestor((node) =3D> node is ConstructorDeclaration); +- if (constructor !=3D null) { +- return constructor.body; +- } +- } +- { +- MethodDeclaration method =3D +- node.getAncestor((node) =3D> node is MethodDeclaration); +- if (method !=3D null) { +- return method.body; +- } +- } +- return null; +- } +- +- void _addAssistFromBuilder(DartChangeBuilder builder, AssistKind kind, +- {List args: null}) { +- SourceChange change =3D builder.sourceChange; +- if (change.edits.isEmpty) { +- _coverageMarker(); +- return; +- } +- change.message =3D formatList(kind.message, args); +- assists.add(new Assist(kind, change)); +- } +- +- Future _addProposal_addTypeAnnotation_DeclaredIdentifier() async { +- DeclaredIdentifier declaredIdentifier =3D +- node.getAncestor((n) =3D> n is DeclaredIdentifier); +- if (declaredIdentifier =3D=3D null) { +- ForEachStatement forEach =3D node.getAncestor((n) =3D> n is ForEach= Statement); +- int offset =3D node.offset; +- if (forEach !=3D null && +- forEach.iterable !=3D null && +- offset < forEach.iterable.offset) { +- declaredIdentifier =3D forEach.loopVariable; +- } +- } +- if (declaredIdentifier =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // Ensure that there isn't already a type annotation. +- if (declaredIdentifier.type !=3D null) { +- _coverageMarker(); +- return; +- } +- DartType type =3D declaredIdentifier.identifier.bestType; +- if (type is! InterfaceType && type is! FunctionType) { +- _coverageMarker(); +- return; +- } +- _configureTargetLocation(node); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- bool validChange =3D true; +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- Token keyword =3D declaredIdentifier.keyword; +- if (keyword.keyword =3D=3D Keyword.VAR) { +- builder.addReplacement(range.token(keyword), (DartEditBuilder bui= lder) { +- validChange =3D builder.writeType(type); +- }); +- } else { +- builder.addInsertion(declaredIdentifier.identifier.offset, +- (DartEditBuilder builder) { +- validChange =3D builder.writeType(type); +- builder.write(' '); +- }); +- } +- }); +- if (validChange) { +- _addAssistFromBuilder(changeBuilder, DartAssistKind.ADD_TYPE_ANNOTA= TION); +- } +- } +- +- Future _addProposal_addTypeAnnotation_SimpleFormalParameter() asy= nc { +- AstNode node =3D this.node; +- // should be the name of a simple parameter +- if (node is! SimpleIdentifier || node.parent is! SimpleFormalParamete= r) { +- _coverageMarker(); +- return; +- } +- SimpleIdentifier name =3D node; +- SimpleFormalParameter parameter =3D node.parent; +- // the parameter should not have a type +- if (parameter.type !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare the type +- DartType type =3D parameter.element.type; +- // TODO(scheglov) If the parameter is in a method declaration, and if= the +- // method overrides a method that has a type for the corresponding +- // parameter, it would be nice to copy down the type from the overrid= den +- // method. +- if (type is! InterfaceType) { +- _coverageMarker(); +- return; +- } +- // prepare type source +- _configureTargetLocation(node); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- bool validChange =3D true; +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(name.offset, (DartEditBuilder builder) { +- validChange =3D builder.writeType(type); +- builder.write(' '); +- }); +- }); +- if (validChange) { +- _addAssistFromBuilder(changeBuilder, DartAssistKind.ADD_TYPE_ANNOTA= TION); +- } +- } +- +- Future _addProposal_addTypeAnnotation_VariableDeclaration() async= { +- AstNode node =3D this.node; +- // prepare VariableDeclarationList +- VariableDeclarationList declarationList =3D +- node.getAncestor((node) =3D> node is VariableDeclarationList); +- if (declarationList =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // may be has type annotation already +- if (declarationList.type !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare single VariableDeclaration +- List variables =3D declarationList.variables; +- if (variables.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- VariableDeclaration variable =3D variables[0]; +- // must be not after the name of the variable +- if (selectionOffset > variable.name.end) { +- _coverageMarker(); +- return; +- } +- // we need an initializer to get the type from +- Expression initializer =3D variable.initializer; +- if (initializer =3D=3D null) { +- _coverageMarker(); +- return; +- } +- DartType type =3D initializer.bestType; +- // prepare type source +- if ((type is! InterfaceType || type.isDartCoreNull) && +- type is! FunctionType) { +- _coverageMarker(); +- return; +- } +- _configureTargetLocation(node); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- bool validChange =3D true; +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- Token keyword =3D declarationList.keyword; +- if (keyword?.keyword =3D=3D Keyword.VAR) { +- builder.addReplacement(range.token(keyword), (DartEditBuilder bui= lder) { +- validChange =3D builder.writeType(type); +- }); +- } else { +- builder.addInsertion(variable.offset, (DartEditBuilder builder) { +- validChange =3D builder.writeType(type); +- builder.write(' '); +- }); +- } +- }); +- if (validChange) { +- _addAssistFromBuilder(changeBuilder, DartAssistKind.ADD_TYPE_ANNOTA= TION); +- } +- } +- +- Future _addProposal_assignToLocalVariable() async { +- // prepare enclosing ExpressionStatement +- ExpressionStatement expressionStatement; +- for (AstNode node =3D this.node; node !=3D null; node =3D node.parent= ) { +- if (node is ExpressionStatement) { +- expressionStatement =3D node; +- break; +- } +- if (node is ArgumentList || +- node is AssignmentExpression || +- node is Statement || +- node is ThrowExpression) { +- _coverageMarker(); +- return; +- } +- } +- if (expressionStatement =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare expression +- Expression expression =3D expressionStatement.expression; +- int offset =3D expression.offset; +- // prepare expression type +- DartType type =3D expression.bestType; +- if (type.isVoid) { +- _coverageMarker(); +- return; +- } +- // prepare excluded names +- Set excluded =3D new Set(); +- ScopedNameFinder scopedNameFinder =3D new ScopedNameFinder(offset); +- expression.accept(scopedNameFinder); +- excluded.addAll(scopedNameFinder.locals.keys.toSet()); +- List suggestions =3D +- getVariableNameSuggestionsForExpression(type, expression, exclude= d); +- +- if (suggestions.isNotEmpty) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addInsertion(offset, (DartEditBuilder builder) { +- builder.write('var '); +- builder.addSimpleLinkedEdit('NAME', suggestions[0], +- kind: LinkedEditSuggestionKind.VARIABLE, +- suggestions: suggestions); +- builder.write(' =3D '); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.ASSIGN_TO_LOCAL_VARIABLE); +- } +- } +- +- Future _addProposal_convertDocumentationIntoBlock() async { +- Comment comment =3D node.getAncestor((n) =3D> n is Comment); +- if (comment =3D=3D null || !comment.isDocumentation) { +- return; +- } +- var tokens =3D comment.tokens; +- if (tokens.isEmpty || +- tokens.any((Token token) =3D> +- token is! DocumentationCommentToken || +- token.type !=3D TokenType.SINGLE_LINE_COMMENT)) { +- return; +- } +- String prefix =3D utils.getNodePrefix(comment); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(comment), (DartEditBuilder builde= r) { +- builder.writeln('/**'); +- for (Token token in comment.tokens) { +- builder.write(prefix); +- builder.write(' *'); +- builder.writeln(token.lexeme.substring('///'.length)); +- } +- builder.write(prefix); +- builder.write(' */'); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_DOCUMENTATION_INTO_BLOCK); +- } +- +- Future _addProposal_convertDocumentationIntoLine() async { +- Comment comment =3D node.getAncestor((n) =3D> n is Comment); +- if (comment =3D=3D null || +- !comment.isDocumentation || +- comment.tokens.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- Token token =3D comment.tokens.first; +- if (token.type !=3D TokenType.MULTI_LINE_COMMENT) { +- _coverageMarker(); +- return; +- } +- String text =3D token.lexeme; +- List lines =3D text.split('\n'); +- String prefix =3D utils.getNodePrefix(comment); +- List newLines =3D []; +- bool firstLine =3D true; +- String linePrefix =3D ''; +- for (String line in lines) { +- if (firstLine) { +- firstLine =3D false; +- String expectedPrefix =3D '/**'; +- if (!line.startsWith(expectedPrefix)) { +- _coverageMarker(); +- return; +- } +- line =3D line.substring(expectedPrefix.length).trim(); +- if (line.isNotEmpty) { +- newLines.add('/// $line'); +- linePrefix =3D eol + prefix; +- } +- } else { +- if (line.startsWith(prefix + ' */')) { +- break; +- } +- String expectedPrefix =3D prefix + ' * '; +- if (!line.startsWith(expectedPrefix)) { +- _coverageMarker(); +- return; +- } +- line =3D line.substring(expectedPrefix.length).trim(); +- newLines.add('$linePrefix/// $line'); +- linePrefix =3D eol + prefix; +- } +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(comment), (DartEditBuilder builde= r) { +- for (String newLine in newLines) { +- builder.write(newLine); +- } +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_DOCUMENTATION_INTO_LINE); +- } +- +- Future _addProposal_convertFlutterChild() async { +- NamedExpression namedExp; +- // Allow assist to activate from either the new-expr or the child: ar= g. +- if (node is SimpleIdentifier && +- node.parent is Label && +- node.parent.parent is NamedExpression) { +- namedExp =3D node.parent.parent as NamedExpression; +- if ((node as SimpleIdentifier).name !=3D 'child' || +- namedExp.expression =3D=3D null) { +- return; +- } +- if (namedExp.parent?.parent is! InstanceCreationExpression) { +- return; +- } +- InstanceCreationExpression newExpr =3D namedExp.parent.parent; +- if (newExpr =3D=3D null || !flutter.isWidgetCreation(newExpr)) { +- return; +- } +- } else { +- InstanceCreationExpression newExpr =3D flutter.identifyNewExpressio= n(node); +- if (newExpr =3D=3D null || !flutter.isWidgetCreation(newExpr)) { +- _coverageMarker(); +- return; +- } +- namedExp =3D flutter.findChildArgument(newExpr); +- if (namedExp =3D=3D null || namedExp.expression =3D=3D null) { +- _coverageMarker(); +- return; +- } +- } +- InstanceCreationExpression childArg =3D +- flutter.getChildWidget(namedExp, false); +- if (childArg =3D=3D null) { +- _coverageMarker(); +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- _convertFlutterChildToChildren(childArg, namedExp, eol, utils.getNo= deText, +- utils.getLinePrefix, utils.getIndent, utils.getText, builder); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.CONVERT_FLUTTER_C= HILD); +- } +- +- Future _addProposal_convertIntoFinalField() async { +- // Find the enclosing getter. +- MethodDeclaration getter; +- for (AstNode n =3D node; n !=3D null; n =3D n.parent) { +- if (n is MethodDeclaration) { +- getter =3D n; +- break; +- } +- if (n is SimpleIdentifier || +- n is TypeAnnotation || +- n is TypeArgumentList) { +- continue; +- } +- break; +- } +- if (getter =3D=3D null || !getter.isGetter) { +- return; +- } +- // Check that there is no corresponding setter. +- { +- ExecutableElement element =3D getter.element; +- if (element =3D=3D null) { +- return; +- } +- Element enclosing =3D element.enclosingElement; +- if (enclosing is ClassElement) { +- if (enclosing.getSetter(element.name) !=3D null) { +- return; +- } +- } +- } +- // Try to find the returned expression. +- Expression expression; +- { +- FunctionBody body =3D getter.body; +- if (body is ExpressionFunctionBody) { +- expression =3D body.expression; +- } else if (body is BlockFunctionBody) { +- List statements =3D body.block.statements; +- if (statements.length =3D=3D 1) { +- Statement statement =3D statements.first; +- if (statement is ReturnStatement) { +- expression =3D statement.expression; +- } +- } +- } +- } +- // Use the returned expression as the field initializer. +- if (expression !=3D null) { +- AstNode beginNodeToReplace =3D getter.name; +- String code =3D 'final'; +- if (getter.returnType !=3D null) { +- beginNodeToReplace =3D getter.returnType; +- code +=3D ' ' + _getNodeText(getter.returnType); +- } +- code +=3D ' ' + _getNodeText(getter.name); +- if (expression is! NullLiteral) { +- code +=3D ' =3D ' + _getNodeText(expression); +- } +- code +=3D ';'; +- SourceRange replacementRange =3D range.startEnd(beginNodeToReplace,= getter); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleReplacement(replacementRange, code); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_INTO_FINAL_FIELD); +- } +- } +- +- Future _addProposal_convertIntoGetter() async { +- // Find the enclosing field declaration. +- FieldDeclaration fieldDeclaration; +- for (AstNode n =3D node; n !=3D null; n =3D n.parent) { +- if (n is FieldDeclaration) { +- fieldDeclaration =3D n; +- break; +- } +- if (n is SimpleIdentifier || +- n is VariableDeclaration || +- n is VariableDeclarationList || +- n is TypeAnnotation || +- n is TypeArgumentList) { +- continue; +- } +- break; +- } +- if (fieldDeclaration =3D=3D null) { +- return; +- } +- // The field must be final and has only one variable. +- VariableDeclarationList fieldList =3D fieldDeclaration.fields; +- if (!fieldList.isFinal || fieldList.variables.length !=3D 1) { +- return; +- } +- VariableDeclaration field =3D fieldList.variables.first; +- // Prepare the initializer. +- Expression initializer =3D field.initializer; +- if (initializer =3D=3D null) { +- return; +- } +- // Add proposal. +- String code =3D ''; +- if (fieldList.type !=3D null) { +- code +=3D _getNodeText(fieldList.type) + ' '; +- } +- code +=3D 'get'; +- code +=3D ' ' + _getNodeText(field.name); +- code +=3D ' =3D> ' + _getNodeText(initializer); +- code +=3D ';'; +- SourceRange replacementRange =3D +- range.startEnd(fieldList.keyword, fieldDeclaration); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(replacementRange, code); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.CONVERT_INTO_GETT= ER); +- } +- +- Future _addProposal_convertPartOfToUri() async { +- PartOfDirective directive =3D +- node.getAncestor((node) =3D> node is PartOfDirective); +- if (directive =3D=3D null || directive.libraryName =3D=3D null) { +- return; +- } +- String libraryPath =3D unitLibraryElement.source.fullName; +- String partPath =3D unit.element.source.fullName; +- String relativePath =3D relative(libraryPath, from: dirname(partPath)= ); +- SourceRange replacementRange =3D range.node(directive.libraryName); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(replacementRange, "'$relativePath'"); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.CONVERT_PART_OF_T= O_URI); +- } +- +- Future _addProposal_convertToBlockFunctionBody() async { +- FunctionBody body =3D getEnclosingFunctionBody(); +- // prepare expression body +- if (body is! ExpressionFunctionBody || body.isGenerator) { +- _coverageMarker(); +- return; +- } +- +- Expression returnValue =3D (body as ExpressionFunctionBody).expressio= n; +- +- // Return expressions can be quite large, e.g. Flutter build() method= s. +- // It is surprising to see this Quick Assist deep in the function bod= y. +- if (selectionOffset >=3D returnValue.offset) { +- _coverageMarker(); +- return; +- } +- +- DartType returnValueType =3D returnValue.staticType; +- String returnValueCode =3D _getNodeText(returnValue); +- // prepare prefix +- String prefix =3D utils.getNodePrefix(body.parent); +- String indent =3D utils.getIndent(1); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(body), (DartEditBuilder builder) { +- if (body.isAsynchronous) { +- builder.write('async '); +- } +- builder.write('{$eol$prefix$indent'); +- if (!returnValueType.isVoid) { +- builder.write('return '); +- } +- builder.write(returnValueCode); +- builder.write(';'); +- builder.selectHere(); +- builder.write('$eol$prefix}'); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_INTO_BLOCK_BODY); +- } +- +- Future _addProposal_convertToExpressionFunctionBody() async { +- // prepare current body +- FunctionBody body =3D getEnclosingFunctionBody(); +- if (body is! BlockFunctionBody || body.isGenerator) { +- _coverageMarker(); +- return; +- } +- // prepare return statement +- List statements =3D (body as BlockFunctionBody).block.stat= ements; +- if (statements.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- Statement onlyStatement =3D statements.first; +- // prepare returned expression +- Expression returnExpression; +- if (onlyStatement is ReturnStatement) { +- returnExpression =3D onlyStatement.expression; +- } else if (onlyStatement is ExpressionStatement) { +- returnExpression =3D onlyStatement.expression; +- } +- if (returnExpression =3D=3D null) { +- _coverageMarker(); +- return; +- } +- +- // Return expressions can be quite large, e.g. Flutter build() method= s. +- // It is surprising to see this Quick Assist deep in the function bod= y. +- if (selectionOffset >=3D returnExpression.offset) { +- _coverageMarker(); +- return; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(body), (DartEditBuilder builder) { +- if (body.isAsynchronous) { +- builder.write('async '); +- } +- builder.write('=3D> '); +- builder.write(_getNodeText(returnExpression)); +- if (body.parent is! FunctionExpression || +- body.parent.parent is FunctionDeclaration) { +- builder.write(';'); +- } +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_INTO_EXPRESSION_BODY); +- } +- +- Future _addProposal_convertToFieldParameter() async { +- if (node =3D=3D null) { +- return; +- } +- // prepare ConstructorDeclaration +- ConstructorDeclaration constructor =3D +- node.getAncestor((node) =3D> node is ConstructorDeclaration); +- if (constructor =3D=3D null) { +- return; +- } +- FormalParameterList parameterList =3D constructor.parameters; +- List initializers =3D constructor.initializer= s; +- // prepare parameter +- SimpleFormalParameter parameter; +- if (node.parent is SimpleFormalParameter && +- node.parent.parent is FormalParameterList && +- node.parent.parent.parent is ConstructorDeclaration) { +- parameter =3D node.parent; +- } +- if (node is SimpleIdentifier && +- node.parent is ConstructorFieldInitializer) { +- String name =3D (node as SimpleIdentifier).name; +- ConstructorFieldInitializer initializer =3D node.parent; +- if (initializer.expression =3D=3D node) { +- for (FormalParameter formalParameter in parameterList.parameters)= { +- if (formalParameter is SimpleFormalParameter && +- formalParameter.identifier.name =3D=3D name) { +- parameter =3D formalParameter; +- } +- } +- } +- } +- // analyze parameter +- if (parameter !=3D null) { +- String parameterName =3D parameter.identifier.name; +- ParameterElement parameterElement =3D parameter.element; +- // check number of references +- { +- int numOfReferences =3D 0; +- AstVisitor visitor =3D +- new _SimpleIdentifierRecursiveAstVisitor((SimpleIdentifier no= de) { +- if (node.staticElement =3D=3D parameterElement) { +- numOfReferences++; +- } +- }); +- for (ConstructorInitializer initializer in initializers) { +- initializer.accept(visitor); +- } +- if (numOfReferences !=3D 1) { +- return; +- } +- } +- // find the field initializer +- ConstructorFieldInitializer parameterInitializer; +- for (ConstructorInitializer initializer in initializers) { +- if (initializer is ConstructorFieldInitializer) { +- Expression expression =3D initializer.expression; +- if (expression is SimpleIdentifier && +- expression.name =3D=3D parameterName) { +- parameterInitializer =3D initializer; +- } +- } +- } +- if (parameterInitializer =3D=3D null) { +- return; +- } +- String fieldName =3D parameterInitializer.fieldName.name; +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- // replace parameter +- builder.addSimpleReplacement(range.node(parameter), 'this.$fieldN= ame'); +- // remove initializer +- int initializerIndex =3D initializers.indexOf(parameterInitialize= r); +- if (initializers.length =3D=3D 1) { +- builder +- .addDeletion(range.endEnd(parameterList, parameterInitializ= er)); +- } else { +- if (initializerIndex =3D=3D 0) { +- ConstructorInitializer next =3D initializers[initializerIndex= + 1]; +- builder.addDeletion(range.startStart(parameterInitializer, ne= xt)); +- } else { +- ConstructorInitializer prev =3D initializers[initializerIndex= - 1]; +- builder.addDeletion(range.endEnd(prev, parameterInitializer)); +- } +- } +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_TO_FIELD_PARAMETER); +- } +- } +- +- Future _addProposal_convertToForIndexLoop() async { +- // find enclosing ForEachStatement +- ForEachStatement forEachStatement =3D +- node.getAncestor((n) =3D> n is ForEachStatement); +- if (forEachStatement =3D=3D null) { +- _coverageMarker(); +- return; +- } +- if (selectionOffset < forEachStatement.offset || +- forEachStatement.rightParenthesis.end < selectionOffset) { +- _coverageMarker(); +- return; +- } +- // loop should declare variable +- DeclaredIdentifier loopVariable =3D forEachStatement.loopVariable; +- if (loopVariable =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // iterable should be VariableElement +- String listName; +- Expression iterable =3D forEachStatement.iterable; +- if (iterable is SimpleIdentifier && +- iterable.staticElement is VariableElement) { +- listName =3D iterable.name; +- } else { +- _coverageMarker(); +- return; +- } +- // iterable should be List +- { +- DartType iterableType =3D iterable.bestType; +- InterfaceType listType =3D typeProvider.listType; +- if (iterableType is! InterfaceType || +- iterableType.element !=3D listType.element) { +- _coverageMarker(); +- return; +- } +- } +- // body should be Block +- if (forEachStatement.body is! Block) { +- _coverageMarker(); +- return; +- } +- Block body =3D forEachStatement.body; +- // prepare a name for the index variable +- String indexName; +- { +- Set conflicts =3D +- utils.findPossibleLocalVariableConflicts(forEachStatement.offse= t); +- if (!conflicts.contains('i')) { +- indexName =3D 'i'; +- } else if (!conflicts.contains('j')) { +- indexName =3D 'j'; +- } else if (!conflicts.contains('k')) { +- indexName =3D 'k'; +- } else { +- _coverageMarker(); +- return; +- } +- } +- // prepare environment +- String prefix =3D utils.getNodePrefix(forEachStatement); +- String indent =3D utils.getIndent(1); +- int firstBlockLine =3D utils.getLineContentEnd(body.leftBracket.end); +- // add change +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- // TODO(brianwilkerson) Create linked positions for the loop variab= le. +- builder.addSimpleReplacement( +- range.startEnd(forEachStatement, forEachStatement.rightParenthe= sis), +- 'for (int $indexName =3D 0; $indexName < $listName.length; $ind= exName++)'); +- builder.addSimpleInsertion(firstBlockLine, +- '$prefix$indent$loopVariable =3D $listName[$indexName];$eol'); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.CONVERT_INTO_FOR_= INDEX); +- } +- +- Future _addProposal_convertToIsNot_onIs() async { +- // may be child of "is" +- AstNode node =3D this.node; +- while (node !=3D null && node is! IsExpression) { +- node =3D node.parent; +- } +- // prepare "is" +- if (node is! IsExpression) { +- _coverageMarker(); +- return; +- } +- IsExpression isExpression =3D node as IsExpression; +- if (isExpression.notOperator !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare enclosing () +- AstNode parent =3D isExpression.parent; +- if (parent is! ParenthesizedExpression) { +- _coverageMarker(); +- return; +- } +- ParenthesizedExpression parExpression =3D parent as ParenthesizedExpr= ession; +- // prepare enclosing !() +- AstNode parent2 =3D parent.parent; +- if (parent2 is! PrefixExpression) { +- _coverageMarker(); +- return; +- } +- PrefixExpression prefExpression =3D parent2 as PrefixExpression; +- if (prefExpression.operator.type !=3D TokenType.BANG) { +- _coverageMarker(); +- return; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- if (getExpressionParentPrecedence(prefExpression) >=3D +- TokenClass.RELATIONAL_OPERATOR.precedence) { +- builder.addDeletion(range.token(prefExpression.operator)); +- } else { +- builder.addDeletion( +- range.startEnd(prefExpression, parExpression.leftParenthesis)= ); +- builder.addDeletion( +- range.startEnd(parExpression.rightParenthesis, prefExpression= )); +- } +- builder.addSimpleInsertion(isExpression.isOperator.end, '!'); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.CONVERT_INTO_IS_N= OT); +- } +- +- Future _addProposal_convertToIsNot_onNot() async { +- // may be () in prefix expression +- if (node is ParenthesizedExpression && node.parent is PrefixExpressio= n) { +- node =3D node.parent; +- } +- // prepare !() +- if (node is! PrefixExpression) { +- _coverageMarker(); +- return; +- } +- PrefixExpression prefExpression =3D node as PrefixExpression; +- // should be ! operator +- if (prefExpression.operator.type !=3D TokenType.BANG) { +- _coverageMarker(); +- return; +- } +- // prepare !() +- Expression operand =3D prefExpression.operand; +- if (operand is! ParenthesizedExpression) { +- _coverageMarker(); +- return; +- } +- ParenthesizedExpression parExpression =3D operand as ParenthesizedExp= ression; +- operand =3D parExpression.expression; +- // prepare "is" +- if (operand is! IsExpression) { +- _coverageMarker(); +- return; +- } +- IsExpression isExpression =3D operand as IsExpression; +- if (isExpression.notOperator !=3D null) { +- _coverageMarker(); +- return; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- if (getExpressionParentPrecedence(prefExpression) >=3D +- TokenClass.RELATIONAL_OPERATOR.precedence) { +- builder.addDeletion(range.token(prefExpression.operator)); +- } else { +- builder.addDeletion( +- range.startEnd(prefExpression, parExpression.leftParenthesis)= ); +- builder.addDeletion( +- range.startEnd(parExpression.rightParenthesis, prefExpression= )); +- } +- builder.addSimpleInsertion(isExpression.isOperator.end, '!'); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.CONVERT_INTO_IS_N= OT); +- } +- +- /** +- * Converts "!isEmpty" -> "isNotEmpty" if possible. +- */ +- Future _addProposal_convertToIsNotEmpty() async { +- // prepare "expr.isEmpty" +- AstNode isEmptyAccess =3D null; +- SimpleIdentifier isEmptyIdentifier =3D null; +- if (node is SimpleIdentifier) { +- SimpleIdentifier identifier =3D node as SimpleIdentifier; +- AstNode parent =3D identifier.parent; +- // normal case (but rare) +- if (parent is PropertyAccess) { +- isEmptyIdentifier =3D parent.propertyName; +- isEmptyAccess =3D parent; +- } +- // usual case +- if (parent is PrefixedIdentifier) { +- isEmptyIdentifier =3D parent.identifier; +- isEmptyAccess =3D parent; +- } +- } +- if (isEmptyIdentifier =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // should be "isEmpty" +- Element propertyElement =3D isEmptyIdentifier.bestElement; +- if (propertyElement =3D=3D null || 'isEmpty' !=3D propertyElement.nam= e) { +- _coverageMarker(); +- return; +- } +- // should have "isNotEmpty" +- Element propertyTarget =3D propertyElement.enclosingElement; +- if (propertyTarget =3D=3D null || +- getChildren(propertyTarget, 'isNotEmpty').isEmpty) { +- _coverageMarker(); +- return; +- } +- // should be in PrefixExpression +- if (isEmptyAccess.parent is! PrefixExpression) { +- _coverageMarker(); +- return; +- } +- PrefixExpression prefixExpression =3D +- isEmptyAccess.parent as PrefixExpression; +- // should be ! +- if (prefixExpression.operator.type !=3D TokenType.BANG) { +- _coverageMarker(); +- return; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion( +- range.startStart(prefixExpression, prefixExpression.operand)); +- builder.addSimpleReplacement(range.node(isEmptyIdentifier), 'isNotE= mpty'); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY); +- } +- +- Future _addProposal_convertToNormalParameter() async { +- if (node is SimpleIdentifier && +- node.parent is FieldFormalParameter && +- node.parent.parent is FormalParameterList && +- node.parent.parent.parent is ConstructorDeclaration) { +- ConstructorDeclaration constructor =3D node.parent.parent.parent; +- FormalParameterList parameterList =3D node.parent.parent; +- FieldFormalParameter parameter =3D node.parent; +- ParameterElement parameterElement =3D parameter.element; +- String name =3D (node as SimpleIdentifier).name; +- // prepare type +- DartType type =3D parameterElement.type; +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- // replace parameter +- if (type.isDynamic) { +- builder.addSimpleReplacement(range.node(parameter), name); +- } else { +- builder.addReplacement(range.node(parameter), +- (DartEditBuilder builder) { +- builder.writeType(type); +- builder.write(' '); +- builder.write(name); +- }); +- } +- // add field initializer +- List initializers =3D constructor.initial= izers; +- if (initializers.isEmpty) { +- builder.addSimpleInsertion(parameterList.end, ' : $name =3D $na= me'); +- } else { +- builder.addSimpleInsertion(initializers.last.end, ', $name =3D = $name'); +- } +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.CONVERT_TO_NORMAL_PARAMETER); +- } +- } +- +- Future _addProposal_encapsulateField() async { +- // find FieldDeclaration +- FieldDeclaration fieldDeclaration =3D +- node.getAncestor((x) =3D> x is FieldDeclaration); +- if (fieldDeclaration =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // not interesting for static +- if (fieldDeclaration.isStatic) { +- _coverageMarker(); +- return; +- } +- // has a parse error +- VariableDeclarationList variableList =3D fieldDeclaration.fields; +- if (variableList.keyword =3D=3D null && variableList.type =3D=3D null= ) { +- _coverageMarker(); +- return; +- } +- // not interesting for final +- if (variableList.isFinal) { +- _coverageMarker(); +- return; +- } +- // should have exactly one field +- List fields =3D variableList.variables; +- if (fields.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- VariableDeclaration field =3D fields.first; +- SimpleIdentifier nameNode =3D field.name; +- FieldElement fieldElement =3D nameNode.staticElement; +- // should have a public name +- String name =3D nameNode.name; +- if (Identifier.isPrivateName(name)) { +- _coverageMarker(); +- return; +- } +- // should be on the name +- if (nameNode !=3D node) { +- _coverageMarker(); +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- // rename field +- builder.addSimpleReplacement(range.node(nameNode), '_$name'); +- // update references in constructors +- ClassDeclaration classDeclaration =3D fieldDeclaration.parent; +- for (ClassMember member in classDeclaration.members) { +- if (member is ConstructorDeclaration) { +- for (FormalParameter parameter in member.parameters.parameters)= { +- ParameterElement parameterElement =3D parameter.element; +- if (parameterElement is FieldFormalParameterElement && +- parameterElement.field =3D=3D fieldElement) { +- SimpleIdentifier identifier =3D parameter.identifier; +- builder.addSimpleReplacement(range.node(identifier), '_$nam= e'); +- } +- } +- } +- } +- // add accessors +- String eol2 =3D eol + eol; +- String typeNameCode =3D variableList.type !=3D null +- ? _getNodeText(variableList.type) + ' ' +- : ''; +- String getterCode =3D '$eol2 ${typeNameCode}get $name =3D> _$name;= '; +- String setterCode =3D '$eol2' +- ' void set $name($typeNameCode$name) {$eol' +- ' _$name =3D $name;$eol' +- ' }'; +- builder.addSimpleInsertion(fieldDeclaration.end, getterCode + sette= rCode); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.ENCAPSULATE_FIELD= ); +- } +- +- Future _addProposal_exchangeOperands() async { +- // check that user invokes quick assist on binary expression +- if (node is! BinaryExpression) { +- _coverageMarker(); +- return; +- } +- BinaryExpression binaryExpression =3D node as BinaryExpression; +- // prepare operator position +- if (!_isOperatorSelected( +- binaryExpression, selectionOffset, selectionLength)) { +- _coverageMarker(); +- return; +- } +- // add edits +- Expression leftOperand =3D binaryExpression.leftOperand; +- Expression rightOperand =3D binaryExpression.rightOperand; +- // find "wide" enclosing binary expression with same operator +- while (binaryExpression.parent is BinaryExpression) { +- BinaryExpression newBinaryExpression =3D +- binaryExpression.parent as BinaryExpression; +- if (newBinaryExpression.operator.type !=3D binaryExpression.operato= r.type) { +- _coverageMarker(); +- break; +- } +- binaryExpression =3D newBinaryExpression; +- } +- // exchange parts of "wide" expression parts +- SourceRange leftRange =3D range.startEnd(binaryExpression, leftOperan= d); +- SourceRange rightRange =3D range.startEnd(rightOperand, binaryExpress= ion); +- // maybe replace the operator +- Token operator =3D binaryExpression.operator; +- // prepare a new operator +- String newOperator =3D null; +- TokenType operatorType =3D operator.type; +- if (operatorType =3D=3D TokenType.LT) { +- newOperator =3D '>'; +- } else if (operatorType =3D=3D TokenType.LT_EQ) { +- newOperator =3D '>=3D'; +- } else if (operatorType =3D=3D TokenType.GT) { +- newOperator =3D '<'; +- } else if (operatorType =3D=3D TokenType.GT_EQ) { +- newOperator =3D '<=3D'; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(leftRange, _getRangeText(rightRange)); +- builder.addSimpleReplacement(rightRange, _getRangeText(leftRange)); +- // Optionally replace the operator. +- if (newOperator !=3D null) { +- builder.addSimpleReplacement(range.token(operator), newOperator); +- } +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.EXCHANGE_OPERANDS= ); +- } +- +- Future _addProposal_importAddShow() async { +- // prepare ImportDirective +- ImportDirective importDirective =3D +- node.getAncestor((node) =3D> node is ImportDirective); +- if (importDirective =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // there should be no existing combinators +- if (importDirective.combinators.isNotEmpty) { +- _coverageMarker(); +- return; +- } +- // prepare whole import namespace +- ImportElement importElement =3D importDirective.element; +- if (importElement =3D=3D null) { +- _coverageMarker(); +- return; +- } +- Map namespace =3D getImportNamespace(importElement); +- // prepare names of referenced elements (from this import) +- SplayTreeSet referencedNames =3D new SplayTreeSet(); +- _SimpleIdentifierRecursiveAstVisitor visitor =3D +- new _SimpleIdentifierRecursiveAstVisitor((SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element !=3D null && namespace[node.name] =3D=3D element) { +- referencedNames.add(element.displayName); +- } +- }); +- unit.accept(visitor); +- // ignore if unused +- if (referencedNames.isEmpty) { +- _coverageMarker(); +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- String showCombinator =3D ' show ${referencedNames.join(', ')}'; +- builder.addSimpleInsertion(importDirective.end - 1, showCombinator); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.IMPORT_ADD_SHOW); +- } +- +- Future _addProposal_introduceLocalTestedType() async { +- AstNode node =3D this.node; +- if (node is IfStatement) { +- node =3D (node as IfStatement).condition; +- } else if (node is WhileStatement) { +- node =3D (node as WhileStatement).condition; +- } +- // prepare IsExpression +- if (node is! IsExpression) { +- _coverageMarker(); +- return; +- } +- IsExpression isExpression =3D node; +- DartType castType =3D isExpression.type.type; +- String castTypeCode =3D _getNodeText(isExpression.type); +- // prepare environment +- String indent =3D utils.getIndent(1); +- String prefix; +- Block targetBlock; +- { +- Statement statement =3D node.getAncestor((n) =3D> n is Statement); +- if (statement is IfStatement && statement.thenStatement is Block) { +- targetBlock =3D statement.thenStatement; +- } else if (statement is WhileStatement && statement.body is Block) { +- targetBlock =3D statement.body; +- } else { +- _coverageMarker(); +- return; +- } +- prefix =3D utils.getNodePrefix(statement); +- } +- // prepare location +- int offset; +- String statementPrefix; +- if (isExpression.notOperator =3D=3D null) { +- offset =3D targetBlock.leftBracket.end; +- statementPrefix =3D indent; +- } else { +- offset =3D targetBlock.rightBracket.end; +- statementPrefix =3D ''; +- } +- // prepare excluded names +- Set excluded =3D new Set(); +- ScopedNameFinder scopedNameFinder =3D new ScopedNameFinder(offset); +- isExpression.accept(scopedNameFinder); +- excluded.addAll(scopedNameFinder.locals.keys.toSet()); +- // name(s) +- List suggestions =3D +- getVariableNameSuggestionsForExpression(castType, null, excluded); +- +- if (suggestions.isNotEmpty) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addInsertion(offset, (DartEditBuilder builder) { +- builder.write(eol + prefix + statementPrefix); +- builder.write(castTypeCode); +- builder.write(' '); +- builder.addSimpleLinkedEdit('NAME', suggestions[0], +- kind: LinkedEditSuggestionKind.VARIABLE, +- suggestions: suggestions); +- builder.write(' =3D '); +- builder.write(_getNodeText(isExpression.expression)); +- builder.write(';'); +- builder.selectHere(); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE); +- } +- } +- +- Future _addProposal_invertIf() async { +- if (node is! IfStatement) { +- return; +- } +- IfStatement ifStatement =3D node as IfStatement; +- Expression condition =3D ifStatement.condition; +- // should have both "then" and "else" +- Statement thenStatement =3D ifStatement.thenStatement; +- Statement elseStatement =3D ifStatement.elseStatement; +- if (thenStatement =3D=3D null || elseStatement =3D=3D null) { +- return; +- } +- // prepare source +- String invertedCondition =3D utils.invertCondition(condition); +- String thenSource =3D _getNodeText(thenStatement); +- String elseSource =3D _getNodeText(elseStatement); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(range.node(condition), invertedConditi= on); +- builder.addSimpleReplacement(range.node(thenStatement), elseSource); +- builder.addSimpleReplacement(range.node(elseStatement), thenSource); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.INVERT_IF_STATEME= NT); +- } +- +- Future _addProposal_joinIfStatementInner() async { +- // climb up condition to the (supposedly) "if" statement +- AstNode node =3D this.node; +- while (node is Expression) { +- node =3D node.parent; +- } +- // prepare target "if" statement +- if (node is! IfStatement) { +- _coverageMarker(); +- return; +- } +- IfStatement targetIfStatement =3D node as IfStatement; +- if (targetIfStatement.elseStatement !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare inner "if" statement +- Statement targetThenStatement =3D targetIfStatement.thenStatement; +- Statement innerStatement =3D getSingleStatement(targetThenStatement); +- if (innerStatement is! IfStatement) { +- _coverageMarker(); +- return; +- } +- IfStatement innerIfStatement =3D innerStatement as IfStatement; +- if (innerIfStatement.elseStatement !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare environment +- String prefix =3D utils.getNodePrefix(targetIfStatement); +- // merge conditions +- String condition; +- { +- Expression targetCondition =3D targetIfStatement.condition; +- Expression innerCondition =3D innerIfStatement.condition; +- String targetConditionSource =3D _getNodeText(targetCondition); +- String innerConditionSource =3D _getNodeText(innerCondition); +- if (_shouldWrapParenthesisBeforeAnd(targetCondition)) { +- targetConditionSource =3D '($targetConditionSource)'; +- } +- if (_shouldWrapParenthesisBeforeAnd(innerCondition)) { +- innerConditionSource =3D '($innerConditionSource)'; +- } +- condition =3D '$targetConditionSource && $innerConditionSource'; +- } +- // replace target "if" statement +- Statement innerThenStatement =3D innerIfStatement.thenStatement; +- List innerThenStatements =3D getStatements(innerThenStatem= ent); +- SourceRange lineRanges =3D utils.getLinesRangeStatements(innerThenSta= tements); +- String oldSource =3D utils.getRangeText(lineRanges); +- String newSource =3D utils.indentSourceLeftRight(oldSource); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(range.node(targetIfStatement), +- 'if ($condition) {$eol$newSource$prefix}'); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.JOIN_IF_WITH_INNE= R); +- } +- +- Future _addProposal_joinIfStatementOuter() async { +- // climb up condition to the (supposedly) "if" statement +- AstNode node =3D this.node; +- while (node is Expression) { +- node =3D node.parent; +- } +- // prepare target "if" statement +- if (node is! IfStatement) { +- _coverageMarker(); +- return; +- } +- IfStatement targetIfStatement =3D node as IfStatement; +- if (targetIfStatement.elseStatement !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare outer "if" statement +- AstNode parent =3D targetIfStatement.parent; +- if (parent is Block) { +- if ((parent as Block).statements.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- parent =3D parent.parent; +- } +- if (parent is! IfStatement) { +- _coverageMarker(); +- return; +- } +- IfStatement outerIfStatement =3D parent as IfStatement; +- if (outerIfStatement.elseStatement !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare environment +- String prefix =3D utils.getNodePrefix(outerIfStatement); +- // merge conditions +- Expression targetCondition =3D targetIfStatement.condition; +- Expression outerCondition =3D outerIfStatement.condition; +- String targetConditionSource =3D _getNodeText(targetCondition); +- String outerConditionSource =3D _getNodeText(outerCondition); +- if (_shouldWrapParenthesisBeforeAnd(targetCondition)) { +- targetConditionSource =3D '($targetConditionSource)'; +- } +- if (_shouldWrapParenthesisBeforeAnd(outerCondition)) { +- outerConditionSource =3D '($outerConditionSource)'; +- } +- String condition =3D '$outerConditionSource && $targetConditionSource= '; +- // replace outer "if" statement +- Statement targetThenStatement =3D targetIfStatement.thenStatement; +- List targetThenStatements =3D getStatements(targetThenStat= ement); +- SourceRange lineRanges =3D +- utils.getLinesRangeStatements(targetThenStatements); +- String oldSource =3D utils.getRangeText(lineRanges); +- String newSource =3D utils.indentSourceLeftRight(oldSource); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(range.node(outerIfStatement), +- 'if ($condition) {$eol$newSource$prefix}'); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.JOIN_IF_WITH_OUTE= R); +- } +- +- Future _addProposal_joinVariableDeclaration_onAssignment() async { +- // check that node is LHS in assignment +- if (node is SimpleIdentifier && +- node.parent is AssignmentExpression && +- (node.parent as AssignmentExpression).leftHandSide =3D=3D node && +- node.parent.parent is ExpressionStatement) {} else { +- _coverageMarker(); +- return; +- } +- AssignmentExpression assignExpression =3D node.parent as AssignmentEx= pression; +- // check that binary expression is assignment +- if (assignExpression.operator.type !=3D TokenType.EQ) { +- _coverageMarker(); +- return; +- } +- // prepare "declaration" statement +- Element element =3D (node as SimpleIdentifier).staticElement; +- if (element =3D=3D null) { +- _coverageMarker(); +- return; +- } +- int declOffset =3D element.nameOffset; +- AstNode declNode =3D new NodeLocator(declOffset).searchWithin(unit); +- if (declNode !=3D null && +- declNode.parent is VariableDeclaration && +- (declNode.parent as VariableDeclaration).name =3D=3D declNode && +- declNode.parent.parent is VariableDeclarationList && +- declNode.parent.parent.parent is VariableDeclarationStatement) {}= else { +- _coverageMarker(); +- return; +- } +- VariableDeclaration decl =3D declNode.parent as VariableDeclaration; +- VariableDeclarationStatement declStatement =3D +- decl.parent.parent as VariableDeclarationStatement; +- // may be has initializer +- if (decl.initializer !=3D null) { +- _coverageMarker(); +- return; +- } +- // check that "declaration" statement declared only one variable +- if (declStatement.variables.variables.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- // check that the "declaration" and "assignment" statements are +- // parts of the same Block +- ExpressionStatement assignStatement =3D +- node.parent.parent as ExpressionStatement; +- if (assignStatement.parent is Block && +- assignStatement.parent =3D=3D declStatement.parent) {} else { +- _coverageMarker(); +- return; +- } +- Block block =3D assignStatement.parent as Block; +- // check that "declaration" and "assignment" statements are adjacent +- List statements =3D block.statements; +- if (statements.indexOf(assignStatement) =3D=3D +- statements.indexOf(declStatement) + 1) {} else { +- _coverageMarker(); +- return; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement( +- range.endStart(declNode, assignExpression.operator), ' '); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.JOIN_VARIABLE_DECLARATION); +- } +- +- Future _addProposal_joinVariableDeclaration_onDeclaration() async= { +- // prepare enclosing VariableDeclarationList +- VariableDeclarationList declList =3D +- node.getAncestor((node) =3D> node is VariableDeclarationList); +- if (declList !=3D null && declList.variables.length =3D=3D 1) {} else= { +- _coverageMarker(); +- return; +- } +- VariableDeclaration decl =3D declList.variables[0]; +- // already initialized +- if (decl.initializer !=3D null) { +- _coverageMarker(); +- return; +- } +- // prepare VariableDeclarationStatement in Block +- if (declList.parent is VariableDeclarationStatement && +- declList.parent.parent is Block) {} else { +- _coverageMarker(); +- return; +- } +- VariableDeclarationStatement declStatement =3D +- declList.parent as VariableDeclarationStatement; +- Block block =3D declStatement.parent as Block; +- List statements =3D block.statements; +- // prepare assignment +- AssignmentExpression assignExpression; +- { +- // declaration should not be last Statement +- int declIndex =3D statements.indexOf(declStatement); +- if (declIndex < statements.length - 1) {} else { +- _coverageMarker(); +- return; +- } +- // next Statement should be assignment +- Statement assignStatement =3D statements[declIndex + 1]; +- if (assignStatement is ExpressionStatement) {} else { +- _coverageMarker(); +- return; +- } +- ExpressionStatement expressionStatement =3D +- assignStatement as ExpressionStatement; +- // expression should be assignment +- if (expressionStatement.expression is AssignmentExpression) {} else= { +- _coverageMarker(); +- return; +- } +- assignExpression =3D expressionStatement.expression as AssignmentEx= pression; +- } +- // check that pure assignment +- if (assignExpression.operator.type !=3D TokenType.EQ) { +- _coverageMarker(); +- return; +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement( +- range.endStart(decl.name, assignExpression.operator), ' '); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.JOIN_VARIABLE_DECLARATION); +- } +- +- Future _addProposal_moveFlutterWidgetDown() async { +- InstanceCreationExpression exprGoingDown =3D +- flutter.identifyNewExpression(node); +- if (exprGoingDown =3D=3D null || !flutter.isWidgetCreation(exprGoingD= own)) { +- _coverageMarker(); +- return; +- } +- InstanceCreationExpression exprGoingUp =3D +- flutter.findChildWidget(exprGoingDown); +- if (exprGoingUp =3D=3D null) { +- _coverageMarker(); +- return; +- } +- NamedExpression stableChild =3D flutter.findChildArgument(exprGoingUp= ); +- if (stableChild =3D=3D null || stableChild.expression =3D=3D null) { +- _coverageMarker(); +- return; +- } +- String exprGoingDownSrc =3D utils.getNodeText(exprGoingDown); +- int dnNewlineIdx =3D exprGoingDownSrc.lastIndexOf(eol); +- if (dnNewlineIdx < 0 || dnNewlineIdx =3D=3D exprGoingDownSrc.length -= 1) { +- _coverageMarker(); +- return; // Outer new-expr needs to be in multi-line format already. +- } +- String exprGoingUpSrc =3D utils.getNodeText(exprGoingUp); +- int upNewlineIdx =3D exprGoingUpSrc.lastIndexOf(eol); +- if (upNewlineIdx < 0 || upNewlineIdx =3D=3D exprGoingUpSrc.length - 1= ) { +- _coverageMarker(); +- return; // Inner new-expr needs to be in multi-line format already. +- } +- await _swapFlutterWidgets(exprGoingDown, exprGoingUp, stableChild, +- DartAssistKind.MOVE_FLUTTER_WIDGET_DOWN); +- } +- +- Future _addProposal_moveFlutterWidgetUp() async { +- InstanceCreationExpression exprGoingUp =3D +- flutter.identifyNewExpression(node); +- if (exprGoingUp =3D=3D null || !flutter.isWidgetCreation(exprGoingUp)= ) { +- _coverageMarker(); +- return; +- } +- AstNode expr =3D exprGoingUp.parent?.parent?.parent; +- if (expr =3D=3D null || expr is! InstanceCreationExpression) { +- _coverageMarker(); +- return; +- } +- InstanceCreationExpression exprGoingDown =3D expr; +- NamedExpression stableChild =3D flutter.findChildArgument(exprGoingUp= ); +- if (stableChild =3D=3D null || stableChild.expression =3D=3D null) { +- _coverageMarker(); +- return; +- } +- String exprGoingUpSrc =3D utils.getNodeText(exprGoingUp); +- int upNewlineIdx =3D exprGoingUpSrc.lastIndexOf(eol); +- if (upNewlineIdx < 0 || upNewlineIdx =3D=3D exprGoingUpSrc.length - 1= ) { +- _coverageMarker(); +- return; // Inner new-expr needs to be in multi-line format already. +- } +- String exprGoingDownSrc =3D utils.getNodeText(exprGoingDown); +- int dnNewlineIdx =3D exprGoingDownSrc.lastIndexOf(eol); +- if (dnNewlineIdx < 0 || dnNewlineIdx =3D=3D exprGoingDownSrc.length -= 1) { +- _coverageMarker(); +- return; // Outer new-expr needs to be in multi-line format already. +- } +- await _swapFlutterWidgets(exprGoingDown, exprGoingUp, stableChild, +- DartAssistKind.MOVE_FLUTTER_WIDGET_UP); +- } +- +- Future _addProposal_removeTypeAnnotation() async { +- VariableDeclarationList declarationList =3D +- node.getAncestor((n) =3D> n is VariableDeclarationList); +- if (declarationList =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // we need a type +- TypeAnnotation typeNode =3D declarationList.type; +- if (typeNode =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // ignore if an incomplete variable declaration +- if (declarationList.variables.length =3D=3D 1 && +- declarationList.variables[0].name.isSynthetic) { +- _coverageMarker(); +- return; +- } +- // must be not after the name of the variable +- VariableDeclaration firstVariable =3D declarationList.variables[0]; +- if (selectionOffset > firstVariable.name.end) { +- _coverageMarker(); +- return; +- } +- // The variable must have an initializer, otherwise there is no other +- // source for its type. +- if (firstVariable.initializer =3D=3D null) { +- _coverageMarker(); +- return; +- } +- Token keyword =3D declarationList.keyword; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- SourceRange typeRange =3D range.startStart(typeNode, firstVariable); +- if (keyword !=3D null && keyword.lexeme !=3D 'var') { +- builder.addSimpleReplacement(typeRange, ''); +- } else { +- builder.addSimpleReplacement(typeRange, 'var '); +- } +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.REMOVE_TYPE_ANNOT= ATION); +- } +- +- Future _addProposal_reparentFlutterList() async { +- if (node is! ListLiteral) { +- return; +- } +- if ((node as ListLiteral).elements.any((Expression exp) =3D> +- !(exp is InstanceCreationExpression && +- flutter.isWidgetCreation(exp)))) { +- _coverageMarker(); +- return; +- } +- String literalSrc =3D utils.getNodeText(node); +- int newlineIdx =3D literalSrc.lastIndexOf(eol); +- if (newlineIdx < 0 || newlineIdx =3D=3D literalSrc.length - 1) { +- _coverageMarker(); +- return; // Lists need to be in multi-line format already. +- } +- String indentOld =3D utils.getLinePrefix(node.offset + 1 + newlineIdx= ); +- String indentArg =3D '$indentOld${utils.getIndent(1)}'; +- String indentList =3D '$indentOld${utils.getIndent(2)}'; +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(node), (DartEditBuilder builder) { +- builder.write('['); +- builder.write(eol); +- builder.write(indentArg); +- builder.write('new '); +- builder.addSimpleLinkedEdit('WIDGET', 'widget'); +- builder.write('('); +- builder.write(eol); +- builder.write(indentList); +- // Linked editing not needed since arg is always a list. +- builder.write('children: '); +- builder.write(literalSrc.replaceAll( +- new RegExp("^$indentOld", multiLine: true), "$indentList")); +- builder.write(','); +- builder.write(eol); +- builder.write(indentArg); +- builder.write('),'); +- builder.write(eol); +- builder.write(indentOld); +- builder.write(']'); +- builder.selectHere(); +- }); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.REPARENT_FLUTTER_= LIST); +- } +- +- Future _addProposal_reparentFlutterWidget() async { +- InstanceCreationExpression newExpr =3D flutter.identifyNewExpression(= node); +- if (newExpr =3D=3D null || !flutter.isWidgetCreation(newExpr)) { +- _coverageMarker(); +- return; +- } +- String newExprSrc =3D utils.getNodeText(newExpr); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(newExpr), (DartEditBuilder builde= r) { +- builder.write('new '); +- builder.addSimpleLinkedEdit('WIDGET', 'widget'); +- builder.write('('); +- if (newExprSrc.contains(eol)) { +- int newlineIdx =3D newExprSrc.lastIndexOf(eol); +- int eolLen =3D eol.length; +- if (newlineIdx =3D=3D newExprSrc.length - eolLen) { +- newlineIdx -=3D eolLen; +- } +- String indentOld =3D +- utils.getLinePrefix(newExpr.offset + eolLen + newlineIdx); +- String indentNew =3D '$indentOld${utils.getIndent(1)}'; +- builder.write(eol); +- builder.write(indentNew); +- newExprSrc =3D newExprSrc.replaceAll( +- new RegExp("^$indentOld", multiLine: true), indentNew); +- newExprSrc +=3D ",$eol$indentOld"; +- } +- builder.addSimpleLinkedEdit('CHILD', 'child'); +- builder.write(': '); +- builder.write(newExprSrc); +- builder.write(')'); +- builder.selectHere(); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.REPARENT_FLUTTER_WIDGET); +- } +- +- Future _addProposal_replaceConditionalWithIfElse() async { +- ConditionalExpression conditional =3D null; +- // may be on Statement with Conditional +- Statement statement =3D node.getAncestor((node) =3D> node is Statemen= t); +- if (statement =3D=3D null) { +- _coverageMarker(); +- return; +- } +- // variable declaration +- bool inVariable =3D false; +- if (statement is VariableDeclarationStatement) { +- VariableDeclarationStatement variableStatement =3D statement; +- for (VariableDeclaration variable +- in variableStatement.variables.variables) { +- if (variable.initializer is ConditionalExpression) { +- conditional =3D variable.initializer as ConditionalExpression; +- inVariable =3D true; +- break; +- } +- } +- } +- // assignment +- bool inAssignment =3D false; +- if (statement is ExpressionStatement) { +- ExpressionStatement exprStmt =3D statement; +- if (exprStmt.expression is AssignmentExpression) { +- AssignmentExpression assignment =3D +- exprStmt.expression as AssignmentExpression; +- if (assignment.operator.type =3D=3D TokenType.EQ && +- assignment.rightHandSide is ConditionalExpression) { +- conditional =3D assignment.rightHandSide as ConditionalExpressi= on; +- inAssignment =3D true; +- } +- } +- } +- // return +- bool inReturn =3D false; +- if (statement is ReturnStatement) { +- ReturnStatement returnStatement =3D statement; +- if (returnStatement.expression is ConditionalExpression) { +- conditional =3D returnStatement.expression as ConditionalExpressi= on; +- inReturn =3D true; +- } +- } +- // prepare environment +- String indent =3D utils.getIndent(1); +- String prefix =3D utils.getNodePrefix(statement); +- +- if (inVariable || inAssignment || inReturn) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- // Type v =3D Conditional; +- if (inVariable) { +- VariableDeclaration variable =3D +- conditional.parent as VariableDeclaration; +- builder.addDeletion(range.endEnd(variable.name, conditional)); +- String conditionSrc =3D _getNodeText(conditional.condition); +- String thenSrc =3D _getNodeText(conditional.thenExpression); +- String elseSrc =3D _getNodeText(conditional.elseExpression); +- String name =3D variable.name.name; +- String src =3D eol; +- src +=3D prefix + 'if ($conditionSrc) {' + eol; +- src +=3D prefix + indent + '$name =3D $thenSrc;' + eol; +- src +=3D prefix + '} else {' + eol; +- src +=3D prefix + indent + '$name =3D $elseSrc;' + eol; +- src +=3D prefix + '}'; +- builder.addSimpleReplacement(range.endLength(statement, 0), src= ); +- } +- // v =3D Conditional; +- if (inAssignment) { +- AssignmentExpression assignment =3D +- conditional.parent as AssignmentExpression; +- Expression leftSide =3D assignment.leftHandSide; +- String conditionSrc =3D _getNodeText(conditional.condition); +- String thenSrc =3D _getNodeText(conditional.thenExpression); +- String elseSrc =3D _getNodeText(conditional.elseExpression); +- String name =3D _getNodeText(leftSide); +- String src =3D ''; +- src +=3D 'if ($conditionSrc) {' + eol; +- src +=3D prefix + indent + '$name =3D $thenSrc;' + eol; +- src +=3D prefix + '} else {' + eol; +- src +=3D prefix + indent + '$name =3D $elseSrc;' + eol; +- src +=3D prefix + '}'; +- builder.addSimpleReplacement(range.node(statement), src); +- } +- // return Conditional; +- if (inReturn) { +- String conditionSrc =3D _getNodeText(conditional.condition); +- String thenSrc =3D _getNodeText(conditional.thenExpression); +- String elseSrc =3D _getNodeText(conditional.elseExpression); +- String src =3D ''; +- src +=3D 'if ($conditionSrc) {' + eol; +- src +=3D prefix + indent + 'return $thenSrc;' + eol; +- src +=3D prefix + '} else {' + eol; +- src +=3D prefix + indent + 'return $elseSrc;' + eol; +- src +=3D prefix + '}'; +- builder.addSimpleReplacement(range.node(statement), src); +- } +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE); +- } +- } +- +- Future _addProposal_replaceIfElseWithConditional() async { +- // should be "if" +- if (node is! IfStatement) { +- _coverageMarker(); +- return; +- } +- IfStatement ifStatement =3D node as IfStatement; +- // single then/else statements +- Statement thenStatement =3D getSingleStatement(ifStatement.thenStatem= ent); +- Statement elseStatement =3D getSingleStatement(ifStatement.elseStatem= ent); +- if (thenStatement =3D=3D null || elseStatement =3D=3D null) { +- _coverageMarker(); +- return; +- } +- Expression thenExpression =3D null; +- Expression elseExpression =3D null; +- bool hasReturnStatements =3D false; +- if (thenStatement is ReturnStatement && elseStatement is ReturnStatem= ent) { +- hasReturnStatements =3D true; +- thenExpression =3D thenStatement.expression; +- elseExpression =3D elseStatement.expression; +- } +- bool hasExpressionStatements =3D false; +- if (thenStatement is ExpressionStatement && +- elseStatement is ExpressionStatement) { +- if (thenStatement.expression is AssignmentExpression && +- elseStatement.expression is AssignmentExpression) { +- hasExpressionStatements =3D true; +- thenExpression =3D thenStatement.expression; +- elseExpression =3D elseStatement.expression; +- } +- } +- +- if (hasReturnStatements || hasExpressionStatements) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- // returns +- if (hasReturnStatements) { +- String conditionSrc =3D _getNodeText(ifStatement.condition); +- String theSrc =3D _getNodeText(thenExpression); +- String elseSrc =3D _getNodeText(elseExpression); +- builder.addSimpleReplacement(range.node(ifStatement), +- 'return $conditionSrc ? $theSrc : $elseSrc;'); +- } +- // assignments -> v =3D Conditional; +- if (hasExpressionStatements) { +- AssignmentExpression thenAssignment =3D thenExpression; +- AssignmentExpression elseAssignment =3D elseExpression; +- String thenTarget =3D _getNodeText(thenAssignment.leftHandSide); +- String elseTarget =3D _getNodeText(elseAssignment.leftHandSide); +- if (thenAssignment.operator.type =3D=3D TokenType.EQ && +- elseAssignment.operator.type =3D=3D TokenType.EQ && +- thenTarget =3D=3D elseTarget) { +- String conditionSrc =3D _getNodeText(ifStatement.condition); +- String theSrc =3D _getNodeText(thenAssignment.rightHandSide); +- String elseSrc =3D _getNodeText(elseAssignment.rightHandSide); +- builder.addSimpleReplacement(range.node(ifStatement), +- '$thenTarget =3D $conditionSrc ? $theSrc : $elseSrc;'); +- } +- } +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.REPLACE_IF_ELSE_WITH_CONDITIONAL); +- } +- } +- +- Future _addProposal_splitAndCondition() async { +- // check that user invokes quick assist on binary expression +- if (node is! BinaryExpression) { +- _coverageMarker(); +- return; +- } +- BinaryExpression binaryExpression =3D node as BinaryExpression; +- // prepare operator position +- if (!_isOperatorSelected( +- binaryExpression, selectionOffset, selectionLength)) { +- _coverageMarker(); +- return; +- } +- // should be && +- if (binaryExpression.operator.type !=3D TokenType.AMPERSAND_AMPERSAND= ) { +- _coverageMarker(); +- return; +- } +- // prepare "if" +- Statement statement =3D node.getAncestor((node) =3D> node is Statemen= t); +- if (statement is! IfStatement) { +- _coverageMarker(); +- return; +- } +- IfStatement ifStatement =3D statement as IfStatement; +- // no support "else" +- if (ifStatement.elseStatement !=3D null) { +- _coverageMarker(); +- return; +- } +- // check that binary expression is part of first level && condition o= f "if" +- BinaryExpression condition =3D binaryExpression; +- while (condition.parent is BinaryExpression && +- (condition.parent as BinaryExpression).operator.type =3D=3D +- TokenType.AMPERSAND_AMPERSAND) { +- condition =3D condition.parent as BinaryExpression; +- } +- if (ifStatement.condition !=3D condition) { +- _coverageMarker(); +- return; +- } +- // prepare environment +- String prefix =3D utils.getNodePrefix(ifStatement); +- String indent =3D utils.getIndent(1); +- // prepare "rightCondition" +- String rightConditionSource; +- { +- SourceRange rightConditionRange =3D +- range.startEnd(binaryExpression.rightOperand, condition); +- rightConditionSource =3D _getRangeText(rightConditionRange); +- } +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- // remove "&& rightCondition" +- builder +- .addDeletion(range.endEnd(binaryExpression.leftOperand, conditi= on)); +- // update "then" statement +- Statement thenStatement =3D ifStatement.thenStatement; +- if (thenStatement is Block) { +- Block thenBlock =3D thenStatement; +- SourceRange thenBlockRange =3D range.node(thenBlock); +- // insert inner "if" with right part of "condition" +- int thenBlockInsideOffset =3D thenBlockRange.offset + 1; +- builder.addSimpleInsertion(thenBlockInsideOffset, +- '$eol$prefix${indent}if ($rightConditionSource) {'); +- // insert closing "}" for inner "if" +- int thenBlockEnd =3D thenBlockRange.end; +- // insert before outer "then" block "}" +- builder.addSimpleInsertion(thenBlockEnd - 1, '$indent}$eol$prefix= '); +- } else { +- // insert inner "if" with right part of "condition" +- String source =3D '$eol$prefix${indent}if ($rightConditionSource)= '; +- builder.addSimpleInsertion( +- ifStatement.rightParenthesis.offset + 1, source); +- } +- // indent "then" statements to correspond inner "if" +- { +- List thenStatements =3D getStatements(thenStatement); +- SourceRange linesRange =3D utils.getLinesRangeStatements(thenStat= ements); +- String thenIndentOld =3D '$prefix$indent'; +- String thenIndentNew =3D '$thenIndentOld$indent'; +- builder.addSimpleReplacement( +- linesRange, +- utils.replaceSourceRangeIndent( +- linesRange, thenIndentOld, thenIndentNew)); +- } +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.SPLIT_AND_CONDITI= ON); +- } +- +- Future _addProposal_splitVariableDeclaration() async { +- // prepare DartVariableStatement, should be part of Block +- VariableDeclarationStatement statement =3D +- node.getAncestor((node) =3D> node is VariableDeclarationStatement= ); +- if (statement !=3D null && statement.parent is Block) {} else { +- _coverageMarker(); +- return; +- } +- // check that statement declares single variable +- List variables =3D statement.variables.variables; +- if (variables.length !=3D 1) { +- _coverageMarker(); +- return; +- } +- VariableDeclaration variable =3D variables[0]; +- // prepare initializer +- Expression initializer =3D variable.initializer; +- if (initializer =3D=3D null) { +- _coverageMarker(); +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- // remove initializer value +- builder.addDeletion(range.endStart(variable.name, statement.semicol= on)); +- // add assignment statement +- String indent =3D utils.getNodePrefix(statement); +- String name =3D variable.name.name; +- String initSrc =3D _getNodeText(initializer); +- SourceRange assignRange =3D range.endLength(statement, 0); +- builder.addSimpleReplacement( +- assignRange, eol + indent + name + ' =3D ' + initSrc + ';'); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.SPLIT_VARIABLE_DECLARATION); +- } +- +- Future _addProposal_surroundWith() async { +- // prepare selected statements +- List selectedStatements; +- { +- StatementAnalyzer selectionAnalyzer =3D new StatementAnalyzer( +- unit, new SourceRange(selectionOffset, selectionLength)); +- unit.accept(selectionAnalyzer); +- List selectedNodes =3D selectionAnalyzer.selectedNodes; +- // convert nodes to statements +- selectedStatements =3D []; +- for (AstNode selectedNode in selectedNodes) { +- if (selectedNode is Statement) { +- selectedStatements.add(selectedNode); +- } +- } +- // we want only statements +- if (selectedStatements.isEmpty || +- selectedStatements.length !=3D selectedNodes.length) { +- return; +- } +- } +- // prepare statement information +- Statement firstStatement =3D selectedStatements[0]; +- Statement lastStatement =3D selectedStatements[selectedStatements.len= gth - 1]; +- SourceRange statementsRange =3D +- utils.getLinesRangeStatements(selectedStatements); +- // prepare environment +- String indentOld =3D utils.getNodePrefix(firstStatement); +- String indentNew =3D '$indentOld${utils.getIndent(1)}'; +- String indentedCode =3D +- utils.replaceSourceRangeIndent(statementsRange, indentOld, indent= New); +- // "block" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleInsertion(statementsRange.offset, '$indentOld{$e= ol'); +- builder.addSimpleReplacement( +- statementsRange, +- utils.replaceSourceRangeIndent( +- statementsRange, indentOld, indentNew)); +- builder.addSimpleInsertion(statementsRange.end, '$indentOld}$eol'= ); +- exitPosition =3D _newPosition(lastStatement.end); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.SURROUND_WITH_B= LOCK); +- } +- // "if" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('if ('); +- builder.addSimpleLinkedEdit('CONDITION', 'condition'); +- builder.write(') {'); +- builder.write(eol); +- builder.write(indentedCode); +- builder.write(indentOld); +- builder.write('}'); +- builder.selectHere(); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.SURROUND_WITH_I= F); +- } +- // "while" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('while ('); +- builder.addSimpleLinkedEdit('CONDITION', 'condition'); +- builder.write(') {'); +- builder.write(eol); +- builder.write(indentedCode); +- builder.write(indentOld); +- builder.write('}'); +- builder.selectHere(); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.SURROUND_WITH_W= HILE); +- } +- // "for-in" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('for (var '); +- builder.addSimpleLinkedEdit('NAME', 'item'); +- builder.write(' in '); +- builder.addSimpleLinkedEdit('ITERABLE', 'iterable'); +- builder.write(') {'); +- builder.write(eol); +- builder.write(indentedCode); +- builder.write(indentOld); +- builder.write('}'); +- builder.selectHere(); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.SURROUND_WITH_F= OR_IN); +- } +- // "for" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('for (var '); +- builder.addSimpleLinkedEdit('VAR', 'v'); +- builder.write(' =3D '); +- builder.addSimpleLinkedEdit('INIT', 'init'); +- builder.write('; '); +- builder.addSimpleLinkedEdit('CONDITION', 'condition'); +- builder.write('; '); +- builder.addSimpleLinkedEdit('INCREMENT', 'increment'); +- builder.write(') {'); +- builder.write(eol); +- builder.write(indentedCode); +- builder.write(indentOld); +- builder.write('}'); +- builder.selectHere(); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder(changeBuilder, DartAssistKind.SURROUND_WITH_F= OR); +- } +- // "do-while" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('do {'); +- builder.write(eol); +- builder.write(indentedCode); +- builder.write(indentOld); +- builder.write('} while ('); +- builder.addSimpleLinkedEdit('CONDITION', 'condition'); +- builder.write(');'); +- builder.selectHere(); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.SURROUND_WITH_DO_WHILE); +- } +- // "try-catch" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('try {'); +- builder.write(eol); +- builder.write(indentedCode); +- builder.write(indentOld); +- builder.write('} on '); +- builder.addSimpleLinkedEdit('EXCEPTION_TYPE', 'Exception'); +- builder.write(' catch ('); +- builder.addSimpleLinkedEdit('EXCEPTION_VAR', 'e'); +- builder.write(') {'); +- builder.write(eol); +- // +- builder.write(indentNew); +- builder.addSimpleLinkedEdit('CATCH', '// TODO'); +- builder.selectHere(); +- builder.write(eol); +- // +- builder.write(indentOld); +- builder.write('}'); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.SURROUND_WITH_TRY_CATCH); +- } +- // "try-finally" +- { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(statementsRange, (DartEditBuilder builder)= { +- builder.write(indentOld); +- builder.write('try {'); +- builder.write(eol); +- // +- builder.write(indentedCode); +- // +- builder.write(indentOld); +- builder.write('} finally {'); +- builder.write(eol); +- // +- builder.write(indentNew); +- builder.addSimpleLinkedEdit('FINALLY', '// TODO'); +- builder.selectHere(); +- builder.write(eol); +- // +- builder.write(indentOld); +- builder.write('}'); +- builder.write(eol); +- }); +- }); +- _addAssistFromBuilder( +- changeBuilder, DartAssistKind.SURROUND_WITH_TRY_FINALLY); +- } +- } +- +- /** +- * Configures [utils] using given [target]. +- */ +- void _configureTargetLocation(Object target) { +- utils.targetClassElement =3D null; +- if (target is AstNode) { +- ClassDeclaration targetClassDeclaration =3D +- target.getAncestor((node) =3D> node is ClassDeclaration); +- if (targetClassDeclaration !=3D null) { +- utils.targetClassElement =3D targetClassDeclaration.element; +- } +- } +- } +- +- void _convertFlutterChildToChildren( +- InstanceCreationExpression childArg, +- NamedExpression namedExp, +- String eol, +- Function getNodeText, +- Function getLinePrefix, +- Function getIndent, +- Function getText, +- DartFileEditBuilder builder) { +- int childLoc =3D namedExp.offset + 'child'.length; +- builder.addSimpleInsertion(childLoc, 'ren'); +- int listLoc =3D childArg.offset; +- String childArgSrc =3D getNodeText(childArg); +- if (!childArgSrc.contains(eol)) { +- builder.addSimpleInsertion(listLoc, '['); +- builder.addSimpleInsertion(listLoc + childArg.length, ']'); +- } else { +- int newlineLoc =3D childArgSrc.lastIndexOf(eol); +- if (newlineLoc =3D=3D childArgSrc.length) { +- newlineLoc -=3D 1; +- } +- String indentOld =3D getLinePrefix(childArg.offset + 1 + newlineLoc= ); +- String indentNew =3D '$indentOld${getIndent(1)}'; +- // The separator includes 'child:' but that has no newlines. +- String separator =3D +- getText(namedExp.offset, childArg.offset - namedExp.offset); +- String prefix =3D separator.contains(eol) ? "" : "$eol$indentNew"; +- if (prefix.isEmpty) { +- builder.addSimpleInsertion( +- namedExp.offset + 'child:'.length, ' ['); +- int argOffset =3D childArg.offset; +- builder +- .addDeletion(range.startOffsetEndOffset(argOffset - 2, argOff= set)); +- } else { +- builder.addSimpleInsertion(listLoc, '['); +- } +- String newChildArgSrc =3D childArgSrc.replaceAll( +- new RegExp("^$indentOld", multiLine: true), "$indentNew"); +- newChildArgSrc =3D "$prefix$newChildArgSrc,$eol$indentOld]"; +- builder.addSimpleReplacement(range.node(childArg), newChildArgSrc); +- } +- } +- +- /** +- * Returns the text of the given node in the unit. +- */ +- String _getNodeText(AstNode node) { +- return utils.getNodeText(node); +- } +- +- /** +- * Returns the text of the given range in the unit. +- */ +- String _getRangeText(SourceRange range) { +- return utils.getRangeText(range); +- } +- +- Position _newPosition(int offset) { +- return new Position(file, offset); +- } +- +- Future _swapFlutterWidgets( +- InstanceCreationExpression exprGoingDown, +- InstanceCreationExpression exprGoingUp, +- NamedExpression stableChild, +- AssistKind assistKind) async { +- String currentSource =3D unitElement.context.getContents(source).data; +- // TODO(messick) Find a better way to get LineInfo for the source. +- LineInfo lineInfo =3D new LineInfo.fromContent(currentSource); +- int currLn =3D lineInfo.getLocation(exprGoingUp.offset).lineNumber; +- int lnOffset =3D lineInfo.getOffsetOfLine(currLn); +- +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(exprGoingDown), +- (DartEditBuilder builder) { +- String argSrc =3D +- utils.getText(exprGoingUp.offset, lnOffset - exprGoingUp.offs= et); +- builder.write(argSrc); // Append child new-expr plus rest of line. +- +- String getSrc(Expression expr) { +- int startLn =3D lineInfo.getLocation(expr.offset).lineNumber; +- int startOffset =3D lineInfo.getOffsetOfLine(startLn - 1); +- int endLn =3D +- lineInfo.getLocation(expr.offset + expr.length).lineNumber = + 1; +- int curOffset =3D lineInfo.getOffsetOfLine(endLn - 1); +- return utils.getText(startOffset, curOffset - startOffset); +- } +- +- String outerIndent =3D utils.getNodePrefix(exprGoingDown.parent); +- String innerIndent =3D utils.getNodePrefix(exprGoingUp.parent); +- exprGoingUp.argumentList.arguments.forEach((arg) { +- if (arg is NamedExpression && arg.name.label.name =3D=3D 'child= ') { +- if (stableChild !=3D arg) { +- _coverageMarker(); +- return; +- } +- // Insert exprGoingDown here. +- // Copy from start of line to offset of exprGoingDown. +- currLn =3D lineInfo.getLocation(stableChild.offset).lineNumbe= r; +- lnOffset =3D lineInfo.getOffsetOfLine(currLn - 1); +- argSrc =3D utils.getText( +- lnOffset, stableChild.expression.offset - lnOffset); +- argSrc =3D argSrc.replaceAll( +- new RegExp("^$innerIndent", multiLine: true), "$outerInde= nt"); +- builder.write(argSrc); +- int nextLn =3D lineInfo.getLocation(exprGoingDown.offset).lin= eNumber; +- lnOffset =3D lineInfo.getOffsetOfLine(nextLn); +- argSrc =3D utils.getText( +- exprGoingDown.offset, lnOffset - exprGoingDown.offset); +- builder.write(argSrc); +- +- exprGoingDown.argumentList.arguments.forEach((val) { +- if (val is NamedExpression && val.name.label.name =3D=3D 'c= hild') { +- // Insert stableChild here at same indent level. +- builder.write(utils.getNodePrefix(arg.name)); +- argSrc =3D utils.getNodeText(stableChild); +- builder.write(argSrc); +- if (assistKind =3D=3D DartAssistKind.MOVE_FLUTTER_WIDGET_= UP) { +- builder.write(',$eol'); +- } +- } else { +- argSrc =3D getSrc(val); +- argSrc =3D argSrc.replaceAll( +- new RegExp("^$outerIndent", multiLine: true), +- "$innerIndent"); +- builder.write(argSrc); +- } +- }); +- if (assistKind =3D=3D DartAssistKind.MOVE_FLUTTER_WIDGET_DOWN= ) { +- builder.write(',$eol'); +- } +- builder.write(innerIndent); +- builder.write('),$eol'); +- } else { +- argSrc =3D getSrc(arg); +- argSrc =3D argSrc.replaceAll( +- new RegExp("^$innerIndent", multiLine: true), "$outerInde= nt"); +- builder.write(argSrc); +- } +- }); +- builder.write(outerIndent); +- builder.write(')'); +- builder.selectHere(); +- }); +- }); +- _addAssistFromBuilder(changeBuilder, assistKind); +- } +- +- /** +- * This method does nothing, but we invoke it in places where Dart VM +- * coverage agent fails to provide coverage information - such as almost +- * all "return" statements. +- * +- * https://code.google.com/p/dart/issues/detail?id=3D19912 +- */ +- static void _coverageMarker() {} +- +- /** +- * Returns `true` if the selection covers an operator of the given +- * [BinaryExpression]. +- */ +- static bool _isOperatorSelected( +- BinaryExpression binaryExpression, int offset, int length) { +- AstNode left =3D binaryExpression.leftOperand; +- AstNode right =3D binaryExpression.rightOperand; +- // between the nodes +- if (offset >=3D left.endToken.end && offset + length <=3D right.offse= t) { +- _coverageMarker(); +- return true; +- } +- // or exactly select the node (but not with infix expressions) +- if (offset =3D=3D left.offset && offset + length =3D=3D right.endToke= n.end) { +- if (left is BinaryExpression || right is BinaryExpression) { +- _coverageMarker(); +- return false; +- } +- _coverageMarker(); +- return true; +- } +- // invalid selection (part of node, etc) +- _coverageMarker(); +- return false; +- } +- +- /** +- * Checks if the given [Expression] should be wrapped with parenthesis = when we +- * want to use it as operand of a logical `and` expression. +- */ +- static bool _shouldWrapParenthesisBeforeAnd(Expression expr) { +- if (expr is BinaryExpression) { +- BinaryExpression binary =3D expr; +- int precedence =3D binary.operator.type.precedence; +- return precedence < TokenClass.LOGICAL_AND_OPERATOR.precedence; +- } +- return false; +- } +-} +- +-/** +- * An [AssistContributor] that provides the default set of assists. +- */ +-class DefaultAssistContributor extends DartAssistContributor { +- @override +- Future> internalComputeAssists(DartAssistContext context) = async { +- try { +- AssistProcessor processor =3D new AssistProcessor(context); +- return processor.compute(); +- } on CancelCorrectionException { +- return Assist.EMPTY_LIST; +- } +- } +-} +- +-class _SimpleIdentifierRecursiveAstVisitor extends RecursiveAstVisitor { +- final _SimpleIdentifierVisitor visitor; +- +- _SimpleIdentifierRecursiveAstVisitor(this.visitor); +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- visitor(node); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/fix.dart b/pk= g/analysis_server/lib/src/services/correction/fix.dart +deleted file mode 100644 +index bfcd0dc5551..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/fix.dart ++++ /dev/null +@@ -1,260 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/plugin/edit/fix/fix_core.dart'; +-import 'package:analysis_server/src/services/correction/fix_internal.dart= '; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/error/codes.dart'; +-import 'package:analyzer/src/generated/parser.dart'; +-import 'package:analyzer_plugin/utilities/fixes/fixes.dart'; +- +-/** +- * Return true if this [errorCode] is likely to have a fix associated wit= h it. +- */ +-bool hasFix(ErrorCode errorCode) =3D> +- errorCode =3D=3D StaticWarningCode.UNDEFINED_CLASS_BOOLEAN || +- errorCode =3D=3D StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBE= R || +- errorCode =3D=3D StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS || +- errorCode =3D=3D StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_B= E_NAMED || +- errorCode =3D=3D StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR || +- errorCode =3D=3D +- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE= || +- errorCode =3D=3D +- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO= || +- errorCode =3D=3D +- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THR= EE || +- errorCode =3D=3D +- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOU= R || +- errorCode =3D=3D +- StaticWarningCode +- .NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS || +- errorCode =3D=3D StaticWarningCode.CAST_TO_NON_TYPE || +- errorCode =3D=3D StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME || +- errorCode =3D=3D StaticWarningCode.UNDEFINED_CLASS || +- errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED || +- errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_= 1 || +- errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_= 2 || +- errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_= 3_PLUS || +- errorCode =3D=3D StaticWarningCode.FUNCTION_WITHOUT_CALL || +- errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIER || +- errorCode =3D=3D +- CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE || +- errorCode =3D=3D CompileTimeErrorCode.INVALID_ANNOTATION || +- errorCode =3D=3D CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EX= PLICIT || +- errorCode =3D=3D CompileTimeErrorCode.PART_OF_NON_PART || +- errorCode =3D=3D +- CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT= || +- errorCode =3D=3D CompileTimeErrorCode.URI_DOES_NOT_EXIST || +- errorCode =3D=3D CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED || +- errorCode =3D=3D HintCode.CAN_BE_NULL_AFTER_NULL_AWARE || +- errorCode =3D=3D HintCode.DEAD_CODE || +- errorCode =3D=3D HintCode.DIVISION_OPTIMIZATION || +- errorCode =3D=3D HintCode.TYPE_CHECK_IS_NOT_NULL || +- errorCode =3D=3D HintCode.TYPE_CHECK_IS_NULL || +- errorCode =3D=3D HintCode.UNDEFINED_GETTER || +- errorCode =3D=3D HintCode.UNDEFINED_SETTER || +- errorCode =3D=3D HintCode.UNNECESSARY_CAST || +- errorCode =3D=3D HintCode.UNUSED_CATCH_CLAUSE || +- errorCode =3D=3D HintCode.UNUSED_CATCH_STACK || +- errorCode =3D=3D HintCode.UNUSED_IMPORT || +- errorCode =3D=3D HintCode.UNDEFINED_METHOD || +- errorCode =3D=3D ParserErrorCode.EXPECTED_TOKEN || +- errorCode =3D=3D ParserErrorCode.GETTER_WITH_PARAMETERS || +- errorCode =3D=3D ParserErrorCode.VAR_AS_TYPE_NAME || +- errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE || +- errorCode =3D=3D StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMB= ER || +- errorCode =3D=3D StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION || +- errorCode =3D=3D StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT || +- errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_FUNCTION || +- errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_GETTER || +- errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_METHOD || +- errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_SETTER || +- errorCode =3D=3D CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER || +- (errorCode is LintCode && +- (errorCode.name =3D=3D LintNames.annotate_overrides || +- errorCode.name =3D=3D LintNames.avoid_init_to_null || +- errorCode.name =3D=3D LintNames.prefer_collection_literals || +- errorCode.name =3D=3D LintNames.prefer_conditional_assignment= || +- errorCode.name =3D=3D LintNames.unnecessary_brace_in_string_i= nterp || +- errorCode.name =3D=3D LintNames.unnecessary_lambdas || +- errorCode.name =3D=3D LintNames.unnecessary_this)); +- +-/** +- * An enumeration of possible quick fix kinds. +- */ +-class DartFixKind { +- static const ADD_ASYNC =3D +- const FixKind('ADD_ASYNC', 50, "Add 'async' modifier"); +- static const ADD_FIELD_FORMAL_PARAMETERS =3D const FixKind( +- 'ADD_FIELD_FORMAL_PARAMETERS', 30, "Add final field formal paramete= rs"); +- static const ADD_MISSING_PARAMETER_POSITIONAL =3D const FixKind( +- 'ADD_MISSING_PARAMETER_POSITIONAL', +- 31, +- "Add optional positional parameter"); +- static const ADD_MISSING_PARAMETER_REQUIRED =3D const FixKind( +- 'ADD_MISSING_PARAMETER_REQUIRED', 30, "Add required parameter"); +- static const ADD_MISSING_REQUIRED_ARGUMENT =3D const FixKind( +- 'ADD_MISSING_REQUIRED_ARGUMENT', 30, "Add required argument '{0}'"); +- static const ADD_NE_NULL =3D const FixKind('ADD_NE_NULL', 50, "Add !=3D= null"); +- static const ADD_PACKAGE_DEPENDENCY =3D const FixKind( +- 'ADD_PACKAGE_DEPENDENCY', 50, "Add dependency on package '{0}'"); +- static const ADD_SUPER_CONSTRUCTOR_INVOCATION =3D const FixKind( +- 'ADD_SUPER_CONSTRUCTOR_INVOCATION', +- 50, +- "Add super constructor {0} invocation"); +- static const CHANGE_TO =3D const FixKind('CHANGE_TO', 49, "Change to '{= 0}'"); +- static const CHANGE_TO_STATIC_ACCESS =3D const FixKind( +- 'CHANGE_TO_STATIC_ACCESS', 50, "Change access to static using '{0}'= "); +- static const CHANGE_TYPE_ANNOTATION =3D const FixKind( +- 'CHANGE_TYPE_ANNOTATION', 50, "Change '{0}' to '{1}' type annotatio= n"); +- static const CONVERT_FLUTTER_CHILD =3D +- const FixKind('CONVERT_FLUTTER_CHILD', 50, "Convert to children:"); +- static const CREATE_CLASS =3D +- const FixKind('CREATE_CLASS', 50, "Create class '{0}'"); +- static const CREATE_CONSTRUCTOR =3D +- const FixKind('CREATE_CONSTRUCTOR', 50, "Create constructor '{0}'"); +- static const CREATE_CONSTRUCTOR_FOR_FINAL_FIELDS =3D const FixKind( +- 'CREATE_CONSTRUCTOR_FOR_FINAL_FIELDS', +- 50, +- "Create constructor for final fields"); +- static const CREATE_CONSTRUCTOR_SUPER =3D const FixKind( +- 'CREATE_CONSTRUCTOR_SUPER', 50, "Create constructor to call {0}"); +- static const CREATE_FIELD =3D +- const FixKind('CREATE_FIELD', 51, "Create field '{0}'"); +- static const CREATE_FILE =3D +- const FixKind('CREATE_FILE', 50, "Create file '{0}'"); +- static const CREATE_FUNCTION =3D +- const FixKind('CREATE_FUNCTION', 51, "Create function '{0}'"); +- static const CREATE_GETTER =3D +- const FixKind('CREATE_GETTER', 50, "Create getter '{0}'"); +- static const CREATE_LOCAL_VARIABLE =3D +- const FixKind('CREATE_LOCAL_VARIABLE', 50, "Create local variable '= {0}'"); +- static const CREATE_METHOD =3D +- const FixKind('CREATE_METHOD', 50, "Create method '{0}'"); +- static const CREATE_MISSING_METHOD_CALL =3D +- const FixKind('CREATE_MISSING_METHOD_CALL', 49, "Create method 'cal= l'."); +- static const CREATE_MISSING_OVERRIDES =3D const FixKind( +- 'CREATE_MISSING_OVERRIDES', 49, "Create {0} missing override(s)"); +- static const CREATE_NO_SUCH_METHOD =3D const FixKind( +- 'CREATE_NO_SUCH_METHOD', 51, "Create 'noSuchMethod' method"); +- static const IMPORT_LIBRARY_PREFIX =3D const FixKind('IMPORT_LIBRARY_PR= EFIX', +- 51, "Use imported library '{0}' with prefix '{1}'"); +- static const IMPORT_LIBRARY_PROJECT1 =3D +- const FixKind('IMPORT_LIBRARY_PROJECT1', 47, "Import library '{0}'"= ); +- static const IMPORT_LIBRARY_PROJECT2 =3D +- const FixKind('IMPORT_LIBRARY_PROJECT2', 48, "Import library '{0}'"= ); +- static const IMPORT_LIBRARY_PROJECT3 =3D +- const FixKind('IMPORT_LIBRARY_PROJECT3', 49, "Import library '{0}'"= ); +- static const IMPORT_LIBRARY_SDK =3D +- const FixKind('IMPORT_LIBRARY_SDK', 46, "Import library '{0}'"); +- static const IMPORT_LIBRARY_SHOW =3D +- const FixKind('IMPORT_LIBRARY_SHOW', 45, "Update library '{0}' impo= rt"); +- static const INSERT_SEMICOLON =3D +- const FixKind('INSERT_SEMICOLON', 50, "Insert ';'"); +- static const INVOKE_CONSTRUCTOR_USING_NEW =3D const FixKind( +- 'INVOKE_CONSTRUCTOR_USING_NEW', 50, "Invoke constructor using 'new'= "); +- static const LINT_ADD_OVERRIDE =3D +- const FixKind('LINT_ADD_OVERRIDE', 50, "Add '@override' annotation"= ); +- static const LINT_ADD_REQUIRED =3D +- const FixKind('LINT_ADD_REQUIRED', 50, "Add '@required' annotation"= ); +- static const LINT_REMOVE_INTERPOLATION_BRACES =3D const FixKind( +- 'LINT_REMOVE_INTERPOLATION_BRACES', +- 50, +- 'Remove unnecessary interpolation braces'); +- static const MAKE_CLASS_ABSTRACT =3D +- const FixKind('MAKE_CLASS_ABSTRACT', 50, "Make class '{0}' abstract= "); +- static const REMOVE_DEAD_CODE =3D +- const FixKind('REMOVE_DEAD_CODE', 50, "Remove dead code"); +- static const MAKE_FIELD_NOT_FINAL =3D +- const FixKind('MAKE_FIELD_NOT_FINAL', 50, "Make field '{0}' not fin= al"); +- static const REMOVE_AWAIT =3D const FixKind('REMOVE_AWAIT', 50, "Remove= await"); +- static const REMOVE_EMPTY_CATCH =3D +- const FixKind('REMOVE_EMPTY_CATCH', 50, "Remove empty catch clause"= ); +- static const REMOVE_EMPTY_CONSTRUCTOR_BODY =3D const FixKind( +- 'REMOVE_EMPTY_CONSTRUCTOR_BODY', 50, "Remove empty constructor body= "); +- static const REMOVE_EMPTY_ELSE =3D +- const FixKind('REMOVE_EMPTY_ELSE', 50, "Remove empty else clause"); +- static const REMOVE_EMPTY_STATEMENT =3D +- const FixKind('REMOVE_EMPTY_STATEMENT', 50, "Remove empty statement= "); +- static const REMOVE_INITIALIZER =3D +- const FixKind('REMOVE_INITIALIZER', 50, "Remove initializer"); +- static const REMOVE_METHOD_DECLARATION =3D const FixKind( +- 'REMOVE_METHOD_DECLARATION', 50, 'Remove method declaration'); +- static const REMOVE_PARAMETERS_IN_GETTER_DECLARATION =3D const FixKind( +- 'REMOVE_PARAMETERS_IN_GETTER_DECLARATION', +- 50, +- "Remove parameters in getter declaration"); +- static const REMOVE_PARENTHESIS_IN_GETTER_INVOCATION =3D const FixKind( +- 'REMOVE_PARENTHESIS_IN_GETTER_INVOCATION', +- 50, +- "Remove parentheses in getter invocation"); +- static const REMOVE_THIS_EXPRESSION =3D +- const FixKind('REMOVE_THIS_EXPRESSION', 50, "Remove this expression= "); +- static const REMOVE_TYPE_NAME =3D +- const FixKind('REMOVE_TYPE_NAME', 50, "Remove type name"); +- static const REMOVE_UNNECESSARY_CAST =3D +- const FixKind('REMOVE_UNNECESSARY_CAST', 50, "Remove unnecessary ca= st"); +- static const REMOVE_UNUSED_CATCH_CLAUSE =3D +- const FixKind('REMOVE_UNUSED_CATCH', 50, "Remove unused 'catch' cla= use"); +- static const REMOVE_UNUSED_CATCH_STACK =3D const FixKind( +- 'REMOVE_UNUSED_CATCH_STACK', 50, "Remove unused stack trace variabl= e"); +- static const REMOVE_UNUSED_IMPORT =3D +- const FixKind('REMOVE_UNUSED_IMPORT', 50, "Remove unused import"); +- static const REPLACE_BOOLEAN_WITH_BOOL =3D const FixKind( +- 'REPLACE_BOOLEAN_WITH_BOOL', 50, "Replace 'boolean' with 'bool'"); +- static const REPLACE_VAR_WITH_DYNAMIC =3D const FixKind( +- 'REPLACE_VAR_WITH_DYNAMIC', 50, "Replace 'var' with 'dynamic'"); +- static const REPLACE_RETURN_TYPE_FUTURE =3D const FixKind( +- 'REPLACE_RETURN_TYPE_FUTURE', +- 50, +- "Return 'Future' from 'async' function"); +- static const REPLACE_WITH_BRACKETS =3D +- const FixKind('REPLACE_WITH_BRACKETS', 50, "Replace with { }"); +- static const REPLACE_WITH_CONDITIONAL_ASSIGNMENT =3D const FixKind( +- 'REPLACE_WITH_CONDITIONAL_ASSIGNMENT', 50, 'Replace with ??=3D'); +- static const REPLACE_WITH_IDENTIFIER =3D +- const FixKind('REPLACE_WITH_IDENTIFIER', 50, "Replace with identifi= er"); +- static const REPLACE_WITH_LITERAL =3D +- const FixKind('REPLACE_WITH_LITERAL', 50, 'Replace with literal'); +- static const REPLACE_WITH_NULL_AWARE =3D const FixKind( +- 'REPLACE_WITH_NULL_AWARE', +- 50, +- "Replace the '.' with a '?.' in the invocation"); +- static const REPLACE_WITH_TEAR_OFF =3D const FixKind( +- 'REPLACE_WITH_TEAR_OFF', 50, "Replace function literal with tear-of= f"); +- static const USE_CONST =3D const FixKind('USE_CONST', 50, "Change to co= nstant"); +- static const USE_EFFECTIVE_INTEGER_DIVISION =3D const FixKind( +- 'USE_EFFECTIVE_INTEGER_DIVISION', +- 50, +- "Use effective integer division ~/"); +- static const USE_EQ_EQ_NULL =3D +- const FixKind('USE_EQ_EQ_NULL', 50, "Use =3D=3D null instead of 'is= Null'"); +- static const USE_IS_NOT_EMPTY =3D const FixKind( +- 'USE_NOT_EMPTY', 50, "Use x.isNotEmpty instead of '!x.isEmpty'"); +- static const USE_NOT_EQ_NULL =3D +- const FixKind('USE_NOT_EQ_NULL', 50, "Use !=3D null instead of 'is!= Null'"); +-} +- +-/** +- * The implementation of [FixContext]. +- */ +-class FixContextImpl implements FixContext { +- @override +- final ResourceProvider resourceProvider; +- +- @override +- final AnalysisDriver analysisDriver; +- +- @override +- final AnalysisError error; +- +- FixContextImpl(this.resourceProvider, this.analysisDriver, this.error); +- +- FixContextImpl.from(FixContext other) +- : resourceProvider =3D other.resourceProvider, +- analysisDriver =3D other.analysisDriver, +- error =3D other.error; +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/fix_internal.= dart b/pkg/analysis_server/lib/src/services/correction/fix_internal.dart +deleted file mode 100644 +index 48771205d9e..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/fix_internal.dart ++++ /dev/null +@@ -1,3284 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:core'; +- +-import 'package:analysis_server/plugin/edit/fix/fix_core.dart'; +-import 'package:analysis_server/plugin/edit/fix/fix_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/utilities.da= rt'; +-import 'package:analysis_server/src/services/correction/fix.dart'; +-import 'package:analysis_server/src/services/correction/levenshtein.dart'; +-import 'package:analysis_server/src/services/correction/namespace.dart'; +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/utilities/flutter.dart' as flutter; +-import 'package:analyzer/dart/analysis/session.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/top_level_declaration.dart'; +-import 'package:analyzer/src/dart/ast/token.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/member.dart'; +-import 'package:analyzer/src/dart/element/type.dart'; +-import 'package:analyzer/src/dart/resolver/inheritance_manager.dart'; +-import 'package:analyzer/src/error/codes.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/error_verifier.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/parser.dart'; +-import 'package:analyzer/src/generated/resolver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/utilities_dart.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- hide AnalysisError, Element, ElementKind; +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +-import 'package:analyzer_plugin/utilities/change_builder/change_builder_d= art.dart'; +-import 'package:analyzer_plugin/utilities/fixes/fixes.dart' hide FixContr= ibutor; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +-import 'package:path/path.dart'; +- +-/** +- * A predicate is a one-argument function that returns a boolean value. +- */ +-typedef bool ElementPredicate(Element argument); +- +-/** +- * The implementation of [DartFixContext]. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-class DartFixContextImpl extends FixContextImpl implements DartFixContext= { +- @override +- final AstProvider astProvider; +- +- @override +- final CompilationUnit unit; +- +- DartFixContextImpl(FixContext fixContext, this.astProvider, this.unit) +- : super.from(fixContext); +- +- GetTopLevelDeclarations get getTopLevelDeclarations =3D> +- analysisDriver.getTopLevelNameDeclarations; +-} +- +-/** +- * A [FixContributor] that provides the default set of fixes. +- */ +-class DefaultFixContributor extends DartFixContributor { +- @override +- Future> internalComputeFixes(DartFixContext context) async { +- try { +- FixProcessor processor =3D new FixProcessor(context); +- List fixes =3D await processor.compute(); +- return fixes; +- } on CancelCorrectionException { +- return Fix.EMPTY_LIST; +- } +- } +-} +- +-/** +- * The computer for Dart fixes. +- */ +-class FixProcessor { +- static const int MAX_LEVENSHTEIN_DISTANCE =3D 3; +- +- ResourceProvider resourceProvider; +- AstProvider astProvider; +- GetTopLevelDeclarations getTopLevelDeclarations; +- CompilationUnit unit; +- AnalysisError error; +- +- /** +- * The analysis driver being used to perform analysis. +- */ +- AnalysisDriver driver; +- +- String file; +- CompilationUnitElement unitElement; +- Source unitSource; +- LibraryElement unitLibraryElement; +- File unitLibraryFile; +- Folder unitLibraryFolder; +- +- final List fixes =3D []; +- +- CorrectionUtils utils; +- int errorOffset; +- int errorLength; +- int errorEnd; +- SourceRange errorRange; +- AstNode node; +- AstNode coveredNode; +- +- TypeProvider _typeProvider; +- TypeSystem _typeSystem; +- +- FixProcessor(DartFixContext dartContext) { +- resourceProvider =3D dartContext.resourceProvider; +- astProvider =3D dartContext.astProvider; +- getTopLevelDeclarations =3D dartContext.getTopLevelDeclarations; +- driver =3D dartContext.analysisDriver; +- // unit +- unit =3D dartContext.unit; +- unitElement =3D unit.element; +- unitSource =3D unitElement.source; +- // file +- file =3D unitSource.fullName; +- // library +- unitLibraryElement =3D unitElement.library; +- String unitLibraryPath =3D unitLibraryElement.source.fullName; +- unitLibraryFile =3D resourceProvider.getFile(unitLibraryPath); +- unitLibraryFolder =3D unitLibraryFile.parent; +- // error +- error =3D dartContext.error; +- } +- +- DartType get coreTypeBool =3D> _getCoreType('bool'); +- +- /** +- * Returns the EOL to use for this [CompilationUnit]. +- */ +- String get eol =3D> utils.endOfLine; +- +- /** +- * Return the analysis session to be used to create the change builder. +- */ +- AnalysisSession get session =3D> driver.currentSession; +- +- TypeProvider get typeProvider { +- if (_typeProvider =3D=3D null) { +- _typeProvider =3D unitElement.context.typeProvider; +- } +- return _typeProvider; +- } +- +- TypeSystem get typeSystem { +- if (_typeSystem =3D=3D null) { +- if (driver.analysisOptions.strongMode) { +- _typeSystem =3D new StrongTypeSystemImpl(typeProvider); +- } else { +- _typeSystem =3D new TypeSystemImpl(typeProvider); +- } +- } +- return _typeSystem; +- } +- +- Future> compute() async { +- try { +- utils =3D new CorrectionUtils(unit); +- } catch (e) { +- throw new CancelCorrectionException(exception: e); +- } +- +- errorOffset =3D error.offset; +- errorLength =3D error.length; +- errorEnd =3D errorOffset + errorLength; +- errorRange =3D new SourceRange(errorOffset, errorLength); +- node =3D new NodeLocator2(errorOffset).searchWithin(unit); +- coveredNode =3D +- new NodeLocator2(errorOffset, errorEnd - 1).searchWithin(unit); +- // analyze ErrorCode +- ErrorCode errorCode =3D error.errorCode; +- if (errorCode =3D=3D StaticWarningCode.UNDEFINED_CLASS_BOOLEAN) { +- await _addFix_boolInsteadOfBoolean(); +- } +- if (errorCode =3D=3D +- CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE) { +- await _addFix_replaceWithConstInstanceCreation(); +- } +- if (errorCode =3D=3D CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT = || +- errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIER_AWAIT) { +- await _addFix_addAsync(); +- } +- if (errorCode =3D=3D CompileTimeErrorCode.INVALID_ANNOTATION) { +- if (node is Annotation) { +- Annotation annotation =3D node; +- Identifier name =3D annotation.name; +- if (name !=3D null && name.staticElement =3D=3D null) { +- node =3D name; +- if (annotation.arguments =3D=3D null) { +- await _addFix_importLibrary_withTopLevelVariable(); +- } else { +- await _addFix_importLibrary_withType(); +- await _addFix_createClass(); +- await _addFix_undefinedClass_useSimilar(); +- } +- } +- } +- } +- if (errorCode =3D=3D +- CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT) { +- await _addFix_createConstructorSuperExplicit(); +- } +- if (errorCode =3D=3D +- CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT) { +- await _addFix_createConstructorSuperImplicit(); +- } +- if (errorCode =3D=3D +- CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT= ) { +- await _addFix_createConstructorSuperExplicit(); +- } +- if (errorCode =3D=3D CompileTimeErrorCode.URI_DOES_NOT_EXIST) { +- await _addFix_createImportUri(); +- await _addFix_createPartUri(); +- } +- if (errorCode =3D=3D HintCode.CAN_BE_NULL_AFTER_NULL_AWARE) { +- await _addFix_canBeNullAfterNullAware(); +- } +- if (errorCode =3D=3D HintCode.DEAD_CODE) { +- await _addFix_removeDeadCode(); +- } +- if (errorCode =3D=3D HintCode.DIVISION_OPTIMIZATION) { +- await _addFix_useEffectiveIntegerDivision(); +- } +- if (errorCode =3D=3D HintCode.TYPE_CHECK_IS_NOT_NULL) { +- await _addFix_isNotNull(); +- } +- if (errorCode =3D=3D HintCode.TYPE_CHECK_IS_NULL) { +- await _addFix_isNull(); +- } +- if (errorCode =3D=3D HintCode.UNDEFINED_GETTER) { +- await _addFix_undefinedClassAccessor_useSimilar(); +- await _addFix_createField(); +- await _addFix_createGetter(); +- } +- if (errorCode =3D=3D HintCode.UNDEFINED_SETTER) { +- await _addFix_undefinedClassAccessor_useSimilar(); +- await _addFix_createField(); +- } +- if (errorCode =3D=3D HintCode.UNNECESSARY_CAST) { +- await _addFix_removeUnnecessaryCast(); +- } +- if (errorCode =3D=3D HintCode.UNUSED_CATCH_CLAUSE) { +- await _addFix_removeUnusedCatchClause(); +- } +- if (errorCode =3D=3D HintCode.UNUSED_CATCH_STACK) { +- await _addFix_removeUnusedCatchStack(); +- } +- if (errorCode =3D=3D HintCode.UNUSED_IMPORT) { +- await _addFix_removeUnusedImport(); +- } +- if (errorCode =3D=3D ParserErrorCode.EXPECTED_TOKEN) { +- await _addFix_insertSemicolon(); +- } +- if (errorCode =3D=3D ParserErrorCode.GETTER_WITH_PARAMETERS) { +- await _addFix_removeParameters_inGetterDeclaration(); +- } +- if (errorCode =3D=3D ParserErrorCode.VAR_AS_TYPE_NAME) { +- await _addFix_replaceVarWithDynamic(); +- } +- if (errorCode =3D=3D StaticWarningCode.ASSIGNMENT_TO_FINAL) { +- await _addFix_makeFieldNotFinal(); +- } +- if (errorCode =3D=3D StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_M= EMBER) { +- await _addFix_makeEnclosingClassAbstract(); +- } +- if (errorCode =3D=3D StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS || +- errorCode =3D=3D +- StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED) { +- await _addFix_createConstructor_insteadOfSyntheticDefault(); +- await _addFix_addMissingParameter(); +- } +- if (errorCode =3D=3D HintCode.MISSING_REQUIRED_PARAM || +- errorCode =3D=3D HintCode.MISSING_REQUIRED_PARAM_WITH_DETAILS) { +- await _addFix_addMissingRequiredArgument(); +- } +- if (errorCode =3D=3D StaticWarningCode.FUNCTION_WITHOUT_CALL) { +- await _addFix_addMissingMethodCall(); +- } +- if (errorCode =3D=3D StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR= ) { +- await _addFix_createConstructor_named(); +- } +- if (errorCode =3D=3D +- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER= _ONE || +- errorCode =3D=3D +- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER= _TWO || +- errorCode =3D=3D +- StaticWarningCode +- .NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE || +- errorCode =3D=3D +- StaticWarningCode +- .NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR || +- errorCode =3D=3D +- StaticWarningCode +- .NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS) { +- // make class abstract +- await _addFix_makeEnclosingClassAbstract(); +- await _addFix_createNoSuchMethod(); +- // implement methods +- await _addFix_createMissingOverrides(); +- } +- if (errorCode =3D=3D CompileTimeErrorCode.UNDEFINED_CLASS || +- errorCode =3D=3D StaticWarningCode.CAST_TO_NON_TYPE || +- errorCode =3D=3D StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME = || +- errorCode =3D=3D StaticWarningCode.UNDEFINED_CLASS) { +- await _addFix_importLibrary_withType(); +- await _addFix_createClass(); +- await _addFix_undefinedClass_useSimilar(); +- } +- if (errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED) { +- await _addFix_createConstructor_forUninitializedFinalFields(); +- } +- if (errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUC= TOR_1 || +- errorCode =3D=3D StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUC= TOR_2 || +- errorCode =3D=3D +- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS) { +- await _addFix_updateConstructor_forUninitializedFinalFields(); +- } +- if (errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIER) { +- await _addFix_undefinedClassAccessor_useSimilar(); +- await _addFix_createClass(); +- await _addFix_createField(); +- await _addFix_createGetter(); +- await _addFix_createFunction_forFunctionType(); +- await _addFix_importLibrary_withType(); +- await _addFix_importLibrary_withTopLevelVariable(); +- await _addFix_createLocalVariable(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_METHOD_WITH_CONS= TRUCTOR) { +- await _addFix_undefinedMethodWithContructor(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE)= { +- await _addFix_illegalAsyncReturnType(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_= MEMBER) { +- await _addFix_useStaticAccess_method(); +- await _addFix_useStaticAccess_property(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.INVALID_ASSIGNMENT) { +- await _addFix_changeTypeAnnotation(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION= ) { +- await _addFix_removeParentheses_inGetterInvocation(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.NON_BOOL_CONDITION) { +- await _addFix_nonBoolCondition_addNotNull(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT)= { +- await _addFix_importLibrary_withType(); +- await _addFix_createClass(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_FUNCTION) { +- await _addFix_importLibrary_withFunction(); +- await _addFix_undefinedFunction_useSimilar(); +- await _addFix_undefinedFunction_create(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_GETTER) { +- await _addFix_undefinedClassAccessor_useSimilar(); +- await _addFix_createField(); +- await _addFix_createGetter(); +- await _addFix_createFunction_forFunctionType(); +- } +- if (errorCode =3D=3D HintCode.UNDEFINED_METHOD || +- errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_METHOD) { +- await _addFix_importLibrary_withFunction(); +- await _addFix_undefinedMethod_useSimilar(); +- await _addFix_undefinedMethod_create(); +- await _addFix_undefinedFunction_create(); +- } +- if (errorCode =3D=3D StaticTypeWarningCode.UNDEFINED_SETTER) { +- await _addFix_undefinedClassAccessor_useSimilar(); +- await _addFix_createField(); +- } +- if (errorCode =3D=3D CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER || +- errorCode =3D=3D StaticWarningCode.UNDEFINED_NAMED_PARAMETER) { +- await _addFix_convertFlutterChild(); +- await _addFix_convertFlutterChildren(); +- } +- if (errorCode =3D=3D +- CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD) { +- await _addFix_createField_initializingFormal(); +- } +- // lints +- if (errorCode is LintCode) { +- String name =3D errorCode.name; +- if (name =3D=3D LintNames.always_require_non_null_named_parameters)= { +- await _addFix_addRequiredAnnotation(); +- } +- if (name =3D=3D LintNames.annotate_overrides) { +- await _addFix_addOverrideAnnotation(); +- } +- if (name =3D=3D LintNames.avoid_annotating_with_dynamic) { +- await _addFix_removeTypeAnnotation(); +- } +- if (name =3D=3D LintNames.avoid_empty_else) { +- await _addFix_removeEmptyElse(); +- } +- if (name =3D=3D LintNames.avoid_init_to_null) { +- await _addFix_removeInitializer(); +- } +- if (name =3D=3D LintNames.avoid_return_types_on_setters) { +- await _addFix_removeTypeAnnotation(); +- } +- if (name =3D=3D LintNames.avoid_types_on_closure_parameters) { +- await _addFix_replaceWithIdentifier(); +- } +- if (name =3D=3D LintNames.await_only_futures) { +- await _addFix_removeAwait(); +- } +- if (name =3D=3D LintNames.empty_catches) { +- await _addFix_removeEmptyCatch(); +- } +- if (name =3D=3D LintNames.empty_constructor_bodies) { +- await _addFix_removeEmptyConstructorBody(); +- } +- if (name =3D=3D LintNames.empty_statements) { +- await _addFix_removeEmptyStatement(); +- } +- if (name =3D=3D LintNames.prefer_collection_literals) { +- await _addFix_replaceWithLiteral(); +- } +- if (name =3D=3D LintNames.prefer_conditional_assignment) { +- await _addFix_replaceWithConditionalAssignment(); +- } +- if (name =3D=3D LintNames.prefer_is_not_empty) { +- await _addFix_isNotEmpty(); +- } +- if (name =3D=3D LintNames.type_init_formals) { +- await _addFix_removeTypeAnnotation(); +- } +- if (name =3D=3D LintNames.unnecessary_brace_in_string_interp) { +- await _addFix_removeInterpolationBraces(); +- } +- if (name =3D=3D LintNames.unnecessary_lambdas) { +- await _addFix_replaceWithTearOff(); +- } +- if (name =3D=3D LintNames.unnecessary_override) { +- await _addFix_removeMethodDeclaration(); +- } +- if (name =3D=3D LintNames.unnecessary_this) { +- await _addFix_removeThisExpression(); +- } +- } +- // done +- return fixes; +- } +- +- /** +- * Returns `true` if the `async` proposal was added. +- */ +- Future _addFix_addAsync() async { +- FunctionBody body =3D node.getAncestor((n) =3D> n is FunctionBody); +- if (body !=3D null && body.keyword =3D=3D null) { +- TypeProvider typeProvider =3D await this.typeProvider; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.convertFunctionFromSyncToAsync(body, typeProvider); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.ADD_ASYNC); +- } +- } +- +- Future _addFix_addMissingMethodCall() async { +- ClassDeclaration targetClass =3D node.parent as ClassDeclaration; +- int insertOffset =3D targetClass.end - 1; +- // prepare environment +- String prefix =3D utils.getIndent(1); +- String prefix2 =3D utils.getIndent(2); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(insertOffset, (DartEditBuilder builder) { +- builder.selectHere(); +- builder.write(prefix); +- builder.write('call() {'); +- // TO-DO +- builder.write(eol); +- builder.write(prefix2); +- builder.write('// TODO: implement call'); +- builder.write(eol); +- // close method +- builder.write(prefix); +- builder.write('}'); +- builder.write(eol); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_MISSING_METHOD_C= ALL); +- } +- +- Future _addFix_addMissingParameter() async { +- if (node is ArgumentList && node.parent is MethodInvocation) { +- ArgumentList argumentList =3D node; +- MethodInvocation invocation =3D node.parent; +- SimpleIdentifier methodName =3D invocation.methodName; +- Element targetElement =3D methodName.bestElement; +- List arguments =3D argumentList.arguments; +- if (targetElement is ExecutableElement) { +- List parameters =3D targetElement.parameters; +- int numParameters =3D parameters.length; +- Iterable requiredParameters =3D parameters +- .takeWhile((p) =3D> p.parameterKind =3D=3D ParameterKind.REQU= IRED); +- Iterable optionalParameters =3D parameters +- .skipWhile((p) =3D> p.parameterKind =3D=3D ParameterKind.REQU= IRED); +- // prepare the argument to add a new parameter for +- int numRequired =3D requiredParameters.length; +- if (numRequired >=3D arguments.length) { +- return; +- } +- Expression argument =3D arguments[numRequired]; +- // prepare target +- int targetOffset; +- if (numRequired !=3D 0) { +- SimpleIdentifier lastName =3D await astProvider +- .getParsedNameForElement(requiredParameters.last); +- if (lastName !=3D null) { +- targetOffset =3D lastName.end; +- } else { +- return; +- } +- } else { +- SimpleIdentifier targetName =3D +- await astProvider.getParsedNameForElement(targetElement); +- AstNode targetDeclaration =3D targetName?.parent; +- if (targetDeclaration is FunctionDeclaration) { +- FunctionExpression function =3D targetDeclaration.functionExp= ression; +- Token paren =3D function.parameters?.leftParenthesis; +- if (paren =3D=3D null) { +- return; +- } +- targetOffset =3D paren.end; +- } else if (targetDeclaration is MethodDeclaration) { +- Token paren =3D targetDeclaration.parameters?.leftParenthesis; +- if (paren =3D=3D null) { +- return; +- } +- targetOffset =3D paren.end; +- } else { +- return; +- } +- } +- Source targetSource =3D targetElement.source; +- String targetFile =3D targetSource.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(targetFile, +- (DartFileEditBuilder builder) { +- builder.addInsertion(targetOffset, (DartEditBuilder builder) { +- if (numRequired !=3D 0) { +- builder.write(', '); +- } +- builder.writeParameterMatchingArgument( +- argument, numRequired, new Set()); +- if (numRequired !=3D numParameters) { +- builder.write(', '); +- } +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.ADD_MISSING_PARAMETER_REQUIRED); +- if (optionalParameters.isEmpty) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(sessi= on); +- await changeBuilder.addFileEdit(targetFile, +- (DartFileEditBuilder builder) { +- builder.addInsertion(targetOffset, (DartEditBuilder builder) { +- if (numRequired !=3D 0) { +- builder.write(', '); +- } +- builder.write('['); +- builder.writeParameterMatchingArgument( +- argument, numRequired, new Set()); +- builder.write(']'); +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.ADD_MISSING_PARAMETER_POSITIONAL= ); +- } +- } +- } +- } +- +- Future _addFix_addMissingRequiredArgument() async { +- Element targetElement; +- ArgumentList argumentList; +- +- if (node is SimpleIdentifier) { +- AstNode invocation =3D node.parent; +- if (invocation is MethodInvocation) { +- targetElement =3D invocation.methodName.bestElement; +- argumentList =3D invocation.argumentList; +- } else { +- AstNode ancestor =3D +- invocation.getAncestor((p) =3D> p is InstanceCreationExpressi= on); +- if (ancestor is InstanceCreationExpression) { +- targetElement =3D ancestor.staticElement; +- argumentList =3D ancestor.argumentList; +- } +- } +- } +- +- if (targetElement is ExecutableElement) { +- // Format: "Missing required argument 'foo" +- List parts =3D error.message.split("'"); +- if (parts.length < 2) { +- return; +- } +- +- // add proposal +- String paramName =3D parts[1]; +- final List args =3D argumentList.arguments; +- int offset =3D +- args.isEmpty ? argumentList.leftParenthesis.end : args.last.end; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addInsertion(offset, (DartEditBuilder builder) { +- if (args.isNotEmpty) { +- builder.write(', '); +- } +- List parameters =3D +- (targetElement as ExecutableElement).parameters; +- ParameterElement element =3D parameters +- .firstWhere((p) =3D> p.name =3D=3D paramName, orElse: () = =3D> null); +- String defaultValue =3D getDefaultStringParameterValue(element); +- builder.write('$paramName: $defaultValue'); +- // Insert a trailing comma after Flutter instance creation para= ms. +- InstanceCreationExpression newExpr =3D +- flutter.identifyNewExpression(node); +- if (newExpr !=3D null && flutter.isWidgetCreation(newExpr)) { +- builder.write(','); +- } +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- args: [paramName]); +- } +- } +- +- Future _addFix_addOverrideAnnotation() async { +- ClassMember member =3D node.getAncestor((n) =3D> n is ClassMember); +- if (member =3D=3D null) { +- return; +- } +- +- //TODO(pq): migrate annotation edit building to change_builder +- +- // Handle doc comments. +- Token token =3D member.beginToken; +- if (token is CommentToken) { +- token =3D (token as CommentToken).parent; +- } +- +- Position exitPosition =3D new Position(file, token.offset - 1); +- String indent =3D utils.getIndent(1); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement( +- range.startLength(token, 0), '@override$eol$indent'); +- }); +- changeBuilder.setSelection(exitPosition); +- _addFixFromBuilder(changeBuilder, DartFixKind.LINT_ADD_OVERRIDE); +- } +- +- Future _addFix_addRequiredAnnotation() async { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleInsertion(node.parent.offset, '@required '); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.LINT_ADD_REQUIRED); +- } +- +- Future _addFix_boolInsteadOfBoolean() async { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(range.error(error), 'bool'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_BOOLEAN_WITH_BO= OL); +- } +- +- Future _addFix_canBeNullAfterNullAware() async { +- AstNode node =3D coveredNode; +- if (node is Expression) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- AstNode parent =3D node.parent; +- while (parent !=3D null) { +- if (parent is MethodInvocation && parent.target =3D=3D node) { +- builder.addSimpleReplacement(range.token(parent.operator), '?= .'); +- } else if (parent is PropertyAccess && parent.target =3D=3D nod= e) { +- builder.addSimpleReplacement(range.token(parent.operator), '?= .'); +- } else { +- break; +- } +- node =3D parent; +- parent =3D node.parent; +- } +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_WITH_NULL_AWA= RE); +- } +- } +- +- Future _addFix_changeTypeAnnotation() async { +- AstNode declaration =3D coveredNode.parent; +- if (declaration is VariableDeclaration && +- declaration.initializer =3D=3D coveredNode) { +- AstNode variableList =3D declaration.parent; +- if (variableList is VariableDeclarationList && +- variableList.variables.length =3D=3D 1) { +- TypeAnnotation typeNode =3D variableList.type; +- if (typeNode !=3D null) { +- Expression initializer =3D coveredNode; +- DartType newType =3D initializer.bestType; +- if (newType is InterfaceType || newType is FunctionType) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(ses= sion); +- await changeBuilder.addFileEdit(file, +- (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(typeNode), +- (DartEditBuilder builder) { +- builder.writeType(newType); +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.CHANGE_TYPE_ANNOTATION, args: [ +- resolutionMap.typeForTypeName(typeNode), +- newType.displayName +- ]); +- } +- } +- } +- } +- } +- +- Future _addFix_convertFlutterChild() async { +- NamedExpression namedExp =3D flutter.findNamedExpression(node, 'child= '); +- if (namedExp =3D=3D null) { +- return; +- } +- InstanceCreationExpression childArg =3D +- flutter.getChildWidget(namedExp, false); +- if (childArg !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- flutter.convertChildToChildren2( +- builder, +- childArg, +- namedExp, +- eol, +- utils.getNodeText, +- utils.getLinePrefix, +- utils.getIndent, +- utils.getText, +- range.node); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CONVERT_FLUTTER_CHILD= ); +- return; +- } +- ListLiteral listArg =3D flutter.getChildList(namedExp); +- if (listArg !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleInsertion(namedExp.offset + 'child'.length, 'ren= '); +- if (listArg.typeArguments =3D=3D null) { +- builder.addSimpleInsertion(listArg.offset, ''); +- } +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CONVERT_FLUTTER_CHILD= ); +- } +- } +- +- Future _addFix_convertFlutterChildren() async { +- // TODO(messick) Implement _addFix_convertFlutterChildren() +- } +- +- Future _addFix_createClass() async { +- Element prefixElement =3D null; +- String name =3D null; +- SimpleIdentifier nameNode; +- if (node is SimpleIdentifier) { +- AstNode parent =3D node.parent; +- if (parent is PrefixedIdentifier) { +- PrefixedIdentifier prefixedIdentifier =3D parent; +- prefixElement =3D prefixedIdentifier.prefix.staticElement; +- if (prefixElement =3D=3D null) { +- return; +- } +- parent =3D prefixedIdentifier.parent; +- nameNode =3D prefixedIdentifier.identifier; +- name =3D prefixedIdentifier.identifier.name; +- } else { +- nameNode =3D node; +- name =3D nameNode.name; +- } +- if (!_mayBeTypeIdentifier(nameNode)) { +- return; +- } +- } else { +- return; +- } +- // prepare environment +- Element targetUnit; +- String prefix =3D ''; +- String suffix =3D ''; +- int offset =3D -1; +- String filePath; +- if (prefixElement =3D=3D null) { +- targetUnit =3D unitElement; +- CompilationUnitMember enclosingMember =3D +- node.getAncestor((node) =3D> node.parent is CompilationUnit); +- if (enclosingMember =3D=3D null) { +- return; +- } +- offset =3D enclosingMember.end; +- filePath =3D file; +- prefix =3D '$eol$eol'; +- } else { +- for (ImportElement import in unitLibraryElement.imports) { +- if (prefixElement is PrefixElement && import.prefix =3D=3D prefix= Element) { +- LibraryElement library =3D import.importedLibrary; +- if (library !=3D null) { +- targetUnit =3D library.definingCompilationUnit; +- Source targetSource =3D targetUnit.source; +- try { +- offset =3D targetSource.contents.data.length; +- filePath =3D targetSource.fullName; +- prefix =3D '$eol'; +- suffix =3D '$eol'; +- } on FileSystemException { +- // If we can't read the file to get the offset, then we can= 't +- // create a fix. +- } +- break; +- } +- } +- } +- } +- if (offset < 0) { +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(filePath, (DartFileEditBuilder builde= r) { +- builder.addInsertion(offset, (DartEditBuilder builder) { +- builder.write(prefix); +- builder.writeClassDeclaration(name, nameGroupName: 'NAME'); +- builder.write(suffix); +- }); +- if (prefixElement =3D=3D null) { +- builder.addLinkedPosition(range.node(node), 'NAME'); +- } +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_CLASS, args: [na= me]); +- } +- +- /** +- * Here we handle cases when there are no constructors in a class, and = the +- * class has uninitialized final fields. +- */ +- Future _addFix_createConstructor_forUninitializedFinalFields() as= ync { +- if (node is! SimpleIdentifier || node.parent is! VariableDeclaration)= { +- return; +- } +- ClassDeclaration classDeclaration =3D +- node.getAncestor((node) =3D> node is ClassDeclaration); +- if (classDeclaration =3D=3D null) { +- return; +- } +- // prepare names of uninitialized final fields +- List fieldNames =3D []; +- for (ClassMember member in classDeclaration.members) { +- if (member is FieldDeclaration) { +- VariableDeclarationList variableList =3D member.fields; +- if (variableList.isFinal) { +- fieldNames.addAll(variableList.variables +- .where((v) =3D> v.initializer =3D=3D null) +- .map((v) =3D> v.name.name)); +- } +- } +- } +- // prepare location for a new constructor +- ClassMemberLocation targetLocation =3D +- utils.prepareNewConstructorLocation(classDeclaration); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(targetLocation.offset, (DartEditBuilder builde= r) { +- builder.write(targetLocation.prefix); +- builder.writeConstructorDeclaration(classDeclaration.name.name, +- fieldNames: fieldNames); +- builder.write(targetLocation.suffix); +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.CREATE_CONSTRUCTOR_FOR_FINAL_FIELDS); +- } +- +- Future _addFix_createConstructor_insteadOfSyntheticDefault() asyn= c { +- if (node is! ArgumentList) { +- return; +- } +- if (node.parent is! InstanceCreationExpression) { +- return; +- } +- InstanceCreationExpression instanceCreation =3D node.parent; +- ConstructorName constructorName =3D instanceCreation.constructorName; +- // should be synthetic default constructor +- ConstructorElement constructorElement =3D constructorName.staticEleme= nt; +- if (constructorElement =3D=3D null || +- !constructorElement.isDefaultConstructor || +- !constructorElement.isSynthetic) { +- return; +- } +- // prepare target +- if (constructorElement.enclosingElement is! ClassElement) { +- return; +- } +- ClassElement targetElement =3D constructorElement.enclosingElement; +- // prepare location for a new constructor +- AstNode targetTypeNode =3D getParsedClassElementNode(targetElement); +- if (targetTypeNode is! ClassDeclaration) { +- return; +- } +- ClassMemberLocation targetLocation =3D +- utils.prepareNewConstructorLocation(targetTypeNode); +- Source targetSource =3D targetElement.source; +- String targetFile =3D targetSource.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(targetFile, (DartFileEditBuilder buil= der) { +- builder.addInsertion(targetLocation.offset, (DartEditBuilder builde= r) { +- builder.write(targetLocation.prefix); +- builder.writeConstructorDeclaration(targetElement.name, +- argumentList: instanceCreation.argumentList); +- builder.write(targetLocation.suffix); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_CONSTRUCTOR, +- args: [constructorName]); +- } +- +- Future _addFix_createConstructor_named() async { +- SimpleIdentifier name =3D null; +- ConstructorName constructorName =3D null; +- InstanceCreationExpression instanceCreation =3D null; +- if (node is SimpleIdentifier) { +- // name +- name =3D node as SimpleIdentifier; +- if (name.parent is ConstructorName) { +- constructorName =3D name.parent as ConstructorName; +- if (constructorName.name =3D=3D name) { +- // Type.name +- if (constructorName.parent is InstanceCreationExpression) { +- instanceCreation =3D +- constructorName.parent as InstanceCreationExpression; +- // new Type.name() +- if (instanceCreation.constructorName !=3D constructorName) { +- return; +- } +- } +- } +- } +- } +- // do we have enough information? +- if (instanceCreation =3D=3D null) { +- return; +- } +- // prepare target interface type +- DartType targetType =3D constructorName.type.type; +- if (targetType is! InterfaceType) { +- return; +- } +- // prepare location for a new constructor +- ClassElement targetElement =3D targetType.element as ClassElement; +- AstNode targetTypeNode =3D getParsedClassElementNode(targetElement); +- if (targetTypeNode is! ClassDeclaration) { +- return; +- } +- ClassMemberLocation targetLocation =3D +- utils.prepareNewConstructorLocation(targetTypeNode); +- String targetFile =3D targetElement.source.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(targetLocation.offset, (DartEditBuilder builde= r) { +- builder.write(targetLocation.prefix); +- builder.writeConstructorDeclaration(targetElement.name, +- argumentList: instanceCreation.argumentList, +- constructorName: name, +- constructorNameGroupName: 'NAME'); +- builder.write(targetLocation.suffix); +- }); +- if (targetFile =3D=3D file) { +- builder.addLinkedPosition(range.node(name), 'NAME'); +- } +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_CONSTRUCTOR, +- args: [constructorName]); +- } +- +- Future _addFix_createConstructorSuperExplicit() async { +- if (node.parent is! ConstructorDeclaration || +- node.parent.parent is! ClassDeclaration) { +- return; +- } +- ConstructorDeclaration targetConstructor =3D +- node.parent as ConstructorDeclaration; +- ClassDeclaration targetClassNode =3D +- targetConstructor.parent as ClassDeclaration; +- ClassElement targetClassElement =3D targetClassNode.element; +- InterfaceType superType =3D targetClassElement.supertype; +- // add proposals for all super constructors +- for (ConstructorElement superConstructor in superType.constructors) { +- String constructorName =3D superConstructor.name; +- // skip private +- if (Identifier.isPrivateName(constructorName)) { +- continue; +- } +- List initializers =3D +- targetConstructor.initializers; +- int insertOffset; +- String prefix; +- if (initializers.isEmpty) { +- insertOffset =3D targetConstructor.parameters.end; +- prefix =3D ' : '; +- } else { +- ConstructorInitializer lastInitializer =3D +- initializers[initializers.length - 1]; +- insertOffset =3D lastInitializer.end; +- prefix =3D ', '; +- } +- String proposalName =3D _getConstructorProposalName(superConstructo= r); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addInsertion(insertOffset, (DartEditBuilder builder) { +- builder.write(prefix); +- // add super constructor name +- builder.write('super'); +- if (!isEmpty(constructorName)) { +- builder.write('.'); +- builder.addSimpleLinkedEdit('NAME', constructorName); +- } +- // add arguments +- builder.write('('); +- bool firstParameter =3D true; +- for (ParameterElement parameter in superConstructor.parameters)= { +- // skip non-required parameters +- if (parameter.parameterKind !=3D ParameterKind.REQUIRED) { +- break; +- } +- // comma +- if (firstParameter) { +- firstParameter =3D false; +- } else { +- builder.write(', '); +- } +- // default value +- builder.addSimpleLinkedEdit( +- parameter.name, getDefaultValueCode(parameter.type)); +- } +- builder.write(')'); +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.ADD_SUPER_CONSTRUCTOR_INVOCATION, +- args: [proposalName]); +- } +- } +- +- Future _addFix_createConstructorSuperImplicit() async { +- ClassDeclaration targetClassNode =3D node.parent as ClassDeclaration; +- ClassElement targetClassElement =3D targetClassNode.element; +- InterfaceType superType =3D targetClassElement.supertype; +- String targetClassName =3D targetClassElement.name; +- // add proposals for all super constructors +- for (ConstructorElement superConstructor in superType.constructors) { +- superConstructor =3D ConstructorMember.from(superConstructor, super= Type); +- String constructorName =3D superConstructor.name; +- // skip private +- if (Identifier.isPrivateName(constructorName)) { +- continue; +- } +- // prepare parameters and arguments +- Iterable requiredParameters =3D +- superConstructor.parameters.where( +- (parameter) =3D> parameter.parameterKind =3D=3D ParameterKi= nd.REQUIRED); +- // add proposal +- ClassMemberLocation targetLocation =3D +- utils.prepareNewConstructorLocation(targetClassNode); +- String proposalName =3D _getConstructorProposalName(superConstructo= r); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addInsertion(targetLocation.offset, (DartEditBuilder buil= der) { +- void writeParameters(bool includeType) { +- bool firstParameter =3D true; +- for (ParameterElement parameter in requiredParameters) { +- if (firstParameter) { +- firstParameter =3D false; +- } else { +- builder.write(', '); +- } +- String parameterName =3D parameter.displayName; +- if (parameterName.length > 1 && parameterName.startsWith('_= ')) { +- parameterName =3D parameterName.substring(1); +- } +- if (includeType && builder.writeType(parameter.type)) { +- builder.write(' '); +- } +- builder.write(parameterName); +- } +- } +- +- builder.write(targetLocation.prefix); +- builder.write(targetClassName); +- if (!constructorName.isEmpty) { +- builder.write('.'); +- builder.addSimpleLinkedEdit('NAME', constructorName); +- } +- builder.write('('); +- writeParameters(true); +- builder.write(') : super'); +- if (!constructorName.isEmpty) { +- builder.write('.'); +- builder.addSimpleLinkedEdit('NAME', constructorName); +- } +- builder.write('('); +- writeParameters(false); +- builder.write(');'); +- builder.write(targetLocation.suffix); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_CONSTRUCTOR_SU= PER, +- args: [proposalName]); +- } +- } +- +- Future _addFix_createField() async { +- if (node is! SimpleIdentifier) { +- return; +- } +- SimpleIdentifier nameNode =3D node; +- String name =3D nameNode.name; +- // prepare target Expression +- Expression target; +- { +- AstNode nameParent =3D nameNode.parent; +- if (nameParent is PrefixedIdentifier) { +- target =3D nameParent.prefix; +- } else if (nameParent is PropertyAccess) { +- target =3D nameParent.realTarget; +- } +- } +- // prepare target ClassElement +- bool staticModifier =3D false; +- ClassElement targetClassElement; +- if (target !=3D null) { +- // prepare target interface type +- DartType targetType =3D target.bestType; +- if (targetType is! InterfaceType) { +- return; +- } +- targetClassElement =3D targetType.element; +- // maybe static +- if (target is Identifier) { +- Identifier targetIdentifier =3D target; +- Element targetElement =3D targetIdentifier.bestElement; +- if (targetElement =3D=3D null) { +- return; +- } +- staticModifier =3D targetElement.kind =3D=3D ElementKind.CLASS; +- } +- } else { +- targetClassElement =3D getEnclosingClassElement(node); +- if (targetClassElement =3D=3D null) { +- return; +- } +- staticModifier =3D _inStaticContext(); +- } +- if (targetClassElement.librarySource.isInSystemLibrary) { +- return; +- } +- utils.targetClassElement =3D targetClassElement; +- // prepare target ClassDeclaration +- AstNode targetTypeNode =3D getParsedClassElementNode(targetClassEleme= nt); +- if (targetTypeNode is! ClassDeclaration) { +- return; +- } +- ClassDeclaration targetClassNode =3D targetTypeNode; +- // prepare location +- ClassMemberLocation targetLocation =3D +- _getUtilsFor(targetClassNode).prepareNewFieldLocation(targetClass= Node); +- // build field source +- Source targetSource =3D targetClassElement.source; +- String targetFile =3D targetSource.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(targetFile, (DartFileEditBuilder buil= der) { +- Expression fieldTypeNode =3D climbPropertyAccess(nameNode); +- DartType fieldType =3D _inferUndefinedExpressionType(fieldTypeNode); +- builder.addInsertion(targetLocation.offset, (DartEditBuilder builde= r) { +- builder.write(targetLocation.prefix); +- builder.writeFieldDeclaration(name, +- isStatic: staticModifier, +- nameGroupName: 'NAME', +- type: fieldType, +- typeGroupName: 'TYPE'); +- builder.write(targetLocation.suffix); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_FIELD, args: [na= me]); +- } +- +- Future _addFix_createField_initializingFormal() async { +- // +- // Ensure that we are in an initializing formal parameter. +- // +- FieldFormalParameter parameter =3D +- node.getAncestor((node) =3D> node is FieldFormalParameter); +- if (parameter =3D=3D null) { +- return; +- } +- ClassDeclaration targetClassNode =3D +- parameter.getAncestor((node) =3D> node is ClassDeclaration); +- if (targetClassNode =3D=3D null) { +- return; +- } +- SimpleIdentifier nameNode =3D parameter.identifier; +- String name =3D nameNode.name; +- ClassMemberLocation targetLocation =3D +- utils.prepareNewFieldLocation(targetClassNode); +- // +- // Add proposal. +- // +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- DartType fieldType =3D parameter.type?.type; +- builder.addInsertion(targetLocation.offset, (DartEditBuilder builde= r) { +- builder.write(targetLocation.prefix); +- builder.writeFieldDeclaration(name, +- nameGroupName: 'NAME', type: fieldType, typeGroupName: 'TYPE'= ); +- builder.write(targetLocation.suffix); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_FIELD, args: [na= me]); +- } +- +- Future _addFix_createFunction_forFunctionType() async { +- if (node is SimpleIdentifier) { +- SimpleIdentifier nameNode =3D node as SimpleIdentifier; +- // prepare argument expression (to get parameter) +- ClassElement targetElement; +- Expression argument; +- { +- Expression target =3D getQualifiedPropertyTarget(node); +- if (target !=3D null) { +- DartType targetType =3D target.bestType; +- if (targetType !=3D null && targetType.element is ClassElement)= { +- targetElement =3D targetType.element as ClassElement; +- argument =3D target.parent as Expression; +- } else { +- return; +- } +- } else { +- ClassDeclaration enclosingClass =3D +- node.getAncestor((node) =3D> node is ClassDeclaration); +- targetElement =3D enclosingClass?.element; +- argument =3D nameNode; +- } +- } +- argument =3D stepUpNamedExpression(argument); +- // should be argument of some invocation +- ParameterElement parameterElement =3D argument.bestParameterElement; +- if (parameterElement =3D=3D null) { +- return; +- } +- // should be parameter of function type +- DartType parameterType =3D parameterElement.type; +- if (parameterType is InterfaceType && parameterType.isDartCoreFunct= ion) { +- ExecutableElement element =3D new MethodElementImpl('', -1); +- parameterType =3D new FunctionTypeImpl(element); +- } +- if (parameterType is! FunctionType) { +- return; +- } +- FunctionType functionType =3D parameterType as FunctionType; +- // add proposal +- if (targetElement !=3D null) { +- await _addProposal_createFunction_method(targetElement, functionT= ype); +- } else { +- await _addProposal_createFunction_function(functionType); +- } +- } +- } +- +- Future _addFix_createGetter() async { +- if (node is! SimpleIdentifier) { +- return; +- } +- SimpleIdentifier nameNode =3D node; +- String name =3D nameNode.name; +- if (!nameNode.inGetterContext()) { +- return; +- } +- // prepare target Expression +- Expression target; +- { +- AstNode nameParent =3D nameNode.parent; +- if (nameParent is PrefixedIdentifier) { +- target =3D nameParent.prefix; +- } else if (nameParent is PropertyAccess) { +- target =3D nameParent.realTarget; +- } +- } +- // prepare target ClassElement +- bool staticModifier =3D false; +- ClassElement targetClassElement; +- if (target !=3D null) { +- // prepare target interface type +- DartType targetType =3D target.bestType; +- if (targetType is! InterfaceType) { +- return; +- } +- targetClassElement =3D targetType.element; +- // maybe static +- if (target is Identifier) { +- Identifier targetIdentifier =3D target; +- Element targetElement =3D targetIdentifier.bestElement; +- staticModifier =3D targetElement.kind =3D=3D ElementKind.CLASS; +- } +- } else { +- targetClassElement =3D getEnclosingClassElement(node); +- if (targetClassElement =3D=3D null) { +- return; +- } +- staticModifier =3D _inStaticContext(); +- } +- if (targetClassElement.librarySource.isInSystemLibrary) { +- return; +- } +- utils.targetClassElement =3D targetClassElement; +- // prepare target ClassDeclaration +- AstNode targetTypeNode =3D getParsedClassElementNode(targetClassEleme= nt); +- if (targetTypeNode is! ClassDeclaration) { +- return; +- } +- ClassDeclaration targetClassNode =3D targetTypeNode; +- // prepare location +- ClassMemberLocation targetLocation =3D +- _getUtilsFor(targetClassNode).prepareNewGetterLocation(targetClas= sNode); +- // build method source +- Source targetSource =3D targetClassElement.source; +- String targetFile =3D targetSource.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(targetFile, (DartFileEditBuilder buil= der) { +- builder.addInsertion(targetLocation.offset, (DartEditBuilder builde= r) { +- Expression fieldTypeNode =3D climbPropertyAccess(nameNode); +- DartType fieldType =3D _inferUndefinedExpressionType(fieldTypeNod= e); +- builder.write(targetLocation.prefix); +- builder.writeGetterDeclaration(name, +- isStatic: staticModifier, +- nameGroupName: 'NAME', +- returnType: fieldType, +- returnTypeGroupName: 'TYPE'); +- builder.write(targetLocation.suffix); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_GETTER, args: [n= ame]); +- } +- +- Future _addFix_createImportUri() async { +- // TODO(brianwilkerson) Generalize this to allow other valid string l= iterals. +- // TODO(brianwilkerson) Support the case where the node's parent is a= Configuration. +- if (node is SimpleStringLiteral && node.parent is ImportDirective) { +- ImportDirective importDirective =3D node.parent; +- Source source =3D importDirective.uriSource; +- if (source !=3D null) { +- String file =3D source.fullName; +- if (isAbsolute(file) && AnalysisEngine.isDartFileName(file)) { +- String libName =3D _computeLibraryName(file); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(sessi= on); +- await changeBuilder.addFileEdit(source.fullName, +- (DartFileEditBuilder builder) { +- builder.addSimpleInsertion(0, 'library $libName;$eol$eol'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_FILE, +- args: [source.shortName]); +- } +- } +- } +- } +- +- Future _addFix_createLocalVariable() async { +- if (node is! SimpleIdentifier) { +- return; +- } +- SimpleIdentifier nameNode =3D node; +- String name =3D nameNode.name; +- // if variable is assigned, convert assignment into declaration +- if (node.parent is AssignmentExpression) { +- AssignmentExpression assignment =3D node.parent; +- if (assignment.leftHandSide =3D=3D node && +- assignment.operator.type =3D=3D TokenType.EQ && +- assignment.parent is ExpressionStatement) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addSimpleInsertion(node.offset, 'var '); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_LOCAL_VARIAB= LE, +- args: [name]); +- return; +- } +- } +- // prepare target Statement +- Statement target =3D node.getAncestor((x) =3D> x is Statement); +- if (target =3D=3D null) { +- return; +- } +- String prefix =3D utils.getNodePrefix(target); +- // compute type +- DartType type =3D _inferUndefinedExpressionType(node); +- if (!(type =3D=3D null || +- type is InterfaceType || +- type is FunctionType && +- type.element !=3D null && +- !type.element.isSynthetic)) { +- return; +- } +- // build variable declaration source +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(target.offset, (DartEditBuilder builder) { +- builder.writeLocalVariableDeclaration(name, +- nameGroupName: 'NAME', type: type, typeGroupName: 'TYPE'); +- builder.write(eol); +- builder.write(prefix); +- }); +- builder.addLinkedPosition(range.node(node), 'NAME'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_LOCAL_VARIABLE, +- args: [name]); +- } +- +- Future _addFix_createMissingOverrides() async { +- // prepare target +- ClassDeclaration targetClass =3D node.parent as ClassDeclaration; +- ClassElement targetClassElement =3D targetClass.element; +- utils.targetClassElement =3D targetClassElement; +- List elements =3D ErrorVerifier +- .computeMissingOverrides( +- driver.analysisOptions.strongMode, +- typeProvider, +- typeSystem, +- new InheritanceManager(unitLibraryElement), +- targetClassElement) +- .toList(); +- // sort by name, getters before setters +- elements.sort((Element a, Element b) { +- int names =3D compareStrings(a.displayName, b.displayName); +- if (names !=3D 0) { +- return names; +- } +- if (a.kind =3D=3D ElementKind.GETTER) { +- return -1; +- } +- return 1; +- }); +- int numElements =3D elements.length; +- +- ClassMemberLocation location =3D +- utils.prepareNewClassMemberLocation(targetClass, (_) =3D> true); +- +- String prefix =3D utils.getIndent(1); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(location.offset, (DartEditBuilder builder) { +- // TODO(brianwilkerson) Compare with builder.writeOverrideOfInher= itedMember +- // The builder method doesn't merge getter/setter pairs into fiel= ds. +- +- // Separator management. +- int numOfMembersWritten =3D 0; +- void addSeparatorBetweenDeclarations() { +- if (numOfMembersWritten =3D=3D 0) { +- builder.write(location.prefix); +- } else { +- builder.write(eol); // after the previous member +- builder.write(eol); // empty line separator +- builder.write(prefix); +- } +- numOfMembersWritten++; +- } +- +- // merge getter/setter pairs into fields +- for (int i =3D 0; i < elements.length; i++) { +- ExecutableElement element =3D elements[i]; +- if (element.kind =3D=3D ElementKind.GETTER && i + 1 < elements.= length) { +- ExecutableElement nextElement =3D elements[i + 1]; +- if (nextElement.kind =3D=3D ElementKind.SETTER) { +- // remove this and the next elements, adjust iterator +- elements.removeAt(i + 1); +- elements.removeAt(i); +- i--; +- numElements--; +- // separator +- addSeparatorBetweenDeclarations(); +- // @override +- builder.write('@override'); +- builder.write(eol); +- // add field +- builder.write(prefix); +- builder.writeType(element.type.returnType, required: true); +- builder.write(' '); +- builder.write(element.name); +- builder.write(';'); +- } +- } +- } +- // add elements +- for (ExecutableElement element in elements) { +- addSeparatorBetweenDeclarations(); +- _addFix_createMissingOverridesForBuilder( +- builder, targetClass, element); +- } +- builder.write(location.suffix); +- }); +- }); +- changeBuilder.setSelection(new Position(file, location.offset)); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_MISSING_OVERRIDE= S, +- args: [numElements]); +- } +- +- void _addFix_createMissingOverridesForBuilder(DartEditBuilder builder, +- ClassDeclaration targetClass, ExecutableElement element) { +- utils.targetExecutableElement =3D element; +- // prepare environment +- String prefix =3D utils.getIndent(1); +- String prefix2 =3D utils.getIndent(2); +- // may be property +- ElementKind elementKind =3D element.kind; +- bool isGetter =3D elementKind =3D=3D ElementKind.GETTER; +- bool isSetter =3D elementKind =3D=3D ElementKind.SETTER; +- bool isMethod =3D elementKind =3D=3D ElementKind.METHOD; +- bool isOperator =3D isMethod && (element as MethodElement).isOperator; +- if (isGetter) { +- builder.write('// TODO: implement ${element.displayName}'); +- builder.write(eol); +- builder.write(prefix); +- } +- // @override +- builder.write('@override'); +- builder.write(eol); +- builder.write(prefix); +- // return type +- if (!isSetter) { +- if (builder.writeType(element.type.returnType, +- methodBeingCopied: element)) { +- builder.write(' '); +- } +- } +- // keyword +- if (isGetter) { +- builder.write('get '); +- } else if (isSetter) { +- builder.write('set '); +- } else if (isOperator) { +- builder.write('operator '); +- } +- // name +- builder.write(element.displayName); +- builder.writeTypeParameters(element.typeParameters); +- // parameters + body +- if (isGetter) { +- builder.write(' =3D> null;'); +- } else { +- List parameters =3D element.parameters; +- builder.writeParameters(parameters, methodBeingCopied: element); +- builder.write(' {'); +- // TO-DO +- builder.write(eol); +- builder.write(prefix2); +- builder.write('// TODO: implement ${element.displayName}'); +- builder.write(eol); +- // close method +- builder.write(prefix); +- builder.write('}'); +- } +- utils.targetExecutableElement =3D null; +- } +- +- Future _addFix_createNoSuchMethod() async { +- ClassDeclaration targetClass =3D node.parent as ClassDeclaration; +- // prepare environment +- String prefix =3D utils.getIndent(1); +- int insertOffset =3D targetClass.end - 1; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(insertOffset, (DartEditBuilder builder) { +- builder.selectHere(); +- // insert empty line before existing member +- if (!targetClass.members.isEmpty) { +- builder.write(eol); +- } +- // append method +- builder.write(prefix); +- builder.write( +- 'noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(= invocation);'); +- builder.write(eol); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_NO_SUCH_METHOD); +- } +- +- Future _addFix_createPartUri() async { +- // TODO(brianwilkerson) Generalize this to allow other valid string l= iterals. +- if (node is SimpleStringLiteral && node.parent is PartDirective) { +- PartDirective partDirective =3D node.parent; +- Source source =3D partDirective.uriSource; +- if (source !=3D null) { +- String libName =3D unitLibraryElement.name; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(source.fullName, +- (DartFileEditBuilder builder) { +- // TODO(brianwilkerson) Consider using the URI rather than name +- builder.addSimpleInsertion(0, 'part of $libName;$eol$eol'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_FILE, +- args: [source.shortName]); +- } +- } +- } +- +- Future _addFix_illegalAsyncReturnType() async { +- // prepare the existing type +- TypeAnnotation typeName =3D node.getAncestor((n) =3D> n is TypeAnnota= tion); +- TypeProvider typeProvider =3D this.typeProvider; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.replaceTypeWithFuture(typeName, typeProvider); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_RETURN_TYPE_FUT= URE); +- } +- +- Future _addFix_importLibrary(FixKind kind, Source library) async { +- String libraryUri =3D getLibrarySourceUri(unitLibraryElement, library= ); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.importLibraries([library]); +- }); +- _addFixFromBuilder(changeBuilder, kind, args: [libraryUri]); +- } +- +- Future _addFix_importLibrary_withElement(String name, +- List elementKinds, TopLevelDeclarationKind kind2) asyn= c { +- // ignore if private +- if (name.startsWith('_')) { +- return; +- } +- // may be there is an existing import, +- // but it is with prefix and we don't use this prefix +- Set alreadyImportedWithPrefix =3D new Set(); +- for (ImportElement imp in unitLibraryElement.imports) { +- // prepare element +- LibraryElement libraryElement =3D imp.importedLibrary; +- Element element =3D getExportedElement(libraryElement, name); +- if (element =3D=3D null) { +- continue; +- } +- if (element is PropertyAccessorElement) { +- element =3D (element as PropertyAccessorElement).variable; +- } +- if (!elementKinds.contains(element.kind)) { +- continue; +- } +- // may be apply prefix +- PrefixElement prefix =3D imp.prefix; +- if (prefix !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addSimpleReplacement( +- range.startLength(node, 0), '${prefix.displayName}.'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.IMPORT_LIBRARY_PREF= IX, +- args: [libraryElement.displayName, prefix.displayName]); +- continue; +- } +- // may be update "show" directive +- List combinators =3D imp.combinators; +- if (combinators.length =3D=3D 1 && combinators[0] is ShowElementCom= binator) { +- ShowElementCombinator showCombinator =3D +- combinators[0] as ShowElementCombinator; +- // prepare new set of names to show +- Set showNames =3D new SplayTreeSet(); +- showNames.addAll(showCombinator.shownNames); +- showNames.add(name); +- // prepare library name - unit name or 'dart:name' for SDK library +- String libraryName =3D libraryElement.definingCompilationUnit.dis= playName; +- if (libraryElement.isInSdk) { +- libraryName =3D libraryElement.source.shortName; +- } +- // don't add this library again +- alreadyImportedWithPrefix.add(libraryElement.source); +- // update library +- String newShowCode =3D 'show ${showNames.join(', ')}'; +- int offset =3D showCombinator.offset; +- int length =3D showCombinator.end - offset; +- String libraryFile =3D unitLibraryElement.source.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(libraryFile, +- (DartFileEditBuilder builder) { +- builder.addSimpleReplacement( +- new SourceRange(offset, length), newShowCode); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.IMPORT_LIBRARY_SHOW, +- args: [libraryName]); +- } +- } +- // Find new top-level declarations. +- { +- List declarations =3D +- await getTopLevelDeclarations(name); +- for (TopLevelDeclarationInSource declaration in declarations) { +- // Check the kind. +- if (declaration.declaration.kind !=3D kind2) { +- continue; +- } +- // Check the source. +- Source librarySource =3D declaration.source; +- if (alreadyImportedWithPrefix.contains(librarySource)) { +- continue; +- } +- if (!_isSourceVisibleToLibrary(librarySource)) { +- continue; +- } +- // Compute the fix kind. +- FixKind fixKind; +- if (librarySource.isInSystemLibrary) { +- fixKind =3D DartFixKind.IMPORT_LIBRARY_SDK; +- } else if (_isLibSrcPath(librarySource.fullName)) { +- // Bad: non-API. +- fixKind =3D DartFixKind.IMPORT_LIBRARY_PROJECT3; +- } else if (declaration.isExported) { +- // Ugly: exports. +- fixKind =3D DartFixKind.IMPORT_LIBRARY_PROJECT2; +- } else { +- // Good: direct declaration. +- fixKind =3D DartFixKind.IMPORT_LIBRARY_PROJECT1; +- } +- // Add the fix. +- await _addFix_importLibrary(fixKind, librarySource); +- } +- } +- } +- +- Future _addFix_importLibrary_withFunction() async { +- if (node is SimpleIdentifier && node.parent is MethodInvocation) { +- MethodInvocation invocation =3D node.parent as MethodInvocation; +- if (invocation.realTarget =3D=3D null && invocation.methodName =3D= =3D node) { +- String name =3D (node as SimpleIdentifier).name; +- await _addFix_importLibrary_withElement(name, +- const [ElementKind.FUNCTION], TopLevelDeclarationKind.functio= n); +- } +- } +- } +- +- Future _addFix_importLibrary_withTopLevelVariable() async { +- if (node is SimpleIdentifier) { +- String name =3D (node as SimpleIdentifier).name; +- await _addFix_importLibrary_withElement( +- name, +- const [ElementKind.TOP_LEVEL_VARIABLE], +- TopLevelDeclarationKind.variable); +- } +- } +- +- Future _addFix_importLibrary_withType() async { +- if (_mayBeTypeIdentifier(node)) { +- String typeName =3D (node as SimpleIdentifier).name; +- await _addFix_importLibrary_withElement( +- typeName, +- const [ElementKind.CLASS, ElementKind.FUNCTION_TYPE_ALIAS], +- TopLevelDeclarationKind.type); +- } +- } +- +- Future _addFix_insertSemicolon() async { +- if (error.message.contains("';'")) { +- if (_isAwaitNode()) { +- return; +- } +- int insertOffset =3D error.offset + error.length; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleInsertion(insertOffset, ';'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.INSERT_SEMICOLON); +- } +- } +- +- Future _addFix_isNotEmpty() async { +- if (node is! PrefixExpression) { +- return; +- } +- PrefixExpression prefixExpression =3D node; +- Token negation =3D prefixExpression.operator; +- if (negation.type !=3D TokenType.BANG) { +- return; +- } +- SimpleIdentifier identifier; +- Expression expression =3D prefixExpression.operand; +- if (expression is PrefixedIdentifier) { +- identifier =3D expression.identifier; +- } else if (expression is PropertyAccess) { +- identifier =3D expression.propertyName; +- } else { +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion(range.token(negation)); +- builder.addSimpleReplacement(range.node(identifier), 'isNotEmpty'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.USE_IS_NOT_EMPTY); +- } +- +- Future _addFix_isNotNull() async { +- if (coveredNode is IsExpression) { +- IsExpression isExpression =3D coveredNode as IsExpression; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder +- .addReplacement(range.endEnd(isExpression.expression, isExpre= ssion), +- (DartEditBuilder builder) { +- builder.write(' !=3D null'); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.USE_NOT_EQ_NULL); +- } +- } +- +- Future _addFix_isNull() async { +- if (coveredNode is IsExpression) { +- IsExpression isExpression =3D coveredNode as IsExpression; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder +- .addReplacement(range.endEnd(isExpression.expression, isExpre= ssion), +- (DartEditBuilder builder) { +- builder.write(' =3D=3D null'); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.USE_EQ_EQ_NULL); +- } +- } +- +- Future _addFix_makeEnclosingClassAbstract() async { +- ClassDeclaration enclosingClass =3D +- node.getAncestor((node) =3D> node is ClassDeclaration); +- if (enclosingClass =3D=3D null) { +- return; +- } +- String className =3D enclosingClass.name.name; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleInsertion( +- enclosingClass.classKeyword.offset, 'abstract '); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.MAKE_CLASS_ABSTRACT, +- args: [className]); +- } +- +- Future _addFix_makeFieldNotFinal() async { +- AstNode node =3D this.node; +- if (node is SimpleIdentifier && +- node.bestElement is PropertyAccessorElement) { +- PropertyAccessorElement getter =3D node.bestElement; +- if (getter.isGetter && +- getter.isSynthetic && +- !getter.variable.isSynthetic && +- getter.variable.setter =3D=3D null && +- getter.enclosingElement is ClassElement) { +- AstNode name =3D +- await astProvider.getParsedNameForElement(getter.variable); +- AstNode variable =3D name?.parent; +- if (variable is VariableDeclaration && +- variable.parent is VariableDeclarationList && +- variable.parent.parent is FieldDeclaration) { +- VariableDeclarationList declarationList =3D variable.parent; +- Token keywordToken =3D declarationList.keyword; +- if (declarationList.variables.length =3D=3D 1 && +- keywordToken.keyword =3D=3D Keyword.FINAL) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(ses= sion); +- await changeBuilder.addFileEdit(file, +- (DartFileEditBuilder builder) { +- if (declarationList.type !=3D null) { +- builder.addReplacement( +- range.startStart(keywordToken, declarationList.type), +- (DartEditBuilder builder) {}); +- } else { +- builder.addReplacement(range.startStart(keywordToken, var= iable), +- (DartEditBuilder builder) { +- builder.write('var '); +- }); +- } +- }); +- String fieldName =3D getter.variable.displayName; +- _addFixFromBuilder(changeBuilder, DartFixKind.MAKE_FIELD_NOT_= FINAL, +- args: [fieldName]); +- } +- } +- } +- } +- } +- +- Future _addFix_nonBoolCondition_addNotNull() async { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleInsertion(error.offset + error.length, ' !=3D null= '); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.ADD_NE_NULL); +- } +- +- Future _addFix_removeAwait() async { +- final awaitExpression =3D node; +- if (awaitExpression is AwaitExpression) { +- final awaitToken =3D awaitExpression.awaitKeyword; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(range.startStart(awaitToken, awaitToken.next)= ); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_AWAIT); +- } +- } +- +- Future _addFix_removeDeadCode() async { +- AstNode coveringNode =3D this.coveredNode; +- if (coveringNode is Expression) { +- AstNode parent =3D coveredNode.parent; +- if (parent is BinaryExpression) { +- if (parent.rightOperand =3D=3D coveredNode) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(sessi= on); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder buil= der) { +- builder.addDeletion(range.endEnd(parent.leftOperand, coveredN= ode)); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_DEAD_CODE); +- } +- } +- } else if (coveringNode is Block) { +- Block block =3D coveringNode; +- List statementsToRemove =3D []; +- for (Statement statement in block.statements) { +- if (range.node(statement).intersects(errorRange)) { +- statementsToRemove.add(statement); +- } +- } +- if (statementsToRemove.isNotEmpty) { +- SourceRange rangeToRemove =3D +- utils.getLinesRangeStatements(statementsToRemove); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addDeletion(rangeToRemove); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_DEAD_CODE); +- } +- } else if (coveringNode is Statement) { +- SourceRange rangeToRemove =3D +- utils.getLinesRangeStatements([coveringNode]); +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(rangeToRemove); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_DEAD_CODE); +- } +- } +- +- Future _addFix_removeEmptyCatch() async { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion(utils.getLinesRange(range.node(node.parent))); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_EMPTY_CATCH); +- } +- +- Future _addFix_removeEmptyConstructorBody() async { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement( +- utils.getLinesRange(range.node(node.parent)), ';'); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.REMOVE_EMPTY_CONSTRUCTOR_BODY); +- } +- +- Future _addFix_removeEmptyElse() async { +- IfStatement ifStatement =3D node.parent; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion(utils.getLinesRange( +- range.startEnd(ifStatement.elseKeyword, ifStatement.elseStateme= nt))); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_EMPTY_ELSE); +- } +- +- Future _addFix_removeEmptyStatement() async { +- EmptyStatement emptyStatement =3D node; +- if (emptyStatement.parent is Block) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(utils.getLinesRange(range.node(emptyStatement= ))); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_EMPTY_STATEMEN= T); +- } else { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleReplacement( +- range.endEnd(emptyStatement.beginToken.previous, emptyStateme= nt), +- ' {}'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_WITH_BRACKETS= ); +- } +- } +- +- Future _addFix_removeInitializer() async { +- // Retrieve the linted node. +- VariableDeclaration ancestor =3D +- node.getAncestor((a) =3D> a is VariableDeclaration); +- if (ancestor =3D=3D null) { +- return; +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion(range.endEnd(ancestor.name, ancestor.initialize= r)); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_INITIALIZER); +- } +- +- Future _addFix_removeInterpolationBraces() async { +- AstNode node =3D this.node; +- if (node is InterpolationExpression) { +- Token right =3D node.rightBracket; +- if (node.expression !=3D null && right !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addSimpleReplacement( +- range.startStart(node, node.expression), r'$'); +- builder.addDeletion(range.token(right)); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.LINT_REMOVE_INTERPOLATION_BRACES); +- } else {} +- } +- } +- +- Future _addFix_removeMethodDeclaration() async { +- MethodDeclaration declaration =3D +- node.getAncestor((node) =3D> node is MethodDeclaration); +- if (declaration !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(utils.getLinesRange(range.node(declaration))); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_METHOD_DECLARA= TION); +- } +- } +- +- Future _addFix_removeParameters_inGetterDeclaration() async { +- if (node is MethodDeclaration) { +- MethodDeclaration method =3D node as MethodDeclaration; +- SimpleIdentifier name =3D method.name; +- FunctionBody body =3D method.body; +- if (name !=3D null && body !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addSimpleReplacement(range.endStart(name, body), ' '); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.REMOVE_PARAMETERS_IN_GETTER_DECLAR= ATION); +- } +- } +- } +- +- Future _addFix_removeParentheses_inGetterInvocation() async { +- if (node is SimpleIdentifier && node.parent is MethodInvocation) { +- MethodInvocation invocation =3D node.parent as MethodInvocation; +- if (invocation.methodName =3D=3D node && invocation.target !=3D nul= l) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addDeletion(range.endEnd(node, invocation)); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.REMOVE_PARENTHESIS_IN_GETTER_INVOC= ATION); +- } +- } +- } +- +- Future _addFix_removeThisExpression() async { +- final thisExpression =3D node is ThisExpression +- ? node +- : node.getAncestor((node) =3D> node is ThisExpression); +- final parent =3D thisExpression.parent; +- if (parent is PropertyAccess) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(range.startEnd(parent, parent.operator)); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_THIS_EXPRESSIO= N); +- } else if (parent is MethodInvocation) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(range.startEnd(parent, parent.operator)); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_THIS_EXPRESSIO= N); +- } +- } +- +- Future _addFix_removeTypeAnnotation() async { +- final TypeAnnotation type =3D +- node.getAncestor((node) =3D> node is TypeAnnotation); +- if (type !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addDeletion(range.startStart(type, type.endToken.next)); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_TYPE_NAME); +- } +- } +- +- Future _addFix_removeUnnecessaryCast() async { +- if (coveredNode is! AsExpression) { +- return; +- } +- AsExpression asExpression =3D coveredNode as AsExpression; +- Expression expression =3D asExpression.expression; +- int expressionPrecedence =3D getExpressionPrecedence(expression); +- // remove 'as T' from 'e as T' +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion(range.endEnd(expression, asExpression)); +- _removeEnclosingParentheses(builder, asExpression, expressionPreced= ence); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_UNNECESSARY_CAST= ); +- } +- +- Future _addFix_removeUnusedCatchClause() async { +- if (node is SimpleIdentifier) { +- AstNode catchClause =3D node.parent; +- if (catchClause is CatchClause && +- catchClause.exceptionParameter =3D=3D node) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addDeletion( +- range.startStart(catchClause.catchKeyword, catchClause.body= )); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.REMOVE_UNUSED_CATCH_CLAUSE); +- } +- } +- } +- +- Future _addFix_removeUnusedCatchStack() async { +- if (node is SimpleIdentifier) { +- AstNode catchClause =3D node.parent; +- if (catchClause is CatchClause && +- catchClause.stackTraceParameter =3D=3D node && +- catchClause.exceptionParameter !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder +- .addDeletion(range.endEnd(catchClause.exceptionParameter, n= ode)); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.REMOVE_UNUSED_CATCH_STACK); +- } +- } +- } +- +- Future _addFix_removeUnusedImport() async { +- // prepare ImportDirective +- ImportDirective importDirective =3D +- node.getAncestor((node) =3D> node is ImportDirective); +- if (importDirective =3D=3D null) { +- return; +- } +- // remove the whole line with import +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addDeletion(utils.getLinesRange(range.node(importDirective)= )); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REMOVE_UNUSED_IMPORT); +- } +- +- Future _addFix_replaceVarWithDynamic() async { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addSimpleReplacement(range.error(error), 'dynamic'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_VAR_WITH_DYNAMI= C); +- } +- +- Future _addFix_replaceWithConditionalAssignment() async { +- IfStatement ifStatement =3D node is IfStatement +- ? node +- : node.getAncestor((node) =3D> node is IfStatement); +- var thenStatement =3D ifStatement.thenStatement; +- Statement uniqueStatement(Statement statement) { +- if (statement is Block) { +- return uniqueStatement(statement.statements.first); +- } +- return statement; +- } +- +- thenStatement =3D uniqueStatement(thenStatement); +- if (thenStatement is ExpressionStatement) { +- final expression =3D thenStatement.expression.unParenthesized; +- if (expression is AssignmentExpression) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addReplacement(range.node(ifStatement), +- (DartEditBuilder builder) { +- builder.write(utils.getNodeText(expression.leftHandSide)); +- builder.write(' ??=3D '); +- builder.write(utils.getNodeText(expression.rightHandSide)); +- builder.write(';'); +- }); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.REPLACE_WITH_CONDITIONAL_ASSIGNMEN= T); +- } +- } +- } +- +- Future _addFix_replaceWithConstInstanceCreation() async { +- if (coveredNode is InstanceCreationExpression) { +- var instanceCreation =3D coveredNode as InstanceCreationExpression; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleReplacement( +- range.token(instanceCreation.keyword), 'const'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.USE_CONST); +- } +- } +- +- Future _addFix_replaceWithIdentifier() async { +- final FunctionTypedFormalParameter functionTyped =3D +- node.getAncestor((node) =3D> node is FunctionTypedFormalParameter= ); +- if (functionTyped !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleReplacement(range.node(functionTyped), +- utils.getNodeText(functionTyped.identifier)); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_WITH_IDENTIFI= ER); +- } else { +- await _addFix_removeTypeAnnotation(); +- } +- } +- +- Future _addFix_replaceWithLiteral() async { +- final InstanceCreationExpression instanceCreation =3D +- node.getAncestor((node) =3D> node is InstanceCreationExpression); +- final InterfaceType type =3D instanceCreation.staticType; +- final generics =3D instanceCreation.constructorName.type.typeArgument= s; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addReplacement(range.node(instanceCreation), +- (DartEditBuilder builder) { +- if (generics !=3D null) { +- builder.write(utils.getNodeText(generics)); +- } +- if (type.name =3D=3D 'List') { +- builder.write('[]'); +- } else { +- builder.write('{}'); +- } +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_WITH_LITERAL); +- } +- +- Future _addFix_replaceWithTearOff() async { +- FunctionExpression ancestor =3D +- node.getAncestor((a) =3D> a is FunctionExpression); +- if (ancestor =3D=3D null) { +- return; +- } +- Future addFixOfExpression(InvocationExpression expression) asyn= c { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addReplacement(range.node(ancestor), (DartEditBuilder bui= lder) { +- if (expression is MethodInvocation && expression.target !=3D nu= ll) { +- builder.write(utils.getNodeText(expression.target)); +- builder.write('.'); +- } +- builder.write(utils.getNodeText(expression.function)); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.REPLACE_WITH_TEAR_OFF= ); +- } +- +- final body =3D ancestor.body; +- if (body is ExpressionFunctionBody) { +- final expression =3D body.expression; +- await addFixOfExpression(expression.unParenthesized); +- } else if (body is BlockFunctionBody) { +- final statement =3D body.block.statements.first; +- if (statement is ExpressionStatement) { +- final expression =3D statement.expression; +- await addFixOfExpression(expression.unParenthesized); +- } else if (statement is ReturnStatement) { +- final expression =3D statement.expression; +- await addFixOfExpression(expression.unParenthesized); +- } +- } +- } +- +- Future _addFix_undefinedClass_useSimilar() async { +- AstNode node =3D this.node; +- // Prepare the optional import prefix name. +- String prefixName =3D null; +- if (node is SimpleIdentifier && node.staticElement is PrefixElement) { +- AstNode parent =3D node.parent; +- if (parent is PrefixedIdentifier && +- parent.prefix =3D=3D node && +- parent.parent is TypeName) { +- prefixName =3D (node as SimpleIdentifier).name; +- node =3D parent.identifier; +- } +- } +- // Process if looks like a type. +- if (_mayBeTypeIdentifier(node)) { +- // Prepare for selecting the closest element. +- String name =3D (node as SimpleIdentifier).name; +- _ClosestElementFinder finder =3D new _ClosestElementFinder( +- name, +- (Element element) =3D> element is ClassElement, +- MAX_LEVENSHTEIN_DISTANCE); +- // Check elements of this library. +- if (prefixName =3D=3D null) { +- for (CompilationUnitElement unit in unitLibraryElement.units) { +- finder._updateList(unit.types); +- } +- } +- // Check elements from imports. +- for (ImportElement importElement in unitLibraryElement.imports) { +- if (importElement.prefix?.name =3D=3D prefixName) { +- Map namespace =3D getImportNamespace(importEle= ment); +- finder._updateList(namespace.values); +- } +- } +- // If we have a close enough element, suggest to use it. +- if (finder._element !=3D null) { +- String closestName =3D finder._element.name; +- if (closestName !=3D null) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(sessi= on); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder buil= der) { +- builder.addSimpleReplacement(range.node(node), closestName); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CHANGE_TO, +- args: [closestName]); +- } +- } +- } +- } +- +- Future _addFix_undefinedClassAccessor_useSimilar() async { +- AstNode node =3D this.node; +- if (node is SimpleIdentifier) { +- // prepare target +- Expression target =3D null; +- if (node.parent is PrefixedIdentifier) { +- PrefixedIdentifier invocation =3D node.parent as PrefixedIdentifi= er; +- target =3D invocation.prefix; +- } +- // find getter +- if (node.inGetterContext()) { +- await _addFix_undefinedClassMember_useSimilar(target, +- (Element element) { +- return element is PropertyAccessorElement && element.isGetter || +- element is FieldElement && element.getter !=3D null; +- }); +- } +- // find setter +- if (node.inSetterContext()) { +- await _addFix_undefinedClassMember_useSimilar(target, +- (Element element) { +- return element is PropertyAccessorElement && element.isSetter || +- element is FieldElement && element.setter !=3D null; +- }); +- } +- } +- } +- +- Future _addFix_undefinedClassMember_useSimilar( +- Expression target, ElementPredicate predicate) async { +- if (node is SimpleIdentifier) { +- String name =3D (node as SimpleIdentifier).name; +- _ClosestElementFinder finder =3D +- new _ClosestElementFinder(name, predicate, MAX_LEVENSHTEIN_DIST= ANCE); +- // unqualified invocation +- if (target =3D=3D null) { +- ClassDeclaration clazz =3D +- node.getAncestor((node) =3D> node is ClassDeclaration); +- if (clazz !=3D null) { +- ClassElement classElement =3D clazz.element; +- _updateFinderWithClassMembers(finder, classElement); +- } +- } else { +- DartType type =3D target.bestType; +- if (type is InterfaceType) { +- ClassElement classElement =3D type.element; +- _updateFinderWithClassMembers(finder, classElement); +- } +- } +- // if we have close enough element, suggest to use it +- if (finder._element !=3D null) { +- String closestName =3D finder._element.name; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addSimpleReplacement(range.node(node), closestName); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CHANGE_TO, +- args: [closestName]); +- } +- } +- } +- +- Future _addFix_undefinedFunction_create() async { +- // should be the name of the invocation +- if (node is SimpleIdentifier && node.parent is MethodInvocation) {} e= lse { +- return; +- } +- String name =3D (node as SimpleIdentifier).name; +- MethodInvocation invocation =3D node.parent as MethodInvocation; +- // function invocation has no target +- Expression target =3D invocation.realTarget; +- if (target !=3D null) { +- return; +- } +- // prepare environment +- int insertOffset; +- String sourcePrefix; +- AstNode enclosingMember =3D +- node.getAncestor((node) =3D> node is CompilationUnitMember); +- insertOffset =3D enclosingMember.end; +- sourcePrefix =3D '$eol$eol'; +- utils.targetClassElement =3D null; +- // build method source +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- builder.addInsertion(insertOffset, (DartEditBuilder builder) { +- builder.write(sourcePrefix); +- // append return type +- { +- DartType type =3D _inferUndefinedExpressionType(invocation); +- if (builder.writeType(type, groupName: 'RETURN_TYPE')) { +- builder.write(' '); +- } +- } +- // append name +- builder.addLinkedEdit('NAME', (DartLinkedEditBuilder builder) { +- builder.write(name); +- }); +- builder.write('('); +- builder.writeParametersMatchingArguments(invocation.argumentList); +- builder.write(') {$eol}'); +- }); +- builder.addLinkedPosition(range.node(node), 'NAME'); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_FUNCTION, +- args: [name]); +- } +- +- Future _addFix_undefinedFunction_useSimilar() async { +- AstNode node =3D this.node; +- if (node is SimpleIdentifier) { +- // Prepare the optional import prefix name. +- String prefixName =3D null; +- { +- AstNode invocation =3D node.parent; +- if (invocation is MethodInvocation && invocation.methodName =3D= =3D node) { +- Expression target =3D invocation.target; +- if (target is SimpleIdentifier && +- target.staticElement is PrefixElement) { +- prefixName =3D target.name; +- } +- } +- } +- // Prepare for selecting the closest element. +- _ClosestElementFinder finder =3D new _ClosestElementFinder( +- node.name, +- (Element element) =3D> element is FunctionElement, +- MAX_LEVENSHTEIN_DISTANCE); +- // Check to this library units. +- if (prefixName =3D=3D null) { +- for (CompilationUnitElement unit in unitLibraryElement.units) { +- finder._updateList(unit.functions); +- } +- } +- // Check unprefixed imports. +- for (ImportElement importElement in unitLibraryElement.imports) { +- if (importElement.prefix?.name =3D=3D prefixName) { +- Map namespace =3D getImportNamespace(importEle= ment); +- finder._updateList(namespace.values); +- } +- } +- // If we have a close enough element, suggest to use it. +- if (finder._element !=3D null) { +- String closestName =3D finder._element.name; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- builder.addSimpleReplacement(range.node(node), closestName); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CHANGE_TO, +- args: [closestName]); +- } +- } +- } +- +- Future _addFix_undefinedMethod_create() async { +- if (node is SimpleIdentifier && node.parent is MethodInvocation) { +- String name =3D (node as SimpleIdentifier).name; +- MethodInvocation invocation =3D node.parent as MethodInvocation; +- // prepare environment +- Element targetElement; +- bool staticModifier =3D false; +- +- ClassDeclaration targetClassNode; +- Expression target =3D invocation.realTarget; +- if (target =3D=3D null) { +- targetElement =3D unitElement; +- ClassMember enclosingMember =3D +- node.getAncestor((node) =3D> node is ClassMember); +- targetClassNode =3D enclosingMember.parent; +- utils.targetClassElement =3D targetClassNode.element; +- staticModifier =3D _inStaticContext(); +- } else { +- // prepare target interface type +- DartType targetType =3D target.bestType; +- if (targetType is! InterfaceType) { +- return; +- } +- ClassElement targetClassElement =3D targetType.element as ClassEl= ement; +- if (targetClassElement.librarySource.isInSystemLibrary) { +- return; +- } +- targetElement =3D targetClassElement; +- // prepare target ClassDeclaration +- AstNode targetTypeNode =3D getParsedClassElementNode(targetClassE= lement); +- if (targetTypeNode is! ClassDeclaration) { +- return; +- } +- targetClassNode =3D targetTypeNode; +- // maybe static +- if (target is Identifier) { +- staticModifier =3D +- resolutionMap.bestElementForIdentifier(target).kind =3D=3D +- ElementKind.CLASS; +- } +- // use different utils +- CompilationUnitElement targetUnitElement =3D +- getCompilationUnitElement(targetClassElement); +- CompilationUnit targetUnit =3D getParsedUnit(targetUnitElement); +- utils =3D new CorrectionUtils(targetUnit); +- } +- ClassMemberLocation targetLocation =3D +- utils.prepareNewMethodLocation(targetClassNode); +- String targetFile =3D targetElement.source.fullName; +- // build method source +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(targetFile, +- (DartFileEditBuilder builder) { +- builder.addInsertion(targetLocation.offset, (DartEditBuilder buil= der) { +- builder.write(targetLocation.prefix); +- // maybe "static" +- if (staticModifier) { +- builder.write('static '); +- } +- // append return type +- { +- DartType type =3D _inferUndefinedExpressionType(invocation); +- if (builder.writeType(type, groupName: 'RETURN_TYPE')) { +- builder.write(' '); +- } +- } +- // append name +- builder.addLinkedEdit('NAME', (DartLinkedEditBuilder builder) { +- builder.write(name); +- }); +- builder.write('('); +- builder.writeParametersMatchingArguments(invocation.argumentLis= t); +- builder.write(') {}'); +- builder.write(targetLocation.suffix); +- }); +- if (targetFile =3D=3D file) { +- builder.addLinkedPosition(range.node(node), 'NAME'); +- } +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_METHOD, +- args: [name]); +- } +- } +- +- Future _addFix_undefinedMethod_useSimilar() async { +- if (node.parent is MethodInvocation) { +- MethodInvocation invocation =3D node.parent as MethodInvocation; +- await _addFix_undefinedClassMember_useSimilar(invocation.realTarget, +- (Element element) =3D> element is MethodElement && !element.isO= perator); +- } +- } +- +- Future _addFix_undefinedMethodWithContructor() async { +- if (node is SimpleIdentifier && node.parent is MethodInvocation) { +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- builder.addSimpleInsertion(node.parent.offset, 'new '); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.INVOKE_CONSTRUCTOR_USING_NEW); +- // TODO(brianwilkerson) Figure out whether the constructor is a `co= nst` +- // constructor and all of the parameters are constant expressions, = and +- // suggest inserting 'const ' if so. +- } +- } +- +- /** +- * Here we handle cases when a constructors does not initialize all of = the +- * final fields. +- */ +- Future _addFix_updateConstructor_forUninitializedFinalFields() as= ync { +- if (node is! SimpleIdentifier || node.parent is! ConstructorDeclarati= on) { +- return; +- } +- ConstructorDeclaration constructor =3D node.parent; +- // add these fields +- List fields =3D +- ErrorVerifier.computeNotInitializedFields(constructor); +- fields.retainWhere((FieldElement field) =3D> field.isFinal); +- // prepare new parameters code +- fields.sort((a, b) =3D> a.nameOffset - b.nameOffset); +- String fieldParametersCode =3D +- fields.map((field) =3D> 'this.${field.name}').join(', '); +- // prepare the last required parameter +- FormalParameter lastRequiredParameter; +- List parameters =3D constructor.parameters.parameter= s; +- for (FormalParameter parameter in parameters) { +- if (parameter.kind =3D=3D ParameterKind.REQUIRED) { +- lastRequiredParameter =3D parameter; +- } +- } +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder) { +- // append new field formal initializers +- if (lastRequiredParameter !=3D null) { +- builder.addSimpleInsertion( +- lastRequiredParameter.end, ', $fieldParametersCode'); +- } else { +- int offset =3D constructor.parameters.leftParenthesis.end; +- if (parameters.isNotEmpty) { +- fieldParametersCode +=3D ', '; +- } +- builder.addSimpleInsertion(offset, fieldParametersCode); +- } +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.ADD_FIELD_FORMAL_PARAME= TERS); +- } +- +- Future _addFix_useEffectiveIntegerDivision() async { +- for (AstNode n =3D node; n !=3D null; n =3D n.parent) { +- if (n is MethodInvocation && +- n.offset =3D=3D errorOffset && +- n.length =3D=3D errorLength) { +- Expression target =3D (n as MethodInvocation).target.unParenthesi= zed; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session= ); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builde= r) { +- // replace "/" with "~/" +- BinaryExpression binary =3D target as BinaryExpression; +- builder.addSimpleReplacement(range.token(binary.operator), '~/'= ); +- // remove everything before and after +- builder.addDeletion(range.startStart(n, binary.leftOperand)); +- builder.addDeletion(range.endEnd(binary.rightOperand, n)); +- }); +- _addFixFromBuilder( +- changeBuilder, DartFixKind.USE_EFFECTIVE_INTEGER_DIVISION); +- // done +- break; +- } +- } +- } +- +- /** +- * Adds a fix that replaces [target] with a reference to the class decl= aring +- * the given [element]. +- */ +- Future _addFix_useStaticAccess(AstNode target, Element element) a= sync { +- Element declaringElement =3D element.enclosingElement; +- if (declaringElement is ClassElement) { +- DartType declaringType =3D declaringElement.type; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(file, (DartFileEditBuilder builder)= { +- // replace "target" with class name +- builder.addReplacement(range.node(target), (DartEditBuilder build= er) { +- builder.writeType(declaringType); +- }); +- }); +- _addFixFromBuilder(changeBuilder, DartFixKind.CHANGE_TO_STATIC_ACCE= SS, +- args: [declaringType]); +- } +- } +- +- Future _addFix_useStaticAccess_method() async { +- if (node is SimpleIdentifier && node.parent is MethodInvocation) { +- MethodInvocation invocation =3D node.parent as MethodInvocation; +- if (invocation.methodName =3D=3D node) { +- Expression target =3D invocation.target; +- Element invokedElement =3D invocation.methodName.bestElement; +- await _addFix_useStaticAccess(target, invokedElement); +- } +- } +- } +- +- Future _addFix_useStaticAccess_property() async { +- if (node is SimpleIdentifier && node.parent is PrefixedIdentifier) { +- PrefixedIdentifier prefixed =3D node.parent as PrefixedIdentifier; +- if (prefixed.identifier =3D=3D node) { +- Expression target =3D prefixed.prefix; +- Element invokedElement =3D prefixed.identifier.bestElement; +- await _addFix_useStaticAccess(target, invokedElement); +- } +- } +- } +- +- void _addFixFromBuilder(DartChangeBuilder builder, FixKind kind, +- {List args: null, bool importsOnly: false}) { +- SourceChange change =3D builder.sourceChange; +- if (change.edits.isEmpty && !importsOnly) { +- return; +- } +- change.message =3D formatList(kind.message, args); +- fixes.add(new Fix(kind, change)); +- } +- +- /** +- * Prepares proposal for creating function corresponding to the given +- * [FunctionType]. +- */ +- Future _addProposal_createFunction( +- FunctionType functionType, +- String name, +- Source targetSource, +- int insertOffset, +- bool isStatic, +- String prefix, +- String sourcePrefix, +- String sourceSuffix, +- Element target) async { +- // build method source +- String targetFile =3D targetSource.fullName; +- DartChangeBuilder changeBuilder =3D new DartChangeBuilder(session); +- await changeBuilder.addFileEdit(targetFile, (DartFileEditBuilder buil= der) { +- builder.addInsertion(insertOffset, (DartEditBuilder builder) { +- builder.write(sourcePrefix); +- builder.write(prefix); +- // may be static +- if (isStatic) { +- builder.write('static '); +- } +- // append return type +- if (builder.writeType(functionType.returnType, +- groupName: 'RETURN_TYPE')) { +- builder.write(' '); +- } +- // append name +- builder.addLinkedEdit('NAME', (DartLinkedEditBuilder builder) { +- builder.write(name); +- }); +- // append parameters +- builder.write('('); +- List parameters =3D functionType.parameters; +- for (int i =3D 0; i < parameters.length; i++) { +- ParameterElement parameter =3D parameters[i]; +- // append separator +- if (i !=3D 0) { +- builder.write(', '); +- } +- // append type name +- DartType type =3D parameter.type; +- if (!type.isDynamic) { +- builder.addLinkedEdit('TYPE$i', +- (DartLinkedEditBuilder innerBuilder) { +- builder.writeType(type); +- innerBuilder.addSuperTypesAsSuggestions(type); +- }); +- builder.write(' '); +- } +- // append parameter name +- builder.addLinkedEdit('ARG$i', (DartLinkedEditBuilder builder) { +- builder.write(parameter.displayName); +- }); +- } +- builder.write(')'); +- // close method +- builder.write(' {$eol$prefix}'); +- builder.write(sourceSuffix); +- }); +- if (targetSource =3D=3D unitSource) { +- builder.addLinkedPosition(range.node(node), 'NAME'); +- } +- }); +- return changeBuilder; +- } +- +- /** +- * Adds proposal for creating method corresponding to the given [Functi= onType] in the given +- * [ClassElement]. +- */ +- Future _addProposal_createFunction_function( +- FunctionType functionType) async { +- String name =3D (node as SimpleIdentifier).name; +- // prepare environment +- int insertOffset =3D unit.end; +- // prepare prefix +- String prefix =3D ''; +- String sourcePrefix =3D '$eol'; +- String sourceSuffix =3D eol; +- DartChangeBuilder changeBuilder =3D await _addProposal_createFunction( +- functionType, +- name, +- unitSource, +- insertOffset, +- false, +- prefix, +- sourcePrefix, +- sourceSuffix, +- unitElement); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_FUNCTION, +- args: [name]); +- } +- +- /** +- * Adds proposal for creating method corresponding to the given [Functi= onType] in the given +- * [ClassElement]. +- */ +- Future _addProposal_createFunction_method( +- ClassElement targetClassElement, FunctionType functionType) async { +- String name =3D (node as SimpleIdentifier).name; +- // prepare environment +- Source targetSource =3D targetClassElement.source; +- // prepare insert offset +- ClassDeclaration targetClassNode =3D +- getParsedClassElementNode(targetClassElement); +- int insertOffset =3D targetClassNode.end - 1; +- // prepare prefix +- String prefix =3D ' '; +- String sourcePrefix; +- if (targetClassNode.members.isEmpty) { +- sourcePrefix =3D ''; +- } else { +- sourcePrefix =3D eol; +- } +- String sourceSuffix =3D eol; +- DartChangeBuilder changeBuilder =3D await _addProposal_createFunction( +- functionType, +- name, +- targetSource, +- insertOffset, +- _inStaticContext(), +- prefix, +- sourcePrefix, +- sourceSuffix, +- targetClassElement); +- _addFixFromBuilder(changeBuilder, DartFixKind.CREATE_METHOD, args: [n= ame]); +- } +- +- /** +- * Computes the name of the library at the given [path]. +- * See https://www.dartlang.org/articles/style-guide/#names for convent= ions. +- */ +- String _computeLibraryName(String path) { +- Context pathContext =3D resourceProvider.pathContext; +- String packageFolder =3D _computePackageFolder(path); +- if (packageFolder =3D=3D null) { +- return pathContext.basenameWithoutExtension(path); +- } +- String packageName =3D pathContext.basename(packageFolder); +- String relPath =3D pathContext.relative(path, from: packageFolder); +- List relPathParts =3D pathContext.split(relPath); +- if (relPathParts.isNotEmpty) { +- if (relPathParts[0].toLowerCase() =3D=3D 'lib') { +- relPathParts.removeAt(0); +- } +- if (relPathParts.isNotEmpty) { +- String nameWithoutExt =3D pathContext.withoutExtension(relPathPar= ts.last); +- relPathParts[relPathParts.length - 1] =3D nameWithoutExt; +- } +- } +- return packageName + '.' + relPathParts.join('.'); +- } +- +- /** +- * Returns the path of the folder which contains the given [path]. +- */ +- String _computePackageFolder(String path) { +- Context pathContext =3D resourceProvider.pathContext; +- String pubspecFolder =3D dirname(path); +- while (true) { +- if (resourceProvider +- .getResource(pathContext.join(pubspecFolder, 'pubspec.yaml')) +- .exists) { +- return pubspecFolder; +- } +- String pubspecFolderNew =3D pathContext.dirname(pubspecFolder); +- if (pubspecFolderNew =3D=3D pubspecFolder) { +- return null; +- } +- pubspecFolder =3D pubspecFolderNew; +- } +- } +- +- /** +- * Return the string to display as the name of the given constructor in= a +- * proposal name. +- */ +- String _getConstructorProposalName(ConstructorElement constructor) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write('super'); +- String constructorName =3D constructor.displayName; +- if (!constructorName.isEmpty) { +- buffer.write('.'); +- buffer.write(constructorName); +- } +- buffer.write('(...)'); +- return buffer.toString(); +- } +- +- /** +- * Returns the [DartType] with given name from the `dart:core` library. +- */ +- DartType _getCoreType(String name) { +- List libraries =3D unitLibraryElement.importedLibrari= es; +- for (LibraryElement library in libraries) { +- if (library.isDartCore) { +- ClassElement classElement =3D library.getType(name); +- if (classElement !=3D null) { +- return classElement.type; +- } +- return null; +- } +- } +- return null; +- } +- +- /** +- * Return the correction utilities that should be used when creating an= edit +- * in the compilation unit containing the given [node]. +- */ +- CorrectionUtils _getUtilsFor(AstNode node) { +- CompilationUnit targetUnit =3D +- node.getAncestor((node) =3D> node is CompilationUnit); +- CompilationUnitElement targetUnitElement =3D targetUnit?.element; +- CorrectionUtils realUtils =3D utils; +- if (targetUnitElement !=3D utils.unit.element) { +- realUtils =3D new CorrectionUtils(targetUnit); +- ClassDeclaration targetClass =3D +- node.getAncestor((node) =3D> node is ClassDeclaration); +- if (targetClass !=3D null) { +- realUtils.targetClassElement =3D targetClass.element; +- } +- } +- return realUtils; +- } +- +- /** +- * Returns an expected [DartType] of [expression], may be `null` if can= not be +- * inferred. +- */ +- DartType _inferUndefinedExpressionType(Expression expression) { +- AstNode parent =3D expression.parent; +- // myFunction(); +- if (parent is ExpressionStatement) { +- if (expression is MethodInvocation) { +- return VoidTypeImpl.instance; +- } +- } +- // return myFunction(); +- if (parent is ReturnStatement) { +- ExecutableElement executable =3D getEnclosingExecutableElement(expr= ession); +- return executable?.returnType; +- } +- // int v =3D myFunction(); +- if (parent is VariableDeclaration) { +- VariableDeclaration variableDeclaration =3D parent; +- if (variableDeclaration.initializer =3D=3D expression) { +- VariableElement variableElement =3D variableDeclaration.element; +- if (variableElement !=3D null) { +- return variableElement.type; +- } +- } +- } +- // myField =3D 42; +- if (parent is AssignmentExpression) { +- AssignmentExpression assignment =3D parent; +- if (assignment.leftHandSide =3D=3D expression) { +- Expression rhs =3D assignment.rightHandSide; +- if (rhs !=3D null) { +- return rhs.bestType; +- } +- } +- } +- // v =3D myFunction(); +- if (parent is AssignmentExpression) { +- AssignmentExpression assignment =3D parent; +- if (assignment.rightHandSide =3D=3D expression) { +- if (assignment.operator.type =3D=3D TokenType.EQ) { +- // v =3D myFunction(); +- Expression lhs =3D assignment.leftHandSide; +- if (lhs !=3D null) { +- return lhs.bestType; +- } +- } else { +- // v +=3D myFunction(); +- MethodElement method =3D assignment.bestElement; +- if (method !=3D null) { +- List parameters =3D method.parameters; +- if (parameters.length =3D=3D 1) { +- return parameters[0].type; +- } +- } +- } +- } +- } +- // v + myFunction(); +- if (parent is BinaryExpression) { +- BinaryExpression binary =3D parent; +- MethodElement method =3D binary.bestElement; +- if (method !=3D null) { +- if (binary.rightOperand =3D=3D expression) { +- List parameters =3D method.parameters; +- return parameters.length =3D=3D 1 ? parameters[0].type : null; +- } +- } +- } +- // foo( myFunction() ); +- if (parent is ArgumentList) { +- ParameterElement parameter =3D expression.bestParameterElement; +- return parameter?.type; +- } +- // bool +- { +- // assert( myFunction() ); +- if (parent is AssertStatement) { +- AssertStatement statement =3D parent; +- if (statement.condition =3D=3D expression) { +- return coreTypeBool; +- } +- } +- // if ( myFunction() ) {} +- if (parent is IfStatement) { +- IfStatement statement =3D parent; +- if (statement.condition =3D=3D expression) { +- return coreTypeBool; +- } +- } +- // while ( myFunction() ) {} +- if (parent is WhileStatement) { +- WhileStatement statement =3D parent; +- if (statement.condition =3D=3D expression) { +- return coreTypeBool; +- } +- } +- // do {} while ( myFunction() ); +- if (parent is DoStatement) { +- DoStatement statement =3D parent; +- if (statement.condition =3D=3D expression) { +- return coreTypeBool; +- } +- } +- // !myFunction() +- if (parent is PrefixExpression) { +- PrefixExpression prefixExpression =3D parent; +- if (prefixExpression.operator.type =3D=3D TokenType.BANG) { +- return coreTypeBool; +- } +- } +- // binary expression '&&' or '||' +- if (parent is BinaryExpression) { +- BinaryExpression binaryExpression =3D parent; +- TokenType operatorType =3D binaryExpression.operator.type; +- if (operatorType =3D=3D TokenType.AMPERSAND_AMPERSAND || +- operatorType =3D=3D TokenType.BAR_BAR) { +- return coreTypeBool; +- } +- } +- } +- // we don't know +- return null; +- } +- +- /** +- * Returns `true` if [node] is in static context. +- */ +- bool _inStaticContext() { +- // constructor initializer cannot reference "this" +- if (node.getAncestor((node) =3D> node is ConstructorInitializer) !=3D= null) { +- return true; +- } +- // field initializer cannot reference "this" +- if (node.getAncestor((node) =3D> node is FieldDeclaration) !=3D null)= { +- return true; +- } +- // static method +- MethodDeclaration method =3D node.getAncestor((node) { +- return node is MethodDeclaration; +- }); +- return method !=3D null && method.isStatic; +- } +- +- bool _isAwaitNode() { +- AstNode node =3D this.node; +- return node is SimpleIdentifier && node.name =3D=3D 'await'; +- } +- +- bool _isLibSrcPath(String path) { +- List parts =3D resourceProvider.pathContext.split(path); +- for (int i =3D 0; i < parts.length - 2; i++) { +- if (parts[i] =3D=3D 'lib' && parts[i + 1] =3D=3D 'src') { +- return true; +- } +- } +- return false; +- } +- +- /** +- * Return `true` if the [source] can be imported into [unitLibraryFile]. +- */ +- bool _isSourceVisibleToLibrary(Source source) { +- if (!source.uri.isScheme('file')) { +- return true; +- } +- +- // Prepare the root of our package. +- Folder packageRoot; +- for (Folder folder =3D unitLibraryFolder; +- folder !=3D null; +- folder =3D folder.parent) { +- if (folder.getChildAssumingFile('pubspec.yaml').exists || +- folder.getChildAssumingFile('BUILD').exists) { +- packageRoot =3D folder; +- break; +- } +- } +- +- // This should be rare / never situation. +- if (packageRoot =3D=3D null) { +- return true; +- } +- +- // We cannot use relative URIs to reference files outside of our pack= age. +- return resourceProvider.pathContext +- .isWithin(packageRoot.path, source.fullName); +- } +- +- /** +- * Removes any [ParenthesizedExpression] enclosing [expr]. +- * +- * [exprPrecedence] - the effective precedence of [expr]. +- */ +- void _removeEnclosingParentheses( +- DartFileEditBuilder builder, Expression expr, int exprPrecedence) { +- while (expr.parent is ParenthesizedExpression) { +- ParenthesizedExpression parenthesized =3D +- expr.parent as ParenthesizedExpression; +- if (getExpressionParentPrecedence(parenthesized) > exprPrecedence) { +- break; +- } +- builder.addDeletion(range.token(parenthesized.leftParenthesis)); +- builder.addDeletion(range.token(parenthesized.rightParenthesis)); +- expr =3D parenthesized; +- } +- } +- +- void _updateFinderWithClassMembers( +- _ClosestElementFinder finder, ClassElement clazz) { +- if (clazz !=3D null) { +- List members =3D getMembers(clazz); +- finder._updateList(members); +- } +- } +- +- static bool _isNameOfType(String name) { +- if (name.isEmpty) { +- return false; +- } +- String firstLetter =3D name.substring(0, 1); +- if (firstLetter.toUpperCase() !=3D firstLetter) { +- return false; +- } +- return true; +- } +- +- /** +- * Returns `true` if [node] is a type name. +- */ +- static bool _mayBeTypeIdentifier(AstNode node) { +- if (node is SimpleIdentifier) { +- AstNode parent =3D node.parent; +- if (parent is TypeName) { +- return true; +- } +- return _isNameOfType(node.name); +- } +- return false; +- } +-} +- +-/** +- * An enumeration of lint names. +- */ +-class LintNames { +- static const String always_require_non_null_named_parameters =3D +- 'always_require_non_null_named_parameters'; +- static const String annotate_overrides =3D 'annotate_overrides'; +- static const String avoid_annotating_with_dynamic =3D +- 'avoid_annotating_with_dynamic'; +- static const String avoid_empty_else =3D 'avoid_empty_else'; +- static const String avoid_init_to_null =3D 'avoid_init_to_null'; +- static const String avoid_return_types_on_setters =3D +- 'avoid_return_types_on_setters'; +- static const String avoid_types_on_closure_parameters =3D +- 'avoid_types_on_closure_parameters'; +- static const String await_only_futures =3D 'await_only_futures'; +- static const String empty_catches =3D 'empty_catches'; +- static const String empty_constructor_bodies =3D 'empty_constructor_bod= ies'; +- static const String empty_statements =3D 'empty_statements'; +- static const String prefer_collection_literals =3D 'prefer_collection_l= iterals'; +- static const String prefer_conditional_assignment =3D +- 'prefer_conditional_assignment'; +- static const String prefer_is_not_empty =3D 'prefer_is_not_empty'; +- static const String type_init_formals =3D 'type_init_formals'; +- static const String unnecessary_brace_in_string_interp =3D +- 'unnecessary_brace_in_string_interp'; +- static const String unnecessary_lambdas =3D 'unnecessary_lambdas'; +- static const String unnecessary_override =3D 'unnecessary_override'; +- static const String unnecessary_this =3D 'unnecessary_this'; +-} +- +-/** +- * Helper for finding [Element] with name closest to the given. +- */ +-class _ClosestElementFinder { +- final String _targetName; +- final ElementPredicate _predicate; +- +- Element _element =3D null; +- int _distance; +- +- _ClosestElementFinder(this._targetName, this._predicate, this._distance= ); +- +- void _update(Element element) { +- if (_predicate(element)) { +- int memberDistance =3D levenshtein(element.name, _targetName, _dist= ance); +- if (memberDistance < _distance) { +- _element =3D element; +- _distance =3D memberDistance; +- } +- } +- } +- +- void _updateList(Iterable elements) { +- for (Element element in elements) { +- _update(element); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/levenshtein.d= art b/pkg/analysis_server/lib/src/services/correction/levenshtein.dart +deleted file mode 100644 +index 61cb493be7a..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/levenshtein.dart ++++ /dev/null +@@ -1,133 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:math' as math; +- +-/** +- * The value returned by [levenshtein] if the distance is determined +- * to be over the specified threshold. +- */ +-const int LEVENSHTEIN_MAX =3D 1 << 20; +- +-const int _MAX_VALUE =3D 1 << 10; +- +-/** +- * Find the Levenshtein distance between two [String]s if it's less than = or +- * equal to a given threshold. +- * +- * This is the number of changes needed to change one String into another, +- * where each change is a single character modification (deletion, insert= ion or +- * substitution). +- * +- * This implementation follows from Algorithms on Strings, Trees and Sequ= ences +- * by Dan Gusfield and Chas Emerick's implementation of the Levenshtein d= istance +- * algorithm. +- */ +-int levenshtein(String s, String t, int threshold, {bool caseSensitive: t= rue}) { +- if (s =3D=3D null || t =3D=3D null) { +- throw new ArgumentError('Strings must not be null'); +- } +- if (threshold < 0) { +- throw new ArgumentError('Threshold must not be negative'); +- } +- +- if (!caseSensitive) { +- s =3D s.toLowerCase(); +- t =3D t.toLowerCase(); +- } +- +- int s_len =3D s.length; +- int t_len =3D t.length; +- +- // if one string is empty, +- // the edit distance is necessarily the length of the other +- if (s_len =3D=3D 0) { +- return t_len <=3D threshold ? t_len : LEVENSHTEIN_MAX; +- } +- if (t_len =3D=3D 0) { +- return s_len <=3D threshold ? s_len : LEVENSHTEIN_MAX; +- } +- // the distance can never be less than abs(s_len - t_len) +- if ((s_len - t_len).abs() > threshold) { +- return LEVENSHTEIN_MAX; +- } +- +- // swap the two strings to consume less memory +- if (s_len > t_len) { +- String tmp =3D s; +- s =3D t; +- t =3D tmp; +- s_len =3D t_len; +- t_len =3D t.length; +- } +- +- // 'previous' cost array, horizontally +- List p =3D new List.filled(s_len + 1, 0); +- // cost array, horizontally +- List d =3D new List.filled(s_len + 1, 0); +- // placeholder to assist in swapping p and d +- List _d; +- +- // fill in starting table values +- int boundary =3D math.min(s_len, threshold) + 1; +- for (int i =3D 0; i < boundary; i++) { +- p[i] =3D i; +- } +- +- // these fills ensure that the value above the rightmost entry of our +- // stripe will be ignored in following loop iterations +- _setRange(p, boundary, p.length, _MAX_VALUE); +- _setRange(d, 0, d.length, _MAX_VALUE); +- +- // iterates through t +- for (int j =3D 1; j <=3D t_len; j++) { +- // jth character of t +- int t_j =3D t.codeUnitAt(j - 1); +- d[0] =3D j; +- +- // compute stripe indices, constrain to array size +- int min =3D math.max(1, j - threshold); +- int max =3D math.min(s_len, j + threshold); +- +- // the stripe may lead off of the table if s and t are of different s= izes +- if (min > max) { +- return LEVENSHTEIN_MAX; +- } +- +- // ignore entry left of leftmost +- if (min > 1) { +- d[min - 1] =3D _MAX_VALUE; +- } +- +- // iterates through [min, max] in s +- for (int i =3D min; i <=3D max; i++) { +- if (s.codeUnitAt(i - 1) =3D=3D t_j) { +- // diagonally left and up +- d[i] =3D p[i - 1]; +- } else { +- // 1 + minimum of cell to the left, to the top, diagonally left a= nd up +- d[i] =3D 1 + math.min(math.min(d[i - 1], p[i]), p[i - 1]); +- } +- } +- +- // copy current distance counts to 'previous row' distance counts +- _d =3D p; +- p =3D d; +- d =3D _d; +- } +- +- // if p[n] is greater than the threshold, +- // there's no guarantee on it being the correct distance +- if (p[s_len] <=3D threshold) { +- return p[s_len]; +- } +- +- return LEVENSHTEIN_MAX; +-} +- +-void _setRange(List a, int start, int end, int value) { +- for (int i =3D start; i < end; i++) { +- a[i] =3D value; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/name_suggesti= on.dart b/pkg/analysis_server/lib/src/services/correction/name_suggestion.d= art +deleted file mode 100644 +index ebf7ae09b80..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/name_suggestion.dart ++++ /dev/null +@@ -1,238 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +- +-List _KNOWN_METHOD_NAME_PREFIXES =3D ['get', 'is', 'to']; +- +-/** +- * Returns all variants of names by removing leading words one by one. +- */ +-List getCamelWordCombinations(String name) { +- List result =3D []; +- List parts =3D getCamelWords(name); +- for (int i =3D 0; i < parts.length; i++) { +- var s1 =3D parts[i].toLowerCase(); +- var s2 =3D parts.skip(i + 1).join(); +- String suggestion =3D '$s1$s2'; +- result.add(suggestion); +- } +- return result; +-} +- +-/** +- * Returns possible names for a variable with the given expected type and +- * expression assigned. +- */ +-List getVariableNameSuggestionsForExpression( +- DartType expectedType, Expression assignedExpression, Set exc= luded, +- {bool isMethod: false}) { +- String prefix; +- +- if (isMethod) { +- // If we're in a build() method, use 'build' as the name prefix. +- MethodDeclaration method =3D +- assignedExpression.getAncestor((n) =3D> n is MethodDeclaration); +- if (method !=3D null) { +- String enclosingName =3D method.name?.name; +- if (enclosingName !=3D null && enclosingName.startsWith('build')) { +- prefix =3D 'build'; +- } +- } +- } +- +- Set res =3D new Set(); +- // use expression +- if (assignedExpression !=3D null) { +- String nameFromExpression =3D _getBaseNameFromExpression(assignedExpr= ession); +- if (nameFromExpression !=3D null) { +- nameFromExpression =3D removeStart(nameFromExpression, '_'); +- _addAll(excluded, res, getCamelWordCombinations(nameFromExpression), +- prefix: prefix); +- } +- String nameFromParent =3D +- _getBaseNameFromLocationInParent(assignedExpression); +- if (nameFromParent !=3D null) { +- _addAll(excluded, res, getCamelWordCombinations(nameFromParent)); +- } +- } +- // use type +- if (expectedType !=3D null && !expectedType.isDynamic) { +- String typeName =3D expectedType.name; +- if ('int' =3D=3D typeName) { +- _addSingleCharacterName(excluded, res, 0x69); +- } else if ('double' =3D=3D typeName) { +- _addSingleCharacterName(excluded, res, 0x64); +- } else if ('String' =3D=3D typeName) { +- _addSingleCharacterName(excluded, res, 0x73); +- } else { +- _addAll(excluded, res, getCamelWordCombinations(typeName)); +- } +- res.remove(typeName); +- } +- // done +- return new List.from(res); +-} +- +-/** +- * Returns possible names for a [String] variable with [text] value. +- */ +-List getVariableNameSuggestionsForText( +- String text, Set excluded) { +- // filter out everything except of letters and white spaces +- { +- StringBuffer sb =3D new StringBuffer(); +- for (int i =3D 0; i < text.length; i++) { +- int c =3D text.codeUnitAt(i); +- if (isLetter(c) || isWhitespace(c)) { +- sb.writeCharCode(c); +- } +- } +- text =3D sb.toString(); +- } +- // make single camel-case text +- { +- List words =3D text.split(' '); +- StringBuffer sb =3D new StringBuffer(); +- for (int i =3D 0; i < words.length; i++) { +- String word =3D words[i]; +- if (i > 0) { +- word =3D capitalize(word); +- } +- sb.write(word); +- } +- text =3D sb.toString(); +- } +- // split camel-case into separate suggested names +- Set res =3D new Set(); +- _addAll(excluded, res, getCamelWordCombinations(text)); +- return new List.from(res); +-} +- +-/** +- * Adds [toAdd] items which are not excluded. +- */ +-void _addAll(Set excluded, Set result, Iterable t= oAdd, +- {String prefix}) { +- for (String item in toAdd) { +- // add name based on "item", but not "excluded" +- for (int suffix =3D 1;; suffix++) { +- // prepare name, just "item" or "item2", "item3", etc +- String name =3D item; +- if (suffix > 1) { +- name +=3D suffix.toString(); +- } +- // add once found not excluded +- if (!excluded.contains(name)) { +- result.add(prefix =3D=3D null ? name : '$prefix${capitalize(name)= }'); +- break; +- } +- } +- } +-} +- +-/** +- * Adds to [result] either [c] or the first ASCII character after it. +- */ +-void _addSingleCharacterName(Set excluded, Set result, in= t c) { +- while (c < 0x7A) { +- String name =3D new String.fromCharCode(c); +- // may be done +- if (!excluded.contains(name)) { +- result.add(name); +- break; +- } +- // next character +- c =3D c + 1; +- } +-} +- +-String _getBaseNameFromExpression(Expression expression) { +- if (expression is AsExpression) { +- return _getBaseNameFromExpression(expression.expression); +- } else if (expression is ParenthesizedExpression) { +- return _getBaseNameFromExpression(expression.expression); +- } +- return _getBaseNameFromUnwrappedExpression(expression); +-} +- +-String _getBaseNameFromLocationInParent(Expression expression) { +- // value in named expression +- if (expression.parent is NamedExpression) { +- NamedExpression namedExpression =3D expression.parent as NamedExpress= ion; +- if (namedExpression.expression =3D=3D expression) { +- return namedExpression.name.label.name; +- } +- } +- // positional argument +- { +- ParameterElement parameter =3D expression.propagatedParameterElement; +- if (parameter =3D=3D null) { +- parameter =3D expression.staticParameterElement; +- } +- if (parameter !=3D null) { +- return parameter.displayName; +- } +- } +- // unknown +- return null; +-} +- +-String _getBaseNameFromUnwrappedExpression(Expression expression) { +- String name =3D null; +- // analyze expressions +- if (expression is SimpleIdentifier) { +- return expression.name; +- } else if (expression is PrefixedIdentifier) { +- return expression.identifier.name; +- } else if (expression is PropertyAccess) { +- return expression.propertyName.name; +- } else if (expression is MethodInvocation) { +- name =3D expression.methodName.name; +- } else if (expression is InstanceCreationExpression) { +- ConstructorName constructorName =3D expression.constructorName; +- TypeName typeName =3D constructorName.type; +- if (typeName !=3D null) { +- Identifier typeNameIdentifier =3D typeName.name; +- // new ClassName() +- if (typeNameIdentifier is SimpleIdentifier) { +- return typeNameIdentifier.name; +- } +- // new prefix.name(); +- if (typeNameIdentifier is PrefixedIdentifier) { +- PrefixedIdentifier prefixed =3D typeNameIdentifier; +- // new prefix.ClassName() +- if (prefixed.prefix.staticElement is PrefixElement) { +- return prefixed.identifier.name; +- } +- // new ClassName.constructorName() +- return prefixed.prefix.name; +- } +- } +- } else if (expression is IndexExpression) { +- name =3D _getBaseNameFromExpression(expression.realTarget); +- if (name.endsWith('s')) { +- name =3D name.substring(0, name.length - 1); +- } +- } +- // strip known prefixes +- if (name !=3D null) { +- for (int i =3D 0; i < _KNOWN_METHOD_NAME_PREFIXES.length; i++) { +- String curr =3D _KNOWN_METHOD_NAME_PREFIXES[i]; +- if (name.startsWith(curr)) { +- if (name =3D=3D curr) { +- return null; +- } else if (isUpperCase(name.codeUnitAt(curr.length))) { +- return name.substring(curr.length); +- } +- } +- } +- } +- // done +- return name; +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/namespace.dar= t b/pkg/analysis_server/lib/src/services/correction/namespace.dart +deleted file mode 100644 +index fc0d7484fd8..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/namespace.dart ++++ /dev/null +@@ -1,183 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/resolver/scope.dart'; +- +-/** +- * Returns the [Element] exported from the given [LibraryElement]. +- */ +-Element getExportedElement(LibraryElement library, String name) { +- if (library =3D=3D null) { +- return null; +- } +- return getExportNamespaceForLibrary(library)[name]; +-} +- +-/** +- * Returns the namespace of the given [ExportElement]. +- */ +-Map getExportNamespaceForDirective(ExportElement exp) { +- Namespace namespace =3D +- new NamespaceBuilder().createExportNamespaceForDirective(exp); +- return namespace.definedNames; +-} +- +-/** +- * Returns the export namespace of the given [LibraryElement]. +- */ +-Map getExportNamespaceForLibrary(LibraryElement library)= { +- Namespace namespace =3D +- new NamespaceBuilder().createExportNamespaceForLibrary(library); +- return namespace.definedNames; +-} +- +-/** +- * Return the [ImportElement] that is referenced by [prefixNode], or `nul= l` if +- * the node does not reference a prefix or if we cannot determine which i= mport +- * is being referenced. +- */ +-ImportElement getImportElement(SimpleIdentifier prefixNode) { +- AstNode parent =3D prefixNode.parent; +- if (parent is ImportDirective) { +- return parent.element; +- } +- ImportElementInfo info =3D internal_getImportElementInfo(prefixNode); +- return info?.element; +-} +- +-/** +- * Return the [ImportElement] that declared [prefix] and imports [element= ]. +- * +- * [libraryElement] - the [LibraryElement] where reference is. +- * [prefix] - the import prefix, maybe `null`. +- * [element] - the referenced element. +- * [importElementsMap] - the cache of [Element]s imported by [ImportEleme= nt]s. +- */ +-ImportElement internal_getImportElement( +- LibraryElement libraryElement, +- String prefix, +- Element element, +- Map> importElementsMap) { +- // validate Element +- if (element =3D=3D null) { +- return null; +- } +- if (element.enclosingElement is! CompilationUnitElement) { +- return null; +- } +- LibraryElement usedLibrary =3D element.library; +- // find ImportElement that imports used library with used prefix +- List candidates =3D null; +- for (ImportElement importElement in libraryElement.imports) { +- // required library +- if (importElement.importedLibrary !=3D usedLibrary) { +- continue; +- } +- // required prefix +- PrefixElement prefixElement =3D importElement.prefix; +- if (prefix =3D=3D null) { +- if (prefixElement !=3D null) { +- continue; +- } +- } else { +- if (prefixElement =3D=3D null) { +- continue; +- } +- if (prefix !=3D prefixElement.name) { +- continue; +- } +- } +- // no combinators =3D> only possible candidate +- if (importElement.combinators.length =3D=3D 0) { +- return importElement; +- } +- // OK, we have candidate +- if (candidates =3D=3D null) { +- candidates =3D []; +- } +- candidates.add(importElement); +- } +- // no candidates, probably element is defined in this library +- if (candidates =3D=3D null) { +- return null; +- } +- // one candidate +- if (candidates.length =3D=3D 1) { +- return candidates[0]; +- } +- // ensure that each ImportElement has set of elements +- for (ImportElement importElement in candidates) { +- if (importElementsMap.containsKey(importElement)) { +- continue; +- } +- Namespace namespace =3D +- new NamespaceBuilder().createImportNamespaceForDirective(importEl= ement); +- Set elements =3D new Set.from(namespace.definedNames.values); +- importElementsMap[importElement] =3D elements; +- } +- // use import namespace to choose correct one +- for (ImportElement importElement in importElementsMap.keys) { +- Set elements =3D importElementsMap[importElement]; +- if (elements.contains(element)) { +- return importElement; +- } +- } +- // not found +- return null; +-} +- +-/** +- * Returns the [ImportElementInfo] with the [ImportElement] that is refer= enced +- * by [prefixNode] with a [PrefixElement], maybe `null`. +- */ +-ImportElementInfo internal_getImportElementInfo(SimpleIdentifier prefixNo= de) { +- ImportElementInfo info =3D new ImportElementInfo(); +- // prepare environment +- AstNode parent =3D prefixNode.parent; +- CompilationUnit unit =3D +- prefixNode.getAncestor((node) =3D> node is CompilationUnit); +- LibraryElement libraryElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(unit).library; +- // prepare used element +- Element usedElement =3D null; +- if (parent is PrefixedIdentifier) { +- PrefixedIdentifier prefixed =3D parent; +- if (prefixed.prefix =3D=3D prefixNode) { +- usedElement =3D prefixed.staticElement; +- info.periodEnd =3D prefixed.period.end; +- } +- } +- if (parent is MethodInvocation) { +- MethodInvocation invocation =3D parent; +- if (invocation.target =3D=3D prefixNode) { +- usedElement =3D invocation.methodName.staticElement; +- info.periodEnd =3D invocation.operator.end; +- } +- } +- // we need used Element +- if (usedElement =3D=3D null) { +- return null; +- } +- // find ImportElement +- String prefix =3D prefixNode.name; +- Map> importElementsMap =3D {}; +- info.element =3D internal_getImportElement( +- libraryElement, prefix, usedElement, importElementsMap); +- if (info.element =3D=3D null) { +- return null; +- } +- return info; +-} +- +-/** +- * Information about [ImportElement] and place where it is referenced usi= ng +- * [PrefixElement]. +- */ +-class ImportElementInfo { +- ImportElement element; +- int periodEnd; +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/organize_dire= ctives.dart b/pkg/analysis_server/lib/src/services/correction/organize_dire= ctives.dart +deleted file mode 100644 +index 83a673c0e90..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/organize_directives.= dart ++++ /dev/null +@@ -1,250 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/src/error/codes.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- hide AnalysisError, Element; +- +-/** +- * Organizer of directives in the [unit]. +- */ +-class DirectiveOrganizer { +- final String initialCode; +- final CompilationUnit unit; +- final List errors; +- final bool removeUnresolved; +- final bool removeUnused; +- String code; +- String endOfLine; +- +- DirectiveOrganizer(this.initialCode, this.unit, this.errors, +- {this.removeUnresolved: true, this.removeUnused: true}) { +- this.code =3D initialCode; +- this.endOfLine =3D getEOL(code); +- } +- +- /** +- * Return the [SourceEdit]s that organize directives in the [unit]. +- */ +- List organize() { +- _organizeDirectives(); +- // prepare edits +- List edits =3D []; +- if (code !=3D initialCode) { +- int suffixLength =3D findCommonSuffix(initialCode, code); +- SourceEdit edit =3D new SourceEdit(0, initialCode.length - suffixLe= ngth, +- code.substring(0, code.length - suffixLength)); +- edits.add(edit); +- } +- return edits; +- } +- +- bool _isUnresolvedUri(UriBasedDirective directive) { +- for (AnalysisError error in errors) { +- ErrorCode errorCode =3D error.errorCode; +- if ((errorCode =3D=3D CompileTimeErrorCode.URI_DOES_NOT_EXIST || +- errorCode =3D=3D CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENE= RATED) && +- directive.uri.offset =3D=3D error.offset) { +- return true; +- } +- } +- return false; +- } +- +- bool _isUnusedImport(UriBasedDirective directive) { +- for (AnalysisError error in errors) { +- if ((error.errorCode =3D=3D HintCode.DUPLICATE_IMPORT || +- error.errorCode =3D=3D HintCode.UNUSED_IMPORT) && +- directive.uri.offset =3D=3D error.offset) { +- return true; +- } +- } +- return false; +- } +- +- /** +- * Oraganize all [Directive]s. +- */ +- void _organizeDirectives() { +- List<_DirectiveInfo> directives =3D []; +- for (Directive directive in unit.directives) { +- if (directive is UriBasedDirective) { +- _DirectivePriority priority =3D getDirectivePriority(directive); +- if (priority !=3D null) { +- int offset =3D directive.offset; +- int length =3D directive.length; +- String text =3D code.substring(offset, offset + length); +- String uriContent =3D directive.uri.stringValue; +- directives +- .add(new _DirectiveInfo(directive, priority, uriContent, te= xt)); +- } +- } +- } +- // nothing to do +- if (directives.isEmpty) { +- return; +- } +- int firstDirectiveOffset =3D directives.first.directive.offset; +- int lastDirectiveEnd =3D directives.last.directive.end; +- // sort +- directives.sort(); +- // append directives with grouping +- String directivesCode; +- { +- StringBuffer sb =3D new StringBuffer(); +- _DirectivePriority currentPriority =3D null; +- for (_DirectiveInfo directiveInfo in directives) { +- if (removeUnresolved && _isUnresolvedUri(directiveInfo.directive)= ) { +- continue; +- } +- if (removeUnused && _isUnusedImport(directiveInfo.directive)) { +- continue; +- } +- if (currentPriority !=3D directiveInfo.priority) { +- if (sb.length !=3D 0) { +- sb.write(endOfLine); +- } +- currentPriority =3D directiveInfo.priority; +- } +- sb.write(directiveInfo.text); +- sb.write(endOfLine); +- } +- directivesCode =3D sb.toString(); +- directivesCode =3D directivesCode.trimRight(); +- } +- // append comment tokens which otherwise would be removed completely +- { +- bool firstCommentToken =3D true; +- Token token =3D unit.beginToken; +- while (token !=3D null && +- token.type !=3D TokenType.EOF && +- token.end < lastDirectiveEnd) { +- Token commentToken =3D token.precedingComments; +- while (commentToken !=3D null) { +- int offset =3D commentToken.offset; +- int end =3D commentToken.end; +- if (offset > firstDirectiveOffset && offset < lastDirectiveEnd)= { +- if (firstCommentToken) { +- directivesCode +=3D endOfLine; +- firstCommentToken =3D false; +- } +- directivesCode +=3D code.substring(offset, end) + endOfLine; +- } +- commentToken =3D commentToken.next; +- } +- token =3D token.next; +- } +- } +- // prepare code +- String beforeDirectives =3D code.substring(0, firstDirectiveOffset); +- String afterDirectives =3D code.substring(lastDirectiveEnd); +- code =3D beforeDirectives + directivesCode + afterDirectives; +- } +- +- static _DirectivePriority getDirectivePriority(UriBasedDirective direct= ive) { +- String uriContent =3D directive.uri.stringValue; +- if (directive is ImportDirective) { +- if (uriContent.startsWith("dart:")) { +- return _DirectivePriority.IMPORT_SDK; +- } else if (uriContent.startsWith("package:")) { +- return _DirectivePriority.IMPORT_PKG; +- } else if (uriContent.contains('://')) { +- return _DirectivePriority.IMPORT_OTHER; +- } else { +- return _DirectivePriority.IMPORT_REL; +- } +- } +- if (directive is ExportDirective) { +- if (uriContent.startsWith("dart:")) { +- return _DirectivePriority.EXPORT_SDK; +- } else if (uriContent.startsWith("package:")) { +- return _DirectivePriority.EXPORT_PKG; +- } else if (uriContent.contains('://')) { +- return _DirectivePriority.EXPORT_OTHER; +- } else { +- return _DirectivePriority.EXPORT_REL; +- } +- } +- if (directive is PartDirective) { +- return _DirectivePriority.PART; +- } +- return null; +- } +- +- /** +- * Return the EOL to use for [code]. +- */ +- static String getEOL(String code) { +- if (code.contains('\r\n')) { +- return '\r\n'; +- } else { +- return '\n'; +- } +- } +-} +- +-class _DirectiveInfo implements Comparable<_DirectiveInfo> { +- final UriBasedDirective directive; +- final _DirectivePriority priority; +- final String uri; +- final String text; +- +- _DirectiveInfo(this.directive, this.priority, this.uri, this.text); +- +- @override +- int compareTo(_DirectiveInfo other) { +- if (priority =3D=3D other.priority) { +- return _compareUri(uri, other.uri); +- } +- return priority.ordinal - other.priority.ordinal; +- } +- +- @override +- String toString() =3D> '(priority=3D$priority; text=3D$text)'; +- +- static int _compareUri(String a, String b) { +- List aList =3D _splitUri(a); +- List bList =3D _splitUri(b); +- int result; +- if ((result =3D aList[0].compareTo(bList[0])) !=3D 0) return result; +- if ((result =3D aList[1].compareTo(bList[1])) !=3D 0) return result; +- return 0; +- } +- +- /** +- * Split the given [uri] like `package:some.name/and/path.dart` into a = list +- * like `[package:some.name, and/path.dart]`. +- */ +- static List _splitUri(String uri) { +- int index =3D uri.indexOf('/'); +- if (index =3D=3D -1) { +- return [uri, '']; +- } +- return [uri.substring(0, index), uri.substring(index + 1)]; +- } +-} +- +-class _DirectivePriority { +- static const IMPORT_SDK =3D const _DirectivePriority('IMPORT_SDK', 0); +- static const IMPORT_PKG =3D const _DirectivePriority('IMPORT_PKG', 1); +- static const IMPORT_OTHER =3D const _DirectivePriority('IMPORT_OTHER', = 2); +- static const IMPORT_REL =3D const _DirectivePriority('IMPORT_REL', 3); +- static const EXPORT_SDK =3D const _DirectivePriority('EXPORT_SDK', 4); +- static const EXPORT_PKG =3D const _DirectivePriority('EXPORT_PKG', 5); +- static const EXPORT_OTHER =3D const _DirectivePriority('EXPORT_OTHER', = 6); +- static const EXPORT_REL =3D const _DirectivePriority('EXPORT_REL', 7); +- static const PART =3D const _DirectivePriority('PART', 8); +- +- final String name; +- final int ordinal; +- +- const _DirectivePriority(this.name, this.ordinal); +- +- @override +- String toString() =3D> name; +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/selection_ana= lyzer.dart b/pkg/analysis_server/lib/src/services/correction/selection_anal= yzer.dart +deleted file mode 100644 +index 9b026bd351f..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/selection_analyzer.d= art ++++ /dev/null +@@ -1,142 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * A visitor for visiting [AstNode]s covered by a selection [SourceRange]. +- */ +-class SelectionAnalyzer extends GeneralizingAstVisitor { +- final SourceRange selection; +- +- AstNode _coveringNode; +- List _selectedNodes; +- +- SelectionAnalyzer(this.selection); +- +- /** +- * Return the [AstNode] with the shortest length which completely cover= s the +- * specified selection. +- */ +- AstNode get coveringNode =3D> _coveringNode; +- +- /** +- * Returns the first selected [AstNode], may be `null`. +- */ +- AstNode get firstSelectedNode { +- if (_selectedNodes =3D=3D null || _selectedNodes.isEmpty) { +- return null; +- } +- return _selectedNodes[0]; +- } +- +- /** +- * Returns `true` if there are [AstNode]s fully covered by the +- * selection [SourceRange]. +- */ +- bool get hasSelectedNodes =3D> +- _selectedNodes !=3D null && !_selectedNodes.isEmpty; +- +- /** +- * Returns `true` if there was no selected nodes yet. +- */ +- bool get isFirstNode =3D> _selectedNodes =3D=3D null; +- +- /** +- * Returns the last selected [AstNode], may be `null`. +- */ +- AstNode get lastSelectedNode { +- if (_selectedNodes =3D=3D null || _selectedNodes.isEmpty) { +- return null; +- } +- return _selectedNodes[_selectedNodes.length - 1]; +- } +- +- /** +- * Returns the [SourceRange] which covers selected [AstNode]s, may be `= null` +- * if there are no [AstNode]s under the selection. +- */ +- SourceRange get selectedNodeRange { +- if (_selectedNodes =3D=3D null || _selectedNodes.isEmpty) { +- return null; +- } +- AstNode firstNode =3D _selectedNodes[0]; +- AstNode lastNode =3D _selectedNodes[_selectedNodes.length - 1]; +- return range.startEnd(firstNode, lastNode); +- } +- +- /** +- * Return the [AstNode]s fully covered by the selection [SourceRange]. +- */ +- List get selectedNodes { +- if (_selectedNodes =3D=3D null || _selectedNodes.isEmpty) { +- return []; +- } +- return _selectedNodes; +- } +- +- /** +- * Adds first selected [AstNode]. +- */ +- void handleFirstSelectedNode(AstNode node) { +- _selectedNodes =3D []; +- _selectedNodes.add(node); +- } +- +- /** +- * Adds second or more selected [AstNode]. +- */ +- void handleNextSelectedNode(AstNode node) { +- if (firstSelectedNode.parent =3D=3D node.parent) { +- _selectedNodes.add(node); +- } +- } +- +- /** +- * Notifies that selection ends in given [AstNode]. +- */ +- void handleSelectionEndsIn(AstNode node) {} +- +- /** +- * Notifies that selection starts in given [AstNode]. +- */ +- void handleSelectionStartsIn(AstNode node) {} +- +- /** +- * Resets selected nodes. +- */ +- void reset() { +- _selectedNodes =3D null; +- } +- +- @override +- Object visitNode(AstNode node) { +- SourceRange nodeRange =3D range.node(node); +- if (selection.covers(nodeRange)) { +- if (isFirstNode) { +- handleFirstSelectedNode(node); +- } else { +- handleNextSelectedNode(node); +- } +- return null; +- } else if (selection.coveredBy(nodeRange)) { +- _coveringNode =3D node; +- node.visitChildren(this); +- return null; +- } else if (selection.startsIn(nodeRange)) { +- handleSelectionStartsIn(node); +- node.visitChildren(this); +- return null; +- } else if (selection.endsIn(nodeRange)) { +- handleSelectionEndsIn(node); +- node.visitChildren(this); +- return null; +- } +- // no intersection +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/sort_members.= dart b/pkg/analysis_server/lib/src/services/correction/sort_members.dart +deleted file mode 100644 +index 00175668a0f..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/sort_members.dart ++++ /dev/null +@@ -1,504 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +- +-/** +- * Sorter for unit/class members. +- */ +-class MemberSorter { +- static List<_PriorityItem> _PRIORITY_ITEMS =3D [ +- new _PriorityItem(false, _MemberKind.UNIT_FUNCTION_MAIN, false), +- new _PriorityItem(false, _MemberKind.UNIT_VARIABLE_CONST, false), +- new _PriorityItem(false, _MemberKind.UNIT_VARIABLE_CONST, true), +- new _PriorityItem(false, _MemberKind.UNIT_VARIABLE, false), +- new _PriorityItem(false, _MemberKind.UNIT_VARIABLE, true), +- new _PriorityItem(false, _MemberKind.UNIT_ACCESSOR, false), +- new _PriorityItem(false, _MemberKind.UNIT_ACCESSOR, true), +- new _PriorityItem(false, _MemberKind.UNIT_FUNCTION, false), +- new _PriorityItem(false, _MemberKind.UNIT_FUNCTION, true), +- new _PriorityItem(false, _MemberKind.UNIT_FUNCTION_TYPE, false), +- new _PriorityItem(false, _MemberKind.UNIT_FUNCTION_TYPE, true), +- new _PriorityItem(false, _MemberKind.UNIT_CLASS, false), +- new _PriorityItem(false, _MemberKind.UNIT_CLASS, true), +- new _PriorityItem(true, _MemberKind.CLASS_FIELD, false), +- new _PriorityItem(true, _MemberKind.CLASS_ACCESSOR, false), +- new _PriorityItem(true, _MemberKind.CLASS_ACCESSOR, true), +- new _PriorityItem(false, _MemberKind.CLASS_FIELD, false), +- new _PriorityItem(false, _MemberKind.CLASS_CONSTRUCTOR, false), +- new _PriorityItem(false, _MemberKind.CLASS_CONSTRUCTOR, true), +- new _PriorityItem(false, _MemberKind.CLASS_ACCESSOR, false), +- new _PriorityItem(false, _MemberKind.CLASS_ACCESSOR, true), +- new _PriorityItem(false, _MemberKind.CLASS_METHOD, false), +- new _PriorityItem(false, _MemberKind.CLASS_METHOD, true), +- new _PriorityItem(true, _MemberKind.CLASS_METHOD, false), +- new _PriorityItem(true, _MemberKind.CLASS_METHOD, true) +- ]; +- +- final String initialCode; +- final CompilationUnit unit; +- String code; +- String endOfLine; +- +- MemberSorter(this.initialCode, this.unit) { +- this.code =3D initialCode; +- this.endOfLine =3D getEOL(code); +- } +- +- /** +- * Return the [SourceEdit]s that sort [unit]. +- */ +- List sort() { +- _sortClassesMembers(); +- _sortUnitMembers(); +- // Must sort unit directives last because it may insert newlines, whi= ch +- // would confuse the offsets used by the other sort functions. +- _sortUnitDirectives(); +- // prepare edits +- List edits =3D []; +- if (code !=3D initialCode) { +- SimpleDiff diff =3D computeSimpleDiff(initialCode, code); +- SourceEdit edit =3D +- new SourceEdit(diff.offset, diff.length, diff.replacement); +- edits.add(edit); +- } +- return edits; +- } +- +- void _sortAndReorderMembers(List<_MemberInfo> members) { +- List<_MemberInfo> membersSorted =3D _getSortedMembers(members); +- int size =3D membersSorted.length; +- for (int i =3D 0; i < size; i++) { +- _MemberInfo newInfo =3D membersSorted[size - 1 - i]; +- _MemberInfo oldInfo =3D members[size - 1 - i]; +- if (newInfo !=3D oldInfo) { +- String beforeCode =3D code.substring(0, oldInfo.offset); +- String afterCode =3D code.substring(oldInfo.end); +- code =3D beforeCode + newInfo.text + afterCode; +- } +- } +- } +- +- /** +- * Sorts all members of all [ClassDeclaration]s. +- */ +- void _sortClassesMembers() { +- for (CompilationUnitMember unitMember in unit.declarations) { +- if (unitMember is ClassDeclaration) { +- ClassDeclaration classDeclaration =3D unitMember; +- _sortClassMembers(classDeclaration); +- } +- } +- } +- +- /** +- * Sorts all members of the given [ClassDeclaration]. +- */ +- void _sortClassMembers(ClassDeclaration classDeclaration) { +- List<_MemberInfo> members =3D <_MemberInfo>[]; +- for (ClassMember member in classDeclaration.members) { +- _MemberKind kind =3D null; +- bool isStatic =3D false; +- String name =3D null; +- if (member is ConstructorDeclaration) { +- kind =3D _MemberKind.CLASS_CONSTRUCTOR; +- SimpleIdentifier nameNode =3D member.name; +- if (nameNode =3D=3D null) { +- name =3D ""; +- } else { +- name =3D nameNode.name; +- } +- } +- if (member is FieldDeclaration) { +- FieldDeclaration fieldDeclaration =3D member; +- List fields =3D fieldDeclaration.fields.vari= ables; +- if (!fields.isEmpty) { +- kind =3D _MemberKind.CLASS_FIELD; +- isStatic =3D fieldDeclaration.isStatic; +- name =3D fields[0].name.name; +- } +- } +- if (member is MethodDeclaration) { +- MethodDeclaration method =3D member; +- isStatic =3D method.isStatic; +- name =3D method.name.name; +- if (method.isGetter) { +- kind =3D _MemberKind.CLASS_ACCESSOR; +- name +=3D " getter"; +- } else if (method.isSetter) { +- kind =3D _MemberKind.CLASS_ACCESSOR; +- name +=3D " setter"; +- } else { +- kind =3D _MemberKind.CLASS_METHOD; +- } +- } +- if (name !=3D null) { +- _PriorityItem item =3D new _PriorityItem.forName(isStatic, name, = kind); +- int offset =3D member.offset; +- int length =3D member.length; +- String text =3D code.substring(offset, offset + length); +- members.add(new _MemberInfo(item, name, offset, length, text)); +- } +- } +- // do sort +- _sortAndReorderMembers(members); +- } +- +- /** +- * Sorts all [Directive]s. +- */ +- void _sortUnitDirectives() { +- bool hasLibraryDirective =3D false; +- List<_DirectiveInfo> directives =3D []; +- for (Directive directive in unit.directives) { +- if (directive is LibraryDirective) { +- hasLibraryDirective =3D true; +- } +- if (directive is! UriBasedDirective) { +- continue; +- } +- UriBasedDirective uriDirective =3D directive as UriBasedDirective; +- String uriContent =3D uriDirective.uri.stringValue; +- _DirectivePriority kind =3D null; +- if (directive is ImportDirective) { +- if (uriContent.startsWith("dart:")) { +- kind =3D _DirectivePriority.IMPORT_SDK; +- } else if (uriContent.startsWith("package:")) { +- kind =3D _DirectivePriority.IMPORT_PKG; +- } else if (uriContent.contains('://')) { +- kind =3D _DirectivePriority.IMPORT_OTHER; +- } else { +- kind =3D _DirectivePriority.IMPORT_REL; +- } +- } +- if (directive is ExportDirective) { +- if (uriContent.startsWith("dart:")) { +- kind =3D _DirectivePriority.EXPORT_SDK; +- } else if (uriContent.startsWith("package:")) { +- kind =3D _DirectivePriority.EXPORT_PKG; +- } else if (uriContent.contains('://')) { +- kind =3D _DirectivePriority.EXPORT_OTHER; +- } else { +- kind =3D _DirectivePriority.EXPORT_REL; +- } +- } +- if (directive is PartDirective) { +- kind =3D _DirectivePriority.PART; +- } +- if (kind !=3D null) { +- String documentationText; +- if (directive.documentationComment !=3D null) { +- documentationText =3D code.substring( +- directive.documentationComment.offset, +- directive.documentationComment.end); +- } +- String annotationText; +- if (directive.metadata.beginToken !=3D null) { +- annotationText =3D code.substring(directive.metadata.beginToken= .offset, +- directive.metadata.endToken.end); +- } +- int offset =3D directive.firstTokenAfterCommentAndMetadata.offset; +- int length =3D directive.end - offset; +- String text =3D code.substring(offset, offset + length); +- directives.add(new _DirectiveInfo(directive, kind, uriContent, +- documentationText, annotationText, text)); +- } +- } +- // nothing to do +- if (directives.isEmpty) { +- return; +- } +- int firstDirectiveOffset =3D directives[0].directive.offset; +- int lastDirectiveEnd =3D directives[directives.length - 1].directive.= end; +- // Without a library directive, the library comment is the comment of= the +- // first directive. +- _DirectiveInfo libraryDocumentationDirective; +- if (!hasLibraryDirective && directives.isNotEmpty) { +- libraryDocumentationDirective =3D directives.first; +- } +- // do sort +- directives.sort(); +- // append directives with grouping +- String directivesCode; +- { +- StringBuffer sb =3D new StringBuffer(); +- String endOfLine =3D this.endOfLine; +- _DirectivePriority currentPriority =3D null; +- bool firstOutputDirective =3D true; +- for (_DirectiveInfo directive in directives) { +- if (currentPriority !=3D directive.priority) { +- if (sb.length !=3D 0) { +- sb.write(endOfLine); +- } +- currentPriority =3D directive.priority; +- } +- if (directive !=3D libraryDocumentationDirective && +- directive.documentationText !=3D null) { +- sb.write(directive.documentationText); +- sb.write(endOfLine); +- } +- if (firstOutputDirective) { +- firstOutputDirective =3D false; +- if (libraryDocumentationDirective !=3D null && +- libraryDocumentationDirective.documentationText !=3D null) { +- sb.write(libraryDocumentationDirective.documentationText); +- sb.write(endOfLine); +- } +- } +- if (directive.annotationText !=3D null) { +- sb.write(directive.annotationText); +- sb.write(endOfLine); +- } +- sb.write(directive.text); +- sb.write(endOfLine); +- } +- directivesCode =3D sb.toString(); +- directivesCode =3D directivesCode.trimRight(); +- } +- // prepare code +- String beforeDirectives =3D code.substring(0, firstDirectiveOffset); +- String afterDirectives =3D code.substring(lastDirectiveEnd); +- code =3D beforeDirectives + directivesCode + afterDirectives; +- } +- +- /** +- * Sorts all [CompilationUnitMember]s. +- */ +- void _sortUnitMembers() { +- List<_MemberInfo> members =3D []; +- for (CompilationUnitMember member in unit.declarations) { +- _MemberKind kind =3D null; +- String name =3D null; +- if (member is ClassDeclaration) { +- kind =3D _MemberKind.UNIT_CLASS; +- name =3D member.name.name; +- } +- if (member is ClassTypeAlias) { +- kind =3D _MemberKind.UNIT_CLASS; +- name =3D member.name.name; +- } +- if (member is EnumDeclaration) { +- kind =3D _MemberKind.UNIT_CLASS; +- name =3D member.name.name; +- } +- if (member is FunctionDeclaration) { +- FunctionDeclaration function =3D member; +- name =3D function.name.name; +- if (function.isGetter) { +- kind =3D _MemberKind.UNIT_ACCESSOR; +- name +=3D " getter"; +- } else if (function.isSetter) { +- kind =3D _MemberKind.UNIT_ACCESSOR; +- name +=3D " setter"; +- } else { +- if (name =3D=3D 'main') { +- kind =3D _MemberKind.UNIT_FUNCTION_MAIN; +- } else { +- kind =3D _MemberKind.UNIT_FUNCTION; +- } +- } +- } +- if (member is FunctionTypeAlias) { +- kind =3D _MemberKind.UNIT_FUNCTION_TYPE; +- name =3D member.name.name; +- } +- if (member is TopLevelVariableDeclaration) { +- TopLevelVariableDeclaration variableDeclaration =3D member; +- List variables =3D +- variableDeclaration.variables.variables; +- if (!variables.isEmpty) { +- if (variableDeclaration.variables.isConst) { +- kind =3D _MemberKind.UNIT_VARIABLE_CONST; +- } else { +- kind =3D _MemberKind.UNIT_VARIABLE; +- } +- name =3D variables[0].name.name; +- } +- } +- if (name !=3D null) { +- _PriorityItem item =3D new _PriorityItem.forName(false, name, kin= d); +- int offset =3D member.offset; +- int length =3D member.length; +- String text =3D code.substring(offset, offset + length); +- members.add(new _MemberInfo(item, name, offset, length, text)); +- } +- } +- // do sort +- _sortAndReorderMembers(members); +- } +- +- /** +- * Return the EOL to use for [code]. +- */ +- static String getEOL(String code) { +- if (code.contains('\r\n')) { +- return '\r\n'; +- } else { +- return '\n'; +- } +- } +- +- static int _getPriority(_PriorityItem item) { +- for (int i =3D 0; i < _PRIORITY_ITEMS.length; i++) { +- if (_PRIORITY_ITEMS[i] =3D=3D item) { +- return i; +- } +- } +- return 0; +- } +- +- static List<_MemberInfo> _getSortedMembers(List<_MemberInfo> members) { +- List<_MemberInfo> membersSorted =3D new List<_MemberInfo>.from(member= s); +- membersSorted.sort((_MemberInfo o1, _MemberInfo o2) { +- int priority1 =3D _getPriority(o1.item); +- int priority2 =3D _getPriority(o2.item); +- if (priority1 =3D=3D priority2) { +- // don't reorder class fields +- if (o1.item.kind =3D=3D _MemberKind.CLASS_FIELD) { +- return o1.offset - o2.offset; +- } +- // sort all other members by name +- String name1 =3D o1.name.toLowerCase(); +- String name2 =3D o2.name.toLowerCase(); +- return name1.compareTo(name2); +- } +- return priority1 - priority2; +- }); +- return membersSorted; +- } +-} +- +-class _DirectiveInfo implements Comparable<_DirectiveInfo> { +- final Directive directive; +- final _DirectivePriority priority; +- final String uri; +- final String documentationText; +- final String annotationText; +- final String text; +- +- _DirectiveInfo(this.directive, this.priority, this.uri, +- this.documentationText, this.annotationText, this.text); +- +- @override +- int compareTo(_DirectiveInfo other) { +- if (priority =3D=3D other.priority) { +- return _compareUri(uri, other.uri); +- } +- return priority.ordinal - other.priority.ordinal; +- } +- +- @override +- String toString() =3D> '(priority=3D$priority; text=3D$text)'; +- +- static int _compareUri(String a, String b) { +- List aList =3D _splitUri(a); +- List bList =3D _splitUri(b); +- int result; +- if ((result =3D aList[0].compareTo(bList[0])) !=3D 0) return result; +- if ((result =3D aList[1].compareTo(bList[1])) !=3D 0) return result; +- return 0; +- } +- +- /** +- * Split the given [uri] like `package:some.name/and/path.dart` into a = list +- * like `[package:some.name, and/path.dart]`. +- */ +- static List _splitUri(String uri) { +- int index =3D uri.indexOf('/'); +- if (index =3D=3D -1) { +- return [uri, '']; +- } +- return [uri.substring(0, index), uri.substring(index + 1)]; +- } +-} +- +-class _DirectivePriority { +- static const IMPORT_SDK =3D const _DirectivePriority('IMPORT_SDK', 0); +- static const IMPORT_PKG =3D const _DirectivePriority('IMPORT_PKG', 1); +- static const IMPORT_OTHER =3D const _DirectivePriority('IMPORT_OTHER', = 2); +- static const IMPORT_REL =3D const _DirectivePriority('IMPORT_REL', 3); +- static const EXPORT_SDK =3D const _DirectivePriority('EXPORT_SDK', 4); +- static const EXPORT_PKG =3D const _DirectivePriority('EXPORT_PKG', 5); +- static const EXPORT_OTHER =3D const _DirectivePriority('EXPORT_OTHER', = 6); +- static const EXPORT_REL =3D const _DirectivePriority('EXPORT_REL', 7); +- static const PART =3D const _DirectivePriority('PART', 8); +- +- final String name; +- final int ordinal; +- +- const _DirectivePriority(this.name, this.ordinal); +- +- @override +- String toString() =3D> name; +-} +- +-class _MemberInfo { +- final _PriorityItem item; +- final String name; +- final int offset; +- final int length; +- final int end; +- final String text; +- +- _MemberInfo(this.item, this.name, int offset, int length, this.text) +- : offset =3D offset, +- length =3D length, +- end =3D offset + length; +- +- @override +- String toString() { +- return '(priority=3D$item; name=3D$name; offset=3D$offset; length=3D$= length)'; +- } +-} +- +-class _MemberKind { +- static const UNIT_FUNCTION_MAIN =3D const _MemberKind('UNIT_FUNCTION_MA= IN', 0); +- static const UNIT_ACCESSOR =3D const _MemberKind('UNIT_ACCESSOR', 1); +- static const UNIT_FUNCTION =3D const _MemberKind('UNIT_FUNCTION', 2); +- static const UNIT_FUNCTION_TYPE =3D const _MemberKind('UNIT_FUNCTION_TY= PE', 3); +- static const UNIT_CLASS =3D const _MemberKind('UNIT_CLASS', 4); +- static const UNIT_VARIABLE_CONST =3D const _MemberKind('UNIT_VARIABLE',= 5); +- static const UNIT_VARIABLE =3D const _MemberKind('UNIT_VARIABLE', 6); +- static const CLASS_ACCESSOR =3D const _MemberKind('CLASS_ACCESSOR', 7); +- static const CLASS_CONSTRUCTOR =3D const _MemberKind('CLASS_CONSTRUCTOR= ', 8); +- static const CLASS_FIELD =3D const _MemberKind('CLASS_FIELD', 9); +- static const CLASS_METHOD =3D const _MemberKind('CLASS_METHOD', 10); +- +- final String name; +- final int ordinal; +- +- const _MemberKind(this.name, this.ordinal); +- +- @override +- String toString() =3D> name; +-} +- +-class _PriorityItem { +- final _MemberKind kind; +- final bool isPrivate; +- final bool isStatic; +- +- _PriorityItem(this.isStatic, this.kind, this.isPrivate); +- +- factory _PriorityItem.forName(bool isStatic, String name, _MemberKind k= ind) { +- bool isPrivate =3D Identifier.isPrivateName(name); +- return new _PriorityItem(isStatic, kind, isPrivate); +- } +- +- @override +- bool operator =3D=3D(Object obj) { +- _PriorityItem other =3D obj as _PriorityItem; +- if (kind =3D=3D _MemberKind.CLASS_FIELD) { +- return other.kind =3D=3D kind && other.isStatic =3D=3D isStatic; +- } +- return other.kind =3D=3D kind && +- other.isPrivate =3D=3D isPrivate && +- other.isStatic =3D=3D isStatic; +- } +- +- @override +- String toString() =3D> kind.toString(); +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/source_buffer= .dart b/pkg/analysis_server/lib/src/services/correction/source_buffer.dart +deleted file mode 100644 +index 24d6848300b..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/source_buffer.dart ++++ /dev/null +@@ -1,99 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * Helper for building Dart source with linked positions. +- */ +-class SourceBuilder { +- final String file; +- final int offset; +- final StringBuffer _buffer =3D new StringBuffer(); +- +- final Map linkedPositionGroups =3D +- {}; +- LinkedEditGroup _currentLinkedPositionGroup; +- int _currentPositionStart; +- int _exitOffset; +- +- SourceBuilder(this.file, this.offset); +- +- SourceBuilder.buffer() +- : file =3D null, +- offset =3D 0; +- +- /** +- * Returns the exit offset, maybe `null` if not set. +- */ +- int get exitOffset { +- if (_exitOffset =3D=3D null) { +- return null; +- } +- return offset + _exitOffset; +- } +- +- int get length =3D> _buffer.length; +- +- void addSuggestion(LinkedEditSuggestionKind kind, String value) { +- var suggestion =3D new LinkedEditSuggestion(value, kind); +- _currentLinkedPositionGroup.addSuggestion(suggestion); +- } +- +- void addSuggestions(LinkedEditSuggestionKind kind, List values)= { +- values.forEach((value) =3D> addSuggestion(kind, value)); +- } +- +- /** +- * Appends [s] to the buffer. +- */ +- SourceBuilder append(String s) { +- _buffer.write(s); +- return this; +- } +- +- /** +- * Ends position started using [startPosition]. +- */ +- void endPosition() { +- assert(_currentLinkedPositionGroup !=3D null); +- _addPosition(); +- _currentLinkedPositionGroup =3D null; +- } +- +- /** +- * Marks the current offset as an "exit" one. +- */ +- void setExitOffset() { +- _exitOffset =3D _buffer.length; +- } +- +- /** +- * Marks start of a new linked position for the group with the given ID. +- */ +- void startPosition(String id) { +- assert(_currentLinkedPositionGroup =3D=3D null); +- _currentLinkedPositionGroup =3D linkedPositionGroups[id]; +- if (_currentLinkedPositionGroup =3D=3D null) { +- _currentLinkedPositionGroup =3D new LinkedEditGroup.empty(); +- linkedPositionGroups[id] =3D _currentLinkedPositionGroup; +- } +- _currentPositionStart =3D _buffer.length; +- } +- +- @override +- String toString() =3D> _buffer.toString(); +- +- /** +- * Adds position location [SourceRange] using current fields. +- */ +- void _addPosition() { +- int start =3D offset + _currentPositionStart; +- int end =3D offset + _buffer.length; +- int length =3D end - start; +- Position position =3D new Position(file, start); +- _currentLinkedPositionGroup.addPosition(position, length); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/statement_ana= lyzer.dart b/pkg/analysis_server/lib/src/services/correction/statement_anal= yzer.dart +deleted file mode 100644 +index 4199f27a4aa..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/statement_analyzer.d= art ++++ /dev/null +@@ -1,230 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/services/correction/selection_analyze= r.dart'; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/scanner/reader.dart'; +-import 'package:analyzer/src/dart/scanner/scanner.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * Returns [Token]s of the given Dart source, not `null`, may be empty if= no +- * tokens or some exception happens. +- */ +-List _getTokens(String text) { +- try { +- List tokens =3D []; +- Scanner scanner =3D new Scanner(null, new CharSequenceReader(text), n= ull); +- Token token =3D scanner.tokenize(); +- while (token.type !=3D TokenType.EOF) { +- tokens.add(token); +- token =3D token.next; +- } +- return tokens; +- } catch (e) { +- return new List(0); +- } +-} +- +-/** +- * Analyzer to check if a selection covers a valid set of statements of A= ST. +- */ +-class StatementAnalyzer extends SelectionAnalyzer { +- final CompilationUnit unit; +- +- RefactoringStatus _status =3D new RefactoringStatus(); +- +- StatementAnalyzer(this.unit, SourceRange selection) : super(selection); +- +- /** +- * Returns the [RefactoringStatus] result of selection checking. +- */ +- RefactoringStatus get status =3D> _status; +- +- /** +- * Records fatal error with given message and [Location]. +- */ +- void invalidSelection(String message, [Location context]) { +- if (!_status.hasFatalError) { +- _status.addFatalError(message, context); +- } +- reset(); +- } +- +- @override +- Object visitCompilationUnit(CompilationUnit node) { +- super.visitCompilationUnit(node); +- if (!hasSelectedNodes) { +- return null; +- } +- // check that selection does not begin/end in comment +- { +- int selectionStart =3D selection.offset; +- int selectionEnd =3D selection.end; +- List commentRanges =3D getCommentRanges(unit); +- for (SourceRange commentRange in commentRanges) { +- if (commentRange.contains(selectionStart)) { +- invalidSelection("Selection begins inside a comment."); +- } +- if (commentRange.containsExclusive(selectionEnd)) { +- invalidSelection("Selection ends inside a comment."); +- } +- } +- } +- // more checks +- if (!_status.hasFatalError) { +- _checkSelectedNodes(node); +- } +- return null; +- } +- +- @override +- Object visitDoStatement(DoStatement node) { +- super.visitDoStatement(node); +- List selectedNodes =3D this.selectedNodes; +- if (_contains(selectedNodes, node.body)) { +- invalidSelection( +- "Operation not applicable to a 'do' statement's body and expres= sion."); +- } +- return null; +- } +- +- @override +- Object visitForStatement(ForStatement node) { +- super.visitForStatement(node); +- List selectedNodes =3D this.selectedNodes; +- bool containsInit =3D _contains(selectedNodes, node.initialization) || +- _contains(selectedNodes, node.variables); +- bool containsCondition =3D _contains(selectedNodes, node.condition); +- bool containsUpdaters =3D _containsAny(selectedNodes, node.updaters); +- bool containsBody =3D _contains(selectedNodes, node.body); +- if (containsInit && containsCondition) { +- invalidSelection( +- "Operation not applicable to a 'for' statement's initializer an= d condition."); +- } else if (containsCondition && containsUpdaters) { +- invalidSelection( +- "Operation not applicable to a 'for' statement's condition and = updaters."); +- } else if (containsUpdaters && containsBody) { +- invalidSelection( +- "Operation not applicable to a 'for' statement's updaters and b= ody."); +- } +- return null; +- } +- +- @override +- Object visitSwitchStatement(SwitchStatement node) { +- super.visitSwitchStatement(node); +- List selectedNodes =3D this.selectedNodes; +- List switchMembers =3D node.members; +- for (AstNode selectedNode in selectedNodes) { +- if (switchMembers.contains(selectedNode)) { +- invalidSelection( +- "Selection must either cover whole switch statement or parts = of a single case block."); +- break; +- } +- } +- return null; +- } +- +- @override +- Object visitTryStatement(TryStatement node) { +- super.visitTryStatement(node); +- AstNode firstSelectedNode =3D this.firstSelectedNode; +- if (firstSelectedNode !=3D null) { +- if (firstSelectedNode =3D=3D node.body || +- firstSelectedNode =3D=3D node.finallyBlock) { +- invalidSelection( +- "Selection must either cover whole try statement or parts of = try, catch, or finally block."); +- } else { +- List catchClauses =3D node.catchClauses; +- for (CatchClause catchClause in catchClauses) { +- if (firstSelectedNode =3D=3D catchClause || +- firstSelectedNode =3D=3D catchClause.body || +- firstSelectedNode =3D=3D catchClause.exceptionParameter) { +- invalidSelection( +- "Selection must either cover whole try statement or parts= of try, catch, or finally block."); +- } +- } +- } +- } +- return null; +- } +- +- @override +- Object visitWhileStatement(WhileStatement node) { +- super.visitWhileStatement(node); +- List selectedNodes =3D this.selectedNodes; +- if (_contains(selectedNodes, node.condition) && +- _contains(selectedNodes, node.body)) { +- invalidSelection( +- "Operation not applicable to a while statement's expression and= body."); +- } +- return null; +- } +- +- /** +- * Checks final selected [AstNode]s after processing [CompilationUnit]. +- */ +- void _checkSelectedNodes(CompilationUnit unit) { +- List nodes =3D selectedNodes; +- // some tokens before first selected node +- { +- AstNode firstNode =3D nodes[0]; +- SourceRange rangeBeforeFirstNode =3D +- range.startOffsetEndOffset(selection.offset, firstNode.offset); +- if (_hasTokens(rangeBeforeFirstNode)) { +- invalidSelection( +- "The beginning of the selection contains characters that " +- "do not belong to a statement.", +- newLocation_fromUnit(unit, rangeBeforeFirstNode)); +- } +- } +- // some tokens after last selected node +- { +- AstNode lastNode =3D nodes.last; +- SourceRange rangeAfterLastNode =3D +- range.startOffsetEndOffset(lastNode.end, selection.end); +- if (_hasTokens(rangeAfterLastNode)) { +- invalidSelection( +- "The end of the selection contains characters that " +- "do not belong to a statement.", +- newLocation_fromUnit(unit, rangeAfterLastNode)); +- } +- } +- } +- +- /** +- * Returns `true` if there are [Token]s in the given [SourceRange]. +- */ +- bool _hasTokens(SourceRange range) { +- CompilationUnitElement unitElement =3D unit.element; +- String fullText =3D unitElement.context.getContents(unitElement.sourc= e).data; +- String rangeText =3D fullText.substring(range.offset, range.end); +- return _getTokens(rangeText).isNotEmpty; +- } +- +- /** +- * Returns `true` if [nodes] contains [node]. +- */ +- static bool _contains(List nodes, AstNode node) =3D> +- nodes.contains(node); +- +- /** +- * Returns `true` if [nodes] contains one of the [otherNodes]. +- */ +- static bool _containsAny(List nodes, List otherNodes)= { +- for (AstNode otherNode in otherNodes) { +- if (nodes.contains(otherNode)) { +- return true; +- } +- } +- return false; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/status.dart b= /pkg/analysis_server/lib/src/services/correction/status.dart +deleted file mode 100644 +index 5cc4cc3b8d8..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/status.dart ++++ /dev/null +@@ -1,179 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * An outcome of a condition checking operation. +- */ +-class RefactoringStatus { +- /** +- * The current severity of this [RefactoringStatus] - the maximum of the +- * severities of its [entries]. +- */ +- RefactoringProblemSeverity _severity =3D null; +- +- /** +- * A list of [RefactoringProblem]s. +- */ +- final List problems =3D []; +- +- /** +- * Creates a new OK [RefactoringStatus]. +- */ +- RefactoringStatus(); +- +- /** +- * Creates a new [RefactoringStatus] with the ERROR severity. +- */ +- factory RefactoringStatus.error(String msg, [Location location]) { +- RefactoringStatus status =3D new RefactoringStatus(); +- status.addError(msg, location); +- return status; +- } +- +- /** +- * Creates a new [RefactoringStatus] with the FATAL severity. +- */ +- factory RefactoringStatus.fatal(String msg, [Location location]) { +- RefactoringStatus status =3D new RefactoringStatus(); +- status.addFatalError(msg, location); +- return status; +- } +- +- /** +- * Creates a new [RefactoringStatus] with the WARNING severity. +- */ +- factory RefactoringStatus.warning(String msg, [Location location]) { +- RefactoringStatus status =3D new RefactoringStatus(); +- status.addWarning(msg, location); +- return status; +- } +- +- /** +- * Returns `true` if the severity is FATAL or ERROR. +- */ +- bool get hasError { +- return _severity =3D=3D RefactoringProblemSeverity.FATAL || +- _severity =3D=3D RefactoringProblemSeverity.ERROR; +- } +- +- /** +- * Returns `true` if the severity is FATAL. +- */ +- bool get hasFatalError =3D> _severity =3D=3D RefactoringProblemSeverity= .FATAL; +- +- /** +- * Returns `true` if the severity is WARNING. +- */ +- bool get hasWarning =3D> _severity =3D=3D RefactoringProblemSeverity.WA= RNING; +- +- /** +- * Return `true` if the severity is `OK`. +- */ +- bool get isOK =3D> _severity =3D=3D null; +- +- /** +- * Returns the message of the [RefactoringProblem] with highest severit= y; +- * may be `null` if no problems. +- */ +- String get message { +- RefactoringProblem problem =3D this.problem; +- if (problem =3D=3D null) { +- return null; +- } +- return problem.message; +- } +- +- /** +- * Returns the first [RefactoringProblem] with the highest severity. +- * +- * Returns `null` if no entries. +- */ +- RefactoringProblem get problem { +- for (RefactoringProblem problem in problems) { +- if (problem.severity =3D=3D _severity) { +- return problem; +- } +- } +- return null; +- } +- +- /** +- * Returns the current severity of this [RefactoringStatus]. +- */ +- RefactoringProblemSeverity get severity =3D> _severity; +- +- /** +- * Adds an ERROR problem with the given message and location. +- */ +- void addError(String msg, [Location location]) { +- _addProblem(new RefactoringProblem(RefactoringProblemSeverity.ERROR, = msg, +- location: location)); +- } +- +- /** +- * Adds a FATAL problem with the given message and location. +- */ +- void addFatalError(String msg, [Location location]) { +- _addProblem(new RefactoringProblem(RefactoringProblemSeverity.FATAL, = msg, +- location: location)); +- } +- +- /** +- * Merges [other] into this [RefactoringStatus]. +- * +- * The [other]'s entries are added to this. +- * +- * The resulting severity is the more severe of this and [other] severi= ties. +- * +- * Merging with `null` is allowed - it has no effect. +- */ +- void addStatus(RefactoringStatus other) { +- if (other =3D=3D null) { +- return; +- } +- problems.addAll(other.problems); +- _severity =3D RefactoringProblemSeverity.max(_severity, other.severit= y); +- } +- +- /** +- * Adds a WARNING problem with the given message and location. +- */ +- void addWarning(String msg, [Location location]) { +- _addProblem(new RefactoringProblem(RefactoringProblemSeverity.WARNING= , msg, +- location: location)); +- } +- +- @override +- String toString() { +- StringBuffer sb =3D new StringBuffer(); +- sb.write("<"); +- if (_severity =3D=3D null) { +- sb.write('OK'); +- } else { +- sb.write(_severity.name); +- } +- if (!isOK) { +- sb.write("\n"); +- for (RefactoringProblem problem in problems) { +- sb.write("\t"); +- sb.write(problem); +- sb.write("\n"); +- } +- } +- sb.write(">"); +- return sb.toString(); +- } +- +- /** +- * Adds the given [RefactoringProblem] and updates [severity]. +- */ +- void _addProblem(RefactoringProblem problem) { +- problems.add(problem); +- // update maximum severity +- RefactoringProblemSeverity severity =3D problem.severity; +- _severity =3D RefactoringProblemSeverity.max(_severity, severity); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/strings.dart = b/pkg/analysis_server/lib/src/services/correction/strings.dart +deleted file mode 100644 +index 33a4c6a99d3..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/strings.dart ++++ /dev/null +@@ -1,263 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:math'; +- +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +- +-/** +- * "$" +- */ +-const int CHAR_DOLLAR =3D 0x24; +- +-/** +- * "." +- */ +-const int CHAR_DOT =3D 0x2E; +- +-/** +- * "_" +- */ +-const int CHAR_UNDERSCORE =3D 0x5F; +- +-String capitalize(String str) { +- if (isEmpty(str)) { +- return str; +- } +- return str.substring(0, 1).toUpperCase() + str.substring(1); +-} +- +-int compareStrings(String a, String b) { +- if (a =3D=3D b) { +- return 0; +- } +- if (a =3D=3D null) { +- return 1; +- } +- if (b =3D=3D null) { +- return -1; +- } +- return a.compareTo(b); +-} +- +-/** +- * Return a simple difference between the given [oldStr] and [newStr]. +- */ +-SimpleDiff computeSimpleDiff(String oldStr, String newStr) { +- int prefixLength =3D findCommonPrefix(oldStr, newStr); +- int suffixLength =3D findCommonSuffix(oldStr, newStr); +- while (prefixLength >=3D 0) { +- int oldReplaceLength =3D oldStr.length - prefixLength - suffixLength; +- int newReplaceLength =3D newStr.length - prefixLength - suffixLength; +- if (oldReplaceLength >=3D 0 && newReplaceLength >=3D 0) { +- return new SimpleDiff(prefixLength, oldReplaceLength, +- newStr.substring(prefixLength, newStr.length - suffixLength)); +- } +- prefixLength--; +- } +- return new SimpleDiff(0, oldStr.length, newStr); +-} +- +-int countLeadingWhitespaces(String str) { +- int i =3D 0; +- for (; i < str.length; i++) { +- int c =3D str.codeUnitAt(i); +- if (!isWhitespace(c)) { +- break; +- } +- } +- return i; +-} +- +-/** +- * Counts how many times [sub] appears in [str]. +- */ +-int countMatches(String str, String sub) { +- if (isEmpty(str) || isEmpty(sub)) { +- return 0; +- } +- int count =3D 0; +- int idx =3D 0; +- while ((idx =3D str.indexOf(sub, idx)) !=3D -1) { +- count++; +- idx +=3D sub.length; +- } +- return count; +-} +- +-int countTrailingWhitespaces(String str) { +- int i =3D 0; +- for (; i < str.length; i++) { +- int c =3D str.codeUnitAt(str.length - 1 - i); +- if (!isWhitespace(c)) { +- break; +- } +- } +- return i; +-} +- +-/** +- * Returns the number of characters common to the end of [a] and the start +- * of [b]. +- */ +-int findCommonOverlap(String a, String b) { +- int a_length =3D a.length; +- int b_length =3D b.length; +- // all empty +- if (a_length =3D=3D 0 || b_length =3D=3D 0) { +- return 0; +- } +- // truncate +- if (a_length > b_length) { +- a =3D a.substring(a_length - b_length); +- } else if (a_length < b_length) { +- b =3D b.substring(0, a_length); +- } +- int text_length =3D min(a_length, b_length); +- // the worst case +- if (a =3D=3D b) { +- return text_length; +- } +- // increase common length one by one +- int length =3D 0; +- while (length < text_length) { +- if (a.codeUnitAt(text_length - 1 - length) !=3D b.codeUnitAt(length))= { +- break; +- } +- length++; +- } +- return length; +-} +- +-/** +- * Return the number of characters common to the start of [a] and [b]. +- */ +-int findCommonPrefix(String a, String b) { +- int n =3D min(a.length, b.length); +- for (int i =3D 0; i < n; i++) { +- if (a.codeUnitAt(i) !=3D b.codeUnitAt(i)) { +- return i; +- } +- } +- return n; +-} +- +-/** +- * Return the number of characters common to the end of [a] and [b]. +- */ +-int findCommonSuffix(String a, String b) { +- int a_length =3D a.length; +- int b_length =3D b.length; +- int n =3D min(a_length, b_length); +- for (int i =3D 1; i <=3D n; i++) { +- if (a.codeUnitAt(a_length - i) !=3D b.codeUnitAt(b_length - i)) { +- return i - 1; +- } +- } +- return n; +-} +- +-/** +- * Checks if [str] is `null`, empty or is whitespace. +- */ +-bool isBlank(String str) { +- if (str =3D=3D null) { +- return true; +- } +- if (str.isEmpty) { +- return true; +- } +- return str.codeUnits.every(isSpace); +-} +- +-bool isDigit(int c) { +- return c >=3D 0x30 && c <=3D 0x39; +-} +- +-bool isEOL(int c) { +- return c =3D=3D 0x0D || c =3D=3D 0x0A; +-} +- +-bool isLetter(int c) { +- return (c >=3D 0x41 && c <=3D 0x5A) || (c >=3D 0x61 && c <=3D 0x7A); +-} +- +-bool isLetterOrDigit(int c) { +- return isLetter(c) || isDigit(c); +-} +- +-bool isSpace(int c) =3D> c =3D=3D 0x20 || c =3D=3D 0x09; +- +-bool isWhitespace(int c) { +- return isSpace(c) || isEOL(c); +-} +- +-String remove(String str, String remove) { +- if (isEmpty(str) || isEmpty(remove)) { +- return str; +- } +- return str.replaceAll(remove, ''); +-} +- +-String removeEnd(String str, String remove) { +- if (isEmpty(str) || isEmpty(remove)) { +- return str; +- } +- if (str.endsWith(remove)) { +- return str.substring(0, str.length - remove.length); +- } +- return str; +-} +- +-String repeat(String s, int n) { +- StringBuffer sb =3D new StringBuffer(); +- for (int i =3D 0; i < n; i++) { +- sb.write(s); +- } +- return sb.toString(); +-} +- +-/** +- * If the [text] length is above the [limit], replace the middle with `..= .`. +- */ +-String shorten(String text, int limit) { +- if (text.length > limit) { +- int headLength =3D limit ~/ 2 - 1; +- int tailLength =3D limit - headLength - 3; +- return text.substring(0, headLength) + +- '...' + +- text.substring(text.length - tailLength); +- } +- return text; +-} +- +-/** +- * Gets the substring after the last occurrence of a separator. +- * The separator is not returned. +- */ +-String substringAfterLast(String str, String separator) { +- if (isEmpty(str)) { +- return str; +- } +- if (isEmpty(separator)) { +- return ''; +- } +- int pos =3D str.lastIndexOf(separator); +- if (pos =3D=3D -1) { +- return str; +- } +- return str.substring(pos + separator.length); +-} +- +-/** +- * Information about a single replacement that should be made to convert = the +- * "old" string to the "new" one. +- */ +-class SimpleDiff { +- final int offset; +- final int length; +- final String replacement; +- +- SimpleDiff(this.offset, this.length, this.replacement); +-} +diff --git a/pkg/analysis_server/lib/src/services/correction/util.dart b/p= kg/analysis_server/lib/src/services/correction/util.dart +deleted file mode 100644 +index b31343cf9b7..00000000000 +--- a/pkg/analysis_server/lib/src/services/correction/util.dart ++++ /dev/null +@@ -1,1530 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:math'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show doSourceChange_addElementEdit; +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/scanner/reader.dart'; +-import 'package:analyzer/src/dart/scanner/scanner.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/resolver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show SourceChange, SourceEdit; +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +-import 'package:path/path.dart'; +- +-/** +- * Adds edits to the given [change] that ensure that all the [libraries] = are +- * imported into the given [targetLibrary]. +- */ +-void addLibraryImports( +- SourceChange change, LibraryElement targetLibrary, Set librar= ies) { +- CorrectionUtils libUtils; +- try { +- CompilationUnitElement unitElement =3D targetLibrary.definingCompilat= ionUnit; +- CompilationUnit unitAst =3D getParsedUnit(unitElement); +- libUtils =3D new CorrectionUtils(unitAst); +- } catch (e) { +- throw new CancelCorrectionException(exception: e); +- } +- String eol =3D libUtils.endOfLine; +- // Prepare information about existing imports. +- LibraryDirective libraryDirective; +- List<_ImportDirectiveInfo> importDirectives =3D <_ImportDirectiveInfo>[= ]; +- for (Directive directive in libUtils.unit.directives) { +- if (directive is LibraryDirective) { +- libraryDirective =3D directive; +- } else if (directive is ImportDirective) { +- importDirectives.add(new _ImportDirectiveInfo( +- directive.uriContent, directive.offset, directive.end)); +- } +- } +- +- // Prepare all URIs to import. +- List uriList =3D libraries +- .map((library) =3D> getLibrarySourceUri(targetLibrary, library)) +- .toList(); +- uriList.sort((a, b) =3D> a.compareTo(b)); +- +- // Insert imports: between existing imports. +- if (importDirectives.isNotEmpty) { +- bool isFirstPackage =3D true; +- for (String importUri in uriList) { +- bool inserted =3D false; +- bool isPackage =3D importUri.startsWith('package:'); +- bool isAfterDart =3D false; +- for (_ImportDirectiveInfo existingImport in importDirectives) { +- if (existingImport.uri.startsWith('dart:')) { +- isAfterDart =3D true; +- } +- if (existingImport.uri.startsWith('package:')) { +- isFirstPackage =3D false; +- } +- if (importUri.compareTo(existingImport.uri) < 0) { +- String importCode =3D "import '$importUri';$eol"; +- doSourceChange_addElementEdit(change, targetLibrary, +- new SourceEdit(existingImport.offset, 0, importCode)); +- inserted =3D true; +- break; +- } +- } +- if (!inserted) { +- String importCode =3D "${eol}import '$importUri';"; +- if (isPackage && isFirstPackage && isAfterDart) { +- importCode =3D eol + importCode; +- } +- doSourceChange_addElementEdit(change, targetLibrary, +- new SourceEdit(importDirectives.last.end, 0, importCode)); +- } +- if (isPackage) { +- isFirstPackage =3D false; +- } +- } +- return; +- } +- +- // Insert imports: after the library directive. +- if (libraryDirective !=3D null) { +- String prefix =3D eol + eol; +- for (String importUri in uriList) { +- String importCode =3D "${prefix}import '$importUri';"; +- prefix =3D eol; +- doSourceChange_addElementEdit(change, targetLibrary, +- new SourceEdit(libraryDirective.end, 0, importCode)); +- } +- return; +- } +- +- // If still at the beginning of the file, skip shebang and line comment= s. +- { +- CorrectionUtils_InsertDesc desc =3D libUtils.getInsertDescTop(); +- int offset =3D desc.offset; +- for (int i =3D 0; i < uriList.length; i++) { +- String importUri =3D uriList[i]; +- String importCode =3D "import '$importUri';$eol"; +- if (i =3D=3D 0) { +- importCode =3D desc.prefix + importCode; +- } +- if (i =3D=3D uriList.length - 1) { +- importCode =3D importCode + desc.suffix; +- } +- doSourceChange_addElementEdit( +- change, targetLibrary, new SourceEdit(offset, 0, importCode)); +- } +- } +-} +- +-/** +- * Climbs up [PrefixedIdentifier] and [PropertyAccess] nodes that include= [node]. +- */ +-Expression climbPropertyAccess(AstNode node) { +- while (true) { +- AstNode parent =3D node.parent; +- if (parent is PrefixedIdentifier && parent.identifier =3D=3D node) { +- node =3D parent; +- continue; +- } +- if (parent is PropertyAccess && parent.propertyName =3D=3D node) { +- node =3D parent; +- continue; +- } +- return node; +- } +-} +- +-/** +- * TODO(scheglov) replace with nodes once there will be [CompilationUnit.= getComments]. +- * +- * Returns [SourceRange]s of all comments in [unit]. +- */ +-List getCommentRanges(CompilationUnit unit) { +- List ranges =3D []; +- Token token =3D unit.beginToken; +- while (token !=3D null && token.type !=3D TokenType.EOF) { +- Token commentToken =3D token.precedingComments; +- while (commentToken !=3D null) { +- ranges.add(range.token(commentToken)); +- commentToken =3D commentToken.next; +- } +- token =3D token.next; +- } +- return ranges; +-} +- +-/** +- * Return the given [element] if it is a [CompilationUnitElement]. +- * Return the enclosing [CompilationUnitElement] of the given [element], +- * maybe `null`. +- */ +-CompilationUnitElement getCompilationUnitElement(Element element) { +- if (element is CompilationUnitElement) { +- return element; +- } +- return element.getAncestor((e) =3D> e is CompilationUnitElement); +-} +- +-String getDefaultValueCode(DartType type) { +- if (type !=3D null) { +- String typeName =3D type.displayName; +- if (typeName =3D=3D "bool") { +- return "false"; +- } +- if (typeName =3D=3D "int") { +- return "0"; +- } +- if (typeName =3D=3D "double") { +- return "0.0"; +- } +- if (typeName =3D=3D "String") { +- return "''"; +- } +- } +- // no better guess +- return "null"; +-} +- +-/** +- * Return all [LocalElement]s defined in the given [node]. +- */ +-List getDefinedLocalElements(AstNode node) { +- var collector =3D new _LocalElementsCollector(); +- node.accept(collector); +- return collector.elements; +-} +- +-/** +- * Return the name of the [Element] kind. +- */ +-String getElementKindName(Element element) { +- return element.kind.displayName; +-} +- +-/** +- * Returns the name to display in the UI for the given [Element]. +- */ +-String getElementQualifiedName(Element element) { +- ElementKind kind =3D element.kind; +- if (kind =3D=3D ElementKind.CONSTRUCTOR || +- kind =3D=3D ElementKind.FIELD || +- kind =3D=3D ElementKind.METHOD) { +- return '${element.enclosingElement.displayName}.${element.displayName= }'; +- } else { +- return element.displayName; +- } +-} +- +-/** +- * If the given [AstNode] is in a [ClassDeclaration], returns the +- * [ClassElement]. Otherwise returns `null`. +- */ +-ClassElement getEnclosingClassElement(AstNode node) { +- ClassDeclaration enclosingClassNode =3D +- node.getAncestor((node) =3D> node is ClassDeclaration); +- if (enclosingClassNode !=3D null) { +- return enclosingClassNode.element; +- } +- return null; +-} +- +-/** +- * Returns a class or an unit member enclosing the given [node]. +- */ +-AstNode getEnclosingClassOrUnitMember(AstNode node) { +- AstNode member =3D node; +- while (node !=3D null) { +- if (node is ClassDeclaration) { +- return member; +- } +- if (node is CompilationUnit) { +- return member; +- } +- member =3D node; +- node =3D node.parent; +- } +- return null; +-} +- +-/** +- * Return the [ExecutableElement] of the enclosing executable [AstNode]. +- */ +-ExecutableElement getEnclosingExecutableElement(AstNode node) { +- while (node !=3D null) { +- if (node is FunctionDeclaration) { +- return node.element; +- } +- if (node is ConstructorDeclaration) { +- return node.element; +- } +- if (node is MethodDeclaration) { +- return node.element; +- } +- node =3D node.parent; +- } +- return null; +-} +- +-/** +- * Return the enclosing executable [AstNode]. +- */ +-AstNode getEnclosingExecutableNode(AstNode node) { +- while (node !=3D null) { +- if (node is FunctionDeclaration) { +- return node; +- } +- if (node is ConstructorDeclaration) { +- return node; +- } +- if (node is MethodDeclaration) { +- return node; +- } +- node =3D node.parent; +- } +- return null; +-} +- +-/** +- * Returns [getExpressionPrecedence] for the parent of [node], or `0` if = the +- * parent node is a [ParenthesizedExpression]. +- * +- * The reason is that `(expr)` is always executed after `expr`. +- */ +-int getExpressionParentPrecedence(AstNode node) { +- AstNode parent =3D node.parent; +- if (parent is ParenthesizedExpression) { +- return 0; +- } else if (parent is IndexExpression && parent.index =3D=3D node) { +- return 0; +- } else if (parent is AssignmentExpression && +- node =3D=3D parent.rightHandSide && +- parent.parent is CascadeExpression) { +- // This is a hack to allow nesting of cascade expressions within other +- // cascade expressions. The problem is that if the precedence of two +- // expressions are equal it sometimes means that we don't need parent= heses +- // (such as replacing the `b` in `a + b` with `c + d`) and sometimes = do +- // (such as replacing the `v` in `..f =3D v` with `a..b`). +- return 3; +- } +- return getExpressionPrecedence(parent); +-} +- +-/** +- * Returns the precedence of [node] it is an [Expression], negative other= wise. +- */ +-int getExpressionPrecedence(AstNode node) { +- if (node is Expression) { +- return node.precedence; +- } +- return -1000; +-} +- +-/** +- * Returns the namespace of the given [ImportElement]. +- */ +-Map getImportNamespace(ImportElement imp) { +- NamespaceBuilder builder =3D new NamespaceBuilder(); +- Namespace namespace =3D builder.createImportNamespaceForDirective(imp); +- return namespace.definedNames; +-} +- +-/** +- * Computes the best URI to import [what] into [from]. +- */ +-String getLibrarySourceUri(LibraryElement from, Source what) { +- String whatPath =3D what.fullName; +- // check if an absolute URI (such as 'dart:' or 'package:') +- Uri whatUri =3D what.uri; +- String whatUriScheme =3D whatUri.scheme; +- if (whatUriScheme !=3D '' && whatUriScheme !=3D 'file') { +- return whatUri.toString(); +- } +- // compute a relative URI +- String fromFolder =3D dirname(from.source.fullName); +- String relativeFile =3D relative(whatPath, from: fromFolder); +- return split(relativeFile).join('/'); +-} +- +-/** +- * Returns the line prefix from the given source, i.e. basically just a +- * whitespace prefix of the given [String]. +- */ +-String getLinePrefix(String line) { +- int index =3D 0; +- while (index < line.length) { +- int c =3D line.codeUnitAt(index); +- if (!isWhitespace(c)) { +- break; +- } +- index++; +- } +- return line.substring(0, index); +-} +- +-/** +- * Return the [LocalVariableElement] if given [node] is a reference to a = local +- * variable, or `null` in the other case. +- */ +-LocalVariableElement getLocalVariableElement(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is LocalVariableElement) { +- return element; +- } +- return null; +-} +- +-/** +- * Return the nearest common ancestor of the given [nodes]. +- */ +-AstNode getNearestCommonAncestor(List nodes) { +- // may be no nodes +- if (nodes.isEmpty) { +- return null; +- } +- // prepare parents +- List> parents =3D []; +- for (AstNode node in nodes) { +- parents.add(getParents(node)); +- } +- // find min length +- int minLength =3D 1 << 20; +- for (List parentList in parents) { +- minLength =3D min(minLength, parentList.length); +- } +- // find deepest parent +- int i =3D 0; +- for (; i < minLength; i++) { +- if (!_allListsIdentical(parents, i)) { +- break; +- } +- } +- return parents[0][i - 1]; +-} +- +-/** +- * Returns the [Expression] qualifier if given [node] is the name part of= a +- * [PropertyAccess] or a [PrefixedIdentifier]. Maybe `null`. +- */ +-Expression getNodeQualifier(SimpleIdentifier node) { +- AstNode parent =3D node.parent; +- if (parent is MethodInvocation && identical(parent.methodName, node)) { +- return parent.target; +- } +- if (parent is PropertyAccess && identical(parent.propertyName, node)) { +- return parent.target; +- } +- if (parent is PrefixedIdentifier && identical(parent.identifier, node))= { +- return parent.prefix; +- } +- return null; +-} +- +-/** +- * Returns the [ParameterElement] if the given [node] is a reference to a +- * parameter, or `null` in the other case. +- */ +-ParameterElement getParameterElement(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is ParameterElement) { +- return element; +- } +- return null; +-} +- +-/** +- * Return parent [AstNode]s from compilation unit (at index "0") to the g= iven +- * [node]. +- */ +-List getParents(AstNode node) { +- // prepare number of parents +- int numParents =3D 0; +- { +- AstNode current =3D node.parent; +- while (current !=3D null) { +- numParents++; +- current =3D current.parent; +- } +- } +- // fill array of parents +- List parents =3D new List(numParents); +- AstNode current =3D node.parent; +- int index =3D numParents; +- while (current !=3D null) { +- parents[--index] =3D current; +- current =3D current.parent; +- } +- return parents; +-} +- +-/** +- * Returns a parsed [AstNode] for the given [classElement]. +- * +- * The resulting AST structure may or may not be resolved. +- */ +-AstNode getParsedClassElementNode(ClassElement classElement) { +- CompilationUnitElement unitElement =3D getCompilationUnitElement(classE= lement); +- CompilationUnit unit =3D getParsedUnit(unitElement); +- int offset =3D classElement.nameOffset; +- AstNode classNameNode =3D new NodeLocator(offset).searchWithin(unit); +- if (classElement.isEnum) { +- return classNameNode.getAncestor((node) =3D> node is EnumDeclaration); +- } else { +- return classNameNode.getAncestor( +- (node) =3D> node is ClassDeclaration || node is ClassTypeAlias); +- } +-} +- +-/** +- * Returns a parsed [CompilationUnit] for the given [unitElement]. +- * +- * The resulting AST structure may or may not be resolved. +- * If it is not resolved, then at least the given [unitElement] will be s= et. +- */ +-CompilationUnit getParsedUnit(CompilationUnitElement unitElement) { +- AnalysisContext context =3D unitElement.context; +- Source source =3D unitElement.source; +- CompilationUnit unit =3D context.parseCompilationUnit(source); +- if (unit.element =3D=3D null) { +- unit.element =3D unitElement; +- } +- return unit; +-} +- +-/** +- * If given [node] is name of qualified property extraction, returns targ= et from +- * which this property is extracted, otherwise `null`. +- */ +-Expression getQualifiedPropertyTarget(AstNode node) { +- AstNode parent =3D node.parent; +- if (parent is PrefixedIdentifier) { +- PrefixedIdentifier prefixed =3D parent; +- if (prefixed.identifier =3D=3D node) { +- return parent.prefix; +- } +- } +- if (parent is PropertyAccess) { +- PropertyAccess access =3D parent; +- if (access.propertyName =3D=3D node) { +- return access.realTarget; +- } +- } +- return null; +-} +- +-/** +- * Returns the given [statement] if not a block, or the first child state= ment if +- * a block, or `null` if more than one child. +- */ +-Statement getSingleStatement(Statement statement) { +- if (statement is Block) { +- List blockStatements =3D statement.statements; +- if (blockStatements.length !=3D 1) { +- return null; +- } +- return blockStatements[0]; +- } +- return statement; +-} +- +-/** +- * Returns the given [statement] if not a block, or all the children stat= ements +- * if a block. +- */ +-List getStatements(Statement statement) { +- if (statement is Block) { +- return statement.statements; +- } +- return [statement]; +-} +- +-/** +- * Checks if the given [element]'s display name equals to the given [name= ]. +- */ +-bool hasDisplayName(Element element, String name) { +- if (element =3D=3D null) { +- return false; +- } +- return element.displayName =3D=3D name; +-} +- +-/** +- * Checks if given [DartNode] is the left hand side of an assignment, or a +- * declaration of a variable. +- */ +-bool isLeftHandOfAssignment(SimpleIdentifier node) { +- if (node.inSetterContext()) { +- return true; +- } +- return node.parent is VariableDeclaration && +- (node.parent as VariableDeclaration).name =3D=3D node; +-} +- +-/** +- * Return `true` if the given [node] is the name of a [NamedExpression]. +- */ +-bool isNamedExpressionName(SimpleIdentifier node) { +- AstNode parent =3D node.parent; +- if (parent is Label) { +- Label label =3D parent; +- if (identical(label.label, node)) { +- AstNode parent2 =3D label.parent; +- if (parent2 is NamedExpression) { +- return identical(parent2.name, label); +- } +- } +- } +- return false; +-} +- +-/** +- * If the given [expression] is the `expression` property of a [NamedExpr= ession] +- * then returns this [NamedExpression], otherwise returns [expression]. +- */ +-Expression stepUpNamedExpression(Expression expression) { +- if (expression !=3D null) { +- AstNode parent =3D expression.parent; +- if (parent is NamedExpression && parent.expression =3D=3D expression)= { +- return parent; +- } +- } +- return expression; +-} +- +-/** +- * Return `true` if the given [lists] are identical at the given [positio= n]. +- */ +-bool _allListsIdentical(List lists, int position) { +- Object element =3D lists[0][position]; +- for (List list in lists) { +- if (list[position] !=3D element) { +- return false; +- } +- } +- return true; +-} +- +-/** +- * This exception is thrown to cancel the current correction operation, +- * such as quick assist or quick fix because an inconsistency was detecte= d. +- * These inconsistencies may happen as a part of normal workflow, e.g. be= cause +- * a resource was deleted, or an analysis result was invalidated. +- */ +-class CancelCorrectionException { +- final Object exception; +- +- CancelCorrectionException({this.exception}); +-} +- +-/** +- * Describes the location for a newly created [ClassMember]. +- */ +-class ClassMemberLocation { +- final String prefix; +- final int offset; +- final String suffix; +- +- ClassMemberLocation(this.prefix, this.offset, this.suffix); +-} +- +-class CorrectionUtils { +- final CompilationUnit unit; +- +- /** +- * The [ClassElement] the generated code is inserted to, so we can deci= de if +- * a type parameter may or may not be used. +- */ +- ClassElement targetClassElement; +- +- ExecutableElement targetExecutableElement; +- +- LibraryElement _library; +- String _buffer; +- String _endOfLine; +- +- CorrectionUtils(this.unit) { +- CompilationUnitElement unitElement =3D unit.element; +- AnalysisContext context =3D unitElement.context; +- if (context =3D=3D null) { +- throw new CancelCorrectionException(); +- } +- this._library =3D unitElement.library; +- this._buffer =3D context.getContents(unitElement.source).data; +- } +- +- /** +- * Returns the EOL to use for this [CompilationUnit]. +- */ +- String get endOfLine { +- if (_endOfLine =3D=3D null) { +- if (_buffer.contains("\r\n")) { +- _endOfLine =3D "\r\n"; +- } else { +- _endOfLine =3D "\n"; +- } +- } +- return _endOfLine; +- } +- +- /** +- * Returns the [AstNode] that encloses the given offset. +- */ +- AstNode findNode(int offset) =3D> new NodeLocator(offset).searchWithin(= unit); +- +- /** +- * Returns names of elements that might conflict with a new local varia= ble +- * declared at [offset]. +- */ +- Set findPossibleLocalVariableConflicts(int offset) { +- Set conflicts =3D new Set(); +- AstNode enclosingNode =3D findNode(offset); +- Block enclosingBlock =3D enclosingNode.getAncestor((node) =3D> node i= s Block); +- if (enclosingBlock !=3D null) { +- _CollectReferencedUnprefixedNames visitor =3D +- new _CollectReferencedUnprefixedNames(); +- enclosingBlock.accept(visitor); +- return visitor.names; +- } +- return conflicts; +- } +- +- /** +- * Returns the indentation with the given level. +- */ +- String getIndent(int level) =3D> repeat(' ', level); +- +- /** +- * Returns a [InsertDesc] describing where to insert a new directive or= a +- * top-level declaration at the top of the file. +- */ +- CorrectionUtils_InsertDesc getInsertDescTop() { +- // skip leading line comments +- int offset =3D 0; +- bool insertEmptyLineBefore =3D false; +- bool insertEmptyLineAfter =3D false; +- String source =3D _buffer; +- // skip hash-bang +- if (offset < source.length - 2) { +- String linePrefix =3D getText(offset, 2); +- if (linePrefix =3D=3D "#!") { +- insertEmptyLineBefore =3D true; +- offset =3D getLineNext(offset); +- // skip empty lines to first line comment +- int emptyOffset =3D offset; +- while (emptyOffset < source.length - 2) { +- int nextLineOffset =3D getLineNext(emptyOffset); +- String line =3D source.substring(emptyOffset, nextLineOffset); +- if (line.trim().isEmpty) { +- emptyOffset =3D nextLineOffset; +- continue; +- } else if (line.startsWith("//")) { +- offset =3D emptyOffset; +- break; +- } else { +- break; +- } +- } +- } +- } +- // skip line comments +- while (offset < source.length - 2) { +- String linePrefix =3D getText(offset, 2); +- if (linePrefix =3D=3D "//") { +- insertEmptyLineBefore =3D true; +- offset =3D getLineNext(offset); +- } else { +- break; +- } +- } +- // determine if empty line is required after +- int nextLineOffset =3D getLineNext(offset); +- String insertLine =3D source.substring(offset, nextLineOffset); +- if (!insertLine.trim().isEmpty) { +- insertEmptyLineAfter =3D true; +- } +- // fill InsertDesc +- CorrectionUtils_InsertDesc desc =3D new CorrectionUtils_InsertDesc(); +- desc.offset =3D offset; +- if (insertEmptyLineBefore) { +- desc.prefix =3D endOfLine; +- } +- if (insertEmptyLineAfter) { +- desc.suffix =3D endOfLine; +- } +- return desc; +- } +- +- /** +- * Skips whitespace characters and single EOL on the right from [index]. +- * +- * If [index] the end of a statement or method, then in the most cases = it is +- * a start of the next line. +- */ +- int getLineContentEnd(int index) { +- int length =3D _buffer.length; +- // skip whitespace characters +- while (index < length) { +- int c =3D _buffer.codeUnitAt(index); +- if (!isWhitespace(c) || c =3D=3D 0x0D || c =3D=3D 0x0A) { +- break; +- } +- index++; +- } +- // skip single \r +- if (index < length && _buffer.codeUnitAt(index) =3D=3D 0x0D) { +- index++; +- } +- // skip single \n +- if (index < length && _buffer.codeUnitAt(index) =3D=3D 0x0A) { +- index++; +- } +- // done +- return index; +- } +- +- /** +- * Skips spaces and tabs on the left from [index]. +- * +- * If [index] is the start or a statement, then in the most cases it is= a +- * start on its line. +- */ +- int getLineContentStart(int index) { +- while (index > 0) { +- int c =3D _buffer.codeUnitAt(index - 1); +- if (!isSpace(c)) { +- break; +- } +- index--; +- } +- return index; +- } +- +- /** +- * Returns a start index of the next line after the line which contains= the +- * given index. +- */ +- int getLineNext(int index) { +- int length =3D _buffer.length; +- // skip to the end of the line +- while (index < length) { +- int c =3D _buffer.codeUnitAt(index); +- if (c =3D=3D 0xD || c =3D=3D 0xA) { +- break; +- } +- index++; +- } +- // skip single \r +- if (index < length && _buffer.codeUnitAt(index) =3D=3D 0xD) { +- index++; +- } +- // skip single \n +- if (index < length && _buffer.codeUnitAt(index) =3D=3D 0xA) { +- index++; +- } +- // done +- return index; +- } +- +- /** +- * Returns the whitespace prefix of the line which contains given offse= t. +- */ +- String getLinePrefix(int index) { +- int lineStart =3D getLineThis(index); +- int length =3D _buffer.length; +- int lineNonWhitespace =3D lineStart; +- while (lineNonWhitespace < length) { +- int c =3D _buffer.codeUnitAt(lineNonWhitespace); +- if (c =3D=3D 0xD || c =3D=3D 0xA) { +- break; +- } +- if (!isWhitespace(c)) { +- break; +- } +- lineNonWhitespace++; +- } +- return getText(lineStart, lineNonWhitespace - lineStart); +- } +- +- /** +- * Returns a [SourceRange] that covers [sourceRange] and extends (if po= ssible) +- * to cover whole lines. +- */ +- SourceRange getLinesRange(SourceRange sourceRange, +- {bool skipLeadingEmptyLines: false}) { +- // start +- int startOffset =3D sourceRange.offset; +- int startLineOffset =3D getLineContentStart(startOffset); +- if (skipLeadingEmptyLines) { +- startLineOffset =3D skipEmptyLinesLeft(startLineOffset); +- } +- // end +- int endOffset =3D sourceRange.end; +- int afterEndLineOffset =3D endOffset; +- int lineStart =3D unit.lineInfo.getOffsetOfLine( +- unit.lineInfo.getLocation(startLineOffset).lineNumber - 1); +- if (lineStart =3D=3D startLineOffset) { +- // Only consume line ends after the end of the range if there is no= thing +- // else on the line containing the beginning of the range. Otherwis= e this +- // will end up incorrectly merging two line. +- afterEndLineOffset =3D getLineContentEnd(endOffset); +- } +- // range +- return range.startOffsetEndOffset(startLineOffset, afterEndLineOffset= ); +- } +- +- /** +- * Returns a [SourceRange] that covers all the given [Statement]s. +- */ +- SourceRange getLinesRangeStatements(List statements) { +- return getLinesRange(range.nodes(statements)); +- } +- +- /** +- * Returns the start index of the line which contains given index. +- */ +- int getLineThis(int index) { +- while (index > 0) { +- int c =3D _buffer.codeUnitAt(index - 1); +- if (c =3D=3D 0xD || c =3D=3D 0xA) { +- break; +- } +- index--; +- } +- return index; +- } +- +- /** +- * Returns the line prefix consisting of spaces and tabs on the left fr= om the given +- * [AstNode]. +- */ +- String getNodePrefix(AstNode node) { +- int offset =3D node.offset; +- // function literal is special, it uses offset of enclosing line +- if (node is FunctionExpression) { +- return getLinePrefix(offset); +- } +- // use just prefix directly before node +- return getPrefix(offset); +- } +- +- /** +- * Returns the text of the given [AstNode] in the unit. +- */ +- String getNodeText(AstNode node) { +- return getText(node.offset, node.length); +- } +- +- /** +- * Returns the line prefix consisting of spaces and tabs on the left fr= om the +- * given offset. +- */ +- String getPrefix(int endIndex) { +- int startIndex =3D getLineContentStart(endIndex); +- return _buffer.substring(startIndex, endIndex); +- } +- +- /** +- * Returns the text of the given range in the unit. +- */ +- String getRangeText(SourceRange range) { +- return getText(range.offset, range.length); +- } +- +- /** +- * Returns the text of the given range in the unit. +- */ +- String getText(int offset, int length) { +- return _buffer.substring(offset, offset + length); +- } +- +- /** +- * Returns the source to reference [type] in this [CompilationUnit]. +- * +- * Fills [librariesToImport] with [LibraryElement]s whose elements are +- * used by the generated source, but not imported. +- */ +- String getTypeSource(DartType type, Set librariesToImport, +- {StringBuffer parametersBuffer}) { +- StringBuffer sb =3D new StringBuffer(); +- // type parameter +- if (!_isTypeVisible(type)) { +- return 'dynamic'; +- } +- +- Element element =3D type.element; +- +- // Typedef(s) are represented as GenericFunctionTypeElement(s). +- if (element is GenericFunctionTypeElement && +- element.typeParameters.isEmpty && +- element.enclosingElement is GenericTypeAliasElement) { +- element =3D element.enclosingElement; +- } +- +- // just a Function, not FunctionTypeAliasElement +- if (type is FunctionType && element is! FunctionTypeAliasElement) { +- if (parametersBuffer =3D=3D null) { +- return "Function"; +- } +- parametersBuffer.write('('); +- for (ParameterElement parameter in type.parameters) { +- String parameterType =3D getTypeSource(parameter.type, librariesT= oImport); +- if (parametersBuffer.length !=3D 1) { +- parametersBuffer.write(', '); +- } +- parametersBuffer.write(parameterType); +- parametersBuffer.write(' '); +- parametersBuffer.write(parameter.name); +- } +- parametersBuffer.write(')'); +- return getTypeSource(type.returnType, librariesToImport); +- } +- // , Null +- if (type.isBottom || type.isDartCoreNull) { +- return 'dynamic'; +- } +- // prepare element +- if (element =3D=3D null) { +- String source =3D type.toString(); +- source =3D source.replaceAll('', ''); +- source =3D source.replaceAll('', ''); +- return source; +- } +- // check if imported +- LibraryElement library =3D element.library; +- if (library !=3D null && library !=3D _library) { +- // no source, if private +- if (element.isPrivate) { +- return null; +- } +- // ensure import +- ImportElement importElement =3D _getImportElement(element); +- if (importElement !=3D null) { +- if (importElement.prefix !=3D null) { +- sb.write(importElement.prefix.displayName); +- sb.write("."); +- } +- } else { +- librariesToImport.add(library.source); +- } +- } +- // append simple name +- String name =3D element.displayName; +- sb.write(name); +- // may be type arguments +- if (type is ParameterizedType) { +- List arguments =3D type.typeArguments; +- // check if has arguments +- bool hasArguments =3D false; +- bool allArgumentsVisible =3D true; +- for (DartType argument in arguments) { +- hasArguments =3D hasArguments || !argument.isDynamic; +- allArgumentsVisible =3D allArgumentsVisible && _isTypeVisible(arg= ument); +- } +- // append type arguments +- if (hasArguments && allArgumentsVisible) { +- sb.write("<"); +- for (int i =3D 0; i < arguments.length; i++) { +- DartType argument =3D arguments[i]; +- if (i !=3D 0) { +- sb.write(", "); +- } +- String argumentSrc =3D getTypeSource(argument, librariesToImpor= t); +- if (argumentSrc !=3D null) { +- sb.write(argumentSrc); +- } else { +- return null; +- } +- } +- sb.write(">"); +- } +- } +- // done +- return sb.toString(); +- } +- +- /** +- * Indents given source left or right. +- */ +- String indentSourceLeftRight(String source, {bool indentLeft: true}) { +- StringBuffer sb =3D new StringBuffer(); +- String indent =3D getIndent(1); +- String eol =3D endOfLine; +- List lines =3D source.split(eol); +- for (int i =3D 0; i < lines.length; i++) { +- String line =3D lines[i]; +- // last line, stop if empty +- if (i =3D=3D lines.length - 1 && isEmpty(line)) { +- break; +- } +- // update line +- if (indentLeft) { +- line =3D removeStart(line, indent); +- } else { +- line =3D "$indent$line"; +- } +- // append line +- sb.write(line); +- sb.write(eol); +- } +- return sb.toString(); +- } +- +- /** +- * @return the source of the inverted condition for the given logical e= xpression. +- */ +- String invertCondition(Expression expression) =3D> +- _invertCondition0(expression)._source; +- +- /** +- * Return `true` if the given [classDeclaration] has open '{' and close= '}' +- * at the same line, e.g. `class X {}`. +- */ +- bool isClassWithEmptyBody(ClassDeclaration classDeclaration) { +- return getLineThis(classDeclaration.leftBracket.offset) =3D=3D +- getLineThis(classDeclaration.rightBracket.offset); +- } +- +- /** +- * @return true if selection range contains only whitespac= e or comments +- */ +- bool isJustWhitespaceOrComment(SourceRange range) { +- String trimmedText =3D getRangeText(range).trim(); +- // may be whitespace +- if (trimmedText.isEmpty) { +- return true; +- } +- // may be comment +- return TokenUtils.getTokens(trimmedText).isEmpty; +- } +- +- ClassMemberLocation prepareNewClassMemberLocation( +- ClassDeclaration classDeclaration, +- bool shouldSkip(ClassMember existingMember)) { +- String indent =3D getIndent(1); +- // Find the last target member. +- ClassMember targetMember =3D null; +- List members =3D classDeclaration.members; +- for (ClassMember member in members) { +- if (shouldSkip(member)) { +- targetMember =3D member; +- } else { +- break; +- } +- } +- // After the last target member. +- if (targetMember !=3D null) { +- return new ClassMemberLocation( +- endOfLine + endOfLine + indent, targetMember.end, ''); +- } +- // At the beginning of the class. +- String suffix =3D members.isNotEmpty || isClassWithEmptyBody(classDec= laration) +- ? endOfLine +- : ''; +- return new ClassMemberLocation( +- endOfLine + indent, classDeclaration.leftBracket.end, suffix); +- } +- +- ClassMemberLocation prepareNewConstructorLocation( +- ClassDeclaration classDeclaration) { +- return prepareNewClassMemberLocation( +- classDeclaration, +- (member) =3D> +- member is FieldDeclaration || member is ConstructorDeclaratio= n); +- } +- +- ClassMemberLocation prepareNewFieldLocation( +- ClassDeclaration classDeclaration) { +- return prepareNewClassMemberLocation( +- classDeclaration, (member) =3D> member is FieldDeclaration); +- } +- +- ClassMemberLocation prepareNewGetterLocation( +- ClassDeclaration classDeclaration) { +- return prepareNewClassMemberLocation( +- classDeclaration, +- (member) =3D> +- member is FieldDeclaration || +- member is ConstructorDeclaration || +- member is MethodDeclaration && member.isGetter); +- } +- +- ClassMemberLocation prepareNewMethodLocation( +- ClassDeclaration classDeclaration) { +- return prepareNewClassMemberLocation( +- classDeclaration, +- (member) =3D> +- member is FieldDeclaration || +- member is ConstructorDeclaration || +- member is MethodDeclaration); +- } +- +- /** +- * Returns the source with indentation changed from [oldIndent] to +- * [newIndent], keeping indentation of lines relative to each other. +- */ +- String replaceSourceIndent( +- String source, String oldIndent, String newIndent) { +- // prepare STRING token ranges +- List lineRanges =3D []; +- { +- List tokens =3D TokenUtils.getTokens(source); +- for (Token token in tokens) { +- if (token.type =3D=3D TokenType.STRING) { +- lineRanges.add(range.token(token)); +- } +- token =3D token.next; +- } +- } +- // re-indent lines +- StringBuffer sb =3D new StringBuffer(); +- String eol =3D endOfLine; +- List lines =3D source.split(eol); +- int lineOffset =3D 0; +- for (int i =3D 0; i < lines.length; i++) { +- String line =3D lines[i]; +- // last line, stop if empty +- if (i =3D=3D lines.length - 1 && isEmpty(line)) { +- break; +- } +- // check if "offset" is in one of the String ranges +- bool inString =3D false; +- for (SourceRange lineRange in lineRanges) { +- if (lineOffset > lineRange.offset && lineOffset < lineRange.end) { +- inString =3D true; +- } +- if (lineOffset > lineRange.end) { +- break; +- } +- } +- lineOffset +=3D line.length + eol.length; +- // update line indent +- if (!inString) { +- line =3D "$newIndent${removeStart(line, oldIndent)}"; +- } +- // append line +- sb.write(line); +- sb.write(eol); +- } +- return sb.toString(); +- } +- +- /** +- * Returns the source of the given [SourceRange] with indentation chang= ed +- * from [oldIndent] to [newIndent], keeping indentation of lines relati= ve +- * to each other. +- */ +- String replaceSourceRangeIndent( +- SourceRange range, String oldIndent, String newIndent) { +- String oldSource =3D getRangeText(range); +- return replaceSourceIndent(oldSource, oldIndent, newIndent); +- } +- +- /** +- * @return true if "selection" covers "node" and there are= any non-whitespace tokens +- * between "selection" and "node" start/end. +- */ +- bool selectionIncludesNonWhitespaceOutsideNode( +- SourceRange selection, AstNode node) { +- return _selectionIncludesNonWhitespaceOutsideRange( +- selection, range.node(node)); +- } +- +- /** +- * Skip spaces, tabs and EOLs on the left from [index]. +- * +- * If [index] is the start of a method, then in the most cases return t= he end +- * of the previous not-whitespace line. +- */ +- int skipEmptyLinesLeft(int index) { +- int lastLine =3D index; +- while (index > 0) { +- int c =3D _buffer.codeUnitAt(index - 1); +- if (!isWhitespace(c)) { +- return lastLine; +- } +- if (isEOL(c)) { +- lastLine =3D index; +- } +- index--; +- } +- return 0; +- } +- +- /** +- * @return the [ImportElement] used to import given [Element] into [lib= rary]. +- * May be `null` if was not imported, i.e. declared in the same= library. +- */ +- ImportElement _getImportElement(Element element) { +- for (ImportElement imp in _library.imports) { +- Map definedNames =3D getImportNamespace(imp); +- if (definedNames.containsValue(element)) { +- return imp; +- } +- } +- return null; +- } +- +- /** +- * @return the [InvertedCondition] for the given logical expression. +- */ +- _InvertedCondition _invertCondition0(Expression expression) { +- if (expression is BooleanLiteral) { +- if (expression.value) { +- return _InvertedCondition._simple("false"); +- } else { +- return _InvertedCondition._simple("true"); +- } +- } else if (expression is BinaryExpression) { +- TokenType operator =3D expression.operator.type; +- Expression le =3D expression.leftOperand; +- Expression re =3D expression.rightOperand; +- _InvertedCondition ls =3D _invertCondition0(le); +- _InvertedCondition rs =3D _invertCondition0(re); +- if (operator =3D=3D TokenType.LT) { +- return _InvertedCondition._binary2(ls, " >=3D ", rs); +- } +- if (operator =3D=3D TokenType.GT) { +- return _InvertedCondition._binary2(ls, " <=3D ", rs); +- } +- if (operator =3D=3D TokenType.LT_EQ) { +- return _InvertedCondition._binary2(ls, " > ", rs); +- } +- if (operator =3D=3D TokenType.GT_EQ) { +- return _InvertedCondition._binary2(ls, " < ", rs); +- } +- if (operator =3D=3D TokenType.EQ_EQ) { +- return _InvertedCondition._binary2(ls, " !=3D ", rs); +- } +- if (operator =3D=3D TokenType.BANG_EQ) { +- return _InvertedCondition._binary2(ls, " =3D=3D ", rs); +- } +- if (operator =3D=3D TokenType.AMPERSAND_AMPERSAND) { +- return _InvertedCondition._binary( +- TokenType.BAR_BAR.precedence, ls, " || ", rs); +- } +- if (operator =3D=3D TokenType.BAR_BAR) { +- return _InvertedCondition._binary( +- TokenType.AMPERSAND_AMPERSAND.precedence, ls, " && ", rs); +- } +- } else if (expression is IsExpression) { +- String expressionSource =3D getNodeText(expression.expression); +- String typeSource =3D getNodeText(expression.type); +- if (expression.notOperator =3D=3D null) { +- return _InvertedCondition._simple("$expressionSource is! $typeSou= rce"); +- } else { +- return _InvertedCondition._simple("$expressionSource is $typeSour= ce"); +- } +- } else if (expression is PrefixExpression) { +- TokenType operator =3D expression.operator.type; +- if (operator =3D=3D TokenType.BANG) { +- Expression operand =3D expression.operand.unParenthesized; +- return _InvertedCondition._simple(getNodeText(operand)); +- } +- } else if (expression is ParenthesizedExpression) { +- return _invertCondition0(expression.unParenthesized); +- } +- DartType type =3D expression.bestType; +- if (type.displayName =3D=3D "bool") { +- return _InvertedCondition._simple("!${getNodeText(expression)}"); +- } +- return _InvertedCondition._simple(getNodeText(expression)); +- } +- +- /** +- * Checks if [type] is visible in [targetExecutableElement] or +- * [targetClassElement]. +- */ +- bool _isTypeVisible(DartType type) { +- if (type is TypeParameterType) { +- TypeParameterElement parameterElement =3D type.element; +- Element parameterClassElement =3D parameterElement.enclosingElement; +- return identical(parameterClassElement, targetExecutableElement) || +- identical(parameterClassElement, targetClassElement); +- } +- return true; +- } +- +- /** +- * @return true if "selection" covers "range" and there ar= e any non-whitespace tokens +- * between "selection" and "range" start/end. +- */ +- bool _selectionIncludesNonWhitespaceOutsideRange( +- SourceRange selection, SourceRange sourceRange) { +- // selection should cover range +- if (!selection.covers(sourceRange)) { +- return false; +- } +- // non-whitespace between selection start and range start +- if (!isJustWhitespaceOrComment( +- range.startOffsetEndOffset(selection.offset, sourceRange.offset))= ) { +- return true; +- } +- // non-whitespace after range +- if (!isJustWhitespaceOrComment( +- range.startOffsetEndOffset(sourceRange.end, selection.end))) { +- return true; +- } +- // only whitespace in selection around range +- return false; +- } +-} +- +-/** +- * Describes where to insert new directive or top-level declaration. +- */ +-class CorrectionUtils_InsertDesc { +- int offset =3D 0; +- String prefix =3D ""; +- String suffix =3D ""; +-} +- +-/** +- * Utilities to work with [Token]s. +- */ +-class TokenUtils { +- /** +- * Return the first token in the list of [tokens] representing the given +- * [keyword], or `null` if there is no such token. +- */ +- static Token findKeywordToken(List tokens, Keyword keyword) { +- for (Token token in tokens) { +- if (token.keyword =3D=3D keyword) { +- return token; +- } +- } +- return null; +- } +- +- /** +- * @return the first [Token] with given [TokenType], may be null<= /code> if not +- * found. +- */ +- static Token findToken(List tokens, TokenType type) { +- for (Token token in tokens) { +- if (token.type =3D=3D type) { +- return token; +- } +- } +- return null; +- } +- +- /** +- * @return [Token]s of the given Dart source, not null, ma= y be empty if no +- * tokens or some exception happens. +- */ +- static List getTokens(String s) { +- try { +- List tokens =3D []; +- Scanner scanner =3D new Scanner(null, new CharSequenceReader(s), nu= ll); +- Token token =3D scanner.tokenize(); +- while (token.type !=3D TokenType.EOF) { +- tokens.add(token); +- token =3D token.next; +- } +- return tokens; +- } catch (e) { +- return []; +- } +- } +- +- /** +- * @return true if given [Token]s contain only single [Tok= en] with given +- * [TokenType]. +- */ +- static bool hasOnly(List tokens, TokenType type) =3D> +- tokens.length =3D=3D 1 && tokens[0].type =3D=3D type; +-} +- +-class _CollectReferencedUnprefixedNames extends RecursiveAstVisitor { +- final Set names =3D new Set(); +- +- void visitSimpleIdentifier(SimpleIdentifier node) { +- if (!_isPrefixed(node)) { +- names.add(node.name); +- } +- } +- +- static bool _isPrefixed(SimpleIdentifier node) { +- AstNode parent =3D node.parent; +- return parent is ConstructorName && parent.name =3D=3D node || +- parent is MethodInvocation && +- parent.methodName =3D=3D node && +- parent.realTarget !=3D null || +- parent is PrefixedIdentifier && parent.identifier =3D=3D node || +- parent is PropertyAccess && parent.target =3D=3D node; +- } +-} +- +-class _ImportDirectiveInfo { +- final String uri; +- final int offset; +- final int end; +- +- _ImportDirectiveInfo(this.uri, this.offset, this.end); +-} +- +-/** +- * A container with a source and its precedence. +- */ +-class _InvertedCondition { +- final int _precedence; +- +- final String _source; +- +- _InvertedCondition(this._precedence, this._source); +- +- static _InvertedCondition _binary(int precedence, _InvertedCondition le= ft, +- String operation, _InvertedCondition right) { +- String src =3D _parenthesizeIfRequired(left, precedence) + +- operation + +- _parenthesizeIfRequired(right, precedence); +- return new _InvertedCondition(precedence, src); +- } +- +- static _InvertedCondition _binary2( +- _InvertedCondition left, String operation, _InvertedCondition right= ) { +- // TODO(scheglov) consider merging with "_binary()" after testing +- return new _InvertedCondition( +- 1 << 20, "${left._source}$operation${right._source}"); +- } +- +- /** +- * Adds enclosing parenthesis if the precedence of the [_InvertedCondit= ion] if less than the +- * precedence of the expression we are going it to use in. +- */ +- static String _parenthesizeIfRequired( +- _InvertedCondition expr, int newOperatorPrecedence) { +- if (expr._precedence < newOperatorPrecedence) { +- return "(${expr._source})"; +- } +- return expr._source; +- } +- +- static _InvertedCondition _simple(String source) =3D> +- new _InvertedCondition(2147483647, source); +-} +- +-/** +- * Visitor that collects defined [LocalElement]s. +- */ +-class _LocalElementsCollector extends RecursiveAstVisitor { +- final elements =3D []; +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- if (node.inDeclarationContext()) { +- Element element =3D node.staticElement; +- if (element is LocalElement) { +- elements.add(element); +- } +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/kythe/kythe_visitors.dar= t b/pkg/analysis_server/lib/src/services/kythe/kythe_visitors.dart +deleted file mode 100644 +index 3f26f7a3759..00000000000 +--- a/pkg/analysis_server/lib/src/services/kythe/kythe_visitors.dart ++++ /dev/null +@@ -1,1407 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/ast/syntactic_entity.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/resolver/inheritance_manager.dart'; +-import 'package:analyzer/src/generated/bazel.dart'; +-import 'package:analyzer/src/generated/gn.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show KytheEntry, KytheVName; +- +-import 'schema.dart' as schema; +- +-const int _notFound =3D -1; +- +-/// Given some [ConstructorElement], this method returns '' a= s the +-/// name of the constructor, unless the constructor is a named constructo= r in +-/// which '.' is returned. +-String _computeConstructorElementName(ConstructorElement element) { +- assert(element !=3D null); +- var name =3D element.enclosingElement.name; +- var constructorName =3D element.name; +- if (!constructorName.isEmpty) { +- name =3D name + '.' + constructorName; +- } +- return name; +-} +- +-/// Create an anchor signature of the form '-'. +-String _getAnchorSignature(int start, int end) { +- return '$start-$end'; +-} +- +-String _getPath(ResourceProvider provider, Element e) { +- // TODO(jwren) This method simply serves to provide the WORKSPACE relat= ive +- // path for sources in Elements, it needs to be written in a more robus= t way. +- // TODO(jwren) figure out what source generates a e !=3D null, but +- // e.source =3D=3D null to ensure that it is not a bug somewhere in the= stack. +- if (e =3D=3D null || e.source =3D=3D null) { +- // null sometimes when the element is used to generate the node type +- // "dynamic" +- return ''; +- } +- String path =3D e.source.fullName; +- BazelWorkspace bazelWorkspace =3D BazelWorkspace.find(provider, path); +- if (bazelWorkspace !=3D null) { +- return provider.pathContext.relative(path, from: bazelWorkspace.root); +- } +- GnWorkspace gnWorkspace =3D GnWorkspace.find(provider, path); +- if (gnWorkspace !=3D null) { +- return provider.pathContext.relative(path, from: gnWorkspace.root); +- } +- if (path.lastIndexOf('CORPUS_NAME') !=3D -1) { +- return path.substring(path.lastIndexOf('CORPUS_NAME') + 12); +- } +- return path; +-} +- +-/// If a non-null element is passed, the [SignatureElementVisitor] is use= d to +-/// generate and return a [String] signature, otherwise [schema.DYNAMIC_K= IND] is +-/// returned. +-String _getSignature(ResourceProvider provider, Element element, +- String nodeKind, String corpus) { +- assert(nodeKind !=3D schema.ANCHOR_KIND); // Call _getAnchorSignature i= nstead +- if (element =3D=3D null) { +- return schema.DYNAMIC_KIND; +- } +- if (element is CompilationUnitElement) { +- return _getPath(provider, element); +- } +- return '$nodeKind:${element.accept(SignatureElementVisitor.instance)}'; +-} +- +-class CodedBufferWriter { +- CodedBufferWriter(var v); +- toBuffer() {} +-} +- +-/// This visitor writes out Kythe facts and edges as specified by the Kyt= he +-/// Schema here https://kythe.io/docs/schema/. This visitor handles all = nodes, +-/// facts and edges. +-class KytheDartVisitor extends GeneralizingAstVisitor with OutputUtils { +- final ResourceProvider resourceProvider; +- final List entries; +- final String corpus; +- final InheritanceManager _inheritanceManager; +- final String _contents; +- +- String _enclosingFilePath =3D ''; +- Element _enclosingElement; +- ClassElement _enclosingClassElement; +- KytheVName _enclosingVName; +- KytheVName _enclosingFileVName; +- KytheVName _enclosingClassVName; +- +- KytheDartVisitor(this.resourceProvider, this.entries, this.corpus, +- this._inheritanceManager, this._contents); +- +- @override +- String get enclosingFilePath =3D> _enclosingFilePath; +- +- @override +- visitAnnotation(Annotation node) { +- // TODO(jwren) To get the full set of cross refs correct, additional = ref +- // edges are needed, example: from "A" in "A.namedConstructor()" +- +- var start =3D node.name.offset; +- var end =3D node.name.end; +- if (node.constructorName !=3D null) { +- end =3D node.constructorName.end; +- } +- var refVName =3D _handleRefEdge( +- node.element, +- const [schema.REF_EDGE], +- start: start, +- end: end, +- ); +- if (refVName !=3D null) { +- var parentNode =3D node.parent; +- if (parentNode is Declaration) { +- Element parentElement =3D parentNode.element; +- if (parentNode is TopLevelVariableDeclaration) { +- _handleVariableDeclarationListAnnotations( +- parentNode.variables, refVName); +- } else if (parentNode is FieldDeclaration) { +- _handleVariableDeclarationListAnnotations( +- parentNode.fields, refVName); +- } else if (parentElement !=3D null) { +- var parentVName =3D +- _vNameFromElement(parentElement, _getNodeKind(parentElement= )); +- addEdge(parentVName, schema.ANNOTATED_BY_EDGE, refVName); +- } else { +- // parentAstNode is not a variable declaration node and +- // parentElement =3D=3D null +- assert(false); +- } +- } else { +- // parentAstNode is not a Declaration +- // TODO(jwren) investigate +-// throw new Exception('parentAstNode.runtimeType =3D ${parentAstNod= e.runtimeType}'); +-// assert(false); +- } +- } +- +- // visit children +- _safelyVisit(node.arguments); +- } +- +- @override +- visitAssignmentExpression(AssignmentExpression node) { +- // +- // operator +- // NOTE: usage node only written out if assignment is not the '=3D' o= perator, +- // we are looking for an operator such as +=3D, -=3D, *=3D, /=3D +- // +- Token operator =3D node.operator; +- MethodElement element =3D node.bestElement; +- if (operator.type !=3D TokenType.EQ && element !=3D null) { +- // method +- _vNameFromElement(element, schema.FUNCTION_KIND); +- +- // anchor- ref/call +- _handleRefCallEdge(element, +- syntacticEntity: node.operator, enclosingTarget: _enclosingVNam= e); +- +- // TODO (jwren) Add function type information +- } +- // visit children +- _safelyVisit(node.leftHandSide); +- _safelyVisit(node.rightHandSide); +- } +- +- @override +- visitBinaryExpression(BinaryExpression node) { +- // +- // operators such as +, -, *, / +- // +- MethodElement element =3D node.bestElement; +- if (element !=3D null) { +- // method +- _vNameFromElement(element, schema.FUNCTION_KIND); +- +- // anchor- ref/call +- _handleRefCallEdge(element, +- syntacticEntity: node.operator, enclosingTarget: _enclosingVNam= e); +- +- // TODO (jwren) Add function type information +- } +- // visit children +- _safelyVisit(node.leftOperand); +- _safelyVisit(node.rightOperand); +- } +- +- @override +- visitClassDeclaration(ClassDeclaration node) { +- return _withEnclosingElement(node.element, () { +- // record/ class node +- addNodeAndFacts(schema.RECORD_KIND, +- nodeVName: _enclosingClassVName, +- subKind: schema.CLASS_SUBKIND, +- completeFact: schema.DEFINITION); +- +- // anchor- defines/binding +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.name, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: _enclosingClassVName, +- enclosingTarget: _enclosingFileVName); +- +- // anchor- defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node, +- edges: [ +- schema.DEFINES_EDGE, +- ], +- target: _enclosingClassVName); +- +- // extends +- var supertype =3D _enclosingClassElement.supertype; +- if (supertype?.element !=3D null) { +- var recordSupertypeVName =3D +- _vNameFromElement(supertype.element, schema.RECORD_KIND); +- addEdge( +- _enclosingClassVName, schema.EXTENDS_EDGE, recordSupertypeVNa= me); +- } +- +- // implements +- var interfaces =3D _enclosingClassElement.interfaces; +- for (var interface in interfaces) { +- if (interface.element !=3D null) { +- var recordInterfaceVName =3D +- _vNameFromElement(interface.element, schema.RECORD_KIND); +- addEdge( +- _enclosingClassVName, schema.EXTENDS_EDGE, recordInterfaceV= Name); +- } +- } +- +- // mixins +- var mixins =3D _enclosingClassElement.mixins; +- for (var mixin in mixins) { +- if (mixin.element !=3D null) { +- var recordMixinVName =3D +- _vNameFromElement(mixin.element, schema.RECORD_KIND); +- addEdge(_enclosingClassVName, schema.EXTENDS_EDGE, recordMixinV= Name); +- } +- } +- +- // TODO (jwren) type parameters +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.extendsClause); +- _safelyVisit(node.implementsClause); +- _safelyVisit(node.withClause); +- _safelyVisit(node.nativeClause); +- _safelyVisitList(node.members); +- _safelyVisit(node.typeParameters); +- }); +- } +- +- @override +- visitClassTypeAlias(ClassTypeAlias node) { +- return _withEnclosingElement(node.element, () { +- // record/ class node +- addNodeAndFacts(schema.RECORD_KIND, +- nodeVName: _enclosingClassVName, +- subKind: schema.CLASS_SUBKIND, +- completeFact: schema.DEFINITION); +- +- // anchor +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.name, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: _enclosingClassVName, +- enclosingTarget: _enclosingFileVName); +- +- // +- // superclass +- // The super type is not in an ExtendsClause (as is the case with +- // ClassDeclarations) and super.visitClassTypeAlias is not sufficie= nt. +- // +- _handleRefEdge( +- node.superclass.name.bestElement, +- const [schema.REF_EDGE], +- syntacticEntity: node.superclass, +- ); +- // TODO(jwren) refactor the following lines into a method that can = be used +- // by visitClassDeclaration() +- // extends +- var recordSupertypeVName =3D _vNameFromElement( +- node.superclass.name.bestElement, schema.RECORD_KIND); +- addEdge(_enclosingClassVName, schema.EXTENDS_EDGE, recordSupertypeV= Name); +- +- // implements +- var interfaces =3D _enclosingClassElement.interfaces; +- for (var interface in interfaces) { +- if (interface.element !=3D null) { +- var recordInterfaceVName =3D +- _vNameFromElement(interface.element, schema.RECORD_KIND); +- addEdge( +- _enclosingClassVName, schema.EXTENDS_EDGE, recordInterfaceV= Name); +- } +- } +- +- // mixins +- var mixins =3D _enclosingClassElement.mixins; +- for (var mixin in mixins) { +- if (mixin.element !=3D null) { +- var recordMixinVName =3D +- _vNameFromElement(mixin.element, schema.RECORD_KIND); +- addEdge(_enclosingClassVName, schema.EXTENDS_EDGE, recordMixinV= Name); +- } +- } +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.typeParameters); +- _safelyVisit(node.withClause); +- _safelyVisit(node.implementsClause); +- }); +- } +- +- @override +- visitCompilationUnit(CompilationUnit node) { +- _enclosingFilePath =3D _getPath(resourceProvider, node.element); +- return _withEnclosingElement(node.element, () { +- addFact(_enclosingFileVName, schema.NODE_KIND_FACT, +- _encode(schema.FILE_KIND)); +- addFact(_enclosingFileVName, schema.TEXT_FACT, _encode(_contents)); +- addFact(_enclosingFileVName, schema.TEXT_ENCODING_FACT, +- _encode(schema.DEFAULT_TEXT_ENCODING)); +- +- // handle LibraryDirective: +- +- // A "package" VName in Kythe, schema.PACKAGE_KIND, is a Dart "libr= ary". +- +- // Don't use visitLibraryDirective as this won't generate a package +- // VName for libraries that don't have a library directive. +- var libraryElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(node).library; +- if (libraryElement.definingCompilationUnit =3D=3D node.element) { +- LibraryDirective libraryDirective; +- for (var directive in node.directives) { +- if (directive is LibraryDirective) { +- libraryDirective =3D directive; +- break; +- } +- } +- +- var start =3D 0; +- var end =3D 0; +- if (libraryDirective !=3D null) { +- start =3D libraryDirective.name.offset; +- end =3D libraryDirective.name.end; +- } +- +- // package node +- var packageVName =3D addNodeAndFacts(schema.PACKAGE_KIND, +- element: libraryElement, completeFact: schema.DEFINITION); +- +- // anchor +- addAnchorEdgesContainingEdge( +- start: start, +- end: end, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: packageVName, +- enclosingTarget: _enclosingFileVName); +- } +- +- super.visitCompilationUnit(node); +- }); +- } +- +- @override +- visitConstructorDeclaration(ConstructorDeclaration node) { +- return _withEnclosingElement(node.element, () { +- // function/ constructor node +- var constructorVName =3D addNodeAndFacts(schema.FUNCTION_KIND, +- element: node.element, +- subKind: schema.CONSTRUCTOR_SUBKIND, +- completeFact: schema.DEFINITION); +- +- // anchor +- var start =3D node.returnType.offset; +- var end =3D node.returnType.end; +- if (node.name !=3D null) { +- end =3D node.name.end; +- } +- addAnchorEdgesContainingEdge( +- start: start, +- end: end, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: constructorVName, +- enclosingTarget: _enclosingClassVName); +- +- // function type +- addFunctionType(node.element, node.parameters, constructorVName, +- returnNode: node.returnType); +- +- // TODO(jwren) handle implicit constructor case +- // TODO(jwren) handle redirected constructor case +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.parameters); +- _safelyVisitList(node.initializers); +- _safelyVisit(node.body); +- }); +- } +- +- @override +- visitDeclaredIdentifier(DeclaredIdentifier node) { +- _handleVariableDeclaration(node.element, node.identifier, +- subKind: schema.LOCAL_SUBKIND, +- type: resolutionMap.elementDeclaredByDeclaredIdentifier(node).typ= e); +- +- // no children +- } +- +- @override +- visitEnumConstantDeclaration(EnumConstantDeclaration node) { +- // constant node +- var constDeclVName =3D +- addNodeAndFacts(schema.CONSTANT_KIND, element: node.element); +- +- // anchor- defines/binding, defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.name, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- schema.DEFINES_EDGE, +- ], +- target: constDeclVName, +- enclosingTarget: _enclosingClassVName); +- +- // no children +- } +- +- @override +- visitEnumDeclaration(EnumDeclaration node) { +- return _withEnclosingElement(node.element, () { +- // record/ enum node +- addNodeAndFacts(schema.RECORD_KIND, +- nodeVName: _enclosingClassVName, +- subKind: schema.ENUM_CLASS_SUBKIND, +- completeFact: schema.DEFINITION); +- +- // anchor- defines/binding +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.name, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: _enclosingClassVName, +- enclosingTarget: _enclosingFileVName); +- +- // anchor- defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node, +- edges: [ +- schema.DEFINES_EDGE, +- ], +- target: _enclosingClassVName); +- +- // visit children +- _safelyVisitList(node.constants); +- }); +- } +- +- @override +- visitFieldFormalParameter(FieldFormalParameter node) { +- // identifier +- // Specified as Element, not var, so that the type can be changed in = the +- // if-block. +- Element element =3D node.element; +- if (element is FieldFormalParameterElement) { +- element =3D (element as FieldFormalParameterElement).field; +- } +- _handleRefEdge( +- element, +- const [schema.REF_EDGE], +- syntacticEntity: node.identifier, +- ); +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.type); +- _safelyVisit(node.typeParameters); +- _safelyVisit(node.parameters); +- } +- +- @override +- visitFunctionDeclaration(FunctionDeclaration node) { +- return _withEnclosingElement(node.element, () { +- // function node +- var functionVName =3D addNodeAndFacts(schema.FUNCTION_KIND, +- element: node.element, completeFact: schema.DEFINITION); +- +- // anchor- defines/binding +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.name, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: functionVName, +- enclosingTarget: _enclosingFileVName); +- +- // anchor- defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node, +- edges: [ +- schema.DEFINES_EDGE, +- ], +- target: functionVName); +- +- // function type +- addFunctionType( +- node.element, node.functionExpression.parameters, functionVName, +- returnNode: node.returnType); +- +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.returnType); +- _safelyVisit(node.functionExpression); +- }); +- } +- +- @override +- visitFunctionExpression(FunctionExpression node) { +- return _withEnclosingElement( +- node.element, () =3D> super.visitFunctionExpression(node)); +- } +- +- @override +- visitFunctionTypeAlias(FunctionTypeAlias node) { +- // +- // return type +- // +- var returnType =3D node.returnType; +- if (returnType is TypeName) { +- _handleRefEdge( +- returnType.name?.bestElement, +- const [schema.REF_EDGE], +- syntacticEntity: returnType.name, +- ); +- } else if (returnType is GenericFunctionType) { +- // TODO(jwren): add support for generic function types. +- throw new UnimplementedError(); +- } else if (returnType !=3D null) { +- throw new StateError( +- 'Unexpected TypeAnnotation subtype: ${returnType.runtimeType}'); +- } +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.typeParameters); +- _safelyVisit(node.parameters); +- } +- +- @override +- visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { +- // TODO(jwren) Missing graph coverage on FunctionTypedFormalParameters +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.identifier); +- _safelyVisit(node.typeParameters); +- _safelyVisit(node.parameters); +- } +- +- @override +- visitImportDirective(ImportDirective node) { +- // uri +- _handleUriReference(node.uri, node.uriElement); +- +- // prefix +- var prefixIdentifier =3D node.prefix; +- +- if (prefixIdentifier !=3D null) { +- // variable +- _handleVariableDeclaration( +- prefixIdentifier.staticElement, prefixIdentifier); +- } +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisitList(node.combinators); +- _safelyVisitList(node.configurations); +- _safelyVisit(node.uri); +- } +- +- @override +- visitIndexExpression(IndexExpression node) { +- // +- // index method ref/call +- // +- var element =3D node.bestElement; +- var start =3D node.leftBracket.offset; +- var end =3D node.rightBracket.end; +- +- // anchor- ref/call +- _handleRefCallEdge(element, +- start: start, end: end, enclosingTarget: _enclosingVName); +- +- // visit children +- _safelyVisit(node.target); +- _safelyVisit(node.index); +- } +- +- @override +- visitInstanceCreationExpression(InstanceCreationExpression node) { +- // +- // constructorName +- // +- var constructorName =3D node.constructorName; +- var constructorElement =3D +- resolutionMap.staticElementForConstructorReference(constructorNam= e); +- if (constructorElement !=3D null) { +- // anchor- ref/call +- _handleRefCallEdge(constructorElement, +- syntacticEntity: constructorName, enclosingTarget: _enclosingVN= ame); +- +- // Now write out a ref edge from the same anchor (constructorName) = to the +- // enclosing class of the called constructor, this will make the +- // invocation of a constructor discoverable when someone inquires a= bout +- // references to the class. +- // +- // We can't call _handleRefEdge as the anchor node has already been +- // written out. +- var enclosingEltVName =3D _vNameFromElement( +- constructorElement.enclosingElement, schema.RECORD_KIND); +- var anchorVName =3D +- _vNameAnchor(constructorName.offset, constructorName.end); +- addEdge(anchorVName, schema.REF_EDGE, enclosingEltVName); +- +- // TODO(jwren): investigate +- // assert (element.enclosingElement !=3D null); +- } +- // visit children +- _safelyVisitList(constructorName.type.typeArguments?.arguments); +- _safelyVisit(node.argumentList); +- } +- +- @override +- visitMethodDeclaration(MethodDeclaration node) { +- return _withEnclosingElement(node.element, () { +- // function node +- var methodVName =3D addNodeAndFacts(schema.FUNCTION_KIND, +- element: node.element, completeFact: schema.DEFINITION); +- +- // anchor- defines/binding +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.name, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: methodVName, +- enclosingTarget: _enclosingClassVName); +- +- // anchor- defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node, +- edges: [ +- schema.DEFINES_EDGE, +- ], +- target: methodVName); +- +- // function type +- addFunctionType(node.element, node.parameters, methodVName, +- returnNode: node.returnType); +- +- // override edges +- List overriddenList =3D +- _inheritanceManager.lookupOverrides(_enclosingClassElement, +- resolutionMap.elementDeclaredByMethodDeclaration(node).name= ); +- for (ExecutableElement overridden in overriddenList) { +- if (overridden is MultiplyInheritedExecutableElement) { +- for (ExecutableElement elt in overridden.inheritedElements) { +- addEdge(methodVName, schema.OVERRIDES_EDGE, +- _vNameFromElement(elt, schema.FUNCTION_KIND)); +- } +- } else { +- addEdge(methodVName, schema.OVERRIDES_EDGE, +- _vNameFromElement(overridden, schema.FUNCTION_KIND)); +- } +- } +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.returnType); +- _safelyVisit(node.typeParameters); +- _safelyVisit(node.parameters); +- _safelyVisit(node.body); +- }); +- } +- +- @override +- visitMethodInvocation(MethodInvocation node) { +- var element =3D node.methodName?.bestElement; +- +- // anchor- ref/call +- _handleRefCallEdge(element, syntacticEntity: node.methodName); +- +- // visit children +- _safelyVisit(node.target); +- _safelyVisit(node.typeArguments); +- _safelyVisit(node.argumentList); +- } +- +- @override +- visitSimpleFormalParameter(SimpleFormalParameter node) { +- // parameter node +- var paramVName =3D addNodeAndFacts(schema.VARIABLE_KIND, +- element: node.element, +- subKind: schema.LOCAL_PARAMETER_SUBKIND, +- completeFact: schema.DEFINITION); +- +- // node.identifier can be null in cases with the new generic function= type +- // syntax +- // TODO(jwren) add test cases for this situation +- if (node.identifier !=3D null) { +- // The anchor and anchor edges generation are broken into two cases= , the +- // first case is "method(parameter_name) ...", where the the parame= ter +- // character range only includes a parameter name. The second case= is for +- // parameter declarations which are prefixed with a type, 'var', or +- // 'dynamic', as in "method(var parameter_name) ...". +- // +- // With the first case a single anchor range is created, for the se= cond +- // case an anchor is created on parameter_name, as well as the range +- // including any prefixes. +- if (node.offset =3D=3D node.identifier.offset && +- node.length =3D=3D node.identifier.length) { +- // anchor- defines/binding, defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.identifier, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- schema.DEFINES_EDGE, +- ], +- target: paramVName, +- enclosingTarget: _enclosingVName); +- } else { +- // anchor- defines/binding +- addAnchorEdgesContainingEdge( +- syntacticEntity: node.identifier, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: paramVName, +- enclosingTarget: _enclosingVName); +- +- // anchor- defines +- addAnchorEdgesContainingEdge( +- syntacticEntity: node, +- edges: [ +- schema.DEFINES_EDGE, +- ], +- target: paramVName); +- } +- } +- +- // type +- addEdge( +- paramVName, +- schema.TYPED_EDGE, +- _vNameFromType( +- resolutionMap.elementDeclaredByFormalParameter(node).type)); +- +- // visit children +- _safelyVisit(node.documentationComment); +- _safelyVisitList(node.metadata); +- _safelyVisit(node.type); +- } +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- // Most simple identifiers are "ref" edges. In cases some cases, the= re may +- // be other ref/* edges. +- +- if (node.getAncestor((node) =3D> node is CommentReference) !=3D null)= { +- // The identifier is in a comment, add just the "ref" edge. +- _handleRefEdge( +- node.bestElement, +- const [schema.REF_EDGE], +- syntacticEntity: node, +- ); +- } else if (node.inDeclarationContext()) { +- // The node is in a declaration context, and should have +- // "ref/defines/binding" edge as well as the default "ref" edge. +- _handleRefEdge( +- node.bestElement, +- const [schema.DEFINES_BINDING_EDGE, schema.REF_EDGE], +- syntacticEntity: node, +- ); +- } else { +- _handleRefCallEdge(node.bestElement, syntacticEntity: node); +- } +- +- // no children to visit +- } +- +- @override +- visitSuperExpression(SuperExpression node) { +- _handleThisOrSuper(node); +- } +- +- @override +- visitThisExpression(ThisExpression node) { +- _handleThisOrSuper(node); +- } +- +- @override +- visitUriBasedDirective(UriBasedDirective node) { +- _handleUriReference(node.uri, node.uriElement); +- +- // visit children +- super.visitUriBasedDirective(node); +- } +- +- @override +- visitVariableDeclaration(VariableDeclaration node) { +- var isLocal =3D _enclosingVName !=3D _enclosingClassVName && +- _enclosingVName !=3D _enclosingFileVName; +- +- // variable +- _handleVariableDeclaration(node.element, node.name, +- subKind: isLocal ? schema.LOCAL_SUBKIND : schema.FIELD_SUBKIND, +- type: resolutionMap.elementDeclaredByVariableDeclaration(node).ty= pe); +- +- // visit children +- _safelyVisit(node.initializer); +- } +- +- Element _findNonSyntheticElement(Element element) { +- if (element =3D=3D null || !element.isSynthetic) { +- return element; +- } +- if (element is PropertyAccessorElement) { +- if (!element.variable.isSynthetic) { +- return element.variable; +- } else if (element.correspondingGetter !=3D null && +- !element.correspondingGetter.isSynthetic) { +- return element.correspondingGetter; +- } else if (element.correspondingSetter !=3D null && +- !element.correspondingSetter.isSynthetic) { +- return element.correspondingSetter; +- } +- } +- return null; +- } +- +- String _getNodeKind(Element e) { +- if (e is FieldElement && e.isEnumConstant) { +- // FieldElement is a kind of VariableElement, so this test case mus= t be +- // before the e is VariableElement check. +- return schema.CONSTANT_KIND; +- } else if (e is VariableElement || e is PrefixElement) { +- return schema.VARIABLE_KIND; +- } else if (e is ExecutableElement) { +- return schema.FUNCTION_KIND; +- } else if (e is ClassElement || e is TypeParameterElement) { +- // TODO(jwren): this should be using absvar instead, see +- // https://kythe.io/docs/schema/#absvar +- return schema.RECORD_KIND; +- } +- return null; +- } +- +- _handleRefCallEdge( +- Element element, { +- SyntacticEntity syntacticEntity: null, +- start: _notFound, +- end: _notFound, +- KytheVName enclosingTarget: null, +- }) { +- if (element is ExecutableElement && +- _enclosingVName !=3D _enclosingFileVName) { +- _handleRefEdge( +- element, +- const [schema.REF_CALL_EDGE, schema.REF_EDGE], +- syntacticEntity: syntacticEntity, +- start: start, +- end: end, +- enclosingTarget: enclosingTarget, +- enclosingAnchor: _enclosingVName, +- ); +- } else { +- _handleRefEdge( +- element, +- const [schema.REF_EDGE], +- syntacticEntity: syntacticEntity, +- start: start, +- end: end, +- enclosingTarget: enclosingTarget, +- ); +- } +- } +- +- /// This is a convenience method for adding ref edges. If the [start] a= nd +- /// [end] offsets are provided, they are used, otherwise the offsets are +- /// computed by using the [syntacticEntity]. The list of edges is assum= ed to +- /// be non-empty, and are added from the anchor to the target generated= using +- /// the passed [Element]. The created [KytheVName] is returned, if not = `null` +- /// is returned. +- KytheVName _handleRefEdge( +- Element element, +- List refEdgeTypes, { +- SyntacticEntity syntacticEntity: null, +- start: _notFound, +- end: _notFound, +- KytheVName enclosingTarget: null, +- KytheVName enclosingAnchor: null, +- }) { +- assert(refEdgeTypes.isNotEmpty); +- element =3D _findNonSyntheticElement(element); +- if (element =3D=3D null) { +- return null; +- } +- +- // vname +- var nodeKind =3D _getNodeKind(element); +- if (nodeKind =3D=3D null || nodeKind.isEmpty) { +- return null; +- } +- var vName =3D _vNameFromElement(element, nodeKind); +- assert(vName !=3D null); +- +- // anchor +- addAnchorEdgesContainingEdge( +- start: start, +- end: end, +- syntacticEntity: syntacticEntity, +- edges: refEdgeTypes, +- target: vName, +- enclosingTarget: enclosingTarget, +- enclosingAnchor: enclosingAnchor, +- ); +- +- return vName; +- } +- +- void _handleThisOrSuper(Expression thisOrSuperNode) { +- DartType type =3D thisOrSuperNode.staticType; +- if (type !=3D null && type.element !=3D null) { +- // Expected SuperExpression.staticType to return the type of the +- // supertype, but it returns the type of the enclosing class (same = as +- // ThisExpression), do some additional work to correct assumption: +- if (thisOrSuperNode is SuperExpression && type.element is ClassElem= ent) { +- DartType supertype =3D (type.element as ClassElement).supertype; +- if (supertype !=3D null) { +- type =3D supertype; +- } +- } +- // vname +- var vName =3D _vNameFromElement(type.element, schema.RECORD_KIND); +- +- // anchor +- var anchorVName =3D addAnchorEdgesContainingEdge( +- syntacticEntity: thisOrSuperNode, +- edges: [schema.REF_EDGE], +- target: vName); +- +- // childof from the anchor +- addEdge(anchorVName, schema.CHILD_OF_EDGE, _enclosingVName); +- } +- +- // no children to visit +- } +- +- void _handleVariableDeclaration( +- Element element, SyntacticEntity syntacticEntity, +- {String subKind, DartType type}) { +- // variable +- var variableVName =3D addNodeAndFacts(schema.VARIABLE_KIND, +- element: element, subKind: subKind, completeFact: schema.DEFINITI= ON); +- +- // anchor +- addAnchorEdgesContainingEdge( +- syntacticEntity: syntacticEntity, +- edges: [ +- schema.DEFINES_BINDING_EDGE, +- ], +- target: variableVName, +- enclosingTarget: _enclosingVName); +- +- // type +- if (type !=3D null) { +- addEdge(variableVName, schema.TYPED_EDGE, _vNameFromType(type)); +- } +- } +- +- /// Add a "ref/imports" edge from the passed [uriNode] location to the +- /// [referencedElement] [Element]. If the passed element is null, the = edge is +- /// not written out. +- void _handleUriReference(StringLiteral uriNode, Element referencedEleme= nt) { +- if (referencedElement !=3D null) { +- var start =3D uriNode.offset; +- var end =3D uriNode.end; +- +- // The following is the expected and common case. +- // The contents between the quotes is used as the location to work = well +- // with CodeSearch. +- if (uriNode is SimpleStringLiteral) { +- start =3D uriNode.contentsOffset; +- end =3D uriNode.contentsEnd; +- } +- +- // package node +- var packageVName =3D +- _vNameFromElement(referencedElement, schema.PACKAGE_KIND); +- +- // anchor +- addAnchorEdgesContainingEdge( +- start: start, +- end: end, +- edges: [schema.REF_IMPORTS_EDGE], +- target: packageVName, +- enclosingTarget: _enclosingFileVName); +- } +- } +- +- _handleVariableDeclarationListAnnotations( +- VariableDeclarationList variableDeclarationList, KytheVName refVNam= e) { +- assert(refVName !=3D null); +- for (var varDecl in variableDeclarationList.variables) { +- if (varDecl.element !=3D null) { +- var parentVName =3D +- _vNameFromElement(varDecl.element, schema.VARIABLE_KIND); +- addEdge(parentVName, schema.ANNOTATED_BY_EDGE, refVName); +- } else { +- // The element out of the VarDeclarationList is null +- assert(false); +- } +- } +- } +- +- /// If the given [node] is not `null`, accept this visitor. +- void _safelyVisit(AstNode node) { +- if (node !=3D null) { +- node.accept(this); +- } +- } +- +- /// If the given [nodeList] is not `null`, accept this visitor. +- void _safelyVisitList(NodeList nodeList) { +- if (nodeList !=3D null) { +- nodeList.accept(this); +- } +- } +- +- _withEnclosingElement(Element element, f()) { +- Element outerEnclosingElement =3D _enclosingElement; +- Element outerEnclosingClassElement =3D _enclosingClassElement; +- var outerEnclosingVName =3D _enclosingVName; +- var outerEnclosingClassVName =3D _enclosingClassVName; +- try { +- _enclosingElement =3D element; +- if (element is CompilationUnitElement) { +- _enclosingFileVName =3D _enclosingVName =3D _vNameFile(); +- } else if (element is ClassElement) { +- _enclosingClassElement =3D element; +- _enclosingClassVName =3D _enclosingVName =3D +- _vNameFromElement(_enclosingClassElement, schema.RECORD_KIND); +- } else if (element is MethodElement || +- element is FunctionElement || +- element is ConstructorElement) { +- _enclosingVName =3D +- _vNameFromElement(_enclosingElement, schema.FUNCTION_KIND); +- } +- return f(); +- } finally { +- _enclosingElement =3D outerEnclosingElement; +- _enclosingClassElement =3D outerEnclosingClassElement; +- _enclosingClassVName =3D outerEnclosingClassVName; +- _enclosingVName =3D outerEnclosingVName; +- } +- } +-} +- +-/// This class is meant to be a mixin to concrete visitor methods to walk= the +-/// [Element] or [AstNode]s produced by the Dart Analyzer to output Kythe +-/// [KytheEntry] protos. +-abstract class OutputUtils { +- /// A set of [String]s which have already had a name [KytheVName] creat= ed. +- final Set nameNodes =3D new Set(); +- +- String get corpus; +- +- KytheVName get dynamicBuiltin =3D> _vName(schema.DYNAMIC_KIND, '', '', = ''); +- +- String get enclosingFilePath; +- +- List get entries; +- +- KytheVName get fnBuiltin =3D> _vName(schema.FN_BUILTIN, '', '', ''); +- +- ResourceProvider get resourceProvider; +- +- KytheVName get voidBuiltin =3D> _vName(schema.VOID_BUILTIN, '', '', ''); +- +- /// This is a convenience method for adding anchors. If the [start] and= [end] +- /// offsets are provided, they are used, otherwise the offsets are comp= uted by +- /// using the [syntacticEntity]. If a non-empty list of edges is provid= ed, as +- /// well as a target, then this method also adds the edges from the anc= hor to +- /// target. The anchor [KytheVName] is returned. +- /// +- /// If a [target] and [enclosingTarget] are provided, a childof edge is +- /// written out from the target to the enclosing target. +- /// +- /// If an [enclosingAnchor] is provided a childof edge is written out f= rom the +- /// anchor to the enclosing anchor. In cases where ref/call is an edge,= this +- /// is required to generate the callgraph. +- /// +- /// Finally, for all anchors, a childof edge with a target of the enclo= sing +- /// file is written out. +- KytheVName addAnchorEdgesContainingEdge({ +- SyntacticEntity syntacticEntity: null, +- int start: _notFound, +- int end: _notFound, +- List edges: const [], +- KytheVName target: null, +- KytheVName enclosingTarget: null, +- KytheVName enclosingAnchor: null, +- }) { +- if (start =3D=3D _notFound && end =3D=3D _notFound) { +- if (syntacticEntity !=3D null) { +- start =3D syntacticEntity.offset; +- end =3D syntacticEntity.end; +- } else { +- throw new Exception('Offset positions were not provided when call= ing ' +- 'addAnchorEdgesContainingEdge'); +- } +- } +- // TODO(jwren) investigate +-// assert(start < end); +- var anchorVName =3D _vNameAnchor(start, end); +- addFact(anchorVName, schema.NODE_KIND_FACT, _encode(schema.ANCHOR_KIN= D)); +- addFact(anchorVName, schema.ANCHOR_START_FACT, _encodeInt(start)); +- addFact(anchorVName, schema.ANCHOR_END_FACT, _encodeInt(end)); +- if (target !=3D null) { +- for (String edge in edges) { +- addEdge(anchorVName, edge, target); +- } +- if (enclosingTarget !=3D null) { +- addEdge(target, schema.CHILD_OF_EDGE, enclosingTarget); +- } +- } +- // If provided, write out the childof edge to the enclosing anchor +- if (enclosingAnchor !=3D null) { +- addEdge(anchorVName, schema.CHILD_OF_EDGE, enclosingAnchor); +- } +- +- // Assert that if ref/call is one of the edges, that and enclosing an= chor +- // was provided for the callgraph. +- // Documentation at http://kythe.io/docs/schema/callgraph.html +- if (edges.contains(schema.REF_CALL_EDGE)) { +- assert(enclosingAnchor !=3D null); +- } +- +- // Finally add the childof edge to the enclosing file VName. +- addEdge(anchorVName, schema.CHILD_OF_EDGE, _vNameFile()); +- return anchorVName; +- } +- +- /// TODO(jwren): for cases where the target is a name, we need the same= kind +- /// of logic as [addNameFact] to prevent the edge from being written ou= t. +- /// This is a convenience method for visitors to add an edge Entry. +- KytheEntry addEdge(KytheVName source, String edgeKind, KytheVName targe= t, +- {int ordinalIntValue: _notFound}) { +- if (ordinalIntValue =3D=3D _notFound) { +- return addEntry(source, edgeKind, target, "/", new List()); +- } else { +- return addEntry(source, edgeKind, target, schema.ORDINAL, +- _encodeInt(ordinalIntValue)); +- } +- } +- +- KytheEntry addEntry(KytheVName source, String edgeKind, KytheVName targ= et, +- String factName, List factValue) { +- assert(source !=3D null); +- assert(factName !=3D null); +- assert(factValue !=3D null); +- // factValue may be an empty array, the fact may be that a file text = or +- // document text is empty +- if (edgeKind =3D=3D null || edgeKind.isEmpty) { +- edgeKind =3D null; +- target =3D null; +- } +- var entry =3D new KytheEntry(source, factName, +- kind: edgeKind, target: target, value: factValue); +- entries.add(entry); +- return entry; +- } +- +- /// This is a convenience method for visitors to add a fact [KytheEntry= ]. +- KytheEntry addFact(KytheVName source, String factName, List factVa= lue) { +- return addEntry(source, null, null, factName, factValue); +- } +- +- /// This is a convenience method for adding function types. +- KytheVName addFunctionType( +- Element functionElement, +- FormalParameterList paramNodes, +- KytheVName functionVName, { +- AstNode returnNode: null, +- }) { +- var i =3D 0; +- var funcTypeVName =3D +- addNodeAndFacts(schema.TAPP_KIND, element: functionElement); +- addEdge(funcTypeVName, schema.PARAM_EDGE, fnBuiltin, ordinalIntValue:= i++); +- +- var returnTypeVName; +- if (returnNode is TypeName) { +- // MethodDeclaration and FunctionDeclaration both return a TypeName= from +- // returnType +- if (resolutionMap.typeForTypeName(returnNode).isVoid) { +- returnTypeVName =3D voidBuiltin; +- } else { +- returnTypeVName =3D +- _vNameFromElement(returnNode.name.bestElement, schema.TAPP_KI= ND); +- } +- } else if (returnNode is Identifier) { +- // ConstructorDeclaration returns an Identifier from returnType +- if (resolutionMap.bestTypeForExpression(returnNode).isVoid) { +- returnTypeVName =3D voidBuiltin; +- } else { +- returnTypeVName =3D +- _vNameFromElement(returnNode.bestElement, schema.TAPP_KIND); +- } +- } +- // else: return type is null, void, unresolved. +- +- if (returnTypeVName !=3D null) { +- addEdge(funcTypeVName, schema.PARAM_EDGE, returnTypeVName, +- ordinalIntValue: i++); +- } +- +- if (paramNodes !=3D null) { +- for (FormalParameter paramNode in paramNodes.parameters) { +- var paramTypeVName =3D dynamicBuiltin; +- if (!resolutionMap +- .elementDeclaredByFormalParameter(paramNode) +- .type +- .isDynamic) { +- paramTypeVName =3D _vNameFromElement( +- resolutionMap +- .elementDeclaredByFormalParameter(paramNode) +- .type +- .element, +- schema.TAPP_KIND); +- } +- addEdge(funcTypeVName, schema.PARAM_EDGE, paramTypeVName, +- ordinalIntValue: i++); +- } +- } +- addEdge(functionVName, schema.TYPED_EDGE, funcTypeVName); +- return funcTypeVName; +- } +- +- /// This is a convenience method for adding nodes with facts. +- /// If an [KytheVName] is passed, it is used, otherwise an element is r= equired +- /// which is used to create a [KytheVName]. Either [nodeVName] must be= non-null or +- /// [element] must be non-null. Other optional parameters if passed are= then +- /// used to set the associated facts on the [KytheVName]. This method d= oes not +- /// currently guarantee that the inputs to these fact kinds are valid f= or the +- /// associated nodeKind- if a non-null, then it will set. +- KytheVName addNodeAndFacts(String nodeKind, +- {Element element: null, +- KytheVName nodeVName: null, +- String subKind: null, +- String completeFact: null}) { +- if (nodeVName =3D=3D null) { +- nodeVName =3D _vNameFromElement(element, nodeKind); +- } +- addFact(nodeVName, schema.NODE_KIND_FACT, _encode(nodeKind)); +- if (subKind !=3D null) { +- addFact(nodeVName, schema.SUBKIND_FACT, _encode(subKind)); +- } +- if (completeFact !=3D null) { +- addFact(nodeVName, schema.COMPLETE_FACT, _encode(completeFact)); +- } +- return nodeVName; +- } +- +- List _encode(String str) { +- return UTF8.encode(str); +- } +- +- List _encodeInt(int i) { +- return UTF8.encode(i.toString()); +- } +- +- /// Given all parameters for a [KytheVName] this method creates and ret= urns a +- /// [KytheVName]. +- KytheVName _vName(String signature, String corpus, String root, String = path, +- [String language =3D schema.DART_LANG]) { +- return new KytheVName(signature, corpus, root, path, language); +- } +- +- /// Returns an anchor [KytheVName] corresponding to the given start and= end +- /// offsets. +- KytheVName _vNameAnchor(int start, int end) { +- return _vName( +- _getAnchorSignature(start, end), corpus, '', enclosingFilePath); +- } +- +- /// Return the [KytheVName] for this file. +- KytheVName _vNameFile() { +- // file vnames, the signature and language are not set +- return _vName('', corpus, '', enclosingFilePath, ''); +- } +- +- /// Given some [Element] and Kythe node kind, this method generates and +- /// returns the [KytheVName]. +- KytheVName _vNameFromElement(Element e, String nodeKind) { +- assert(nodeKind !=3D schema.FILE_KIND); +- // general case +- return _vName(_getSignature(resourceProvider, e, nodeKind, corpus), c= orpus, +- '', _getPath(resourceProvider, e)); +- } +- +- /// Returns a [KytheVName] corresponding to the given [DartType]. +- KytheVName _vNameFromType(DartType type) { +- if (type =3D=3D null || type.isDynamic) { +- return dynamicBuiltin; +- } else if (type.isVoid) { +- return voidBuiltin; +- } else if (type.element is ClassElement) { +- return _vNameFromElement(type.element, schema.RECORD_KIND); +- } else { +- return dynamicBuiltin; +- } +- } +-} +- +-/// This visitor class should be used by [_getSignature]. +-/// +-/// This visitor is an [GeneralizingElementVisitor] which builds up a [St= ring] +-/// signature for a given [Element], uniqueness is guaranteed within the +-/// enclosing file. +-class SignatureElementVisitor extends GeneralizingElementVisitor { +- static SignatureElementVisitor instance =3D new SignatureElementVisitor= (); +- +- @override +- StringBuffer visitCompilationUnitElement(CompilationUnitElement e) { +- return new StringBuffer(); +- } +- +- @override +- StringBuffer visitElement(Element e) { +- assert(e is! MultiplyInheritedExecutableElement); +- var enclosingElt =3D e.enclosingElement; +- var buffer =3D enclosingElt.accept(this); +- if (buffer.isNotEmpty) { +- buffer.write('#'); +- } +- if (e is MethodElement && e.name =3D=3D '-' && e.parameters.length = =3D=3D 1) { +- buffer.write('unary-'); +- } else if (e is ConstructorElement) { +- buffer.write(_computeConstructorElementName(e)); +- } else { +- buffer.write(e.name); +- } +- if (enclosingElt is ExecutableElement) { +- buffer..write('@')..write(e.nameOffset - enclosingElt.nameOffset); +- } +- return buffer; +- } +- +- @override +- StringBuffer visitLibraryElement(LibraryElement e) { +- return new StringBuffer('library:${e.displayName}'); +- } +- +- @override +- StringBuffer visitTypeParameterElement(TypeParameterElement e) { +- // It is legal to have a named constructor with the same name as a ty= pe +- // parameter. So we distinguish them by using '.' between the class = (or +- // typedef) name and the type parameter name. +- return e.enclosingElement.accept(this)..write('.')..write(e.name); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/kythe/schema.dart b/pkg/= analysis_server/lib/src/services/kythe/schema.dart +deleted file mode 100644 +index c354abb498b..00000000000 +--- a/pkg/analysis_server/lib/src/services/kythe/schema.dart ++++ /dev/null +@@ -1,82 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/// This file gathers constant strings from the Kythe Schema: +-/// kythe.io/docs/schema/ +- +-/// Dart specific facts, labels, and kinds +-const DART_LANG =3D 'dart'; +-const DYNAMIC_KIND =3D 'dynamic#builtin'; +-const FN_BUILTIN =3D 'fn#builtin'; +-const VOID_BUILTIN =3D 'void#builtin'; +- +-/// Kythe node fact labels +-const NODE_KIND_FACT =3D '/kythe/node/kind'; +-const SUBKIND_FACT =3D '/kythe/subkind'; +- +-const ANCHOR_START_FACT =3D '/kythe/loc/start'; +-const ANCHOR_END_FACT =3D '/kythe/loc/end'; +- +-const SNIPPET_START_FACT =3D '/kythe/snippet/start'; +-const SNIPPET_END_FACT =3D '/kythe/snippet/end'; +- +-const TEXT_FACT =3D '/kythe/text'; +-const TEXT_ENCODING_FACT =3D '/kythe/text/encoding'; +- +-const COMPLETE_FACT =3D '/kythe/complete'; +- +-const TEXT_FORMAT =3D '/kythe/format'; +- +-/// DEFAULT_TEXT_ENCODING is the assumed value of the TEXT_ENCODING_FACT = if it +-/// is empty or missing from a node with a TEXT_FACT. +-const DEFAULT_TEXT_ENCODING =3D 'UTF-8'; +- +-/// Kythe node kinds +-const ANCHOR_KIND =3D 'anchor'; +-const FILE_KIND =3D 'file'; +- +-const CONSTANT_KIND =3D 'constant'; +-const DOC_KIND =3D 'doc'; +-const ENUM_KIND =3D 'enum'; +-const FUNCTION_KIND =3D 'function'; +-const PACKAGE_KIND =3D 'package'; +-const RECORD_KIND =3D 'record'; +-const TAPP_KIND =3D 'tapp'; +-const VARIABLE_KIND =3D 'variable'; +- +-/// Kythe node subkinds +-const CLASS_SUBKIND =3D 'class'; +-const CONSTRUCTOR_SUBKIND =3D 'constructor'; +-const ENUM_CLASS_SUBKIND =3D 'enumClass'; +-const IMPLICIT_SUBKIND =3D 'implicit'; +-const FIELD_SUBKIND =3D 'field'; +-const LOCAL_SUBKIND =3D 'local'; +-const LOCAL_PARAMETER_SUBKIND =3D 'local/parameter'; +- +-/// Kythe complete states +-const INCOMPLETE =3D 'incomplete'; +-const DEFINITION =3D 'definition'; +- +-/// Kythe ordinal +-const ORDINAL =3D '/kythe/ordinal'; +- +-/// EdgePrefix is the standard Kythe prefix for all edge kinds. +-const EDGE_PREFIX =3D '/kythe/edge/'; +- +-/// Kythe edge kinds +-const ANNOTATED_BY_EDGE =3D EDGE_PREFIX + "annotatedby"; +-const CHILD_OF_EDGE =3D EDGE_PREFIX + "childof"; +-const EXTENDS_EDGE =3D EDGE_PREFIX + "extends"; +-const INSTANTIATES_EDGE =3D EDGE_PREFIX + "instantiates"; +-const OVERRIDES_EDGE =3D EDGE_PREFIX + "overrides"; +-const PARAM_EDGE =3D EDGE_PREFIX + "param"; +-const TYPED_EDGE =3D EDGE_PREFIX + "typed"; +- +-/// Kythe edge kinds associated with anchors +-const DEFINES_EDGE =3D EDGE_PREFIX + "defines"; +-const DEFINES_BINDING_EDGE =3D EDGE_PREFIX + "defines/binding"; +-const DOCUMENTS_EDGE =3D EDGE_PREFIX + "documents"; +-const REF_EDGE =3D EDGE_PREFIX + "ref"; +-const REF_CALL_EDGE =3D EDGE_PREFIX + "ref/call"; +-const REF_IMPORTS_EDGE =3D EDGE_PREFIX + "ref/imports"; +diff --git a/pkg/analysis_server/lib/src/services/refactoring/convert_gett= er_to_method.dart b/pkg/analysis_server/lib/src/services/refactoring/conver= t_getter_to_method.dart +deleted file mode 100644 +index 0051772b52a..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/convert_getter_to_m= ethod.dart ++++ /dev/null +@@ -1,127 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * [ConvertMethodToGetterRefactoring] implementation. +- */ +-class ConvertGetterToMethodRefactoringImpl extends RefactoringImpl +- implements ConvertGetterToMethodRefactoring { +- final SearchEngine searchEngine; +- final AstProvider astProvider; +- final PropertyAccessorElement element; +- +- SourceChange change; +- +- ConvertGetterToMethodRefactoringImpl( +- this.searchEngine, this.astProvider, this.element); +- +- @override +- String get refactoringName =3D> 'Convert Getter To Method'; +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- Future checkInitialConditions() { +- RefactoringStatus result =3D _checkInitialConditions(); +- return new Future.value(result); +- } +- +- @override +- Future createChange() async { +- change =3D new SourceChange(refactoringName); +- // function +- if (element.enclosingElement is CompilationUnitElement) { +- await _updateElementDeclaration(element); +- await _updateElementReferences(element); +- } +- // method +- if (element.enclosingElement is ClassElement) { +- FieldElement field =3D element.variable; +- Set elements =3D +- await getHierarchyMembers(searchEngine, field); +- await Future.forEach(elements, (ClassMemberElement member) async { +- if (member is FieldElement) { +- PropertyAccessorElement getter =3D member.getter; +- if (!getter.isSynthetic) { +- await _updateElementDeclaration(getter); +- return _updateElementReferences(getter); +- } +- } +- }); +- } +- // done +- return change; +- } +- +- @override +- bool requiresPreview() =3D> false; +- +- RefactoringStatus _checkInitialConditions() { +- if (!element.isGetter || element.isSynthetic) { +- return new RefactoringStatus.fatal( +- 'Only explicit getters can be converted to methods.'); +- } +- return new RefactoringStatus(); +- } +- +- Future _updateElementDeclaration( +- PropertyAccessorElement element) async { +- // prepare "get" keyword +- Token getKeyword =3D null; +- { +- AstNode name =3D await astProvider.getParsedNameForElement(element); +- AstNode declaration =3D name?.parent; +- if (declaration is MethodDeclaration) { +- getKeyword =3D declaration.propertyKeyword; +- } else if (declaration is FunctionDeclaration) { +- getKeyword =3D declaration.propertyKeyword; +- } else { +- return; +- } +- } +- // remove "get " +- if (getKeyword !=3D null) { +- SourceRange getRange =3D +- range.startOffsetEndOffset(getKeyword.offset, element.nameOffse= t); +- SourceEdit edit =3D newSourceEdit_range(getRange, ''); +- doSourceChange_addElementEdit(change, element, edit); +- } +- // add parameters "()" +- { +- SourceEdit edit =3D new SourceEdit(range.elementName(element).end, = 0, '()'); +- doSourceChange_addElementEdit(change, element, edit); +- } +- } +- +- Future _updateElementReferences(Element element) async { +- List matches =3D await searchEngine.searchReferences(ele= ment); +- List references =3D getSourceReferences(matches); +- for (SourceReference reference in references) { +- Element refElement =3D reference.element; +- SourceRange refRange =3D reference.range; +- // insert "()" +- var edit =3D new SourceEdit(refRange.end, 0, "()"); +- doSourceChange_addElementEdit(change, refElement, edit); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/convert_meth= od_to_getter.dart b/pkg/analysis_server/lib/src/services/refactoring/conver= t_method_to_getter.dart +deleted file mode 100644 +index 2ff0f5bf10d..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/convert_method_to_g= etter.dart ++++ /dev/null +@@ -1,143 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * [ConvertMethodToGetterRefactoring] implementation. +- */ +-class ConvertMethodToGetterRefactoringImpl extends RefactoringImpl +- implements ConvertMethodToGetterRefactoring { +- final SearchEngine searchEngine; +- final AstProvider astProvider; +- final ExecutableElement element; +- +- SourceChange change; +- +- ConvertMethodToGetterRefactoringImpl( +- this.searchEngine, this.astProvider, this.element); +- +- @override +- String get refactoringName =3D> 'Convert Method To Getter'; +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- Future checkInitialConditions() async { +- // check Element type +- if (element is FunctionElement) { +- if (element.enclosingElement is! CompilationUnitElement) { +- return new RefactoringStatus.fatal( +- 'Only top-level functions can be converted to getters.'); +- } +- } else if (element is! MethodElement) { +- return new RefactoringStatus.fatal( +- 'Only class methods or top-level functions can be converted to = getters.'); +- } +- // returns a value +- if (element.returnType !=3D null && element.returnType.isVoid) { +- return new RefactoringStatus.fatal( +- 'Cannot convert ${element.kind.displayName} returning void.'); +- } +- // no parameters +- if (element.parameters.isNotEmpty) { +- return new RefactoringStatus.fatal( +- 'Only methods without parameters can be converted to getters.'); +- } +- // OK +- return new RefactoringStatus(); +- } +- +- @override +- Future createChange() async { +- change =3D new SourceChange(refactoringName); +- // FunctionElement +- if (element is FunctionElement) { +- await _updateElementDeclaration(element); +- await _updateElementReferences(element); +- } +- // MethodElement +- if (element is MethodElement) { +- MethodElement method =3D element; +- Set elements =3D +- await getHierarchyMembers(searchEngine, method); +- await Future.forEach(elements, (Element element) async { +- await _updateElementDeclaration(element); +- return _updateElementReferences(element); +- }); +- } +- // done +- return change; +- } +- +- @override +- bool requiresPreview() =3D> false; +- +- Future _updateElementDeclaration(Element element) async { +- // prepare parameters +- FormalParameterList parameters; +- { +- AstNode name =3D await astProvider.getParsedNameForElement(element); +- AstNode declaration =3D name?.parent; +- if (declaration is MethodDeclaration) { +- parameters =3D declaration.parameters; +- } else if (declaration is FunctionDeclaration) { +- parameters =3D declaration.functionExpression.parameters; +- } else { +- return; +- } +- } +- // insert "get " +- { +- SourceEdit edit =3D new SourceEdit(element.nameOffset, 0, 'get '); +- doSourceChange_addElementEdit(change, element, edit); +- } +- // remove parameters +- { +- SourceEdit edit =3D newSourceEdit_range(range.node(parameters), ''); +- doSourceChange_addElementEdit(change, element, edit); +- } +- } +- +- Future _updateElementReferences(Element element) async { +- List matches =3D await searchEngine.searchReferences(ele= ment); +- List references =3D getSourceReferences(matches); +- for (SourceReference reference in references) { +- Element refElement =3D reference.element; +- SourceRange refRange =3D reference.range; +- // prepare invocation +- MethodInvocation invocation; +- { +- CompilationUnit refUnit =3D +- await astProvider.getParsedUnitForElement(refElement); +- AstNode refNode =3D +- new NodeLocator(refRange.offset).searchWithin(refUnit); +- invocation =3D refNode.getAncestor((node) =3D> node is MethodInvo= cation); +- } +- // we need invocation +- if (invocation !=3D null) { +- SourceEdit edit =3D newSourceEdit_range( +- range.startOffsetEndOffset(refRange.end, invocation.end), ''); +- doSourceChange_addElementEdit(change, refElement, edit); +- } +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/extract_loca= l.dart b/pkg/analysis_server/lib/src/services/refactoring/extract_local.dart +deleted file mode 100644 +index 59153af0251..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/extract_local.dart ++++ /dev/null +@@ -1,699 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/name_suggestion.d= art'; +-import 'package:analysis_server/src/services/correction/selection_analyze= r.dart'; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-const String _TOKEN_SEPARATOR =3D "\uFFFF"; +- +-/** +- * [ExtractLocalRefactoring] implementation. +- */ +-class ExtractLocalRefactoringImpl extends RefactoringImpl +- implements ExtractLocalRefactoring { +- final CompilationUnit unit; +- final int selectionOffset; +- final int selectionLength; +- CompilationUnitElement unitElement; +- String file; +- SourceRange selectionRange; +- CorrectionUtils utils; +- +- String name; +- bool extractAll =3D true; +- final List coveringExpressionOffsets =3D []; +- final List coveringExpressionLengths =3D []; +- final List names =3D []; +- final List offsets =3D []; +- final List lengths =3D []; +- +- Expression rootExpression; +- Expression singleExpression; +- bool wholeStatementExpression =3D false; +- String stringLiteralPart; +- final List occurrences =3D []; +- final Map elementIds =3D {}; +- Set excludedVariableNames =3D new Set(); +- +- ExtractLocalRefactoringImpl( +- this.unit, this.selectionOffset, this.selectionLength) { +- unitElement =3D unit.element; +- selectionRange =3D new SourceRange(selectionOffset, selectionLength); +- utils =3D new CorrectionUtils(unit); +- file =3D unitElement.source.fullName; +- } +- +- @override +- String get refactoringName =3D> 'Extract Local Variable'; +- +- String get _declarationKeyword { +- if (_isPartOfConstantExpression(rootExpression)) { +- return "const"; +- } else { +- return "var"; +- } +- } +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- result.addStatus(checkName()); +- return new Future.value(result); +- } +- +- @override +- Future checkInitialConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- // selection +- result.addStatus(_checkSelection()); +- if (result.hasFatalError) { +- return new Future.value(result); +- } +- // occurrences +- _prepareOccurrences(); +- _prepareOffsetsLengths(); +- // names +- excludedVariableNames =3D +- utils.findPossibleLocalVariableConflicts(selectionOffset); +- _prepareNames(); +- // done +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkName() { +- RefactoringStatus result =3D new RefactoringStatus(); +- result.addStatus(validateVariableName(name)); +- if (excludedVariableNames.contains(name)) { +- result.addError( +- format("The name '{0}' is already used in the scope.", name)); +- } +- return result; +- } +- +- @override +- Future createChange() { +- SourceChange change =3D new SourceChange(refactoringName); +- // prepare occurrences +- List occurrences; +- if (extractAll) { +- occurrences =3D this.occurrences; +- } else { +- occurrences =3D [selectionRange]; +- } +- occurrences.sort((a, b) =3D> a.offset - b.offset); +- // If the whole expression of a statement is selected, like '1 + 2', +- // then convert it into a variable declaration statement. +- if (wholeStatementExpression && occurrences.length =3D=3D 1) { +- String keyword =3D _declarationKeyword; +- String declarationSource =3D '$keyword $name =3D '; +- SourceEdit edit =3D +- new SourceEdit(singleExpression.offset, 0, declarationSource); +- doSourceChange_addElementEdit(change, unitElement, edit); +- return new Future.value(change); +- } +- // prepare positions +- List positions =3D []; +- int occurrencesShift =3D 0; +- void addPosition(int offset) { +- positions.add(new Position(file, offset)); +- } +- +- // add variable declaration +- { +- String declarationCode; +- int nameOffsetInDeclarationCode; +- if (stringLiteralPart !=3D null) { +- declarationCode =3D 'var '; +- nameOffsetInDeclarationCode =3D declarationCode.length; +- declarationCode +=3D "$name =3D '$stringLiteralPart';"; +- } else { +- String keyword =3D _declarationKeyword; +- String initializerCode =3D utils.getRangeText(selectionRange); +- declarationCode =3D '$keyword '; +- nameOffsetInDeclarationCode =3D declarationCode.length; +- declarationCode +=3D '$name =3D $initializerCode;'; +- } +- // prepare location for declaration +- AstNode target =3D _findDeclarationTarget(occurrences); +- String eol =3D utils.endOfLine; +- // insert variable declaration +- if (target is Statement) { +- String prefix =3D utils.getNodePrefix(target); +- SourceEdit edit =3D +- new SourceEdit(target.offset, 0, declarationCode + eol + pref= ix); +- doSourceChange_addElementEdit(change, unitElement, edit); +- addPosition(edit.offset + nameOffsetInDeclarationCode); +- occurrencesShift =3D edit.replacement.length; +- } else if (target is ExpressionFunctionBody) { +- String prefix =3D utils.getNodePrefix(target.parent); +- String indent =3D utils.getIndent(1); +- Expression expr =3D target.expression; +- { +- String code =3D '{' + eol + prefix + indent; +- addPosition( +- target.offset + code.length + nameOffsetInDeclarationCode); +- code +=3D declarationCode + eol; +- code +=3D prefix + indent + 'return '; +- SourceEdit edit =3D +- new SourceEdit(target.offset, expr.offset - target.offset, = code); +- occurrencesShift =3D target.offset + code.length - expr.offset; +- doSourceChange_addElementEdit(change, unitElement, edit); +- } +- doSourceChange_addElementEdit( +- change, +- unitElement, +- new SourceEdit( +- expr.end, target.end - expr.end, ';' + eol + prefix + '}'= )); +- } +- } +- // prepare replacement +- String occurrenceReplacement =3D name; +- if (stringLiteralPart !=3D null) { +- occurrenceReplacement =3D "\${$name}"; +- occurrencesShift +=3D 2; +- } +- // replace occurrences with variable reference +- for (SourceRange range in occurrences) { +- SourceEdit edit =3D newSourceEdit_range(range, occurrenceReplacemen= t); +- addPosition(range.offset + occurrencesShift); +- occurrencesShift +=3D name.length - range.length; +- doSourceChange_addElementEdit(change, unitElement, edit); +- } +- // add the linked group +- change.addLinkedEditGroup(new LinkedEditGroup( +- positions, +- name.length, +- names +- .map((name) =3D> new LinkedEditSuggestion( +- name, LinkedEditSuggestionKind.VARIABLE)) +- .toList())); +- // done +- return new Future.value(change); +- } +- +- @override +- bool requiresPreview() =3D> false; +- +- /** +- * Checks if [selectionRange] selects [Expression] which can be extract= ed, and +- * location of this [Expression] in AST allows extracting. +- */ +- RefactoringStatus _checkSelection() { +- String selectionStr; +- // exclude whitespaces +- { +- selectionStr =3D utils.getRangeText(selectionRange); +- int numLeading =3D countLeadingWhitespaces(selectionStr); +- int numTrailing =3D countTrailingWhitespaces(selectionStr); +- int offset =3D selectionRange.offset + numLeading; +- int end =3D selectionRange.end - numTrailing; +- selectionRange =3D new SourceRange(offset, end - offset); +- } +- // get covering node +- AstNode coveringNode =3D +- new NodeLocator(selectionRange.offset, selectionRange.end) +- .searchWithin(unit); +- // compute covering expressions +- for (AstNode node =3D coveringNode; node !=3D null; node =3D node.par= ent) { +- AstNode parent =3D node.parent; +- // skip some nodes +- if (node is ArgumentList || +- node is AssignmentExpression || +- node is NamedExpression || +- node is TypeArgumentList) { +- continue; +- } +- if (node is ConstructorName || node is Label || node is TypeName) { +- rootExpression =3D null; +- coveringExpressionOffsets.clear(); +- coveringExpressionLengths.clear(); +- continue; +- } +- // cannot extract the name part of a property access +- if (parent is PrefixedIdentifier && parent.identifier =3D=3D node || +- parent is PropertyAccess && parent.propertyName =3D=3D node) { +- continue; +- } +- // stop if not an Expression +- if (node is! Expression) { +- break; +- } +- // stop at void method invocations +- if (node is MethodInvocation) { +- MethodInvocation invocation =3D node; +- Element element =3D invocation.methodName.bestElement; +- if (element is ExecutableElement && +- element.returnType !=3D null && +- element.returnType.isVoid) { +- if (rootExpression =3D=3D null) { +- return new RefactoringStatus.fatal( +- 'Cannot extract the void expression.', +- newLocation_fromNode(node)); +- } +- break; +- } +- } +- // fatal selection problems +- if (coveringExpressionOffsets.isEmpty) { +- if (node is SimpleIdentifier) { +- if (node.inDeclarationContext()) { +- return new RefactoringStatus.fatal( +- 'Cannot extract the name part of a declaration.', +- newLocation_fromNode(node)); +- } +- Element element =3D node.bestElement; +- if (element is FunctionElement || element is MethodElement) { +- continue; +- } +- } +- if (parent is AssignmentExpression && parent.leftHandSide =3D=3D = node) { +- return new RefactoringStatus.fatal( +- 'Cannot extract the left-hand side of an assignment.', +- newLocation_fromNode(node)); +- } +- } +- // set selected expression +- if (coveringExpressionOffsets.isEmpty) { +- rootExpression =3D node; +- } +- // add the expression range +- coveringExpressionOffsets.add(node.offset); +- coveringExpressionLengths.add(node.length); +- } +- // We need an enclosing function. +- // If it has a block body, we can add a new variable declaration stat= ement +- // into this block. If it has an expression body, we can convert it = into +- // the block body first. +- if (coveringNode =3D=3D null || +- coveringNode.getAncestor((node) =3D> node is FunctionBody) =3D=3D= null) { +- return new RefactoringStatus.fatal( +- 'An expression inside a function must be selected ' +- 'to activate this refactoring.'); +- } +- // part of string literal +- if (coveringNode is StringLiteral) { +- if (selectionRange.length !=3D 0 && +- selectionRange.offset > coveringNode.offset && +- selectionRange.end < coveringNode.end) { +- stringLiteralPart =3D selectionStr; +- return new RefactoringStatus(); +- } +- } +- // single node selected +- if (rootExpression !=3D null) { +- singleExpression =3D rootExpression; +- selectionRange =3D range.node(singleExpression); +- wholeStatementExpression =3D singleExpression.parent is ExpressionS= tatement; +- return new RefactoringStatus(); +- } +- // invalid selection +- return new RefactoringStatus.fatal( +- 'Expression must be selected to activate this refactoring.'); +- } +- +- /** +- * Return an unique identifier for the given [Element], or `null` if [e= lement] +- * is `null`. +- */ +- int _encodeElement(Element element) { +- if (element =3D=3D null) { +- return null; +- } +- int id =3D elementIds[element]; +- if (id =3D=3D null) { +- id =3D elementIds.length; +- elementIds[element] =3D id; +- } +- return id; +- } +- +- /** +- * Returns an [Element]-sensitive encoding of [tokens]. +- * Each [Token] with a [LocalVariableElement] has a suffix of the eleme= nt id. +- * +- * So, we can distinguish different local variables with the same name,= if +- * there are multiple variables with the same name are declared in the +- * function we are searching occurrences in. +- */ +- String _encodeExpressionTokens(Expression expr, List tokens) { +- // no expression, i.e. a part of a string +- if (expr =3D=3D null) { +- return tokens.join(_TOKEN_SEPARATOR); +- } +- // prepare Token -> LocalElement map +- Map map =3D new HashMap( +- equals: (Token a, Token b) =3D> a.lexeme =3D=3D b.lexeme, +- hashCode: (Token t) =3D> t.lexeme.hashCode); +- expr.accept(new _TokenLocalElementVisitor(map)); +- // map and join tokens +- return tokens.map((Token token) { +- String tokenString =3D token.lexeme; +- // append token's Element id +- Element element =3D map[token]; +- if (element !=3D null) { +- int elementId =3D _encodeElement(element); +- if (elementId !=3D null) { +- tokenString +=3D '-$elementId'; +- } +- } +- // done +- return tokenString; +- }).join(_TOKEN_SEPARATOR); +- } +- +- /** +- * Return the [AstNode] to defined the variable before. +- * It should be accessible by all the given [occurrences]. +- */ +- AstNode _findDeclarationTarget(List occurrences) { +- List nodes =3D _findNodes(occurrences); +- AstNode commonParent =3D getNearestCommonAncestor(nodes); +- // Block +- if (commonParent is Block) { +- List firstParents =3D getParents(nodes[0]); +- int commonIndex =3D firstParents.indexOf(commonParent); +- return firstParents[commonIndex + 1]; +- } +- // ExpressionFunctionBody +- AstNode expressionBody =3D _getEnclosingExpressionBody(commonParent); +- if (expressionBody !=3D null) { +- return expressionBody; +- } +- // single Statement +- AstNode target =3D commonParent.getAncestor((node) =3D> node is State= ment); +- while (target.parent is! Block) { +- target =3D target.parent; +- } +- return target; +- } +- +- /** +- * Returns [AstNode]s at the offsets of the given [SourceRange]s. +- */ +- List _findNodes(List ranges) { +- List nodes =3D []; +- for (SourceRange range in ranges) { +- AstNode node =3D new NodeLocator(range.offset).searchWithin(unit); +- nodes.add(node); +- } +- return nodes; +- } +- +- /** +- * Returns the [ExpressionFunctionBody] that encloses [node], or `null` +- * if [node] is not enclosed with an [ExpressionFunctionBody]. +- */ +- ExpressionFunctionBody _getEnclosingExpressionBody(AstNode node) { +- while (node !=3D null) { +- if (node is Statement) { +- return null; +- } +- if (node is ExpressionFunctionBody) { +- return node; +- } +- node =3D node.parent; +- } +- return null; +- } +- +- /** +- * Checks if it is OK to extract the node with the given [SourceRange]. +- */ +- bool _isExtractable(SourceRange range) { +- _ExtractExpressionAnalyzer analyzer =3D new _ExtractExpressionAnalyze= r(range); +- utils.unit.accept(analyzer); +- return analyzer.status.isOK; +- } +- +- bool _isPartOfConstantExpression(AstNode node) { +- if (node is TypedLiteral) { +- return node.constKeyword !=3D null; +- } +- if (node is InstanceCreationExpression) { +- InstanceCreationExpression creation =3D node; +- return creation.isConst; +- } +- if (node is ArgumentList || +- node is ConditionalExpression || +- node is BinaryExpression || +- node is ParenthesizedExpression || +- node is PrefixExpression || +- node is Literal || +- node is MapLiteralEntry) { +- return _isPartOfConstantExpression(node.parent); +- } +- return false; +- } +- +- void _prepareNames() { +- names.clear(); +- if (stringLiteralPart !=3D null) { +- names.addAll(getVariableNameSuggestionsForText( +- stringLiteralPart, excludedVariableNames)); +- } else if (singleExpression !=3D null) { +- names.addAll(getVariableNameSuggestionsForExpression( +- singleExpression.staticType, +- singleExpression, +- excludedVariableNames)); +- } +- } +- +- /** +- * Prepares all occurrences of the source which matches given selection, +- * sorted by offsets. +- */ +- void _prepareOccurrences() { +- occurrences.clear(); +- elementIds.clear(); +- // prepare selection +- String selectionSource; +- { +- String rawSelectionSource =3D utils.getRangeText(selectionRange); +- List selectionTokens =3D TokenUtils.getTokens(rawSelectionSo= urce); +- selectionSource =3D +- _encodeExpressionTokens(rootExpression, selectionTokens); +- } +- // prepare enclosing function +- AstNode enclosingFunction; +- { +- AstNode selectionNode =3D +- new NodeLocator(selectionOffset).searchWithin(unit); +- enclosingFunction =3D getEnclosingExecutableNode(selectionNode); +- } +- // visit function +- enclosingFunction +- .accept(new _OccurrencesVisitor(this, occurrences, selectionSourc= e)); +- } +- +- void _prepareOffsetsLengths() { +- offsets.clear(); +- lengths.clear(); +- for (SourceRange occurrence in occurrences) { +- offsets.add(occurrence.offset); +- lengths.add(occurrence.length); +- } +- } +-} +- +-/** +- * [SelectionAnalyzer] for [ExtractLocalRefactoringImpl]. +- */ +-class _ExtractExpressionAnalyzer extends SelectionAnalyzer { +- final RefactoringStatus status =3D new RefactoringStatus(); +- +- _ExtractExpressionAnalyzer(SourceRange selection) : super(selection); +- +- /** +- * Records fatal error with given message. +- */ +- void invalidSelection(String message) { +- _invalidSelection(message, null); +- } +- +- @override +- Object visitAssignmentExpression(AssignmentExpression node) { +- super.visitAssignmentExpression(node); +- Expression lhs =3D node.leftHandSide; +- if (_isFirstSelectedNode(lhs)) { +- _invalidSelection('Cannot extract the left-hand side of an assignme= nt.', +- newLocation_fromNode(lhs)); +- } +- return null; +- } +- +- @override +- Object visitSimpleIdentifier(SimpleIdentifier node) { +- super.visitSimpleIdentifier(node); +- if (_isFirstSelectedNode(node)) { +- // name of declaration +- if (node.inDeclarationContext()) { +- invalidSelection('Cannot extract the name part of a declaration.'= ); +- } +- // method name +- Element element =3D node.bestElement; +- if (element is FunctionElement || element is MethodElement) { +- invalidSelection('Cannot extract a single method name.'); +- } +- // name in property access +- AstNode parent =3D node.parent; +- if (parent is PrefixedIdentifier && identical(parent.identifier, no= de)) { +- invalidSelection('Cannot extract name part of a property access.'= ); +- } +- if (parent is PropertyAccess && identical(parent.propertyName, node= )) { +- invalidSelection('Cannot extract name part of a property access.'= ); +- } +- } +- return null; +- } +- +- /** +- * Records fatal error with given [message] and [location]. +- */ +- void _invalidSelection(String message, Location location) { +- status.addFatalError(message, location); +- reset(); +- } +- +- bool _isFirstSelectedNode(AstNode node) =3D> node =3D=3D firstSelectedN= ode; +-} +- +-class _HasStatementVisitor extends GeneralizingAstVisitor { +- bool result =3D false; +- +- _HasStatementVisitor(); +- +- @override +- visitStatement(Statement node) { +- result =3D true; +- } +-} +- +-class _OccurrencesVisitor extends GeneralizingAstVisitor { +- final ExtractLocalRefactoringImpl ref; +- final List occurrences; +- final String selectionSource; +- +- _OccurrencesVisitor(this.ref, this.occurrences, this.selectionSource); +- +- @override +- Object visitBinaryExpression(BinaryExpression node) { +- if (!_hasStatements(node)) { +- _tryToFindOccurrenceFragments(node); +- return null; +- } +- return super.visitBinaryExpression(node); +- } +- +- @override +- Object visitExpression(Expression node) { +- if (ref._isExtractable(range.node(node))) { +- _tryToFindOccurrence(node); +- } +- return super.visitExpression(node); +- } +- +- @override +- Object visitStringLiteral(StringLiteral node) { +- if (ref.stringLiteralPart !=3D null) { +- int length =3D ref.stringLiteralPart.length; +- String value =3D ref.utils.getNodeText(node); +- int lastIndex =3D 0; +- while (true) { +- int index =3D value.indexOf(ref.stringLiteralPart, lastIndex); +- if (index =3D=3D -1) { +- break; +- } +- lastIndex =3D index + length; +- int start =3D node.offset + index; +- SourceRange range =3D new SourceRange(start, length); +- occurrences.add(range); +- } +- return null; +- } +- return visitExpression(node); +- } +- +- void _addOccurrence(SourceRange range) { +- if (range.intersects(ref.selectionRange)) { +- occurrences.add(ref.selectionRange); +- } else { +- occurrences.add(range); +- } +- } +- +- bool _hasStatements(AstNode root) { +- _HasStatementVisitor visitor =3D new _HasStatementVisitor(); +- root.accept(visitor); +- return visitor.result; +- } +- +- void _tryToFindOccurrence(Expression node) { +- String nodeSource =3D ref.utils.getNodeText(node); +- List nodeTokens =3D TokenUtils.getTokens(nodeSource); +- nodeSource =3D ref._encodeExpressionTokens(node, nodeTokens); +- if (nodeSource =3D=3D selectionSource) { +- _addOccurrence(range.node(node)); +- } +- } +- +- void _tryToFindOccurrenceFragments(Expression node) { +- int nodeOffset =3D node.offset; +- String nodeSource =3D ref.utils.getNodeText(node); +- List nodeTokens =3D TokenUtils.getTokens(nodeSource); +- nodeSource =3D ref._encodeExpressionTokens(node, nodeTokens); +- // find "selection" in "node" tokens +- int lastIndex =3D 0; +- while (true) { +- // find next occurrence +- int index =3D nodeSource.indexOf(selectionSource, lastIndex); +- if (index =3D=3D -1) { +- break; +- } +- lastIndex =3D index + selectionSource.length; +- // find start/end tokens +- int startTokenIndex =3D +- countMatches(nodeSource.substring(0, index), _TOKEN_SEPARATOR); +- int endTokenIndex =3D +- countMatches(nodeSource.substring(0, lastIndex), _TOKEN_SEPARAT= OR); +- Token startToken =3D nodeTokens[startTokenIndex]; +- Token endToken =3D nodeTokens[endTokenIndex]; +- // add occurrence range +- int start =3D nodeOffset + startToken.offset; +- int end =3D nodeOffset + endToken.end; +- _addOccurrence(range.startOffsetEndOffset(start, end)); +- } +- } +-} +- +-class _TokenLocalElementVisitor extends RecursiveAstVisitor { +- final Map map; +- +- _TokenLocalElementVisitor(this.map); +- +- visitSimpleIdentifier(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is LocalVariableElement) { +- map[node.token] =3D element; +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/extract_meth= od.dart b/pkg/analysis_server/lib/src/services/refactoring/extract_method.d= art +deleted file mode 100644 +index 65905be2076..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/extract_method.dart ++++ /dev/null +@@ -1,1350 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/name_suggestion.d= art'; +-import 'package:analysis_server/src/services/correction/selection_analyze= r.dart'; +-import 'package:analysis_server/src/services/correction/statement_analyze= r.dart'; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/refactoring/rename_class_mem= ber.dart'; +-import 'package:analysis_server/src/services/refactoring/rename_unit_memb= er.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/analysis/session.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/resolver.dart' show ExitDetector; +-import 'package:analyzer/src/generated/resolver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/type_system.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-const String _TOKEN_SEPARATOR =3D '\uFFFF'; +- +-Element _getLocalElement(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is LocalVariableElement || +- element is ParameterElement || +- element is FunctionElement && element.visibleRange !=3D null) { +- return element; +- } +- return null; +-} +- +-/** +- * Returns the "normalized" version of the given source, which is reconst= ructed +- * from tokens, so ignores all the comments and spaces. +- */ +-String _getNormalizedSource(String src) { +- List selectionTokens =3D TokenUtils.getTokens(src); +- return selectionTokens.join(_TOKEN_SEPARATOR); +-} +- +-/** +- * Returns the [Map] which maps [map] values to their keys. +- */ +-Map _inverseMap(Map map) { +- Map result =3D {}; +- map.forEach((String key, String value) { +- result[value] =3D key; +- }); +- return result; +-} +- +-/** +- * [ExtractMethodRefactoring] implementation. +- */ +-class ExtractMethodRefactoringImpl extends RefactoringImpl +- implements ExtractMethodRefactoring { +- static const ERROR_EXITS =3D +- 'Selected statements contain a return statement, but not all possib= le ' +- 'execution flows exit. Semantics may not be preserved.'; +- +- final SearchEngine searchEngine; +- final AstProvider astProvider; +- final CompilationUnit unit; +- final int selectionOffset; +- final int selectionLength; +- AnalysisSession session; +- CompilationUnitElement unitElement; +- LibraryElement libraryElement; +- SourceRange selectionRange; +- CorrectionUtils utils; +- Set librariesToImport =3D new Set(); +- +- String returnType =3D ''; +- String variableType; +- String name; +- bool extractAll =3D true; +- bool canCreateGetter =3D false; +- bool createGetter =3D false; +- final List names =3D []; +- final List offsets =3D []; +- final List lengths =3D []; +- +- /** +- * The map of local names to their visibility ranges. +- */ +- Map> _localNames =3D >{}; +- +- /** +- * The set of names that are referenced without any qualifier. +- */ +- Set _unqualifiedNames =3D new Set(); +- +- Set _excludedNames =3D new Set(); +- List _parameters =3D []; +- Map _parametersMap =3D +- {}; +- Map> _parameterReferencesMap =3D +- >{}; +- bool _hasAwait =3D false; +- DartType _returnType; +- String _returnVariableName; +- AstNode _parentMember; +- Expression _selectionExpression; +- FunctionExpression _selectionFunctionExpression; +- List _selectionStatements; +- List<_Occurrence> _occurrences =3D []; +- bool _staticContext =3D false; +- +- ExtractMethodRefactoringImpl(this.searchEngine, this.astProvider, this.= unit, +- this.selectionOffset, this.selectionLength) { +- unitElement =3D unit.element; +- libraryElement =3D unitElement.library; +- session =3D astProvider.driver.currentSession; +- selectionRange =3D new SourceRange(selectionOffset, selectionLength); +- utils =3D new CorrectionUtils(unit); +- } +- +- @override +- List get parameters =3D> _parameters; +- +- @override +- void set parameters(List parameters) { +- _parameters =3D parameters.toList(); +- } +- +- @override +- String get refactoringName { +- AstNode node =3D new NodeLocator(selectionOffset).searchWithin(unit); +- if (node !=3D null && +- node.getAncestor((node) =3D> node is ClassDeclaration) !=3D null)= { +- return 'Extract Method'; +- } +- return 'Extract Function'; +- } +- +- String get signature { +- StringBuffer sb =3D new StringBuffer(); +- if (createGetter) { +- sb.write('get '); +- sb.write(name); +- } else { +- sb.write(name); +- sb.write('('); +- // add all parameters +- bool firstParameter =3D true; +- for (RefactoringMethodParameter parameter in _parameters) { +- // may be comma +- if (firstParameter) { +- firstParameter =3D false; +- } else { +- sb.write(', '); +- } +- // type +- { +- String typeSource =3D parameter.type; +- if ('dynamic' !=3D typeSource && '' !=3D typeSource) { +- sb.write(typeSource); +- sb.write(' '); +- } +- } +- // name +- sb.write(parameter.name); +- // optional function-typed parameter parameters +- if (parameter.parameters !=3D null) { +- sb.write(parameter.parameters); +- } +- } +- sb.write(')'); +- } +- // done +- return sb.toString(); +- } +- +- @override +- Future checkFinalConditions() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- result.addStatus(validateMethodName(name)); +- result.addStatus(_checkParameterNames()); +- RefactoringStatus status =3D await _checkPossibleConflicts(); +- result.addStatus(status); +- return result; +- } +- +- @override +- Future checkInitialConditions() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- // selection +- result.addStatus(_checkSelection()); +- if (result.hasFatalError) { +- return result; +- } +- // prepare parts +- RefactoringStatus status =3D await _initializeParameters(); +- result.addStatus(status); +- _initializeHasAwait(); +- await _initializeReturnType(); +- // occurrences +- _initializeOccurrences(); +- _prepareOffsetsLengths(); +- // getter +- canCreateGetter =3D _computeCanCreateGetter(); +- createGetter =3D +- canCreateGetter && _isExpressionForGetter(_selectionExpression); +- // names +- _prepareExcludedNames(); +- _prepareNames(); +- // closure cannot have parameters +- if (_selectionFunctionExpression !=3D null && !_parameters.isEmpty) { +- String message =3D format( +- 'Cannot extract closure as method, it references {0} external v= ariable(s).', +- _parameters.length); +- return new RefactoringStatus.fatal(message); +- } +- return result; +- } +- +- @override +- RefactoringStatus checkName() { +- return validateMethodName(name); +- } +- +- @override +- Future createChange() async { +- SourceChange change =3D new SourceChange(refactoringName); +- // replace occurrences with method invocation +- for (_Occurrence occurrence in _occurrences) { +- SourceRange range =3D occurrence.range; +- // may be replacement of duplicates disabled +- if (!extractAll && !occurrence.isSelection) { +- continue; +- } +- // prepare invocation source +- String invocationSource; +- if (_selectionFunctionExpression !=3D null) { +- invocationSource =3D name; +- } else { +- StringBuffer sb =3D new StringBuffer(); +- // may be returns value +- if (_selectionStatements !=3D null && variableType !=3D null) { +- // single variable assignment / return statement +- if (_returnVariableName !=3D null) { +- String occurrenceName =3D +- occurrence._parameterOldToOccurrenceName[_returnVariableN= ame]; +- // may be declare variable +- if (!_parametersMap.containsKey(_returnVariableName)) { +- if (variableType.isEmpty) { +- sb.write('var '); +- } else { +- sb.write(variableType); +- sb.write(' '); +- } +- } +- // assign the return value +- sb.write(occurrenceName); +- sb.write(' =3D '); +- } else { +- sb.write('return '); +- } +- } +- // await +- if (_hasAwait) { +- sb.write('await '); +- } +- // invocation itself +- sb.write(name); +- if (!createGetter) { +- sb.write('('); +- bool firstParameter =3D true; +- for (RefactoringMethodParameter parameter in _parameters) { +- // may be comma +- if (firstParameter) { +- firstParameter =3D false; +- } else { +- sb.write(', '); +- } +- // argument name +- { +- String argumentName =3D +- occurrence._parameterOldToOccurrenceName[parameter.id]; +- sb.write(argumentName); +- } +- } +- sb.write(')'); +- } +- invocationSource =3D sb.toString(); +- // statements as extracted with their ";", so add new after invoc= ation +- if (_selectionStatements !=3D null) { +- invocationSource +=3D ';'; +- } +- } +- // add replace edit +- SourceEdit edit =3D newSourceEdit_range(range, invocationSource); +- doSourceChange_addElementEdit(change, unitElement, edit); +- } +- // add method declaration +- { +- // prepare environment +- String prefix =3D utils.getNodePrefix(_parentMember); +- String eol =3D utils.endOfLine; +- // prepare annotations +- String annotations =3D ''; +- { +- // may be "static" +- if (_staticContext) { +- annotations =3D 'static '; +- } +- } +- // prepare declaration source +- String declarationSource =3D null; +- { +- String returnExpressionSource =3D _getMethodBodySource(); +- // closure +- if (_selectionFunctionExpression !=3D null) { +- String returnTypeCode =3D _getExpectedClosureReturnTypeCode(); +- declarationSource =3D '$returnTypeCode$name$returnExpressionSou= rce'; +- if (_selectionFunctionExpression.body is ExpressionFunctionBody= ) { +- declarationSource +=3D ';'; +- } +- } +- // optional 'async' body modifier +- String asyncKeyword =3D _hasAwait ? ' async' : ''; +- // expression +- if (_selectionExpression !=3D null) { +- bool isMultiLine =3D returnExpressionSource.contains(eol); +- +- // We generate the method body using the shorthand syntax if it= fits +- // into a single line and use the regular method syntax otherwi= se. +- if (!isMultiLine) { +- // add return type +- if (returnType.isNotEmpty) { +- annotations +=3D '$returnType '; +- } +- // just return expression +- declarationSource =3D '$annotations$signature$asyncKeyword = =3D> '; +- declarationSource +=3D '$returnExpressionSource;'; +- } else { +- // Left indent once; returnExpressionSource was indented for = method +- // shorthands. +- returnExpressionSource =3D utils +- .indentSourceLeftRight('${returnExpressionSource.trim()};= ') +- .trim(); +- +- // add return type +- if (returnType.isNotEmpty) { +- annotations +=3D '$returnType '; +- } +- declarationSource =3D '$annotations$signature$asyncKeyword {$= eol'; +- declarationSource +=3D '$prefix '; +- if (returnType.isNotEmpty) { +- declarationSource +=3D 'return '; +- } +- declarationSource +=3D '$returnExpressionSource$eol$prefix}'; +- } +- } +- // statements +- if (_selectionStatements !=3D null) { +- if (returnType.isNotEmpty) { +- annotations +=3D returnType + ' '; +- } +- declarationSource =3D '$annotations$signature$asyncKeyword {$eo= l'; +- declarationSource +=3D returnExpressionSource; +- if (_returnVariableName !=3D null) { +- declarationSource +=3D '$prefix return $_returnVariableName;= $eol'; +- } +- declarationSource +=3D '$prefix}'; +- } +- } +- // insert declaration +- if (declarationSource !=3D null) { +- int offset =3D _parentMember.end; +- SourceEdit edit =3D +- new SourceEdit(offset, 0, '$eol$eol$prefix$declarationSource'= ); +- doSourceChange_addElementEdit(change, unitElement, edit); +- } +- } +- // done +- addLibraryImports(change, libraryElement, librariesToImport); +- return change; +- } +- +- @override +- bool requiresPreview() =3D> false; +- +- /** +- * Adds a new reference to the parameter with the given name. +- */ +- void _addParameterReference(String name, SourceRange range) { +- List references =3D _parameterReferencesMap[name]; +- if (references =3D=3D null) { +- references =3D []; +- _parameterReferencesMap[name] =3D references; +- } +- references.add(range); +- } +- +- RefactoringStatus _checkParameterNames() { +- RefactoringStatus result =3D new RefactoringStatus(); +- for (RefactoringMethodParameter parameter in _parameters) { +- result.addStatus(validateParameterName(parameter.name)); +- for (RefactoringMethodParameter other in _parameters) { +- if (!identical(parameter, other) && other.name =3D=3D parameter.n= ame) { +- result.addError( +- format("Parameter '{0}' already exists", parameter.name)); +- return result; +- } +- } +- if (_isParameterNameConflictWithBody(parameter)) { +- result.addError(format( +- "'{0}' is already used as a name in the selected code", +- parameter.name)); +- return result; +- } +- } +- return result; +- } +- +- /** +- * Checks if created method will shadow or will be shadowed by other el= ements. +- */ +- Future _checkPossibleConflicts() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- AstNode parent =3D _parentMember.parent; +- // top-level function +- if (parent is CompilationUnit) { +- LibraryElement libraryElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(parent).library; +- return validateCreateFunction(searchEngine, libraryElement, name); +- } +- // method of class +- if (parent is ClassDeclaration) { +- ClassElement classElement =3D parent.element; +- return validateCreateMethod( +- searchEngine, astProvider, classElement, name); +- } +- // OK +- return new Future.value(result); +- } +- +- /** +- * Checks if [selectionRange] selects [Expression] which can be extract= ed, and +- * location of this [DartExpression] in AST allows extracting. +- */ +- RefactoringStatus _checkSelection() { +- // Check for implicitly selected closure. +- { +- FunctionExpression function =3D _findFunctionExpression(); +- if (function !=3D null) { +- _selectionFunctionExpression =3D function; +- selectionRange =3D range.node(function); +- _parentMember =3D getEnclosingClassOrUnitMember(function); +- return new RefactoringStatus(); +- } +- } +- +- _ExtractMethodAnalyzer selectionAnalyzer =3D +- new _ExtractMethodAnalyzer(unit, selectionRange); +- unit.accept(selectionAnalyzer); +- // May be a fatal error. +- { +- RefactoringStatus status =3D selectionAnalyzer.status; +- if (status.hasFatalError) { +- return status; +- } +- } +- List selectedNodes =3D selectionAnalyzer.selectedNodes; +- +- // Check selected nodes. +- if (!selectedNodes.isEmpty) { +- AstNode selectedNode =3D selectedNodes.first; +- _parentMember =3D getEnclosingClassOrUnitMember(selectedNode); +- // single expression selected +- if (selectedNodes.length =3D=3D 1) { +- if (!utils.selectionIncludesNonWhitespaceOutsideNode( +- selectionRange, selectedNode)) { +- if (selectedNode is Expression) { +- _selectionExpression =3D selectedNode; +- // additional check for closure +- if (_selectionExpression is FunctionExpression) { +- _selectionFunctionExpression =3D +- _selectionExpression as FunctionExpression; +- _selectionExpression =3D null; +- } +- // OK +- return new RefactoringStatus(); +- } +- } +- } +- // statements selected +- { +- List selectedStatements =3D []; +- for (AstNode selectedNode in selectedNodes) { +- if (selectedNode is Statement) { +- selectedStatements.add(selectedNode); +- } +- } +- if (selectedStatements.length =3D=3D selectedNodes.length) { +- _selectionStatements =3D selectedStatements; +- return new RefactoringStatus(); +- } +- } +- } +- // invalid selection +- return new RefactoringStatus.fatal( +- 'Can only extract a single expression or a set of statements.'); +- } +- +- /** +- * Initializes [canCreateGetter] flag. +- */ +- bool _computeCanCreateGetter() { +- // is a function expression +- if (_selectionFunctionExpression !=3D null) { +- return false; +- } +- // has parameters +- if (!parameters.isEmpty) { +- return false; +- } +- // is assignment +- if (_selectionExpression !=3D null) { +- if (_selectionExpression is AssignmentExpression) { +- return false; +- } +- } +- // doesn't return a value +- if (_selectionStatements !=3D null) { +- return returnType !=3D 'void'; +- } +- // OK +- return true; +- } +- +- /** +- * If the [selectionRange] is associated with a [FunctionExpression], r= eturn +- * this [FunctionExpression]. +- */ +- FunctionExpression _findFunctionExpression() { +- if (selectionRange.length !=3D 0) { +- return null; +- } +- int offset =3D selectionRange.offset; +- AstNode node =3D new NodeLocator2(offset, offset).searchWithin(unit); +- +- // Check for the parameter list of a FunctionExpression. +- { +- FunctionExpression function =3D +- node?.getAncestor((n) =3D> n is FunctionExpression); +- if (function !=3D null && +- function.parameters !=3D null && +- range.node(function.parameters).contains(offset)) { +- return function; +- } +- } +- +- // Check for the name of the named argument with the closure expressi= on. +- if (node is SimpleIdentifier && +- node.parent is Label && +- node.parent.parent is NamedExpression) { +- NamedExpression namedExpression =3D node.parent.parent; +- Expression expression =3D namedExpression.expression; +- if (expression is FunctionExpression) { +- return expression; +- } +- } +- +- return null; +- } +- +- /** +- * If the selected closure (i.e. [_selectionFunctionExpression]) is an +- * argument for a function typed parameter (as it should be), and the +- * function type has the return type specified, return this return type= 's +- * code. Otherwise return the empty string. +- */ +- String _getExpectedClosureReturnTypeCode() { +- Expression argument =3D _selectionFunctionExpression; +- if (argument.parent is NamedExpression) { +- argument =3D argument.parent as NamedExpression; +- } +- ParameterElement parameter =3D argument.bestParameterElement; +- if (parameter !=3D null) { +- DartType parameterType =3D parameter.type; +- if (parameterType is FunctionType) { +- String typeCode =3D _getTypeCode(parameterType.returnType); +- if (typeCode !=3D 'dynamic') { +- return typeCode + ' '; +- } +- } +- } +- return ''; +- } +- +- /** +- * Returns the selected [Expression] source, with applying new parameter +- * names. +- */ +- String _getMethodBodySource() { +- String source =3D utils.getRangeText(selectionRange); +- // prepare operations to replace variables with parameters +- List replaceEdits =3D []; +- for (RefactoringMethodParameter parameter in _parameters) { +- List ranges =3D _parameterReferencesMap[parameter.id]; +- if (ranges !=3D null) { +- for (SourceRange range in ranges) { +- replaceEdits.add(new SourceEdit(range.offset - selectionRange.o= ffset, +- range.length, parameter.name)); +- } +- } +- } +- replaceEdits.sort((a, b) =3D> b.offset - a.offset); +- // apply replacements +- source =3D SourceEdit.applySequence(source, replaceEdits); +- // change indentation +- if (_selectionFunctionExpression !=3D null) { +- AstNode baseNode =3D +- _selectionFunctionExpression.getAncestor((node) =3D> node is St= atement); +- if (baseNode !=3D null) { +- String baseIndent =3D utils.getNodePrefix(baseNode); +- String targetIndent =3D utils.getNodePrefix(_parentMember); +- source =3D utils.replaceSourceIndent(source, baseIndent, targetIn= dent); +- source =3D source.trim(); +- } +- } +- if (_selectionStatements !=3D null) { +- String selectionIndent =3D utils.getNodePrefix(_selectionStatements= [0]); +- String targetIndent =3D utils.getNodePrefix(_parentMember) + ' '; +- source =3D utils.replaceSourceIndent(source, selectionIndent, targe= tIndent); +- } +- // done +- return source; +- } +- +- _SourcePattern _getSourcePattern(SourceRange range) { +- String originalSource =3D utils.getText(range.offset, range.length); +- _SourcePattern pattern =3D new _SourcePattern(); +- List replaceEdits =3D []; +- unit.accept(new _GetSourcePatternVisitor(range, pattern, replaceEdits= )); +- replaceEdits =3D replaceEdits.reversed.toList(); +- String source =3D SourceEdit.applySequence(originalSource, replaceEdi= ts); +- pattern.normalizedSource =3D _getNormalizedSource(source); +- return pattern; +- } +- +- String _getTypeCode(DartType type) { +- return utils.getTypeSource(type, librariesToImport); +- } +- +- void _initializeHasAwait() { +- _HasAwaitVisitor visitor =3D new _HasAwaitVisitor(); +- if (_selectionExpression !=3D null) { +- _selectionExpression.accept(visitor); +- } else if (_selectionStatements !=3D null) { +- _selectionStatements.forEach((statement) { +- statement.accept(visitor); +- }); +- } +- _hasAwait =3D visitor.result; +- } +- +- /** +- * Fills [_occurrences] field. +- */ +- void _initializeOccurrences() { +- _occurrences.clear(); +- // prepare selection +- _SourcePattern selectionPattern =3D _getSourcePattern(selectionRange); +- Map patternToSelectionName =3D +- _inverseMap(selectionPattern.originalToPatternNames); +- // prepare an enclosing parent - class or unit +- AstNode enclosingMemberParent =3D _parentMember.parent; +- // visit nodes which will able to access extracted method +- enclosingMemberParent.accept(new _InitializeOccurrencesVisitor( +- this, selectionPattern, patternToSelectionName)); +- } +- +- /** +- * Prepares information about used variables, which should be turned in= to +- * parameters. +- */ +- Future _initializeParameters() async { +- _parameters.clear(); +- _parametersMap.clear(); +- _parameterReferencesMap.clear(); +- RefactoringStatus result =3D new RefactoringStatus(); +- List assignedUsedVariables =3D []; +- unit.accept(new _InitializeParametersVisitor(this, assignedUsedVariab= les)); +- // single expression +- if (_selectionExpression !=3D null) { +- _returnType =3D _selectionExpression.bestType; +- } +- // verify that none or all execution flows end with a "return" +- if (_selectionStatements !=3D null) { +- bool hasReturn =3D _selectionStatements.any(_mayEndWithReturnStatem= ent); +- if (hasReturn && !ExitDetector.exits(_selectionStatements.last)) { +- result.addError(ERROR_EXITS); +- } +- } +- // maybe ends with "return" statement +- if (_selectionStatements !=3D null) { +- TypeSystem typeSystem =3D await session.typeSystem; +- _ReturnTypeComputer returnTypeComputer =3D +- new _ReturnTypeComputer(typeSystem); +- _selectionStatements.forEach((statement) { +- statement.accept(returnTypeComputer); +- }); +- _returnType =3D returnTypeComputer.returnType; +- } +- // maybe single variable to return +- if (assignedUsedVariables.length =3D=3D 1) { +- // we cannot both return variable and have explicit return statement +- if (_returnType !=3D null) { +- result.addFatalError( +- 'Ambiguous return value: Selected block contains assignment(s= ) to ' +- 'local variables and return statement.'); +- return result; +- } +- // prepare to return an assigned variable +- VariableElement returnVariable =3D assignedUsedVariables[0]; +- _returnType =3D returnVariable.type; +- _returnVariableName =3D returnVariable.displayName; +- } +- // fatal, if multiple variables assigned and used after selection +- if (assignedUsedVariables.length > 1) { +- StringBuffer sb =3D new StringBuffer(); +- for (VariableElement variable in assignedUsedVariables) { +- sb.write(variable.displayName); +- sb.write('\n'); +- } +- result.addFatalError(format( +- 'Ambiguous return value: Selected block contains more than one ' +- 'assignment to local variables. Affected variables are:\n\n{0}', +- sb.toString().trim())); +- } +- // done +- return result; +- } +- +- Future _initializeReturnType() async { +- TypeProvider typeProvider =3D await session.typeProvider; +- InterfaceType futureType =3D typeProvider.futureType; +- if (_selectionFunctionExpression !=3D null) { +- variableType =3D ''; +- returnType =3D ''; +- } else if (_returnType =3D=3D null) { +- variableType =3D null; +- if (_hasAwait) { +- returnType =3D _getTypeCode(futureType); +- } else { +- returnType =3D 'void'; +- } +- } else if (_returnType.isDynamic) { +- variableType =3D ''; +- if (_hasAwait) { +- returnType =3D _getTypeCode(futureType); +- } else { +- returnType =3D ''; +- } +- } else { +- variableType =3D _getTypeCode(_returnType); +- if (_hasAwait) { +- if (_returnType.element !=3D futureType.element) { +- returnType =3D _getTypeCode(futureType.instantiate([_returnType= ])); +- } +- } else { +- returnType =3D variableType; +- } +- } +- } +- +- /** +- * Checks if the given [element] is declared in [selectionRange]. +- */ +- bool _isDeclaredInSelection(Element element) { +- return selectionRange.contains(element.nameOffset); +- } +- +- /** +- * Checks if it is OK to extract the node with the given [SourceRange]. +- */ +- bool _isExtractable(SourceRange range) { +- _ExtractMethodAnalyzer analyzer =3D new _ExtractMethodAnalyzer(unit, = range); +- utils.unit.accept(analyzer); +- return analyzer.status.isOK; +- } +- +- bool _isParameterNameConflictWithBody(RefactoringMethodParameter parame= ter) { +- String id =3D parameter.id; +- String name =3D parameter.name; +- List parameterRanges =3D _parameterReferencesMap[id]; +- List otherRanges =3D _localNames[name]; +- for (SourceRange parameterRange in parameterRanges) { +- if (otherRanges !=3D null) { +- for (SourceRange otherRange in otherRanges) { +- if (parameterRange.intersects(otherRange)) { +- return true; +- } +- } +- } +- } +- if (_unqualifiedNames.contains(name)) { +- return true; +- } +- return false; +- } +- +- /** +- * Checks if [element] is referenced after [selectionRange]. +- */ +- bool _isUsedAfterSelection(Element element) { +- var visitor =3D new _IsUsedAfterSelectionVisitor(this, element); +- _parentMember.accept(visitor); +- return visitor.result; +- } +- +- /** +- * Prepare names that are used in the enclosing function, so should not= be +- * proposed as names of the extracted method. +- */ +- void _prepareExcludedNames() { +- _excludedNames.clear(); +- List localElements =3D getDefinedLocalElements(_parentM= ember); +- _excludedNames.addAll(localElements.map((e) =3D> e.name)); +- } +- +- void _prepareNames() { +- names.clear(); +- if (_selectionExpression !=3D null) { +- names.addAll(getVariableNameSuggestionsForExpression( +- _selectionExpression.staticType, _selectionExpression, _exclude= dNames, +- isMethod: true)); +- } +- } +- +- void _prepareOffsetsLengths() { +- offsets.clear(); +- lengths.clear(); +- for (_Occurrence occurrence in _occurrences) { +- offsets.add(occurrence.range.offset); +- lengths.add(occurrence.range.length); +- } +- } +- +- /** +- * Checks if the given [expression] is reasonable to extract as a gette= r. +- */ +- static bool _isExpressionForGetter(Expression expression) { +- if (expression is BinaryExpression) { +- return _isExpressionForGetter(expression.leftOperand) && +- _isExpressionForGetter(expression.rightOperand); +- } +- if (expression is Literal) { +- return true; +- } +- if (expression is PrefixExpression) { +- return _isExpressionForGetter(expression.operand); +- } +- if (expression is PrefixedIdentifier) { +- return _isExpressionForGetter(expression.prefix); +- } +- if (expression is PropertyAccess) { +- return _isExpressionForGetter(expression.target); +- } +- if (expression is SimpleIdentifier) { +- return true; +- } +- return false; +- } +- +- /** +- * Returns `true` if the given [statement] may end with a [ReturnStatem= ent]. +- */ +- static bool _mayEndWithReturnStatement(Statement statement) { +- _HasReturnStatementVisitor visitor =3D new _HasReturnStatementVisitor= (); +- statement.accept(visitor); +- return visitor.hasReturn; +- } +-} +- +-/** +- * [SelectionAnalyzer] for [ExtractMethodRefactoringImpl]. +- */ +-class _ExtractMethodAnalyzer extends StatementAnalyzer { +- _ExtractMethodAnalyzer(CompilationUnit unit, SourceRange selection) +- : super(unit, selection); +- +- @override +- void handleNextSelectedNode(AstNode node) { +- super.handleNextSelectedNode(node); +- _checkParent(node); +- } +- +- @override +- void handleSelectionEndsIn(AstNode node) { +- super.handleSelectionEndsIn(node); +- invalidSelection( +- 'The selection does not cover a set of statements or an expressio= n. ' +- 'Extend selection to a valid range.'); +- } +- +- @override +- Object visitAssignmentExpression(AssignmentExpression node) { +- super.visitAssignmentExpression(node); +- Expression lhs =3D node.leftHandSide; +- if (_isFirstSelectedNode(lhs)) { +- invalidSelection('Cannot extract the left-hand side of an assignmen= t.', +- newLocation_fromNode(lhs)); +- } +- return null; +- } +- +- @override +- Object visitConstructorInitializer(ConstructorInitializer node) { +- super.visitConstructorInitializer(node); +- if (_isFirstSelectedNode(node)) { +- invalidSelection( +- 'Cannot extract a constructor initializer. ' +- 'Select expression part of initializer.', +- newLocation_fromNode(node)); +- } +- return null; +- } +- +- @override +- Object visitForStatement(ForStatement node) { +- super.visitForStatement(node); +- if (identical(node.variables, firstSelectedNode)) { +- invalidSelection( +- "Cannot extract initialization part of a 'for' statement."); +- } else if (node.updaters.contains(lastSelectedNode)) { +- invalidSelection("Cannot extract increment part of a 'for' statemen= t."); +- } +- return null; +- } +- +- @override +- Object visitGenericFunctionType(GenericFunctionType node) { +- super.visitGenericFunctionType(node); +- if (_isFirstSelectedNode(node)) { +- invalidSelection('Cannot extract a single type reference.'); +- } +- return null; +- } +- +- @override +- Object visitSimpleIdentifier(SimpleIdentifier node) { +- super.visitSimpleIdentifier(node); +- if (_isFirstSelectedNode(node)) { +- // name of declaration +- if (node.inDeclarationContext()) { +- invalidSelection('Cannot extract the name part of a declaration.'= ); +- } +- // method name +- Element element =3D node.bestElement; +- if (element is FunctionElement || element is MethodElement) { +- invalidSelection('Cannot extract a single method name.'); +- } +- // name in property access +- if (node.parent is PrefixedIdentifier && +- (node.parent as PrefixedIdentifier).identifier =3D=3D node) { +- invalidSelection('Can not extract name part of a property access.= '); +- } +- } +- return null; +- } +- +- @override +- Object visitTypeName(TypeName node) { +- super.visitTypeName(node); +- if (_isFirstSelectedNode(node)) { +- invalidSelection('Cannot extract a single type reference.'); +- } +- return null; +- } +- +- @override +- Object visitVariableDeclaration(VariableDeclaration node) { +- super.visitVariableDeclaration(node); +- if (_isFirstSelectedNode(node)) { +- invalidSelection( +- 'Cannot extract a variable declaration fragment. ' +- 'Select whole declaration statement.', +- newLocation_fromNode(node)); +- } +- return null; +- } +- +- void _checkParent(AstNode node) { +- AstNode firstParent =3D firstSelectedNode.parent; +- do { +- node =3D node.parent; +- if (identical(node, firstParent)) { +- return; +- } +- } while (node !=3D null); +- invalidSelection( +- 'Not all selected statements are enclosed by the same parent stat= ement.'); +- } +- +- bool _isFirstSelectedNode(AstNode node) =3D> identical(firstSelectedNod= e, node); +-} +- +-class _GetSourcePatternVisitor extends GeneralizingAstVisitor { +- final SourceRange partRange; +- final _SourcePattern pattern; +- final List replaceEdits; +- +- _GetSourcePatternVisitor(this.partRange, this.pattern, this.replaceEdit= s); +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- SourceRange nodeRange =3D range.node(node); +- if (partRange.covers(nodeRange)) { +- Element element =3D _getLocalElement(node); +- if (element !=3D null) { +- // name of a named expression +- if (isNamedExpressionName(node)) { +- return; +- } +- // continue +- String originalName =3D element.displayName; +- String patternName =3D pattern.originalToPatternNames[originalNam= e]; +- if (patternName =3D=3D null) { +- DartType parameterType =3D _getElementType(element); +- pattern.parameterTypes.add(parameterType); +- patternName =3D '__refVar${pattern.originalToPatternNames.lengt= h}'; +- pattern.originalToPatternNames[originalName] =3D patternName; +- } +- replaceEdits.add(new SourceEdit(nodeRange.offset - partRange.offs= et, +- nodeRange.length, patternName)); +- } +- } +- } +- +- DartType _getElementType(Element element) { +- if (element is VariableElement) { +- return element.type; +- } +- if (element is FunctionElement) { +- return element.type; +- } +- throw new StateError('Unknown element type: ${element?.runtimeType}'); +- } +-} +- +-class _HasAwaitVisitor extends GeneralizingAstVisitor { +- bool result =3D false; +- +- @override +- visitAwaitExpression(AwaitExpression node) { +- result =3D true; +- } +- +- @override +- visitForEachStatement(ForEachStatement node) { +- if (node.awaitKeyword !=3D null) { +- result =3D true; +- } +- super.visitForEachStatement(node); +- } +-} +- +-class _HasReturnStatementVisitor extends RecursiveAstVisitor { +- bool hasReturn =3D false; +- +- @override +- visitBlockFunctionBody(BlockFunctionBody node) {} +- +- @override +- visitReturnStatement(ReturnStatement node) { +- hasReturn =3D true; +- } +-} +- +-class _InitializeOccurrencesVisitor extends GeneralizingAstVisitor { +- final ExtractMethodRefactoringImpl ref; +- final _SourcePattern selectionPattern; +- final Map patternToSelectionName; +- +- bool forceStatic =3D false; +- +- _InitializeOccurrencesVisitor( +- this.ref, this.selectionPattern, this.patternToSelectionName); +- +- @override +- Object visitBlock(Block node) { +- if (ref._selectionStatements !=3D null) { +- _visitStatements(node.statements); +- } +- return super.visitBlock(node); +- } +- +- @override +- Object visitConstructorInitializer(ConstructorInitializer node) { +- forceStatic =3D true; +- try { +- return super.visitConstructorInitializer(node); +- } finally { +- forceStatic =3D false; +- } +- } +- +- @override +- Object visitExpression(Expression node) { +- if (ref._selectionFunctionExpression !=3D null || +- ref._selectionExpression !=3D null && +- node.runtimeType =3D=3D ref._selectionExpression.runtimeType)= { +- SourceRange nodeRange =3D range.node(node); +- _tryToFindOccurrence(nodeRange); +- } +- return super.visitExpression(node); +- } +- +- @override +- Object visitMethodDeclaration(MethodDeclaration node) { +- forceStatic =3D node.isStatic; +- try { +- return super.visitMethodDeclaration(node); +- } finally { +- forceStatic =3D false; +- } +- } +- +- @override +- Object visitSwitchMember(SwitchMember node) { +- if (ref._selectionStatements !=3D null) { +- _visitStatements(node.statements); +- } +- return super.visitSwitchMember(node); +- } +- +- /** +- * Checks if given [SourceRange] matched selection source and adds [_Oc= currence]. +- */ +- bool _tryToFindOccurrence(SourceRange nodeRange) { +- // check if can be extracted +- if (!ref._isExtractable(nodeRange)) { +- return false; +- } +- // prepare node source +- _SourcePattern nodePattern =3D ref._getSourcePattern(nodeRange); +- // if matches normalized node source, then add as occurrence +- if (selectionPattern.isCompatible(nodePattern)) { +- _Occurrence occurrence =3D +- new _Occurrence(nodeRange, ref.selectionRange.intersects(nodeRa= nge)); +- ref._occurrences.add(occurrence); +- // prepare mapping of parameter names to the occurrence variables +- nodePattern.originalToPatternNames +- .forEach((String originalName, String patternName) { +- String selectionName =3D patternToSelectionName[patternName]; +- occurrence._parameterOldToOccurrenceName[selectionName] =3D origi= nalName; +- }); +- // update static +- if (forceStatic) { +- ref._staticContext =3D true; +- } +- // we have match +- return true; +- } +- // no match +- return false; +- } +- +- void _visitStatements(List statements) { +- int beginStatementIndex =3D 0; +- int selectionCount =3D ref._selectionStatements.length; +- while (beginStatementIndex + selectionCount <=3D statements.length) { +- SourceRange nodeRange =3D range.startEnd(statements[beginStatementI= ndex], +- statements[beginStatementIndex + selectionCount - 1]); +- bool found =3D _tryToFindOccurrence(nodeRange); +- // next statement +- if (found) { +- beginStatementIndex +=3D selectionCount; +- } else { +- beginStatementIndex++; +- } +- } +- } +-} +- +-class _InitializeParametersVisitor extends GeneralizingAstVisitor { +- final ExtractMethodRefactoringImpl ref; +- final List assignedUsedVariables; +- +- _InitializeParametersVisitor(this.ref, this.assignedUsedVariables); +- +- @override +- void visitSimpleIdentifier(SimpleIdentifier node) { +- SourceRange nodeRange =3D range.node(node); +- if (!ref.selectionRange.covers(nodeRange)) { +- return; +- } +- String name =3D node.name; +- // analyze local element +- Element element =3D _getLocalElement(node); +- if (element !=3D null) { +- // name of the named expression +- if (isNamedExpressionName(node)) { +- return; +- } +- // if declared outside, add parameter +- if (!ref._isDeclaredInSelection(element)) { +- // add parameter +- RefactoringMethodParameter parameter =3D ref._parametersMap[name]; +- if (parameter =3D=3D null) { +- DartType parameterType =3D node.bestType; +- StringBuffer parametersBuffer =3D new StringBuffer(); +- String parameterTypeCode =3D ref.utils.getTypeSource( +- parameterType, ref.librariesToImport, +- parametersBuffer: parametersBuffer); +- String parametersCode =3D +- parametersBuffer.isNotEmpty ? parametersBuffer.toString() := null; +- parameter =3D new RefactoringMethodParameter( +- RefactoringMethodParameterKind.REQUIRED, parameterTypeCode,= name, +- parameters: parametersCode, id: name); +- ref._parameters.add(parameter); +- ref._parametersMap[name] =3D parameter; +- } +- // add reference to parameter +- ref._addParameterReference(name, nodeRange); +- } +- // remember, if assigned and used after selection +- if (isLeftHandOfAssignment(node) && ref._isUsedAfterSelection(eleme= nt)) { +- if (!assignedUsedVariables.contains(element)) { +- assignedUsedVariables.add(element); +- } +- } +- } +- // remember information for conflicts checking +- if (element is LocalElement) { +- // declared local elements +- if (node.inDeclarationContext()) { +- ref._localNames.putIfAbsent(name, () =3D> []); +- ref._localNames[name].add(element.visibleRange); +- } +- } else { +- // unqualified non-local names +- if (!node.isQualified) { +- ref._unqualifiedNames.add(name); +- } +- } +- } +-} +- +-class _IsUsedAfterSelectionVisitor extends GeneralizingAstVisitor { +- final ExtractMethodRefactoringImpl ref; +- final Element element; +- bool result =3D false; +- +- _IsUsedAfterSelectionVisitor(this.ref, this.element); +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- Element nodeElement =3D node.staticElement; +- if (identical(nodeElement, element)) { +- int nodeOffset =3D node.offset; +- if (nodeOffset > ref.selectionRange.end) { +- result =3D true; +- } +- } +- } +-} +- +-/** +- * Description of a single occurrence of the selected expression or set of +- * statements. +- */ +-class _Occurrence { +- final SourceRange range; +- final bool isSelection; +- +- Map _parameterOldToOccurrenceName =3D {= }; +- +- _Occurrence(this.range, this.isSelection); +-} +- +-class _ReturnTypeComputer extends RecursiveAstVisitor { +- final TypeSystem typeSystem; +- +- DartType returnType; +- +- _ReturnTypeComputer(this.typeSystem); +- +- @override +- visitBlockFunctionBody(BlockFunctionBody node) {} +- +- @override +- visitReturnStatement(ReturnStatement node) { +- // prepare expression +- Expression expression =3D node.expression; +- if (expression =3D=3D null) { +- return; +- } +- // prepare type +- DartType type =3D expression.bestType; +- if (type.isBottom) { +- return; +- } +- // combine types +- if (returnType =3D=3D null) { +- returnType =3D type; +- } else { +- if (returnType is InterfaceType && type is InterfaceType) { +- returnType =3D InterfaceType.getSmartLeastUpperBound(returnType, = type); +- } else { +- returnType =3D typeSystem.getLeastUpperBound(returnType, type); +- } +- } +- } +-} +- +-/** +- * Generalized version of some source, in which references to the specific +- * variables are replaced with pattern variables, with back mapping from = the +- * pattern to the original variable names. +- */ +-class _SourcePattern { +- final List parameterTypes =3D []; +- String normalizedSource; +- Map originalToPatternNames =3D {}; +- +- bool isCompatible(_SourcePattern other) { +- if (other.normalizedSource !=3D normalizedSource) { +- return false; +- } +- if (other.parameterTypes.length !=3D parameterTypes.length) { +- return false; +- } +- for (int i =3D 0; i < parameterTypes.length; i++) { +- if (other.parameterTypes[i] !=3D parameterTypes[i]) { +- return false; +- } +- } +- return true; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/inline_local= .dart b/pkg/analysis_server/lib/src/services/refactoring/inline_local.dart +deleted file mode 100644 +index 586080a3afa..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/inline_local.dart ++++ /dev/null +@@ -1,213 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * [InlineLocalRefactoring] implementation. +- */ +-class InlineLocalRefactoringImpl extends RefactoringImpl +- implements InlineLocalRefactoring { +- final SearchEngine searchEngine; +- final AstProvider astProvider; +- final CompilationUnit unit; +- final int offset; +- CompilationUnitElement unitElement; +- CorrectionUtils utils; +- +- Element _variableElement; +- VariableDeclaration _variableNode; +- List _references; +- +- InlineLocalRefactoringImpl( +- this.searchEngine, this.astProvider, this.unit, this.offset) { +- unitElement =3D unit.element; +- utils =3D new CorrectionUtils(unit); +- } +- +- @override +- String get refactoringName =3D> 'Inline Local Variable'; +- +- @override +- int get referenceCount { +- if (_references =3D=3D null) { +- return 0; +- } +- return _references.length; +- } +- +- @override +- String get variableName { +- if (_variableElement =3D=3D null) { +- return null; +- } +- return _variableElement.name; +- } +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- Future checkInitialConditions() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- // prepare variable +- { +- AstNode offsetNode =3D new NodeLocator(offset).searchWithin(unit); +- if (offsetNode is SimpleIdentifier) { +- Element element =3D offsetNode.staticElement; +- if (element is LocalVariableElement) { +- _variableElement =3D element; +- AstNode name =3D await astProvider.getResolvedNameForElement(el= ement); +- _variableNode =3D name.parent as VariableDeclaration; +- } +- } +- } +- // validate node declaration +- if (!_isVariableDeclaredInStatement()) { +- result =3D new RefactoringStatus.fatal( +- 'Local variable declaration or reference must be selected ' +- 'to activate this refactoring.'); +- return new Future.value(result); +- } +- // should have initializer at declaration +- if (_variableNode.initializer =3D=3D null) { +- String message =3D format( +- "Local variable '{0}' is not initialized at declaration.", +- _variableElement.displayName); +- result =3D new RefactoringStatus.fatal( +- message, newLocation_fromNode(_variableNode)); +- return new Future.value(result); +- } +- // prepare references +- _references =3D await searchEngine.searchReferences(_variableElement); +- // should not have assignments +- for (SearchMatch reference in _references) { +- if (reference.kind !=3D MatchKind.READ) { +- String message =3D format( +- "Local variable '{0}' is assigned more than once.", +- [_variableElement.displayName]); +- return new RefactoringStatus.fatal( +- message, newLocation_fromMatch(reference)); +- } +- } +- // done +- return result; +- } +- +- @override +- Future createChange() { +- SourceChange change =3D new SourceChange(refactoringName); +- // remove declaration +- { +- Statement declarationStatement =3D _variableNode +- .getAncestor((node) =3D> node is VariableDeclarationStatement); +- SourceRange range =3D utils.getLinesRangeStatements([declarationSta= tement]); +- doSourceChange_addElementEdit( +- change, unitElement, newSourceEdit_range(range, '')); +- } +- // prepare initializer +- Expression initializer =3D _variableNode.initializer; +- String initializerCode =3D utils.getNodeText(initializer); +- // replace references +- for (SearchMatch reference in _references) { +- SourceRange editRange =3D reference.sourceRange; +- // prepare context +- int offset =3D editRange.offset; +- AstNode node =3D utils.findNode(offset); +- AstNode parent =3D node.parent; +- // prepare code +- String codeForReference; +- if (parent is InterpolationExpression) { +- StringInterpolation target =3D parent.parent; +- if (initializer is SingleStringLiteral && +- !initializer.isRaw && +- initializer.isSingleQuoted =3D=3D target.isSingleQuoted && +- (!initializer.isMultiline || target.isMultiline)) { +- editRange =3D range.node(parent); +- // unwrap the literal being inlined +- int initOffset =3D initializer.contentsOffset; +- int initLength =3D initializer.contentsEnd - initOffset; +- codeForReference =3D utils.getText(initOffset, initLength); +- } else if (_shouldBeExpressionInterpolation(parent, initializer))= { +- codeForReference =3D '{$initializerCode}'; +- } else { +- codeForReference =3D initializerCode; +- } +- } else if (_shouldUseParenthesis(initializer, node)) { +- codeForReference =3D '($initializerCode)'; +- } else { +- codeForReference =3D initializerCode; +- } +- // do replace +- doSourceChange_addElementEdit(change, unitElement, +- newSourceEdit_range(editRange, codeForReference)); +- } +- // done +- return new Future.value(change); +- } +- +- @override +- bool requiresPreview() =3D> false; +- +- bool _isVariableDeclaredInStatement() { +- if (_variableNode =3D=3D null) { +- return false; +- } +- AstNode parent =3D _variableNode.parent; +- if (parent is VariableDeclarationList) { +- parent =3D parent.parent; +- if (parent is VariableDeclarationStatement) { +- parent =3D parent.parent; +- return parent is Block || parent is SwitchCase; +- } +- } +- return false; +- } +- +- static bool _shouldBeExpressionInterpolation( +- InterpolationExpression target, Expression expression) { +- TokenType targetType =3D target.beginToken.type; +- return targetType =3D=3D TokenType.STRING_INTERPOLATION_IDENTIFIER && +- expression is! SimpleIdentifier; +- } +- +- static bool _shouldUseParenthesis(Expression init, AstNode node) { +- // check precedence +- int initPrecedence =3D getExpressionPrecedence(init); +- if (initPrecedence < getExpressionParentPrecedence(node)) { +- return true; +- } +- // special case for '-' +- AstNode parent =3D node.parent; +- if (init is PrefixExpression && parent is PrefixExpression) { +- if (parent.operator.type =3D=3D TokenType.MINUS) { +- TokenType initializerOperator =3D init.operator.type; +- if (initializerOperator =3D=3D TokenType.MINUS || +- initializerOperator =3D=3D TokenType.MINUS_MINUS) { +- return true; +- } +- } +- } +- // no () is needed +- return false; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/inline_metho= d.dart b/pkg/analysis_server/lib/src/services/refactoring/inline_method.dart +deleted file mode 100644 +index caf7a35f521..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/inline_method.dart ++++ /dev/null +@@ -1,880 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/utilities_dart.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * Returns the [SourceRange] to find conflicting locals in. +- */ +-SourceRange _getLocalsConflictingRange(AstNode node) { +- // maybe Block +- Block block =3D node.getAncestor((node) =3D> node is Block); +- if (block !=3D null) { +- return range.startEnd(node, block); +- } +- // maybe whole executable +- AstNode executableNode =3D getEnclosingExecutableNode(node); +- if (executableNode !=3D null) { +- return range.node(executableNode); +- } +- // not a part of a declaration with locals +- return SourceRange.EMPTY; +-} +- +-/** +- * Returns the source which should replace given invocation with given +- * arguments. +- */ +-String _getMethodSourceForInvocation( +- RefactoringStatus status, +- _SourcePart part, +- CorrectionUtils utils, +- AstNode contextNode, +- Expression targetExpression, +- List arguments) { +- // prepare edits to replace parameters with arguments +- List edits =3D []; +- part._parameters.forEach( +- (ParameterElement parameter, List<_ParameterOccurrence> occurrences= ) { +- // prepare argument +- Expression argument =3D null; +- for (Expression arg in arguments) { +- if (arg.bestParameterElement =3D=3D parameter) { +- argument =3D arg; +- break; +- } +- } +- if (argument is NamedExpression) { +- argument =3D (argument as NamedExpression).expression; +- } +- // prepare argument properties +- int argumentPrecedence; +- String argumentSource; +- if (argument !=3D null) { +- argumentPrecedence =3D getExpressionPrecedence(argument); +- argumentSource =3D utils.getNodeText(argument); +- } else { +- // report about a missing required parameter +- if (parameter.parameterKind =3D=3D ParameterKind.REQUIRED) { +- status.addError('No argument for the parameter "${parameter.name}= ".', +- newLocation_fromNode(contextNode)); +- return; +- } +- // an optional parameter +- argumentPrecedence =3D -1000; +- argumentSource =3D parameter.defaultValueCode; +- if (argumentSource =3D=3D null) { +- argumentSource =3D 'null'; +- } +- } +- // replace all occurrences of this parameter +- for (_ParameterOccurrence occurrence in occurrences) { +- SourceRange range =3D occurrence.range; +- // prepare argument source to apply at this occurrence +- String occurrenceArgumentSource; +- if (argumentPrecedence < occurrence.parentPrecedence) { +- occurrenceArgumentSource =3D "($argumentSource)"; +- } else { +- occurrenceArgumentSource =3D argumentSource; +- } +- // do replace +- edits.add(newSourceEdit_range(range, occurrenceArgumentSource)); +- } +- }); +- // replace static field "qualifier" with invocation target +- part._implicitClassNameOffsets.forEach((String className, List off= sets) { +- for (int offset in offsets) { +-// edits.add(newSourceEdit_range(range, className + '.')); +- edits.add(new SourceEdit(offset, 0, className + '.')); +- } +- }); +- // replace "this" references with invocation target +- if (targetExpression !=3D null) { +- String targetSource =3D utils.getNodeText(targetExpression); +- // explicit "this" references +- for (int offset in part._explicitThisOffsets) { +- edits.add(new SourceEdit(offset, 4, targetSource)); +- } +- // implicit "this" references +- targetSource +=3D '.'; +- for (int offset in part._implicitThisOffsets) { +- edits.add(new SourceEdit(offset, 0, targetSource)); +- } +- } +- // prepare edits to replace conflicting variables +- Set conflictingNames =3D _getNamesConflictingAt(contextNode); +- part._variables.forEach((VariableElement variable, List ra= nges) { +- String originalName =3D variable.displayName; +- // prepare unique name +- String uniqueName; +- { +- uniqueName =3D originalName; +- int uniqueIndex =3D 2; +- while (conflictingNames.contains(uniqueName)) { +- uniqueName =3D originalName + uniqueIndex.toString(); +- uniqueIndex++; +- } +- } +- // update references, if name was change +- if (uniqueName !=3D originalName) { +- for (SourceRange range in ranges) { +- edits.add(newSourceEdit_range(range, uniqueName)); +- } +- } +- }); +- // prepare source with applied arguments +- edits.sort((SourceEdit a, SourceEdit b) =3D> b.offset - a.offset); +- return SourceEdit.applySequence(part._source, edits); +-} +- +-/** +- * Returns the names which will shadow or will be shadowed by any declara= tion +- * at [node]. +- */ +-Set _getNamesConflictingAt(AstNode node) { +- Set result =3D new Set(); +- // local variables and functions +- { +- SourceRange localsRange =3D _getLocalsConflictingRange(node); +- AstNode enclosingExecutable =3D getEnclosingExecutableNode(node); +- List elements =3D getDefinedLocalElements(enclosingExec= utable); +- for (LocalElement element in elements) { +- SourceRange elementRange =3D element.visibleRange; +- if (elementRange !=3D null && elementRange.intersects(localsRange))= { +- result.add(element.displayName); +- } +- } +- } +- // fields +- { +- ClassElement enclosingClassElement =3D getEnclosingClassElement(node); +- if (enclosingClassElement !=3D null) { +- Set elements =3D new Set(); +- elements.add(enclosingClassElement); +- elements.addAll(getSuperClasses(enclosingClassElement)); +- for (ClassElement classElement in elements) { +- List classMembers =3D getChildren(classElement); +- for (Element classMemberElement in classMembers) { +- result.add(classMemberElement.displayName); +- } +- } +- } +- } +- // done +- return result; +-} +- +-/** +- * [InlineMethodRefactoring] implementation. +- */ +-class InlineMethodRefactoringImpl extends RefactoringImpl +- implements InlineMethodRefactoring { +- final SearchEngine searchEngine; +- final AstProvider astProvider; +- final CompilationUnit unit; +- final int offset; +- ResolvedUnitCache _unitCache; +- CorrectionUtils utils; +- SourceChange change; +- +- bool isDeclaration =3D false; +- bool deleteSource =3D false; +- bool inlineAll =3D true; +- +- ExecutableElement _methodElement; +- bool _isAccessor; +- CompilationUnit _methodUnit; +- CorrectionUtils _methodUtils; +- AstNode _methodNode; +- FormalParameterList _methodParameters; +- FunctionBody _methodBody; +- Expression _methodExpression; +- _SourcePart _methodExpressionPart; +- _SourcePart _methodStatementsPart; +- List<_ReferenceProcessor> _referenceProcessors =3D []; +- Set _alreadyMadeAsync =3D new Set(); +- +- InlineMethodRefactoringImpl( +- this.searchEngine, this.astProvider, this.unit, this.offset) { +- _unitCache =3D new ResolvedUnitCache(astProvider, unit); +- utils =3D new CorrectionUtils(unit); +- } +- +- @override +- String get className { +- if (_methodElement =3D=3D null) { +- return null; +- } +- Element classElement =3D _methodElement.enclosingElement; +- if (classElement is ClassElement) { +- return classElement.displayName; +- } +- return null; +- } +- +- @override +- String get methodName { +- if (_methodElement =3D=3D null) { +- return null; +- } +- return _methodElement.displayName; +- } +- +- @override +- String get refactoringName { +- if (_methodElement is MethodElement) { +- return "Inline Method"; +- } else { +- return "Inline Function"; +- } +- } +- +- @override +- Future checkFinalConditions() { +- change =3D new SourceChange(refactoringName); +- RefactoringStatus result =3D new RefactoringStatus(); +- // check for compatibility of "deleteSource" and "inlineAll" +- if (deleteSource && !inlineAll) { +- result.addError('All references must be inlined to remove the sourc= e.'); +- } +- // prepare changes +- for (_ReferenceProcessor processor in _referenceProcessors) { +- processor._process(result); +- } +- // delete method +- if (deleteSource && inlineAll) { +- SourceRange methodRange =3D range.node(_methodNode); +- SourceRange linesRange =3D +- _methodUtils.getLinesRange(methodRange, skipLeadingEmptyLines: = true); +- doSourceChange_addElementEdit( +- change, _methodElement, newSourceEdit_range(linesRange, '')); +- } +- // done +- return new Future.value(result); +- } +- +- @override +- Future checkInitialConditions() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- // prepare method information +- result.addStatus(await _prepareMethod()); +- if (result.hasFatalError) { +- return new Future.value(result); +- } +- // maybe operator +- if (_methodElement.isOperator) { +- result =3D new RefactoringStatus.fatal('Cannot inline operator.'); +- return new Future.value(result); +- } +- // maybe [a]sync* +- if (_methodElement.isGenerator) { +- result =3D new RefactoringStatus.fatal('Cannot inline a generator.'= ); +- return new Future.value(result); +- } +- // analyze method body +- result.addStatus(_prepareMethodParts()); +- // process references +- List references =3D +- await searchEngine.searchReferences(_methodElement); +- _referenceProcessors.clear(); +- for (SearchMatch reference in references) { +- _ReferenceProcessor processor =3D new _ReferenceProcessor(this, ref= erence); +- await processor.init(); +- _referenceProcessors.add(processor); +- } +- return result; +- } +- +- @override +- Future createChange() { +- return new Future.value(change); +- } +- +- @override +- bool requiresPreview() =3D> false; +- +- Future _computeFunctionDeclaration() async { +- CompilationUnit unit =3D await _unitCache.getUnit(_methodElement); +- return new NodeLocator(_methodElement.nameOffset) +- .searchWithin(unit) +- .getAncestor((n) =3D> n is FunctionDeclaration) as FunctionDeclar= ation; +- } +- +- Future _computeMethodDeclaration() async { +- CompilationUnit unit =3D await _unitCache.getUnit(_methodElement); +- return new NodeLocator(_methodElement.nameOffset) +- .searchWithin(unit) +- .getAncestor((n) =3D> n is MethodDeclaration) as MethodDeclaratio= n; +- } +- +- _SourcePart _createSourcePart(SourceRange range) { +- String source =3D _methodUtils.getRangeText(range); +- String prefix =3D getLinePrefix(source); +- _SourcePart result =3D new _SourcePart(range.offset, source, prefix); +- // remember parameters and variables occurrences +- _methodUnit.accept(new _VariablesVisitor(_methodElement, range, resul= t)); +- // done +- return result; +- } +- +- /** +- * Initializes [_methodElement] and related fields. +- */ +- Future _prepareMethod() async { +- _methodElement =3D null; +- _methodParameters =3D null; +- _methodBody =3D null; +- deleteSource =3D false; +- inlineAll =3D false; +- // prepare for failure +- RefactoringStatus fatalStatus =3D new RefactoringStatus.fatal( +- 'Method declaration or reference must be selected to activate thi= s refactoring.'); +- // prepare selected SimpleIdentifier +- AstNode node =3D new NodeLocator(offset).searchWithin(unit); +- if (node is! SimpleIdentifier) { +- return fatalStatus; +- } +- SimpleIdentifier identifier =3D node as SimpleIdentifier; +- // prepare selected ExecutableElement +- Element element =3D identifier.bestElement; +- if (element is! ExecutableElement) { +- return fatalStatus; +- } +- if (element.isSynthetic) { +- return fatalStatus; +- } +- _methodElement =3D element as ExecutableElement; +- _isAccessor =3D element is PropertyAccessorElement; +- _methodUnit =3D await _unitCache.getUnit(element); +- _methodUtils =3D new CorrectionUtils(_methodUnit); +- // class member +- bool isClassMember =3D element.enclosingElement is ClassElement; +- if (element is MethodElement || _isAccessor && isClassMember) { +- MethodDeclaration methodDeclaration =3D await _computeMethodDeclara= tion(); +- _methodNode =3D methodDeclaration; +- _methodParameters =3D methodDeclaration.parameters; +- _methodBody =3D methodDeclaration.body; +- // prepare mode +- isDeclaration =3D node =3D=3D methodDeclaration.name; +- deleteSource =3D isDeclaration; +- inlineAll =3D deleteSource; +- return new RefactoringStatus(); +- } +- // unit member +- bool isUnitMember =3D element.enclosingElement is CompilationUnitElem= ent; +- if (element is FunctionElement || _isAccessor && isUnitMember) { +- FunctionDeclaration functionDeclaration =3D +- await _computeFunctionDeclaration(); +- _methodNode =3D functionDeclaration; +- _methodParameters =3D functionDeclaration.functionExpression.parame= ters; +- _methodBody =3D functionDeclaration.functionExpression.body; +- // prepare mode +- isDeclaration =3D node =3D=3D functionDeclaration.name; +- deleteSource =3D isDeclaration; +- inlineAll =3D deleteSource; +- return new RefactoringStatus(); +- } +- // OK +- return fatalStatus; +- } +- +- /** +- * Analyze [_methodBody] to fill [_methodExpressionPart] and +- * [_methodStatementsPart]. +- */ +- RefactoringStatus _prepareMethodParts() { +- RefactoringStatus result =3D new RefactoringStatus(); +- if (_methodBody is ExpressionFunctionBody) { +- ExpressionFunctionBody body =3D _methodBody as ExpressionFunctionBo= dy; +- _methodExpression =3D body.expression; +- SourceRange methodExpressionRange =3D range.node(_methodExpression); +- _methodExpressionPart =3D _createSourcePart(methodExpressionRange); +- } else if (_methodBody is BlockFunctionBody) { +- Block body =3D (_methodBody as BlockFunctionBody).block; +- List statements =3D body.statements; +- if (statements.length >=3D 1) { +- Statement lastStatement =3D statements[statements.length - 1]; +- // "return" statement requires special handling +- if (lastStatement is ReturnStatement) { +- _methodExpression =3D lastStatement.expression; +- SourceRange methodExpressionRange =3D range.node(_methodExpress= ion); +- _methodExpressionPart =3D _createSourcePart(methodExpressionRan= ge); +- // exclude "return" statement from statements +- statements =3D statements.sublist(0, statements.length - 1); +- } +- // if there are statements, process them +- if (!statements.isEmpty) { +- SourceRange statementsRange =3D +- _methodUtils.getLinesRangeStatements(statements); +- _methodStatementsPart =3D _createSourcePart(statementsRange); +- } +- } +- // check if more than one return +- body.accept(new _ReturnsValidatorVisitor(result)); +- } else { +- return new RefactoringStatus.fatal('Cannot inline method without bo= dy.'); +- } +- return result; +- } +-} +- +-class _ParameterOccurrence { +- final int parentPrecedence; +- final SourceRange range; +- _ParameterOccurrence(this.parentPrecedence, this.range); +-} +- +-/** +- * Processor for single [SearchMatch] reference to [methodElement]. +- */ +-class _ReferenceProcessor { +- final InlineMethodRefactoringImpl ref; +- final SearchMatch reference; +- +- Element refElement; +- CorrectionUtils _refUtils; +- SimpleIdentifier _node; +- SourceRange _refLineRange; +- String _refPrefix; +- +- _ReferenceProcessor(this.ref, this.reference); +- +- Future init() async { +- refElement =3D reference.element; +- // prepare CorrectionUtils +- CompilationUnit refUnit =3D await ref._unitCache.getUnit(refElement); +- _refUtils =3D new CorrectionUtils(refUnit); +- // prepare node and environment +- _node =3D _refUtils.findNode(reference.sourceRange.offset); +- Statement refStatement =3D _node.getAncestor((node) =3D> node is Stat= ement); +- if (refStatement !=3D null) { +- _refLineRange =3D _refUtils.getLinesRangeStatements([refStatement]); +- _refPrefix =3D _refUtils.getNodePrefix(refStatement); +- } else { +- _refLineRange =3D null; +- _refPrefix =3D _refUtils.getLinePrefix(_node.offset); +- } +- } +- +- void _addRefEdit(SourceEdit edit) { +- doSourceChange_addElementEdit(ref.change, refElement, edit); +- } +- +- bool _canInlineBody(AstNode usage) { +- // no statements, usually just expression +- if (ref._methodStatementsPart =3D=3D null) { +- // empty method, inline as closure +- if (ref._methodExpressionPart =3D=3D null) { +- return false; +- } +- // OK, just expression +- return true; +- } +- // analyze point of invocation +- AstNode parent =3D usage.parent; +- AstNode parent2 =3D parent.parent; +- // OK, if statement in block +- if (parent is Statement) { +- return parent2 is Block; +- } +- // maybe assignment, in block +- if (parent is AssignmentExpression) { +- AssignmentExpression assignment =3D parent; +- // inlining setter +- if (assignment.leftHandSide =3D=3D usage) { +- return parent2 is Statement && parent2.parent is Block; +- } +- // inlining initializer +- return ref._methodExpressionPart !=3D null; +- } +- // maybe value for variable initializer, in block +- if (ref._methodExpressionPart !=3D null) { +- if (parent is VariableDeclaration) { +- if (parent2 is VariableDeclarationList) { +- AstNode parent3 =3D parent2.parent; +- return parent3 is VariableDeclarationStatement && +- parent3.parent is Block; +- } +- } +- } +- // not in block, cannot inline body +- return false; +- } +- +- void _inlineMethodInvocation(RefactoringStatus status, Expression usage, +- bool cascaded, Expression target, List arguments) { +- // we don't support cascade +- if (cascaded) { +- status.addError( +- 'Cannot inline cascade invocation.', newLocation_fromNode(usage= )); +- } +- // can we inline method body into "methodUsage" block? +- if (_canInlineBody(usage)) { +- // insert non-return statements +- if (ref._methodStatementsPart !=3D null) { +- // prepare statements source for invocation +- String source =3D _getMethodSourceForInvocation(status, +- ref._methodStatementsPart, _refUtils, usage, target, argument= s); +- source =3D _refUtils.replaceSourceIndent( +- source, ref._methodStatementsPart._prefix, _refPrefix); +- // do insert +- SourceEdit edit =3D newSourceEdit_range( +- new SourceRange(_refLineRange.offset, 0), source); +- _addRefEdit(edit); +- } +- // replace invocation with return expression +- if (ref._methodExpressionPart !=3D null) { +- // prepare expression source for invocation +- String source =3D _getMethodSourceForInvocation(status, +- ref._methodExpressionPart, _refUtils, usage, target, argument= s); +- if (getExpressionPrecedence(ref._methodExpression) < +- getExpressionParentPrecedence(usage)) { +- source =3D "($source)"; +- } +- // do replace +- SourceRange methodUsageRange =3D range.node(usage); +- SourceEdit edit =3D newSourceEdit_range(methodUsageRange, source); +- _addRefEdit(edit); +- } else { +- SourceEdit edit =3D newSourceEdit_range(_refLineRange, ""); +- _addRefEdit(edit); +- } +- return; +- } +- // inline as closure invocation +- String source; +- { +- source =3D ref._methodUtils.getRangeText(range.startEnd( +- ref._methodParameters.leftParenthesis, ref._methodNode)); +- String methodPrefix =3D +- ref._methodUtils.getLinePrefix(ref._methodNode.offset); +- source =3D _refUtils.replaceSourceIndent(source, methodPrefix, _ref= Prefix); +- source =3D source.trim(); +- } +- // do insert +- SourceEdit edit =3D newSourceEdit_range(range.node(_node), source); +- _addRefEdit(edit); +- } +- +- void _process(RefactoringStatus status) { +- AstNode nodeParent =3D _node.parent; +- // may be only single place should be inlined +- if (!_shouldProcess()) { +- return; +- } +- // If the element being inlined is async, ensure that the function +- // body that encloses the method is also async. +- if (ref._methodElement.isAsynchronous) { +- FunctionBody body =3D _node.getAncestor((n) =3D> n is FunctionBody); +- if (body !=3D null) { +- if (body.isSynchronous) { +- if (body.isGenerator) { +- status.addFatalError( +- 'Cannot inline async into sync*.', newLocation_fromNode(_= node)); +- return; +- } +- if (refElement is ExecutableElement) { +- var executable =3D refElement as ExecutableElement; +- if (!executable.returnType.isDartAsyncFuture) { +- status.addFatalError( +- 'Cannot inline async into a function that does not retu= rn a Future.', +- newLocation_fromNode(_node)); +- return; +- } +- } +- if (ref._alreadyMadeAsync.add(body)) { +- SourceRange bodyStart =3D range.startLength(body, 0); +- _addRefEdit(newSourceEdit_range(bodyStart, 'async ')); +- } +- } +- } +- } +- // may be invocation of inline method +- if (nodeParent is MethodInvocation) { +- MethodInvocation invocation =3D nodeParent; +- Expression target =3D invocation.target; +- List arguments =3D invocation.argumentList.arguments; +- _inlineMethodInvocation( +- status, invocation, invocation.isCascaded, target, arguments); +- } else { +- // cannot inline reference to method: var v =3D new A().method; +- if (ref._methodElement is MethodElement) { +- status.addFatalError('Cannot inline class method reference.', +- newLocation_fromNode(_node)); +- return; +- } +- // PropertyAccessorElement +- if (ref._methodElement is PropertyAccessorElement) { +- Expression usage =3D _node; +- Expression target =3D null; +- bool cascade =3D false; +- if (nodeParent is PrefixedIdentifier) { +- PrefixedIdentifier propertyAccess =3D nodeParent; +- usage =3D propertyAccess; +- target =3D propertyAccess.prefix; +- cascade =3D false; +- } +- if (nodeParent is PropertyAccess) { +- PropertyAccess propertyAccess =3D nodeParent; +- usage =3D propertyAccess; +- target =3D propertyAccess.realTarget; +- cascade =3D propertyAccess.isCascaded; +- } +- // prepare arguments +- List arguments =3D []; +- if (_node.inSetterContext()) { +- AssignmentExpression assignment =3D +- _node.getAncestor((node) =3D> node is AssignmentExpression); +- arguments.add(assignment.rightHandSide); +- } +- // inline body +- _inlineMethodInvocation(status, usage, cascade, target, arguments= ); +- return; +- } +- // not invocation, just reference to function +- String source; +- { +- source =3D ref._methodUtils.getRangeText(range.startEnd( +- ref._methodParameters.leftParenthesis, ref._methodNode)); +- String methodPrefix =3D +- ref._methodUtils.getLinePrefix(ref._methodNode.offset); +- source =3D +- _refUtils.replaceSourceIndent(source, methodPrefix, _refPrefi= x); +- source =3D source.trim(); +- source =3D removeEnd(source, ';'); +- } +- // do insert +- SourceEdit edit =3D newSourceEdit_range(range.node(_node), source); +- _addRefEdit(edit); +- } +- } +- +- bool _shouldProcess() { +- if (!ref.inlineAll) { +- SourceRange parentRange =3D range.node(_node); +- return parentRange.contains(ref.offset); +- } +- return true; +- } +-} +- +-class _ReturnsValidatorVisitor extends RecursiveAstVisitor { +- final RefactoringStatus result; +- int _numReturns =3D 0; +- +- _ReturnsValidatorVisitor(this.result); +- +- @override +- visitReturnStatement(ReturnStatement node) { +- _numReturns++; +- if (_numReturns =3D=3D 2) { +- result.addError('Ambiguous return value.', newLocation_fromNode(nod= e)); +- } +- } +-} +- +-/** +- * Information about the source of a method being inlined. +- */ +-class _SourcePart { +- /** +- * The base for all [SourceRange]s. +- */ +- final int _base; +- +- /** +- * The source of the method. +- */ +- final String _source; +- +- /** +- * The original prefix of the method. +- */ +- final String _prefix; +- +- /** +- * The occurrences of the method parameters. +- */ +- final Map> _parameters =3D= {}; +- +- /** +- * The occurrences of the method local variables. +- */ +- final Map> _variables =3D {}; +- +- /** +- * The offsets of explicit `this` expression references. +- */ +- final List _explicitThisOffsets =3D []; +- +- /** +- * The offsets of implicit `this` expression references. +- */ +- final List _implicitThisOffsets =3D []; +- +- /** +- * The offsets of the implicit class references in static member refere= nces. +- */ +- final Map> _implicitClassNameOffsets =3D {}; +- +- _SourcePart(this._base, this._source, this._prefix); +- +- void addExplicitThisOffset(int offset) { +- _explicitThisOffsets.add(offset - _base); +- } +- +- void addImplicitClassNameOffset(String className, int offset) { +- List offsets =3D _implicitClassNameOffsets[className]; +- if (offsets =3D=3D null) { +- offsets =3D []; +- _implicitClassNameOffsets[className] =3D offsets; +- } +- offsets.add(offset - _base); +- } +- +- void addImplicitThisOffset(int offset) { +- _implicitThisOffsets.add(offset - _base); +- } +- +- void addParameterOccurrence( +- ParameterElement parameter, SourceRange identifierRange, int preced= ence) { +- if (parameter !=3D null) { +- List<_ParameterOccurrence> occurrences =3D _parameters[parameter]; +- if (occurrences =3D=3D null) { +- occurrences =3D []; +- _parameters[parameter] =3D occurrences; +- } +- identifierRange =3D range.offsetBy(identifierRange, -_base); +- occurrences.add(new _ParameterOccurrence(precedence, identifierRang= e)); +- } +- } +- +- void addVariable(VariableElement element, SourceRange identifierRange) { +- List ranges =3D _variables[element]; +- if (ranges =3D=3D null) { +- ranges =3D []; +- _variables[element] =3D ranges; +- } +- identifierRange =3D range.offsetBy(identifierRange, -_base); +- ranges.add(identifierRange); +- } +-} +- +-/** +- * A visitor that fills [_SourcePart] with fields, parameters and variabl= es. +- */ +-class _VariablesVisitor extends GeneralizingAstVisitor { +- /** +- * The [ExecutableElement] being inlined. +- */ +- final ExecutableElement methodElement; +- +- /** +- * The [SourceRange] of the element body. +- */ +- SourceRange bodyRange; +- +- /** +- * The [_SourcePart] to record reference into. +- */ +- _SourcePart result; +- +- int offset; +- +- _VariablesVisitor(this.methodElement, this.bodyRange, this.result); +- +- @override +- visitNode(AstNode node) { +- SourceRange nodeRange =3D range.node(node); +- if (!bodyRange.intersects(nodeRange)) { +- return null; +- } +- super.visitNode(node); +- } +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- SourceRange nodeRange =3D range.node(node); +- if (bodyRange.covers(nodeRange)) { +- _addMemberQualifier(node); +- _addParameter(node); +- _addVariable(node); +- } +- } +- +- @override +- visitThisExpression(ThisExpression node) { +- int offset =3D node.offset; +- if (bodyRange.contains(offset)) { +- result.addExplicitThisOffset(offset); +- } +- } +- +- void _addMemberQualifier(SimpleIdentifier node) { +- // should be unqualified +- AstNode qualifier =3D getNodeQualifier(node); +- if (qualifier !=3D null) { +- return; +- } +- // should be a method or field reference +- Element element =3D node.staticElement; +- if (!(element is MethodElement || element is PropertyAccessorElement)= ) { +- return; +- } +- if (element.enclosingElement is! ClassElement) { +- return; +- } +- // record the implicit static or instance reference +- ExecutableElement member =3D element; +- int offset =3D node.offset; +- if (member.isStatic) { +- String className =3D member.enclosingElement.displayName; +- result.addImplicitClassNameOffset(className, offset); +- } else { +- result.addImplicitThisOffset(offset); +- } +- } +- +- void _addParameter(SimpleIdentifier node) { +- ParameterElement parameterElement =3D getParameterElement(node); +- // not a parameter +- if (parameterElement =3D=3D null) { +- return; +- } +- // not a parameter of the function being inlined +- if (!methodElement.parameters.contains(parameterElement)) { +- return; +- } +- // OK, add occurrence +- SourceRange nodeRange =3D range.node(node); +- int parentPrecedence =3D getExpressionParentPrecedence(node); +- result.addParameterOccurrence( +- parameterElement, nodeRange, parentPrecedence); +- } +- +- void _addVariable(SimpleIdentifier node) { +- VariableElement variableElement =3D getLocalVariableElement(node); +- if (variableElement !=3D null) { +- SourceRange nodeRange =3D range.node(node); +- result.addVariable(variableElement, nodeRange); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/naming_conve= ntions.dart b/pkg/analysis_server/lib/src/services/refactoring/naming_conve= ntions.dart +deleted file mode 100644 +index 7691fbb32fe..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/naming_conventions.= dart ++++ /dev/null +@@ -1,263 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +-import 'package:front_end/src/scanner/token.dart' show Keyword; +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateClassName(String name) { +- return _validateUpperCamelCase(name, "Class"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateConstructorName(String name) { +- if (name !=3D null && name.isEmpty) { +- return new RefactoringStatus(); +- } +- return _validateLowerCamelCase(name, "Constructor"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateFieldName(String name) { +- return _validateLowerCamelCase(name, "Field"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateFunctionName(String name) { +- return _validateLowerCamelCase(name, "Function"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateFunctionTypeAliasName(String name) { +- return _validateUpperCamelCase(name, "Function type alias"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateImportPrefixName(String name) { +- if (name !=3D null && name.isEmpty) { +- return new RefactoringStatus(); +- } +- return _validateLowerCamelCase(name, "Import prefix"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateLabelName(String name) { +- return _validateLowerCamelCase(name, "Label"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateLibraryName(String name) { +- // null +- if (name =3D=3D null) { +- return new RefactoringStatus.fatal("Library name must not be null."); +- } +- // blank +- if (isBlank(name)) { +- return new RefactoringStatus.fatal("Library name must not be blank."); +- } +- // check identifiers +- List identifiers =3D name.split('.'); +- for (String identifier in identifiers) { +- RefactoringStatus status =3D _validateIdentifier(identifier, +- "Library name identifier", "a lowercase letter or underscore"); +- if (!status.isOK) { +- return status; +- } +- } +- // should not have upper-case letters +- for (String identifier in identifiers) { +- for (int c in identifier.codeUnits) { +- if (isUpperCase(c)) { +- return new RefactoringStatus.warning( +- "Library name should consist of lowercase identifier separate= d by dots."); +- } +- } +- } +- // OK +- return new RefactoringStatus(); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateMethodName(String name) { +- return _validateLowerCamelCase(name, "Method"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateParameterName(String name) { +- return _validateLowerCamelCase(name, "Parameter"); +-} +- +-/** +- * Returns the [RefactoringStatus] with severity: +- * OK if the name is valid; +- * WARNING if the name is discouraged; +- * FATAL if the name is illegal. +- */ +-RefactoringStatus validateVariableName(String name) { +- return _validateLowerCamelCase(name, "Variable"); +-} +- +-RefactoringStatus _validateIdentifier( +- String identifier, String desc, String beginDesc) { +- // has leading/trailing spaces +- String trimmed =3D identifier.trim(); +- if (identifier !=3D trimmed) { +- String message =3D "$desc must not start or end with a blank."; +- return new RefactoringStatus.fatal(message); +- } +- // empty +- int length =3D identifier.length; +- if (length =3D=3D 0) { +- String message =3D "$desc must not be empty."; +- return new RefactoringStatus.fatal(message); +- } +- // keyword +- { +- Keyword keyword =3D Keyword.keywords[identifier]; +- if (keyword !=3D null) { +- String message =3D "$desc must not be a keyword."; +- return new RefactoringStatus.fatal(message); +- } +- } +- // first character +- int currentChar =3D identifier.codeUnitAt(0); +- if (!isLetter(currentChar) && +- currentChar !=3D CHAR_UNDERSCORE && +- currentChar !=3D CHAR_DOLLAR) { +- String message =3D "$desc must begin with $beginDesc."; +- return new RefactoringStatus.fatal(message); +- } +- // other characters +- for (int i =3D 1; i < length; i++) { +- currentChar =3D identifier.codeUnitAt(i); +- if (!isLetterOrDigit(currentChar) && +- currentChar !=3D CHAR_UNDERSCORE && +- currentChar !=3D CHAR_DOLLAR) { +- String charStr =3D new String.fromCharCode(currentChar); +- String message =3D "$desc must not contain '$charStr'."; +- return new RefactoringStatus.fatal(message); +- } +- } +- // OK +- return new RefactoringStatus(); +-} +- +-/** +- * Validates [identifier], should be lower camel case. +- */ +-RefactoringStatus _validateLowerCamelCase(String identifier, String desc)= { +- desc +=3D ' name'; +- // null +- if (identifier =3D=3D null) { +- String message =3D "$desc must not be null."; +- return new RefactoringStatus.fatal(message); +- } +- // is not identifier +- RefactoringStatus status =3D +- _validateIdentifier(identifier, desc, "a lowercase letter or unders= core"); +- if (!status.isOK) { +- return status; +- } +- // is private, OK +- if (identifier.codeUnitAt(0) =3D=3D CHAR_UNDERSCORE) { +- return new RefactoringStatus(); +- } +- // leading $, OK +- if (identifier.codeUnitAt(0) =3D=3D CHAR_DOLLAR) { +- return new RefactoringStatus(); +- } +- // does not start with lower case +- if (!isLowerCase(identifier.codeUnitAt(0))) { +- String message =3D "$desc should start with a lowercase letter."; +- return new RefactoringStatus.warning(message); +- } +- // OK +- return new RefactoringStatus(); +-} +- +-/** +- * Validate the given identifier, which should be upper camel case. +- */ +-RefactoringStatus _validateUpperCamelCase(String identifier, String desc)= { +- desc +=3D ' name'; +- // null +- if (identifier =3D=3D null) { +- String message =3D "$desc must not be null."; +- return new RefactoringStatus.fatal(message); +- } +- // is not identifier +- RefactoringStatus status =3D _validateIdentifier( +- identifier, desc, "an uppercase letter or underscore"); +- if (!status.isOK) { +- return status; +- } +- // is private, OK +- if (identifier.codeUnitAt(0) =3D=3D CHAR_UNDERSCORE) { +- return new RefactoringStatus(); +- } +- // leading $, OK +- if (identifier.codeUnitAt(0) =3D=3D CHAR_DOLLAR) { +- return new RefactoringStatus(); +- } +- // does not start with upper case +- if (!isUpperCase(identifier.codeUnitAt(0))) { +- // By convention, class names usually start with an uppercase letter +- String message =3D "$desc should start with an uppercase letter."; +- return new RefactoringStatus.warning(message); +- } +- // OK +- return new RefactoringStatus(); +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/refactoring.= dart b/pkg/analysis_server/lib/src/services/refactoring/refactoring.dart +deleted file mode 100644 +index 1e51c6fd526..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/refactoring.dart ++++ /dev/null +@@ -1,444 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/convert_getter_t= o_method.dart'; +-import 'package:analysis_server/src/services/refactoring/convert_method_t= o_getter.dart'; +-import 'package:analysis_server/src/services/refactoring/extract_local.da= rt'; +-import 'package:analysis_server/src/services/refactoring/extract_method.d= art'; +-import 'package:analysis_server/src/services/refactoring/inline_local.dar= t'; +-import 'package:analysis_server/src/services/refactoring/inline_method.da= rt'; +-import 'package:analysis_server/src/services/refactoring/rename_class_mem= ber.dart'; +-import 'package:analysis_server/src/services/refactoring/rename_construct= or.dart'; +-import 'package:analysis_server/src/services/refactoring/rename_import.da= rt'; +-import 'package:analysis_server/src/services/refactoring/rename_label.dar= t'; +-import 'package:analysis_server/src/services/refactoring/rename_library.d= art'; +-import 'package:analysis_server/src/services/refactoring/rename_local.dar= t'; +-import 'package:analysis_server/src/services/refactoring/rename_unit_memb= er.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show RefactoringMethodParameter, SourceChange; +- +-/** +- * [Refactoring] to convert getters into normal [MethodDeclaration]s. +- */ +-abstract class ConvertGetterToMethodRefactoring implements Refactoring { +- /** +- * Returns a new [ConvertMethodToGetterRefactoring] instance for conver= ting +- * [element] and all the corresponding hierarchy elements. +- */ +- factory ConvertGetterToMethodRefactoring(SearchEngine searchEngine, +- AstProvider astProvider, PropertyAccessorElement element) { +- return new ConvertGetterToMethodRefactoringImpl( +- searchEngine, astProvider, element); +- } +-} +- +-/** +- * [Refactoring] to convert normal [MethodDeclaration]s into getters. +- */ +-abstract class ConvertMethodToGetterRefactoring implements Refactoring { +- /** +- * Returns a new [ConvertMethodToGetterRefactoring] instance for conver= ting +- * [element] and all the corresponding hierarchy elements. +- */ +- factory ConvertMethodToGetterRefactoring(SearchEngine searchEngine, +- AstProvider astProvider, ExecutableElement element) { +- return new ConvertMethodToGetterRefactoringImpl( +- searchEngine, astProvider, element); +- } +-} +- +-/** +- * [Refactoring] to extract an expression into a local variable declarati= on. +- */ +-abstract class ExtractLocalRefactoring implements Refactoring { +- /** +- * Returns a new [ExtractLocalRefactoring] instance. +- */ +- factory ExtractLocalRefactoring( +- CompilationUnit unit, int selectionOffset, int selectionLength) { +- return new ExtractLocalRefactoringImpl( +- unit, selectionOffset, selectionLength); +- } +- +- /** +- * The lengths of the expressions that cover the specified selection, +- * from the down most to the up most. +- */ +- List get coveringExpressionLengths; +- +- /** +- * The offsets of the expressions that cover the specified selection, +- * from the down most to the up most. +- */ +- List get coveringExpressionOffsets; +- +- /** +- * True if all occurrences of the expression within the scope in which = the +- * variable will be defined should be replaced by a reference to the lo= cal +- * variable. The expression used to initiate the refactoring will alway= s be +- * replaced. +- */ +- void set extractAll(bool extractAll); +- +- /** +- * The lengths of the expressions that would be replaced by a reference= to the +- * variable. The lengths correspond to the offsets. In other words, for= a +- * given expression, if the offset of that expression is offsets[i], th= en the +- * length of that expression is lengths[i]. +- */ +- List get lengths; +- +- /** +- * The name that the local variable should be given. +- */ +- void set name(String name); +- +- /** +- * The proposed names for the local variable. +- * +- * The first proposal should be used as the "best guess" (if it exists). +- */ +- List get names; +- +- /** +- * The offsets of the expressions that would be replaced by a reference= to +- * the variable. +- */ +- List get offsets; +- +- /** +- * Validates that the [name] is a valid identifier and is appropriate f= or +- * local variable. +- * +- * It does not perform all the checks (such as checking for conflicts w= ith any +- * existing names in any of the scopes containing the current name), as= many +- * of these checks require search engine. Use [checkFinalConditions] fo= r this +- * level of checking. +- */ +- RefactoringStatus checkName(); +-} +- +-/** +- * [Refactoring] to extract an [Expression] or [Statement]s into a new me= thod. +- */ +-abstract class ExtractMethodRefactoring implements Refactoring { +- /** +- * Returns a new [ExtractMethodRefactoring] instance. +- */ +- factory ExtractMethodRefactoring( +- SearchEngine searchEngine, +- AstProvider astProvider, +- CompilationUnit unit, +- int selectionOffset, +- int selectionLength) { +- return new ExtractMethodRefactoringImpl( +- searchEngine, astProvider, unit, selectionOffset, selectionLength= ); +- } +- +- /** +- * True if a getter could be created rather than a method. +- */ +- bool get canCreateGetter; +- +- /** +- * True if a getter should be created rather than a method. +- */ +- void set createGetter(bool createGetter); +- +- /** +- * True if all occurrences of the expression or statements should be re= placed +- * by an invocation of the method. The expression or statements used to +- * initiate the refactoring will always be replaced. +- */ +- void set extractAll(bool extractAll); +- +- /** +- * The lengths of the expressions or statements that would be replaced = by an +- * invocation of the method. The lengths correspond to the offsets. +- * In other words, for a given expression (or block of statements), if = the +- * offset of that expression is offsets[i], then the length of that exp= ression +- * is lengths[i]. +- */ +- List get lengths; +- +- /** +- * The name that the method should be given. +- */ +- void set name(String name); +- +- /** +- * The proposed names for the method. +- * +- * The first proposal should be used as the "best guess" (if it exists). +- */ +- List get names; +- +- /** +- * The offsets of the expressions or statements that would be replaced = by an +- * invocation of the method. +- */ +- List get offsets; +- +- /** +- * The proposed parameters for the method. +- */ +- List get parameters; +- +- /** +- * The parameters that should be defined for the method. +- */ +- void set parameters(List parameters); +- +- /** +- * The proposed return type for the method. +- */ +- String get returnType; +- +- /** +- * The return type that should be defined for the method. +- */ +- void set returnType(String returnType); +- +- /** +- * Validates that the [name] is a valid identifier and is appropriate f= or a +- * method. +- * +- * It does not perform all the checks (such as checking for conflicts w= ith any +- * existing names in any of the scopes containing the current name), as= many +- * of these checks require search engine. Use [checkFinalConditions] fo= r this +- * level of checking. +- */ +- RefactoringStatus checkName(); +-} +- +-/** +- * [Refactoring] to inline a local [VariableElement]. +- */ +-abstract class InlineLocalRefactoring implements Refactoring { +- /** +- * Returns a new [InlineLocalRefactoring] instance. +- */ +- factory InlineLocalRefactoring(SearchEngine searchEngine, +- AstProvider astProvider, CompilationUnit unit, int offset) { +- return new InlineLocalRefactoringImpl( +- searchEngine, astProvider, unit, offset); +- } +- +- /** +- * Returns the number of references to the [VariableElement]. +- */ +- int get referenceCount; +- +- /** +- * Returns the name of the variable being inlined. +- */ +- String get variableName; +-} +- +-/** +- * [Refactoring] to inline an [ExecutableElement]. +- */ +-abstract class InlineMethodRefactoring implements Refactoring { +- /** +- * Returns a new [InlineMethodRefactoring] instance. +- */ +- factory InlineMethodRefactoring(SearchEngine searchEngine, +- AstProvider astProvider, CompilationUnit unit, int offset) { +- return new InlineMethodRefactoringImpl( +- searchEngine, astProvider, unit, offset); +- } +- +- /** +- * The name of the class enclosing the method being inlined. +- * If not a class member is being inlined, then `null`. +- */ +- String get className; +- +- /** +- * True if the method being inlined should be removed. +- * It is an error if this field is `true` and [inlineAll] is `false`. +- */ +- void set deleteSource(bool deleteSource); +- +- /** +- * True if all invocations of the method should be inlined, or false if= only +- * the invocation site used to create this refactoring should be inline= d. +- */ +- void set inlineAll(bool inlineAll); +- +- /** +- * True if the declaration of the method is selected. +- * So, all references should be inlined. +- */ +- bool get isDeclaration; +- +- /** +- * The name of the method (or function) being inlined. +- */ +- String get methodName; +-} +- +-/** +- * Abstract interface for all refactorings. +- */ +-abstract class Refactoring { +- /** +- * The ids of source edits that are not known to be valid. +- * +- * An edit is not known to be valid if there was insufficient type info= rmation +- * for the server to be able to determine whether or not the code needs= to be +- * modified, such as when a member is being renamed and there is a refe= rence +- * to a member from an unknown type. This field will be omitted if the = change +- * field is omitted or if there are no potential edits for the refactor= ing. +- */ +- List get potentialEditIds; +- +- /** +- * Returns the human readable name of this [Refactoring]. +- */ +- String get refactoringName; +- +- /** +- * Checks all conditions - [checkInitialConditions] and +- * [checkFinalConditions] to decide if refactoring can be performed. +- */ +- Future checkAllConditions(); +- +- /** +- * Validates environment to check if this refactoring can be performed. +- * +- * This check may be slow, because many refactorings use search engine. +- */ +- Future checkFinalConditions(); +- +- /** +- * Validates arguments to check if this refactoring can be performed. +- * +- * This check should be quick because it is used often as arguments cha= nge. +- */ +- Future checkInitialConditions(); +- +- /** +- * Returns the [Change] to apply to perform this refactoring. +- */ +- Future createChange(); +- +- /** +- * Returs `true` if the [Change] created by refactoring may be unsafe, +- * so we want user to review the [Change] to ensure that he understands= it. +- */ +- bool requiresPreview(); +-} +- +-/** +- * Abstract [Refactoring] for renaming some [Element]. +- */ +-abstract class RenameRefactoring implements Refactoring { +- /** +- * Returns a new [RenameRefactoring] instance for renaming [element], +- * maybe `null` if there is no support for renaming [Element]s of the g= iven +- * type. +- */ +- factory RenameRefactoring( +- SearchEngine searchEngine, AstProvider astProvider, Element element= ) { +- if (element =3D=3D null) { +- return null; +- } +- if (element is PropertyAccessorElement) { +- element =3D (element as PropertyAccessorElement).variable; +- } +- if (element.enclosingElement is CompilationUnitElement) { +- return new RenameUnitMemberRefactoringImpl(searchEngine, element); +- } +- if (element is ConstructorElement) { +- return new RenameConstructorRefactoringImpl( +- searchEngine, astProvider, element); +- } +- if (element is ImportElement) { +- return new RenameImportRefactoringImpl( +- searchEngine, astProvider, element); +- } +- if (element is LabelElement) { +- return new RenameLabelRefactoringImpl(searchEngine, element); +- } +- if (element is LibraryElement) { +- return new RenameLibraryRefactoringImpl(searchEngine, element); +- } +- if (element is LocalElement) { +- return new RenameLocalRefactoringImpl(searchEngine, astProvider, el= ement); +- } +- if (element.enclosingElement is ClassElement) { +- return new RenameClassMemberRefactoringImpl( +- searchEngine, astProvider, element); +- } +- return null; +- } +- +- /** +- * Returns the human-readable description of the kind of element being = renamed +- * (such as =E2=80=9Cclass=E2=80=9D or =E2=80=9Cfunction type alias=E2= =80=9D). +- */ +- String get elementKindName; +- +- /** +- * Sets the new name for the [Element]. +- */ +- void set newName(String newName); +- +- /** +- * Returns the old name of the [Element] being renamed. +- */ +- String get oldName; +- +- /** +- * Validates that the [newName] is a valid identifier and is appropriat= e for +- * the type of the [Element] being renamed. +- * +- * It does not perform all the checks (such as checking for conflicts w= ith any +- * existing names in any of the scopes containing the current name), as= many +- * of these checks require search engine. Use [checkFinalConditions] fo= r this +- * level of checking. +- */ +- RefactoringStatus checkNewName(); +-} +- +-/** +- * Cache for accessing resolved [CompilationUnit]s by [Element]s. +- * +- * Must by short-lived. +- * +- * TODO(scheglov) consider moving to request-bound object. +- */ +-class ResolvedUnitCache { +- final AstProvider _astProvider; +- final Map _map =3D {}; +- +- ResolvedUnitCache(this._astProvider, [CompilationUnit unit]) { +- if (unit !=3D null) { +- _map[unit.element] =3D unit; +- } +- } +- +- Future getUnit(Element element) async { +- CompilationUnitElement unitElement =3D getUnitElement(element); +- CompilationUnit unit =3D _map[unitElement]; +- if (unit =3D=3D null) { +- unit =3D await _astProvider.getResolvedUnitForElement(element); +- _map[unitElement] =3D unit; +- } +- return unit; +- } +- +- CompilationUnitElement getUnitElement(Element element) { +- return element.getAncestor((e) =3D> e is CompilationUnitElement) +- as CompilationUnitElement; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/refactoring_= internal.dart b/pkg/analysis_server/lib/src/services/refactoring/refactorin= g_internal.dart +deleted file mode 100644 +index eebc587e59a..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/refactoring_interna= l.dart ++++ /dev/null +@@ -1,116 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * Return a new [SourceReference] instance for the given [match]. +- */ +-SourceReference getSourceReference(SearchMatch match) { +- return new SourceReference(match); +-} +- +-/** +- * When a [Source] (a file) is used in more than one context, [SearchEngi= ne] +- * will return separate [SearchMatch]s for each context. But in rename +- * refactorings we want to update each [Source] only once. +- */ +-List getSourceReferences(List matches) { +- var uniqueReferences =3D new HashMap(= ); +- for (SearchMatch match in matches) { +- SourceReference newReference =3D getSourceReference(match); +- SourceReference oldReference =3D uniqueReferences[newReference]; +- if (oldReference =3D=3D null) { +- uniqueReferences[newReference] =3D newReference; +- oldReference =3D newReference; +- } +- } +- return uniqueReferences.keys.toList(); +-} +- +-/** +- * Abstract implementation of [Refactoring]. +- */ +-abstract class RefactoringImpl implements Refactoring { +- final List potentialEditIds =3D []; +- +- @override +- Future checkAllConditions() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- result.addStatus(await checkInitialConditions()); +- if (result.hasFatalError) { +- return result; +- } +- result.addStatus(await checkFinalConditions()); +- return result; +- } +-} +- +-/** +- * The [SourceRange] in some [Source]. +- * +- * TODO(scheglov) inline this class as SearchMatch +- */ +-class SourceReference { +- final SearchMatch _match; +- +- SourceReference(this._match); +- +- Element get element =3D> _match.element; +- +- /** +- * The full path of the file containing the match. +- */ +- String get file =3D> _match.file; +- +- @override +- int get hashCode { +- int hash =3D file.hashCode; +- hash =3D ((hash << 16) & 0xFFFFFFFF) + range.hashCode; +- return hash; +- } +- +- bool get isResolved =3D> _match.isResolved; +- +- SourceRange get range =3D> _match.sourceRange; +- +- Source get unitSource =3D> _match.unitSource; +- +- @override +- bool operator =3D=3D(Object other) { +- if (identical(other, this)) { +- return true; +- } +- if (other is SourceReference) { +- return other.file =3D=3D file && other.range =3D=3D range; +- } +- return false; +- } +- +- /** +- * Adds the [SourceEdit] to replace this reference. +- */ +- void addEdit(SourceChange change, String newText, {String id}) { +- SourceEdit edit =3D createEdit(newText, id: id); +- doSourceChange_addSourceEdit(change, unitSource, edit); +- } +- +- /** +- * Returns the [SourceEdit] to replace this reference. +- */ +- SourceEdit createEdit(String newText, {String id}) { +- return newSourceEdit_range(range, newText, id: id); +- } +- +- @override +- String toString() =3D> '$file@$range'; +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename.dart = b/pkg/analysis_server/lib/src/services/refactoring/rename.dart +deleted file mode 100644 +index db79f492bae..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename.dart ++++ /dev/null +@@ -1,148 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +-import 'package:path/path.dart' as pathos; +- +-bool isElementInPubCache(Element element) { +- Source source =3D element.source; +- String path =3D source.fullName; +- return isPathInPubCache(path); +-} +- +-bool isElementInSdkOrPubCache(Element element) { +- Source source =3D element.source; +- String path =3D source.fullName; +- return source.isInSystemLibrary || isPathInPubCache(path); +-} +- +-bool isPathInPubCache(String path) { +- List parts =3D pathos.split(path); +- if (parts.contains('.pub-cache')) { +- return true; +- } +- for (int i =3D 0; i < parts.length - 1; i++) { +- if (parts[i] =3D=3D 'Pub' && parts[i + 1] =3D=3D 'Cache') { +- return true; +- } +- if (parts[i] =3D=3D 'third_party' && +- (parts[i + 1] =3D=3D 'pkg' || parts[i + 1] =3D=3D 'pkg_tested')) { +- return true; +- } +- } +- return false; +-} +- +-/** +- * An abstract implementation of [RenameRefactoring]. +- */ +-abstract class RenameRefactoringImpl extends RefactoringImpl +- implements RenameRefactoring { +- final SearchEngine searchEngine; +- final Element _element; +- final String elementKindName; +- final String oldName; +- SourceChange change; +- +- String newName; +- +- RenameRefactoringImpl(SearchEngine searchEngine, Element element) +- : searchEngine =3D searchEngine, +- _element =3D element, +- elementKindName =3D element.kind.displayName, +- oldName =3D _getDisplayName(element); +- +- Element get element =3D> _element; +- +- /** +- * Adds a [SourceEdit] to update [element] name to [change]. +- */ +- void addDeclarationEdit(Element element) { +- if (element !=3D null) { +- SourceEdit edit =3D +- newSourceEdit_range(range.elementName(element), newName); +- doSourceChange_addElementEdit(change, element, edit); +- } +- } +- +- /** +- * Adds [SourceEdit]s to update [matches] to [change]. +- */ +- void addReferenceEdits(List matches) { +- List references =3D getSourceReferences(matches); +- for (SourceReference reference in references) { +- reference.addEdit(change, newName); +- } +- } +- +- @override +- Future checkInitialConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- if (element.source.isInSystemLibrary) { +- String message =3D format( +- "The {0} '{1}' is defined in the SDK, so cannot be renamed.", +- getElementKindName(element), +- getElementQualifiedName(element)); +- result.addFatalError(message); +- } +- if (isElementInPubCache(element)) { +- String message =3D format( +- "The {0} '{1}' is defined in a pub package, so cannot be rename= d.", +- getElementKindName(element), +- getElementQualifiedName(element)); +- result.addFatalError(message); +- } +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D new RefactoringStatus(); +- if (newName =3D=3D oldName) { +- result.addFatalError( +- "The new name must be different than the current name."); +- } +- return result; +- } +- +- @override +- Future createChange() async { +- String changeName =3D "$refactoringName '$oldName' to '$newName'"; +- change =3D new SourceChange(changeName); +- await fillChange(); +- return change; +- } +- +- /** +- * Adds individual edits to [change]. +- */ +- Future fillChange(); +- +- @override +- bool requiresPreview() { +- return false; +- } +- +- static String _getDisplayName(Element element) { +- if (element is ImportElement) { +- PrefixElement prefix =3D element.prefix; +- if (prefix !=3D null) { +- return prefix.displayName; +- } +- return ''; +- } +- return element.displayName; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_class= _member.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_clas= s_member.dart +deleted file mode 100644 +index 22aa8eeb4ab..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_class_member= .dart ++++ /dev/null +@@ -1,345 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- hide Element, ElementKind; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +- +-/** +- * Checks if creating a method with the given [name] in [classElement] wi= ll +- * cause any conflicts. +- */ +-Future validateCreateMethod(SearchEngine searchEngine, +- AstProvider astProvider, ClassElement classElement, String name) { +- return new _ClassMemberValidator.forCreate( +- searchEngine, astProvider, classElement, name) +- .validate(); +-} +- +-/** +- * A [Refactoring] for renaming class member [Element]s. +- */ +-class RenameClassMemberRefactoringImpl extends RenameRefactoringImpl { +- final AstProvider astProvider; +- +- _ClassMemberValidator _validator; +- +- RenameClassMemberRefactoringImpl( +- SearchEngine searchEngine, this.astProvider, Element element) +- : super(searchEngine, element); +- +- @override +- String get refactoringName { +- if (element is TypeParameterElement) { +- return "Rename Type Parameter"; +- } +- if (element is FieldElement) { +- return "Rename Field"; +- } +- return "Rename Method"; +- } +- +- @override +- Future checkFinalConditions() { +- _validator =3D new _ClassMemberValidator.forRename( +- searchEngine, astProvider, element, newName); +- return _validator.validate(); +- } +- +- @override +- Future checkInitialConditions() async { +- RefactoringStatus result =3D await super.checkInitialConditions(); +- if (element is MethodElement && (element as MethodElement).isOperator= ) { +- result.addFatalError('Cannot rename operator.'); +- } +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- if (element is FieldElement) { +- result.addStatus(validateFieldName(newName)); +- } +- if (element is MethodElement) { +- result.addStatus(validateMethodName(newName)); +- } +- return result; +- } +- +- @override +- Future fillChange() async { +- // update declarations +- for (Element renameElement in _validator.elements) { +- if (renameElement.isSynthetic && renameElement is FieldElement) { +- addDeclarationEdit(renameElement.getter); +- addDeclarationEdit(renameElement.setter); +- } else { +- addDeclarationEdit(renameElement); +- } +- } +- // update references +- addReferenceEdits(_validator.references); +- // potential matches +- List nameMatches =3D +- await searchEngine.searchMemberReferences(oldName); +- List nameRefs =3D getSourceReferences(nameMatches); +- for (SourceReference reference in nameRefs) { +- // ignore references from SDK and pub cache +- if (isElementInSdkOrPubCache(reference.element)) { +- continue; +- } +- // check the element being renamed is accessible +- { +- LibraryElement whereLibrary =3D reference.element.library; +- if (!element.isAccessibleIn(whereLibrary)) { +- continue; +- } +- } +- // add edit +- reference.addEdit(change, newName, id: _newPotentialId()); +- } +- } +- +- String _newPotentialId() { +- String id =3D potentialEditIds.length.toString(); +- potentialEditIds.add(id); +- return id; +- } +-} +- +-/** +- * Helper to check if the created or renamed [Element] will cause any con= flicts. +- */ +-class _ClassMemberValidator { +- final SearchEngine searchEngine; +- final ResolvedUnitCache unitCache; +- final LibraryElement library; +- final Element element; +- final ClassElement elementClass; +- final ElementKind elementKind; +- final String name; +- final bool isRename; +- +- final RefactoringStatus result =3D new RefactoringStatus(); +- Set elements =3D new Set(); +- List references =3D []; +- +- _ClassMemberValidator.forCreate( +- this.searchEngine, AstProvider astProvider, this.elementClass, this= .name) +- : unitCache =3D new ResolvedUnitCache(astProvider), +- isRename =3D false, +- library =3D null, +- element =3D null, +- elementKind =3D ElementKind.METHOD; +- +- _ClassMemberValidator.forRename( +- this.searchEngine, AstProvider astProvider, Element element, this.n= ame) +- : unitCache =3D new ResolvedUnitCache(astProvider), +- isRename =3D true, +- library =3D element.library, +- element =3D element, +- elementClass =3D element.enclosingElement, +- elementKind =3D element.kind; +- +- Future validate() async { +- // check if there is a member with "newName" in the same ClassElement +- for (Element newNameMember in getChildren(elementClass, name)) { +- result.addError( +- format( +- "Class '{0}' already declares {1} with name '{2}'.", +- elementClass.displayName, +- getElementKindName(newNameMember), +- name), +- newLocation_fromElement(newNameMember)); +- } +- // do chained computations +- Set superClasses =3D getSuperClasses(elementClass); +- await _prepareReferences(); +- Set subClasses =3D +- await searchEngine.searchAllSubtypes(elementClass); +- // check shadowing of class names +- if (element !=3D null) { +- for (Element element in elements) { +- ClassElement clazz =3D element.enclosingElement; +- if (clazz.name =3D=3D name) { +- result.addError( +- format( +- "Renamed {0} has the same name as the declaring class '= {1}'.", +- elementKind.displayName, +- name), +- newLocation_fromElement(element)); +- } +- } +- } else { +- if (elementClass.name =3D=3D name) { +- result.addError( +- format( +- "Created {0} has the same name as the declaring class '{1= }'.", +- elementKind.displayName, +- name), +- newLocation_fromElement(elementClass)); +- } +- } +- // usage of the renamed Element is shadowed by a local element +- { +- _MatchShadowedByLocal conflict =3D await _getShadowingLocalElement(= ); +- if (conflict !=3D null) { +- LocalElement localElement =3D conflict.localElement; +- result.addError( +- format( +- "Usage of renamed {0} will be shadowed by {1} '{2}'.", +- elementKind.displayName, +- getElementKindName(localElement), +- localElement.displayName), +- newLocation_fromMatch(conflict.match)); +- } +- } +- // check shadowing in the hierarchy +- List declarations =3D +- await searchEngine.searchMemberDeclarations(name); +- for (SearchMatch declaration in declarations) { +- Element nameElement =3D getSyntheticAccessorVariable(declaration.el= ement); +- Element nameClass =3D nameElement.enclosingElement; +- // the renamed Element shadows a member of a superclass +- if (superClasses.contains(nameClass)) { +- result.addError( +- format( +- isRename +- ? "Renamed {0} will shadow {1} '{2}'." +- : "Created {0} will shadow {1} '{2}'.", +- elementKind.displayName, +- getElementKindName(nameElement), +- getElementQualifiedName(nameElement)), +- newLocation_fromElement(nameElement)); +- } +- // the renamed Element is shadowed by a member of a subclass +- if (isRename && subClasses.contains(nameClass)) { +- result.addError( +- format( +- "Renamed {0} will be shadowed by {1} '{2}'.", +- elementKind.displayName, +- getElementKindName(nameElement), +- getElementQualifiedName(nameElement)), +- newLocation_fromElement(nameElement)); +- } +- } +- // visibility +- if (isRename) { +- _validateWillBeInvisible(); +- } +- // done +- return result; +- } +- +- Future<_MatchShadowedByLocal> _getShadowingLocalElement() async { +- var localElementMap =3D >{= }; +- Future> getLocalElements(Element element) async { +- var unitElement =3D unitCache.getUnitElement(element); +- var localElements =3D localElementMap[unitElement]; +- if (localElements =3D=3D null) { +- var unit =3D await unitCache.getUnit(unitElement); +- var collector =3D new _LocalElementsCollector(name); +- unit.accept(collector); +- localElements =3D collector.elements; +- localElementMap[unitElement] =3D localElements; +- } +- return localElements; +- } +- +- for (SearchMatch match in references) { +- // Qualified reference cannot be shadowed by local elements. +- if (match.isQualified) { +- continue; +- } +- // Check local elements that might shadow the reference. +- var localElements =3D await getLocalElements(match.element); +- for (LocalElement localElement in localElements) { +- if (localElement.visibleRange.intersects(match.sourceRange)) { +- return new _MatchShadowedByLocal(match, localElement); +- } +- } +- } +- return null; +- } +- +- /** +- * Fills [elements] with [Element]s to rename. +- */ +- Future _prepareElements() async { +- if (element is ClassMemberElement) { +- elements =3D await getHierarchyMembers(searchEngine, element); +- } else { +- elements =3D new Set.from([element]); +- } +- } +- +- /** +- * Fills [references] with all references to [elements]. +- */ +- Future _prepareReferences() async { +- if (!isRename) { +- return new Future.value(); +- } +- await _prepareElements(); +- await Future.forEach(elements, (Element element) async { +- List elementReferences =3D +- await searchEngine.searchReferences(element); +- references.addAll(elementReferences); +- }); +- } +- +- /** +- * Validates if any usage of [element] renamed to [name] will be invisi= ble. +- */ +- void _validateWillBeInvisible() { +- if (!Identifier.isPrivateName(name)) { +- return; +- } +- for (SearchMatch reference in references) { +- Element refElement =3D reference.element; +- LibraryElement refLibrary =3D refElement.library; +- if (refLibrary !=3D library) { +- String message =3D format("Renamed {0} will be invisible in '{1}'= .", +- getElementKindName(element), getElementQualifiedName(refLibra= ry)); +- result.addError(message, newLocation_fromMatch(reference)); +- } +- } +- } +-} +- +-class _LocalElementsCollector extends GeneralizingAstVisitor { +- final String name; +- final List elements =3D []; +- +- _LocalElementsCollector(this.name); +- +- visitSimpleIdentifier(SimpleIdentifier node) { +- Element element =3D node.staticElement; +- if (element is LocalElement && element.name =3D=3D name) { +- elements.add(element); +- } +- } +-} +- +-class _MatchShadowedByLocal { +- final SearchMatch match; +- final LocalElement localElement; +- +- _MatchShadowedByLocal(this.match, this.localElement); +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_const= ructor.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_const= ructor.dart +deleted file mode 100644 +index e079875f2f6..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_constructor.= dart ++++ /dev/null +@@ -1,131 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analysis_server/src/services/search/search_engine_interna= l.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * A [Refactoring] for renaming [ConstructorElement]s. +- */ +-class RenameConstructorRefactoringImpl extends RenameRefactoringImpl { +- final AstProvider astProvider; +- +- RenameConstructorRefactoringImpl( +- SearchEngine searchEngine, this.astProvider, ConstructorElement ele= ment) +- : super(searchEngine, element); +- +- @override +- ConstructorElement get element =3D> super.element as ConstructorElement; +- +- @override +- String get refactoringName { +- return "Rename Constructor"; +- } +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- result.addStatus(validateConstructorName(newName)); +- if (newName !=3D null) { +- _analyzePossibleConflicts(result); +- } +- return result; +- } +- +- @override +- Future fillChange() async { +- // prepare references +- List matches =3D await searchEngine.searchReferences(ele= ment); +- List references =3D getSourceReferences(matches); +- // append declaration +- if (element.isSynthetic) { +- await _replaceSynthetic(); +- } else { +- references.add(_createDeclarationReference()); +- } +- // update references +- String replacement =3D newName.isEmpty ? '' : '.$newName'; +- for (SourceReference reference in references) { +- reference.addEdit(change, replacement); +- } +- } +- +- void _analyzePossibleConflicts(RefactoringStatus result) { +- ClassElement parentClass =3D element.enclosingElement; +- // Check if the "newName" is the name of the enclosing class. +- if (parentClass.name =3D=3D newName) { +- result.addError('The constructor should not have the same name ' +- 'as the name of the enclosing class.'); +- } +- // check if there are members with "newName" in the same ClassElement +- for (Element newNameMember in getChildren(parentClass, newName)) { +- String message =3D format( +- "Class '{0}' already declares {1} with name '{2}'.", +- parentClass.displayName, +- getElementKindName(newNameMember), +- newName); +- result.addError(message, newLocation_fromElement(newNameMember)); +- } +- } +- +- SourceReference _createDeclarationReference() { +- SourceRange sourceRange; +- int offset =3D element.periodOffset; +- if (offset !=3D null) { +- sourceRange =3D range.startOffsetEndOffset(offset, element.nameEnd); +- } else { +- sourceRange =3D new SourceRange(element.nameEnd, 0); +- } +- return new SourceReference(new SearchMatchImpl( +- element.source.fullName, +- element.library.source, +- element.source, +- element.library, +- element, +- true, +- true, +- MatchKind.DECLARATION, +- sourceRange)); +- } +- +- Future _replaceSynthetic() async { +- ClassElement classElement =3D element.enclosingElement; +- AstNode name =3D await astProvider.getResolvedNameForElement(classEle= ment); +- ClassDeclaration classNode =3D name.parent as ClassDeclaration; +- CorrectionUtils utils =3D new CorrectionUtils(classNode.parent); +- ClassMemberLocation location =3D +- utils.prepareNewConstructorLocation(classNode); +- doSourceChange_addElementEdit( +- change, +- classElement, +- new SourceEdit( +- location.offset, +- 0, +- location.prefix + +- '${classElement.name}.$newName();' + +- location.suffix)); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_impor= t.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_import.dart +deleted file mode 100644 +index 2adca4d232f..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_import.dart ++++ /dev/null +@@ -1,137 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/refactoring_inte= rnal.dart'; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/analysis/results.dart'; +-import 'package:analyzer/dart/analysis/session.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +- +-/** +- * A [Refactoring] for renaming [ImportElement]s. +- */ +-class RenameImportRefactoringImpl extends RenameRefactoringImpl { +- final AstProvider astProvider; +- +- RenameImportRefactoringImpl( +- SearchEngine searchEngine, this.astProvider, ImportElement element) +- : super(searchEngine, element); +- +- @override +- ImportElement get element =3D> super.element as ImportElement; +- +- @override +- String get refactoringName { +- return "Rename Import Prefix"; +- } +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- result.addStatus(validateImportPrefixName(newName)); +- return result; +- } +- +- @override +- Future fillChange() async { +- // update declaration +- { +- PrefixElement prefix =3D element.prefix; +- SourceEdit edit =3D null; +- if (newName.isEmpty) { +- ImportDirective node =3D await _findNode(); +- int uriEnd =3D node.uri.end; +- int prefixEnd =3D element.prefixOffset + prefix.nameLength; +- edit =3D newSourceEdit_range( +- range.startOffsetEndOffset(uriEnd, prefixEnd), ""); +- } else { +- if (prefix =3D=3D null) { +- ImportDirective node =3D await _findNode(); +- int uriEnd =3D node.uri.end; +- edit =3D +- newSourceEdit_range(new SourceRange(uriEnd, 0), " as $newNa= me"); +- } else { +- int offset =3D element.prefixOffset; +- int length =3D prefix.nameLength; +- edit =3D newSourceEdit_range(new SourceRange(offset, length), n= ewName); +- } +- } +- if (edit !=3D null) { +- doSourceChange_addElementEdit(change, element, edit); +- } +- } +- // update references +- List matches =3D await searchEngine.searchReferences(ele= ment); +- List references =3D getSourceReferences(matches); +- for (SourceReference reference in references) { +- if (newName.isEmpty) { +- reference.addEdit(change, ''); +- } else { +- SimpleIdentifier interpolationIdentifier =3D +- await _getInterpolationIdentifier(reference); +- if (interpolationIdentifier !=3D null) { +- doSourceChange_addElementEdit( +- change, +- reference.element, +- new SourceEdit( +- interpolationIdentifier.offset, +- interpolationIdentifier.length, +- '{$newName.${interpolationIdentifier.name}}')); +- } else { +- reference.addEdit(change, '$newName.'); +- } +- } +- } +- } +- +- /** +- * Return the [ImportDirective] node that corresponds to the [element]. +- */ +- Future _findNode() async { +- LibraryElement library =3D element.library; +- CompilationUnit unit =3D await astProvider.getParsedUnitForElement(li= brary); +- int index =3D library.imports.indexOf(element); +- return unit.directives.where((d) =3D> d is ImportDirective).toList()[= index]; +- } +- +- /** +- * If the given [reference] is before an interpolated [SimpleIdentifier= ] in +- * an [InterpolationExpression] without surrounding curly brackets, ret= urn it. +- * Otherwise return `null`. +- */ +- Future _getInterpolationIdentifier( +- SourceReference reference) async { +- Source source =3D reference.element.source; +- AnalysisSession currentSession =3D astProvider.driver.currentSession; +- ParseResult result =3D await currentSession.getParsedAst(source.fullN= ame); +- CompilationUnit unit =3D result.unit; +- NodeLocator nodeLocator =3D new NodeLocator(reference.range.offset); +- AstNode node =3D nodeLocator.searchWithin(unit); +- if (node is SimpleIdentifier) { +- AstNode parent =3D node.parent; +- if (parent is InterpolationExpression && parent.rightBracket =3D=3D= null) { +- return node; +- } +- } +- return null; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_label= .dart b/pkg/analysis_server/lib/src/services/refactoring/rename_label.dart +deleted file mode 100644 +index 651fc7ac095..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_label.dart ++++ /dev/null +@@ -1,45 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-/** +- * A [Refactoring] for renaming [LabelElement]s. +- */ +-class RenameLabelRefactoringImpl extends RenameRefactoringImpl { +- RenameLabelRefactoringImpl(SearchEngine searchEngine, LabelElement elem= ent) +- : super(searchEngine, element); +- +- @override +- LabelElement get element =3D> super.element as LabelElement; +- +- @override +- String get refactoringName =3D> "Rename Label"; +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- result.addStatus(validateLabelName(newName)); +- return result; +- } +- +- @override +- Future fillChange() { +- addDeclarationEdit(element); +- return searchEngine.searchReferences(element).then(addReferenceEdits); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_libra= ry.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_library.d= art +deleted file mode 100644 +index 1c72c892c77..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_library.dart ++++ /dev/null +@@ -1,48 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +- +-/** +- * A [Refactoring] for renaming [LibraryElement]s. +- */ +-class RenameLibraryRefactoringImpl extends RenameRefactoringImpl { +- RenameLibraryRefactoringImpl( +- SearchEngine searchEngine, LibraryElement element) +- : super(searchEngine, element); +- +- @override +- LibraryElement get element =3D> super.element as LibraryElement; +- +- @override +- String get refactoringName { +- return "Rename Library"; +- } +- +- @override +- Future checkFinalConditions() { +- RefactoringStatus result =3D new RefactoringStatus(); +- return new Future.value(result); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- result.addStatus(validateLibraryName(newName)); +- return result; +- } +- +- @override +- Future fillChange() { +- addDeclarationEdit(element); +- return searchEngine.searchReferences(element).then(addReferenceEdits); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_local= .dart b/pkg/analysis_server/lib/src/services/refactoring/rename_local.dart +deleted file mode 100644 +index 85f86e4aa83..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_local.dart ++++ /dev/null +@@ -1,171 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- hide Element, ElementKind; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/utilities_dart.dart'; +- +-/** +- * A [Refactoring] for renaming [LocalElement]s. +- */ +-class RenameLocalRefactoringImpl extends RenameRefactoringImpl { +- final AstProvider astProvider; +- final ResolvedUnitCache unitCache; +- +- Set elements =3D new Set(); +- +- RenameLocalRefactoringImpl( +- SearchEngine searchEngine, this.astProvider, LocalElement element) +- : unitCache =3D new ResolvedUnitCache(astProvider), +- super(searchEngine, element); +- +- @override +- LocalElement get element =3D> super.element as LocalElement; +- +- @override +- String get refactoringName { +- if (element is ParameterElement) { +- return "Rename Parameter"; +- } +- if (element is FunctionElement) { +- return "Rename Local Function"; +- } +- return "Rename Local Variable"; +- } +- +- @override +- Future checkFinalConditions() async { +- RefactoringStatus result =3D new RefactoringStatus(); +- await _prepareElements(); +- for (LocalElement element in elements) { +- CompilationUnit unit =3D await unitCache.getUnit(element); +- if (unit !=3D null) { +- unit.accept(new _ConflictValidatorVisitor(result, newName, elemen= t)); +- } +- } +- return result; +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- if (element is LocalVariableElement) { +- result.addStatus(validateVariableName(newName)); +- } else if (element is ParameterElement) { +- result.addStatus(validateParameterName(newName)); +- } else if (element is FunctionElement) { +- result.addStatus(validateFunctionName(newName)); +- } +- return result; +- } +- +- @override +- Future fillChange() async { +- for (Element element in elements) { +- addDeclarationEdit(element); +- await searchEngine.searchReferences(element).then(addReferenceEdits= ); +- } +- } +- +- /** +- * Fills [elements] with [Element]s to rename. +- */ +- Future _prepareElements() async { +- Element enclosing =3D element.enclosingElement; +- if (enclosing is MethodElement && +- element is ParameterElement && +- (element as ParameterElement).parameterKind =3D=3D ParameterKind.= NAMED) { +- // prepare hierarchy methods +- Set methods =3D +- await getHierarchyMembers(searchEngine, enclosing); +- // add named parameter from each method +- for (ClassMemberElement method in methods) { +- if (method is MethodElement) { +- for (ParameterElement parameter in method.parameters) { +- if (parameter.parameterKind =3D=3D ParameterKind.NAMED && +- parameter.name =3D=3D element.name) { +- elements.add(parameter); +- } +- } +- } +- } +- } else { +- elements =3D new Set.from([element]); +- } +- } +-} +- +-class _ConflictValidatorVisitor extends RecursiveAstVisitor { +- final RefactoringStatus result; +- final String newName; +- final LocalElement target; +- final Set conflictingLocals =3D new Set(); +- +- _ConflictValidatorVisitor(this.result, this.newName, this.target); +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- Element nodeElement =3D node.bestElement; +- if (nodeElement !=3D null && nodeElement.name =3D=3D newName) { +- // Duplicate declaration. +- if (node.inDeclarationContext() && _isVisibleWithTarget(nodeElement= )) { +- conflictingLocals.add(nodeElement); +- String nodeKind =3D nodeElement.kind.displayName; +- String message =3D "Duplicate $nodeKind '$newName'."; +- result.addError(message, newLocation_fromElement(nodeElement)); +- return; +- } +- if (conflictingLocals.contains(nodeElement)) { +- return; +- } +- // Shadowing by the target element. +- SourceRange targetRange =3D target.visibleRange; +- if (targetRange !=3D null && +- targetRange.contains(node.offset) && +- !node.isQualified && +- !_isNamedExpressionName(node)) { +- nodeElement =3D getSyntheticAccessorVariable(nodeElement); +- String nodeKind =3D nodeElement.kind.displayName; +- String nodeName =3D getElementQualifiedName(nodeElement); +- String nameElementSourceName =3D nodeElement.source.shortName; +- String refKind =3D target.kind.displayName; +- String message =3D 'Usage of $nodeKind "$nodeName" declared in ' +- '"$nameElementSourceName" will be shadowed by renamed $refKin= d.'; +- result.addError(message, newLocation_fromNode(node)); +- } +- } +- } +- +- /** +- * Returns whether [element] and [target] are visible together. +- */ +- bool _isVisibleWithTarget(Element element) { +- if (element is LocalElement) { +- SourceRange targetRange =3D target.visibleRange; +- SourceRange elementRange =3D element.visibleRange; +- return targetRange !=3D null && +- elementRange !=3D null && +- elementRange.intersects(targetRange); +- } +- return false; +- } +- +- static bool _isNamedExpressionName(SimpleIdentifier node) { +- return node.parent is Label && node.parent.parent is NamedExpression; +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_unit_= member.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_unit_= member.dart +deleted file mode 100644 +index fea2831d608..00000000000 +--- a/pkg/analysis_server/lib/src/services/refactoring/rename_unit_member.= dart ++++ /dev/null +@@ -1,263 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/protocol_server.dart' +- show newLocation_fromElement, newLocation_fromMatch; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/refactoring/rename.dart'; +-import 'package:analysis_server/src/services/search/element_visitors.dart= '; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart' show Identifier; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/java_core.dart'; +- +-/** +- * Checks if creating a top-level function with the given [name] in [libr= ary] +- * will cause any conflicts. +- */ +-Future validateCreateFunction( +- SearchEngine searchEngine, LibraryElement library, String name) { +- return new _RenameUnitMemberValidator.forCreate( +- searchEngine, library, ElementKind.FUNCTION, name) +- .validate(); +-} +- +-/** +- * Checks if creating a top-level function with the given [name] in [elem= ent] +- * will cause any conflicts. +- */ +-Future validateRenameTopLevel( +- SearchEngine searchEngine, Element element, String name) { +- return new _RenameUnitMemberValidator.forRename(searchEngine, element, = name) +- .validate(); +-} +- +-/** +- * A [Refactoring] for renaming compilation unit member [Element]s. +- */ +-class RenameUnitMemberRefactoringImpl extends RenameRefactoringImpl { +- RenameUnitMemberRefactoringImpl(SearchEngine searchEngine, Element elem= ent) +- : super(searchEngine, element); +- +- @override +- String get refactoringName { +- if (element is FunctionElement) { +- return "Rename Top-Level Function"; +- } +- if (element is FunctionTypeAliasElement) { +- return "Rename Function Type Alias"; +- } +- if (element is TopLevelVariableElement) { +- return "Rename Top-Level Variable"; +- } +- return "Rename Class"; +- } +- +- @override +- Future checkFinalConditions() { +- return validateRenameTopLevel(searchEngine, element, newName); +- } +- +- @override +- RefactoringStatus checkNewName() { +- RefactoringStatus result =3D super.checkNewName(); +- if (element is TopLevelVariableElement) { +- result.addStatus(validateVariableName(newName)); +- } +- if (element is FunctionElement) { +- result.addStatus(validateFunctionName(newName)); +- } +- if (element is FunctionTypeAliasElement) { +- result.addStatus(validateFunctionTypeAliasName(newName)); +- } +- if (element is ClassElement) { +- result.addStatus(validateClassName(newName)); +- } +- return result; +- } +- +- @override +- Future fillChange() { +- // prepare elements +- List elements =3D []; +- if (element is PropertyInducingElement && element.isSynthetic) { +- PropertyInducingElement property =3D element as PropertyInducingEle= ment; +- PropertyAccessorElement getter =3D property.getter; +- PropertyAccessorElement setter =3D property.setter; +- if (getter !=3D null) { +- elements.add(getter); +- } +- if (setter !=3D null) { +- elements.add(setter); +- } +- } else { +- elements.add(element); +- } +- // update each element +- return Future.forEach(elements, (Element element) { +- addDeclarationEdit(element); +- return searchEngine.searchReferences(element).then(addReferenceEdit= s); +- }); +- } +-} +- +-/** +- * Helper to check if the created or renamed [Element] will cause any con= flicts. +- */ +-class _RenameUnitMemberValidator { +- final SearchEngine searchEngine; +- LibraryElement library; +- Element element; +- ElementKind elementKind; +- final String name; +- final bool isRename; +- List references =3D []; +- +- final RefactoringStatus result =3D new RefactoringStatus(); +- +- _RenameUnitMemberValidator.forCreate( +- this.searchEngine, this.library, this.elementKind, this.name) +- : isRename =3D false; +- +- _RenameUnitMemberValidator.forRename( +- this.searchEngine, this.element, this.name) +- : isRename =3D true { +- library =3D element.library; +- elementKind =3D element.kind; +- } +- +- Future validate() async { +- _validateWillConflict(); +- if (isRename) { +- references =3D await searchEngine.searchReferences(element); +- _validateWillBeInvisible(); +- _validateWillBeShadowed(); +- } +- await _validateWillShadow(); +- return result; +- } +- +- /** +- * Returns `true` if [element] is visible at the given [SearchMatch]. +- */ +- bool _isVisibleAt(Element element, SearchMatch at) { +- LibraryElement atLibrary =3D at.element.library; +- // may be the same library +- if (library =3D=3D atLibrary) { +- return true; +- } +- // check imports +- for (ImportElement importElement in atLibrary.imports) { +- // ignore if imported with prefix +- if (importElement.prefix !=3D null) { +- continue; +- } +- // check imported elements +- if (getImportNamespace(importElement).containsValue(element)) { +- return true; +- } +- } +- // no, it is not visible +- return false; +- } +- +- /** +- * Validates if any usage of [element] renamed to [name] will be invisi= ble. +- */ +- void _validateWillBeInvisible() { +- if (!Identifier.isPrivateName(name)) { +- return; +- } +- for (SearchMatch reference in references) { +- Element refElement =3D reference.element; +- LibraryElement refLibrary =3D refElement.library; +- if (refLibrary !=3D library) { +- String message =3D format("Renamed {0} will be invisible in '{1}'= .", +- getElementKindName(element), getElementQualifiedName(refLibra= ry)); +- result.addError(message, newLocation_fromMatch(reference)); +- } +- } +- } +- +- /** +- * Validates if any usage of [element] renamed to [name] will be shadow= ed. +- */ +- void _validateWillBeShadowed() { +- for (SearchMatch reference in references) { +- Element refElement =3D reference.element; +- ClassElement refClass =3D refElement.getAncestor((e) =3D> e is Clas= sElement); +- if (refClass !=3D null) { +- visitChildren(refClass, (shadow) { +- if (hasDisplayName(shadow, name)) { +- String message =3D format( +- "Reference to renamed {0} will be shadowed by {1} '{2}'.", +- getElementKindName(element), +- getElementKindName(shadow), +- getElementQualifiedName(shadow)); +- result.addError(message, newLocation_fromElement(shadow)); +- } +- }); +- } +- } +- } +- +- /** +- * Validates if [element] renamed to [name] will conflict with another +- * top-level [Element] in the same library. +- */ +- void _validateWillConflict() { +- visitLibraryTopLevelElements(library, (element) { +- if (hasDisplayName(element, name)) { +- String message =3D format("Library already declares {0} with name= '{1}'.", +- getElementKindName(element), name); +- result.addError(message, newLocation_fromElement(element)); +- } +- }); +- } +- +- /** +- * Validates if renamed [element] will shadow any [Element] named [name= ]. +- */ +- Future _validateWillShadow() async { +- List declarations =3D +- await searchEngine.searchMemberDeclarations(name); +- for (SearchMatch declaration in declarations) { +- Element member =3D declaration.element; +- ClassElement declaringClass =3D member.enclosingElement; +- List memberReferences =3D +- await searchEngine.searchReferences(member); +- for (SearchMatch memberReference in memberReferences) { +- Element refElement =3D memberReference.element; +- // cannot be shadowed if qualified +- if (memberReference.isQualified) { +- continue; +- } +- // cannot be shadowed if declared in the same class as reference +- ClassElement refClass =3D +- refElement.getAncestor((e) =3D> e is ClassElement); +- if (refClass =3D=3D declaringClass) { +- continue; +- } +- // ignore if not visible +- if (!_isVisibleAt(element, memberReference)) { +- continue; +- } +- // OK, reference will be shadowed be the element being renamed +- String message =3D format( +- isRename +- ? "Renamed {0} will shadow {1} '{2}'." +- : "Created {0} will shadow {1} '{2}'.", +- elementKind.displayName, +- getElementKindName(member), +- getElementQualifiedName(member)); +- result.addError(message, newLocation_fromMatch(memberReference)); +- } +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/search/element_visitors.= dart b/pkg/analysis_server/lib/src/services/search/element_visitors.dart +deleted file mode 100644 +index 3297709905b..00000000000 +--- a/pkg/analysis_server/lib/src/services/search/element_visitors.dart ++++ /dev/null +@@ -1,63 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +- +-/** +- * Uses [processor] to visit all of the children of [element]. +- * If [processor] returns `true`, then children of a child are visited to= o. +- */ +-void visitChildren(Element element, ElementProcessor processor) { +- element.visitChildren(new _ElementVisitorAdapter(processor)); +-} +- +-/** +- * Uses [processor] to visit all of the top-level elements of [library]. +- */ +-void visitLibraryTopLevelElements( +- LibraryElement library, ElementProcessor processor) { +- library.visitChildren(new _TopLevelElementsVisitor(processor)); +-} +- +-/** +- * An [Element] processor function type. +- * If `true` is returned, children of [element] will be visited. +- */ +-typedef bool ElementProcessor(Element element); +- +-/** +- * A [GeneralizingElementVisitor] adapter for [ElementProcessor]. +- */ +-class _ElementVisitorAdapter extends GeneralizingElementVisitor { +- final ElementProcessor processor; +- +- _ElementVisitorAdapter(this.processor); +- +- @override +- void visitElement(Element element) { +- bool visitChildren =3D processor(element); +- if (visitChildren =3D=3D true) { +- element.visitChildren(this); +- } +- } +-} +- +-/** +- * A [GeneralizingElementVisitor] for visiting top-level elements. +- */ +-class _TopLevelElementsVisitor extends GeneralizingElementVisitor { +- final ElementProcessor processor; +- +- _TopLevelElementsVisitor(this.processor); +- +- @override +- void visitElement(Element element) { +- if (element is CompilationUnitElement) { +- element.visitChildren(this); +- } else { +- processor(element); +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/search/hierarchy.dart b/= pkg/analysis_server/lib/src/services/search/hierarchy.dart +deleted file mode 100644 +index 93bb9a8166c..00000000000 +--- a/pkg/analysis_server/lib/src/services/search/hierarchy.dart ++++ /dev/null +@@ -1,162 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analysis_server/src/services/search/element_visitors.dart= '; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +- +-/** +- * Returns direct children of [parent]. +- */ +-List getChildren(Element parent, [String name]) { +- List children =3D []; +- visitChildren(parent, (Element element) { +- if (name =3D=3D null || element.displayName =3D=3D name) { +- children.add(element); +- } +- }); +- return children; +-} +- +-/** +- * Returns direct non-synthetic children of the given [ClassElement]. +- * +- * Includes: fields, accessors and methods. +- * Excludes: constructors and synthetic elements. +- */ +-List getClassMembers(ClassElement clazz, [String name]) { +- List members =3D []; +- visitChildren(clazz, (Element element) { +- if (element.isSynthetic) { +- return false; +- } +- if (element is ConstructorElement) { +- return false; +- } +- if (name !=3D null && element.displayName !=3D name) { +- return false; +- } +- if (element is ExecutableElement) { +- members.add(element); +- } +- if (element is FieldElement) { +- members.add(element); +- } +- return false; +- }); +- return members; +-} +- +-/** +- * Returns a [Set] with direct subclasses of [seed]. +- */ +-Future> getDirectSubClasses( +- SearchEngine searchEngine, ClassElement seed) async { +- List matches =3D await searchEngine.searchSubtypes(seed); +- return matches.map((match) =3D> match.element).toSet(); +-} +- +-/** +- * @return all implementations of the given {@link ClassMemberElement} is= its superclasses and +- * their subclasses. +- */ +-Future> getHierarchyMembers( +- SearchEngine searchEngine, ClassMemberElement member) async { +- Set result =3D new HashSet(); +- // static elements +- if (member.isStatic || member is ConstructorElement) { +- result.add(member); +- return new Future.value(result); +- } +- // method, field, etc +- String name =3D member.displayName; +- ClassElement memberClass =3D member.enclosingElement; +- Set searchClasses =3D getSuperClasses(memberClass); +- searchClasses.add(memberClass); +- for (ClassElement superClass in searchClasses) { +- // ignore if super- class does not declare member +- if (getClassMembers(superClass, name).isEmpty) { +- continue; +- } +- // check all sub- classes +- Set subClasses =3D +- await searchEngine.searchAllSubtypes(superClass); +- subClasses.add(superClass); +- for (ClassElement subClass in subClasses) { +- List subClassMembers =3D getChildren(subClass, name); +- for (Element member in subClassMembers) { +- if (member is ClassMemberElement) { +- result.add(member); +- } +- } +- } +- } +- return result; +-} +- +-/** +- * Returns non-synthetic members of the given [ClassElement] and its super +- * classes. +- * +- * Includes: fields, accessors and methods. +- * Excludes: constructors and synthetic elements. +- */ +-List getMembers(ClassElement clazz) { +- List members =3D []; +- members.addAll(getClassMembers(clazz)); +- Set superClasses =3D getSuperClasses(clazz); +- for (ClassElement superClass in superClasses) { +- members.addAll(getClassMembers(superClass)); +- } +- return members; +-} +- +-/** +- * Returns a [Set] with all direct and indirect superclasses of [seed]. +- */ +-Set getSuperClasses(ClassElement seed) { +- Set result =3D new HashSet(); +- // prepare queue +- List queue =3D new List(); +- queue.add(seed); +- // process queue +- while (!queue.isEmpty) { +- ClassElement current =3D queue.removeLast(); +- // add if not checked already +- if (!result.add(current)) { +- continue; +- } +- // append supertype +- { +- InterfaceType superType =3D current.supertype; +- if (superType !=3D null) { +- queue.add(superType.element); +- } +- } +- // append interfaces +- for (InterfaceType interface in current.interfaces) { +- queue.add(interface.element); +- } +- } +- // we don't need "seed" itself +- result.remove(seed); +- return result; +-} +- +-/** +- * If the given [element] is a synthetic [PropertyAccessorElement] returns +- * its variable, otherwise returns [element]. +- */ +-Element getSyntheticAccessorVariable(Element element) { +- if (element is PropertyAccessorElement) { +- if (element.isSynthetic) { +- return element.variable; +- } +- } +- return element; +-} +diff --git a/pkg/analysis_server/lib/src/services/search/search_engine.dar= t b/pkg/analysis_server/lib/src/services/search/search_engine.dart +deleted file mode 100644 +index df6e31c4d72..00000000000 +--- a/pkg/analysis_server/lib/src/services/search/search_engine.dart ++++ /dev/null +@@ -1,171 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * Instances of the enum [MatchKind] represent the kind of reference that= was +- * found when a match represents a reference to an element. +- */ +-class MatchKind { +- /** +- * A declaration of an element. +- */ +- static const MatchKind DECLARATION =3D const MatchKind('DECLARATION'); +- +- /** +- * A reference to an element in which it is being read. +- */ +- static const MatchKind READ =3D const MatchKind('READ'); +- +- /** +- * A reference to an element in which it is being both read and written. +- */ +- static const MatchKind READ_WRITE =3D const MatchKind('READ_WRITE'); +- +- /** +- * A reference to an element in which it is being written. +- */ +- static const MatchKind WRITE =3D const MatchKind('WRITE'); +- +- /** +- * A reference to an element in which it is being invoked. +- */ +- static const MatchKind INVOCATION =3D const MatchKind('INVOCATION'); +- +- /** +- * A reference to an element in which it is referenced. +- */ +- static const MatchKind REFERENCE =3D const MatchKind('REFERENCE'); +- +- final String name; +- +- const MatchKind(this.name); +- +- @override +- String toString() =3D> name; +-} +- +-/** +- * The interface [SearchEngine] defines the behavior of objects that can = be used +- * to search for various pieces of information. +- */ +-abstract class SearchEngine { +- /** +- * If the [type] has subtypes, return the set of names of members which= these +- * subtypes declare, possibly empty. If the [type] does not have subty= pes, +- * return `null`. +- */ +- Future> membersOfSubtypes(ClassElement type); +- +- /** +- * Returns all subtypes of the given [type]. +- * +- * [type] - the [ClassElement] being subtyped by the found matches. +- */ +- Future> searchAllSubtypes(ClassElement type); +- +- /** +- * Returns declarations of class members with the given name. +- * +- * [name] - the name being declared by the found matches. +- */ +- Future> searchMemberDeclarations(String name); +- +- /** +- * Returns all resolved and unresolved qualified references to the class +- * members with given [name]. +- * +- * [name] - the name being referenced by the found matches. +- */ +- Future> searchMemberReferences(String name); +- +- /** +- * Returns references to the given [Element]. +- * +- * [element] - the [Element] being referenced by the found matches. +- */ +- Future> searchReferences(Element element); +- +- /** +- * Returns direct subtypes of the given [type]. +- * +- * [type] - the [ClassElement] being subtyped by the found matches. +- */ +- Future> searchSubtypes(ClassElement type); +- +- /** +- * Returns all the top-level declarations matching the given pattern. +- * +- * [pattern] the regular expression used to match the names of the +- * declarations to be found. +- */ +- Future> searchTopLevelDeclarations(String pattern); +-} +- +-/** +- * Instances of the class [SearchMatch] represent a match found by +- * [SearchEngine]. +- */ +-abstract class SearchMatch { +- /** +- * Return the [Element] containing the match. Can return `null` if the = unit +- * does not exist, or its element was invalidated, or the element canno= t be +- * found, etc. +- */ +- Element get element; +- +- /** +- * The absolute path of the file containing the match. +- */ +- String get file; +- +- /** +- * Is `true` if field or method access is done using qualifier. +- */ +- bool get isQualified; +- +- /** +- * Is `true` if the match is a resolved reference to some [Element]. +- */ +- bool get isResolved; +- +- /** +- * The kind of the match. +- */ +- MatchKind get kind; +- +- /** +- * Return the [LibraryElement] for the [libraryUri] in the [context]. +- */ +- LibraryElement get libraryElement; +- +- /** +- * The library [Source] of the reference. +- */ +- Source get librarySource; +- +- /** +- * The source range that was matched. +- */ +- SourceRange get sourceRange; +- +- /** +- * The unit [Source] of the reference. +- */ +- Source get unitSource; +- +- /** +- * Return elements of [matches] which has not-null elements. +- * +- * When [SearchMatch.element] is not `null` we cache its value, so it c= annot +- * become `null` later. +- */ +- static List withNotNullElement(List matches) { +- return matches.where((match) =3D> match.element !=3D null).toList(); +- } +-} +diff --git a/pkg/analysis_server/lib/src/services/search/search_engine_int= ernal.dart b/pkg/analysis_server/lib/src/services/search/search_engine_inte= rnal.dart +deleted file mode 100644 +index 8e1519ed165..00000000000 +--- a/pkg/analysis_server/lib/src/services/search/search_engine_internal.d= art ++++ /dev/null +@@ -1,238 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/search.dart'; +-import 'package:analyzer/src/generated/source.dart' show Source, SourceRa= nge; +-import 'package:meta/meta.dart'; +- +-/** +- * A [SearchEngine] implementation. +- */ +-class SearchEngineImpl implements SearchEngine { +- final Iterable _drivers; +- +- SearchEngineImpl(this._drivers); +- +- @override +- Future> membersOfSubtypes(ClassElement type) async { +- List drivers =3D _drivers.toList(); +- +- String libraryUriStr =3D type.librarySource.uri.toString(); +- bool hasSubtypes =3D false; +- Set visitedIds =3D new Set(); +- Set members =3D new Set(); +- +- Future addMembers(ClassElement type, SubtypeResult subtype) asy= nc { +- if (subtype !=3D null && !visitedIds.add(subtype.id)) { +- return; +- } +- for (AnalysisDriver driver in drivers) { +- List subtypes =3D +- await driver.search.subtypes(type: type, subtype: subtype); +- for (SubtypeResult subtype in subtypes) { +- hasSubtypes =3D true; +- members.addAll(subtype.libraryUri =3D=3D libraryUriStr +- ? subtype.members +- : subtype.members.where((name) =3D> !name.startsWith('_'))); +- await addMembers(null, subtype); +- } +- } +- } +- +- await addMembers(type, null); +- +- if (!hasSubtypes) { +- return null; +- } +- return members; +- } +- +- @override +- Future> searchAllSubtypes(ClassElement type) async { +- Set allSubtypes =3D new Set(); +- +- Future addSubtypes(ClassElement type) async { +- List directResults =3D await _searchDirectSubtypes(ty= pe); +- for (SearchResult directResult in directResults) { +- var directSubtype =3D directResult.enclosingElement as ClassEleme= nt; +- if (allSubtypes.add(directSubtype)) { +- await addSubtypes(directSubtype); +- } +- } +- } +- +- await addSubtypes(type); +- return allSubtypes; +- } +- +- @override +- Future> searchMemberDeclarations(String name) async { +- List allDeclarations =3D []; +- List drivers =3D _drivers.toList(); +- for (AnalysisDriver driver in drivers) { +- List elements =3D await driver.search.classMembers(name); +- allDeclarations.addAll(elements.map(SearchMatchImpl.forElement)); +- } +- return allDeclarations; +- } +- +- @override +- Future> searchMemberReferences(String name) async { +- List allResults =3D []; +- List drivers =3D _drivers.toList(); +- for (AnalysisDriver driver in drivers) { +- List results =3D +- await driver.search.unresolvedMemberReferences(name); +- allResults.addAll(results); +- } +- return allResults.map(SearchMatchImpl.forSearchResult).toList(); +- } +- +- @override +- Future> searchReferences(Element element) async { +- List allResults =3D []; +- List drivers =3D _drivers.toList(); +- for (AnalysisDriver driver in drivers) { +- List results =3D await driver.search.references(eleme= nt); +- allResults.addAll(results); +- } +- return allResults.map(SearchMatchImpl.forSearchResult).toList(); +- } +- +- @override +- Future> searchSubtypes(ClassElement type) async { +- List results =3D await _searchDirectSubtypes(type); +- return results.map(SearchMatchImpl.forSearchResult).toList(); +- } +- +- @override +- Future> searchTopLevelDeclarations(String pattern) as= ync { +- List allDeclarations =3D []; +- RegExp regExp =3D new RegExp(pattern); +- List drivers =3D _drivers.toList(); +- for (AnalysisDriver driver in drivers) { +- List elements =3D await driver.search.topLevelElements(reg= Exp); +- allDeclarations.addAll(elements.map(SearchMatchImpl.forElement)); +- } +- return allDeclarations; +- } +- +- Future> _searchDirectSubtypes(ClassElement type) asy= nc { +- List allResults =3D []; +- List drivers =3D _drivers.toList(); +- for (AnalysisDriver driver in drivers) { +- List results =3D await driver.search.subTypes(type); +- allResults.addAll(results); +- } +- return allResults; +- } +-} +- +-@visibleForTesting +-class SearchMatchImpl implements SearchMatch { +- @override +- final String file; +- +- @override +- final Source librarySource; +- +- @override +- final Source unitSource; +- +- @override +- final LibraryElement libraryElement; +- +- @override +- final Element element; +- +- @override +- final bool isResolved; +- +- @override +- final bool isQualified; +- +- @override +- final MatchKind kind; +- +- @override +- final SourceRange sourceRange; +- +- SearchMatchImpl( +- this.file, +- this.librarySource, +- this.unitSource, +- this.libraryElement, +- this.element, +- this.isResolved, +- this.isQualified, +- this.kind, +- this.sourceRange); +- +- @override +- String toString() { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write("SearchMatch(kind=3D"); +- buffer.write(kind); +- buffer.write(", libraryUri=3D"); +- buffer.write(librarySource.uri); +- buffer.write(", unitUri=3D"); +- buffer.write(unitSource.uri); +- buffer.write(", range=3D"); +- buffer.write(sourceRange); +- buffer.write(", isResolved=3D"); +- buffer.write(isResolved); +- buffer.write(", isQualified=3D"); +- buffer.write(isQualified); +- buffer.write(")"); +- return buffer.toString(); +- } +- +- static SearchMatchImpl forElement(Element element) { +- return new SearchMatchImpl( +- element.source.fullName, +- element.librarySource, +- element.source, +- element.library, +- element, +- true, +- true, +- MatchKind.DECLARATION, +- new SourceRange(element.nameOffset, element.nameLength)); +- } +- +- static SearchMatchImpl forSearchResult(SearchResult result) { +- Element enclosingElement =3D result.enclosingElement; +- return new SearchMatchImpl( +- enclosingElement.source.fullName, +- enclosingElement.librarySource, +- enclosingElement.source, +- enclosingElement.library, +- enclosingElement, +- result.isResolved, +- result.isQualified, +- toMatchKind(result.kind), +- new SourceRange(result.offset, result.length)); +- } +- +- static MatchKind toMatchKind(SearchResultKind kind) { +- if (kind =3D=3D SearchResultKind.READ) { +- return MatchKind.READ; +- } +- if (kind =3D=3D SearchResultKind.READ_WRITE) { +- return MatchKind.READ_WRITE; +- } +- if (kind =3D=3D SearchResultKind.WRITE) { +- return MatchKind.WRITE; +- } +- if (kind =3D=3D SearchResultKind.INVOCATION) { +- return MatchKind.INVOCATION; +- } +- return MatchKind.REFERENCE; +- } +-} +diff --git a/pkg/analysis_server/lib/src/socket_server.dart b/pkg/analysis= _server/lib/src/socket_server.dart +deleted file mode 100644 +index 4676e0263ee..00000000000 +--- a/pkg/analysis_server/lib/src/socket_server.dart ++++ /dev/null +@@ -1,90 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/channel/channel.dart'; +-import 'package:analysis_server/src/server/diagnostic_server.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/plugin/resolver_provider.dart'; +-import 'package:analyzer/source/pub_package_map_provider.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +- +-/** +- * Instances of the class [SocketServer] implement the common parts of +- * http-based and stdio-based analysis servers. The primary responsibili= ty of +- * the SocketServer is to manage the lifetime of the AnalysisServer and to +- * encode and decode the JSON messages exchanged with the client. +- */ +-class SocketServer { +- final AnalysisServerOptions analysisServerOptions; +- +- /** +- * The function used to create a new SDK using the default SDK. +- */ +- final DartSdkManager sdkManager; +- +- final DartSdk defaultSdk; +- final InstrumentationService instrumentationService; +- final DiagnosticServer diagnosticServer; +- final ResolverProvider fileResolverProvider; +- final ResolverProvider packageResolverProvider; +- +- /** +- * The analysis server that was created when a client established a +- * connection, or `null` if no such connection has yet been established. +- */ +- AnalysisServer analysisServer; +- +- SocketServer( +- this.analysisServerOptions, +- this.sdkManager, +- this.defaultSdk, +- this.instrumentationService, +- this.diagnosticServer, +- this.fileResolverProvider, +- this.packageResolverProvider); +- +- /** +- * Create an analysis server which will communicate with the client usi= ng the +- * given serverChannel. +- */ +- void createAnalysisServer(ServerCommunicationChannel serverChannel) { +- if (analysisServer !=3D null) { +- RequestError error =3D new RequestError( +- RequestErrorCode.SERVER_ALREADY_STARTED, "Server already starte= d"); +- serverChannel.sendResponse(new Response('', error: error)); +- serverChannel.listen((Request request) { +- serverChannel.sendResponse(new Response(request.id, error: error)= ); +- }); +- return; +- } +- +- PhysicalResourceProvider resourceProvider; +- if (analysisServerOptions.fileReadMode =3D=3D 'as-is') { +- resourceProvider =3D new PhysicalResourceProvider(null, +- stateLocation: analysisServerOptions.cacheFolder); +- } else if (analysisServerOptions.fileReadMode =3D=3D 'normalize-eol-a= lways') { +- resourceProvider =3D new PhysicalResourceProvider( +- PhysicalResourceProvider.NORMALIZE_EOL_ALWAYS, +- stateLocation: analysisServerOptions.cacheFolder); +- } else { +- throw new Exception( +- 'File read mode was set to the unknown mode: $analysisServerOpt= ions.fileReadMode'); +- } +- +- analysisServer =3D new AnalysisServer( +- serverChannel, +- resourceProvider, +- new PubPackageMapProvider(resourceProvider, defaultSdk), +- analysisServerOptions, +- sdkManager, +- instrumentationService, +- diagnosticServer: diagnosticServer, +- fileResolverProvider: fileResolverProvider, +- packageResolverProvider: packageResolverProvider); +- } +-} +diff --git a/pkg/analysis_server/lib/src/status/ast_writer.dart b/pkg/anal= ysis_server/lib/src/status/ast_writer.dart +deleted file mode 100644 +index 908cb67c594..00000000000 +--- a/pkg/analysis_server/lib/src/status/ast_writer.dart ++++ /dev/null +@@ -1,243 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:collection'; +- +-import 'package:analysis_server/src/status/tree_writer.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/src/dart/ast/ast.dart'; +- +-/** +- * A visitor that will produce an HTML representation of an AST structure. +- */ +-class AstWriter extends UnifyingAstVisitor with TreeWriter { +- /** +- * Initialize a newly created element writer to write the HTML represen= tation +- * of visited nodes on the given [buffer]. +- */ +- AstWriter(StringBuffer buffer) { +- this.buffer =3D buffer; +- } +- +- @override +- void visitNode(AstNode node) { +- _writeNode(node); +- writeProperties(_computeProperties(node)); +- indentLevel++; +- try { +- node.visitChildren(this); +- } finally { +- indentLevel--; +- } +- } +- +- /** +- * Write a representation of the properties of the given [node] to the = buffer. +- */ +- Map _computeProperties(AstNode node) { +- Map properties =3D new HashMap(); +- +- properties['name'] =3D _getName(node); +- if (node is ArgumentListImpl) { +- properties['static parameter types'] =3D node.correspondingStaticPa= rameters; +- properties['propagated parameter types'] =3D +- node.correspondingPropagatedParameters; +- } else if (node is Annotation) { +- properties['element'] =3D node.element; +- properties['element annotation'] =3D node.elementAnnotation; +- } else if (node is BinaryExpression) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is ClassDeclaration) { +- properties['element'] =3D node.element; +- properties['abstract keyword'] =3D node.abstractKeyword; +- } else if (node is ClassTypeAlias) { +- properties['element'] =3D node.element; +- properties['abstract keyword'] =3D node.abstractKeyword; +- } else if (node is CompilationUnit) { +- properties['element'] =3D node.element; +- } else if (node is Configuration) { +- properties['uriSource'] =3D node.uriSource; +- } else if (node is ConstructorName) { +- properties['static element'] =3D node.staticElement; +- } else if (node is DeclaredIdentifier) { +- properties['element'] =3D node.element; +- properties['keyword'] =3D node.keyword; +- } else if (node is ExportDirective) { +- properties['element'] =3D node.element; +- properties['selectedSource'] =3D node.selectedSource; +- properties['uriSource'] =3D node.uriSource; +- } else if (node is FieldDeclaration) { +- properties['static keyword'] =3D node.staticKeyword; +- } else if (node is FormalParameter) { +- properties['element'] =3D node.element; +- properties['kind'] =3D node.kind; +- } else if (node is FunctionDeclaration) { +- properties['element'] =3D node.element; +- properties['external keyword'] =3D node.externalKeyword; +- properties['property keyword'] =3D node.propertyKeyword; +- } else if (node is FunctionExpressionInvocation) { +- properties['static element'] =3D node.staticElement; +- properties['static invoke type'] =3D node.staticInvokeType; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated invoke type'] =3D node.propagatedInvokeType; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is GenericFunctionType) { +- properties['type'] =3D node.type; +- } else if (node is ImportDirective) { +- properties['element'] =3D node.element; +- properties['selectedSource'] =3D node.selectedSource; +- properties['uriSource'] =3D node.uriSource; +- } else if (node is IndexExpression) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is InstanceCreationExpression) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is LibraryDirective) { +- properties['element'] =3D node.element; +- } else if (node is MethodDeclaration) { +- properties['element'] =3D node.element; +- properties['external keyword'] =3D node.externalKeyword; +- properties['modifier keyword'] =3D node.modifierKeyword; +- properties['operator keyword'] =3D node.operatorKeyword; +- properties['property keyword'] =3D node.propertyKeyword; +- } else if (node is MethodInvocation) { +- properties['static invoke type'] =3D node.staticInvokeType; +- properties['static type'] =3D node.staticType; +- properties['propagated invoke type'] =3D node.propagatedInvokeType; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is PartDirective) { +- properties['element'] =3D node.element; +- properties['uriSource'] =3D node.uriSource; +- } else if (node is PartOfDirective) { +- properties['element'] =3D node.element; +- } else if (node is PostfixExpression) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is PrefixExpression) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is RedirectingConstructorInvocation) { +- properties['static element'] =3D node.staticElement; +- } else if (node is SimpleIdentifier) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is SimpleStringLiteral) { +- properties['value'] =3D node.value; +- } else if (node is SuperConstructorInvocation) { +- properties['static element'] =3D node.staticElement; +- } else if (node is TypeAnnotation) { +- properties['type'] =3D node.type; +- } else if (node is VariableDeclarationList) { +- properties['keyword'] =3D node.keyword; +- } else if (node is Declaration) { +- properties['element'] =3D node.element; +- } else if (node is Expression) { +- properties['static type'] =3D node.staticType; +- properties['propagated type'] =3D node.propagatedType; +- } else if (node is FunctionBody) { +- properties['isAsynchronous'] =3D node.isAsynchronous; +- properties['isGenerator'] =3D node.isGenerator; +- } else if (node is Identifier) { +- properties['static element'] =3D node.staticElement; +- properties['static type'] =3D node.staticType; +- properties['propagated element'] =3D node.propagatedElement; +- properties['propagated type'] =3D node.propagatedType; +- } +- +- return properties; +- } +- +- /** +- * Return the name of the given [node], or `null` if the given node is = not a +- * declaration. +- */ +- String _getName(AstNode node) { +- if (node is ClassTypeAlias) { +- return node.name.name; +- } else if (node is ClassDeclaration) { +- return node.name.name; +- } else if (node is ConstructorDeclaration) { +- if (node.name =3D=3D null) { +- return node.returnType.name; +- } else { +- return node.returnType.name + '.' + node.name.name; +- } +- } else if (node is ConstructorName) { +- return node.toSource(); +- } else if (node is FieldDeclaration) { +- return _getNames(node.fields); +- } else if (node is FunctionDeclaration) { +- SimpleIdentifier nameNode =3D node.name; +- if (nameNode !=3D null) { +- return nameNode.name; +- } +- } else if (node is FunctionTypeAlias) { +- return node.name.name; +- } else if (node is Identifier) { +- return node.name; +- } else if (node is MethodDeclaration) { +- return node.name.name; +- } else if (node is TopLevelVariableDeclaration) { +- return _getNames(node.variables); +- } else if (node is TypeAnnotation) { +- return node.toSource(); +- } else if (node is TypeParameter) { +- return node.name.name; +- } else if (node is VariableDeclaration) { +- return node.name.name; +- } +- return null; +- } +- +- /** +- * Return a string containing a comma-separated list of the names of al= l of +- * the variables in the given list of [variables]. +- */ +- String _getNames(VariableDeclarationList variables) { +- StringBuffer buffer =3D new StringBuffer(); +- bool first =3D true; +- for (VariableDeclaration variable in variables.variables) { +- if (first) { +- first =3D false; +- } else { +- buffer.write(', '); +- } +- buffer.write(variable.name.name); +- } +- return buffer.toString(); +- } +- +- /** +- * Write a representation of the given [node] to the buffer. +- */ +- void _writeNode(AstNode node) { +- indent(); +- buffer.write(node.runtimeType); +- buffer.write(' ['); +- buffer.write(node.offset); +- buffer.write('..'); +- buffer.write(node.offset + node.length - 1); +- buffer.write(']'); +- if (node.isSynthetic) { +- buffer.write(' (synthetic)'); +- } +- buffer.write(''); +- buffer.write('
'); +- } +-} +diff --git a/pkg/analysis_server/lib/src/status/diagnostics.dart b/pkg/ana= lysis_server/lib/src/status/diagnostics.dart +deleted file mode 100644 +index 25902ead0f2..00000000000 +--- a/pkg/analysis_server/lib/src/status/diagnostics.dart ++++ /dev/null +@@ -1,1229 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/domain_completion.dart'; +-import 'package:analysis_server/src/domain_diagnostic.dart'; +-import 'package:analysis_server/src/domain_execution.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/server/http_server.dart'; +-import 'package:analysis_server/src/services/completion/completion_perfor= mance.dart'; +-import 'package:analysis_server/src/socket_server.dart'; +-import 'package:analysis_server/src/status/ast_writer.dart'; +-import 'package:analysis_server/src/status/element_writer.dart'; +-import 'package:analysis_server/src/status/pages.dart'; +-import 'package:analysis_server/src/utilities/profiling.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/source/sdk_ext.dart'; +-import 'package:analyzer/src/context/source.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/file_state.dart'; +-import 'package:analyzer/src/dart/sdk/sdk.dart'; +-import 'package:analyzer/src/generated/engine.dart' hide AnalysisResult; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/utilities_general.dart'; +-import 'package:analyzer/src/lint/linter.dart'; +-import 'package:analyzer/src/lint/registry.dart'; +-import 'package:analyzer/src/services/lint.dart'; +-import 'package:path/path.dart' as pathPackage; +- +-final String kCustomCss =3D ''' +-.lead, .page-title+.markdown-body>p:first-child { +- margin-bottom: 30px; +- font-size: 20px; +- font-weight: 300; +- color: #555; +-} +- +-.container { +- width: 1160px; +-} +- +-.masthead { +- padding-top: 1rem; +- padding-bottom: 1rem; +- margin-bottom: 1.5rem; +- text-align: center; +- background-color: #4078c0; +-} +- +-.masthead .masthead-logo { +- display: inline-block; +- font-size: 1.5rem; +- color: #fff; +- float: left; +-} +- +-.masthead .mega-octicon { +- font-size: 1.5rem; +-} +- +-.masthead-nav { +- float: right; +- margin-top: .5rem; +-} +- +-.masthead-nav a:not(:last-child) { +- margin-right: 1.25rem; +-} +- +-.masthead a { +- color: rgba(255,255,255,0.5); +- font-size: 1rem; +-} +- +-.masthead a:hover { +- color: #fff; +- text-decoration: none; +-} +- +-.masthead-nav .active { +- color: #fff; +- font-weight: 500; +-} +- +-.counter { +- display: inline-block; +- padding: 2px 5px; +- font-size: 11px; +- font-weight: bold; +- line-height: 1; +- color: #666; +- background-color: #eee; +- border-radius: 20px; +-} +- +-.menu-item .counter { +- float: right; +- margin-left: 5px; +-} +- +-td.right { +- text-align: right; +-} +- +-table td { +- max-width: 600px; +- vertical-align: text-top; +-} +- +-td.pre { +- white-space: pre; +-} +- +-.nowrap { +- white-space: nowrap; +-} +- +-.scroll-table { +- max-height: 190px; +- overflow-x: auto; +-} +- +-.footer { +- padding-top: 3rem; +- padding-bottom: 3rem; +- margin-top: 3rem; +- line-height: 1.75; +- color: #7a7a7a; +- border-top: 1px solid #eee; +-} +- +-.footer strong { +- color: #333; +-} +-'''; +- +-final bool _showLints =3D false; +- +-String get _sdkVersion { +- String version =3D Platform.version; +- if (version.contains(' ')) { +- version =3D version.substring(0, version.indexOf(' ')); +- } +- return version; +-} +- +-String writeOption(String name, dynamic value) { +- return '$name: $value
'; +-} +- +-class AstPage extends DiagnosticPageWithNav { +- String _description; +- +- AstPage(DiagnosticsSite site) +- : super(site, 'ast', 'AST', description: 'The AST for a file.'); +- +- @override +- String get description =3D> _description ?? super.description; +- +- @override +- bool get showInNav =3D> false; +- +- @override +- Future generateContent(Map params) async { +- String path =3D params['file']; +- if (path =3D=3D null) { +- p('No file path provided.'); +- return; +- } +- AnalysisDriver driver =3D server.getAnalysisDriver(path); +- if (driver =3D=3D null) { +- p('The file ${escape(path)} is not being analyzed.', +- raw: true); +- return; +- } +- AnalysisResult result =3D await driver.getResult(path); +- if (result =3D=3D null) { +- p( +- 'An AST could not be produced for the file ${escape( +- path)}.', +- raw: true); +- return; +- } +- +- AstWriter writer =3D new AstWriter(buf); +- result.unit.accept(writer); +- } +- +- @override +- Future generatePage(Map params) async { +- try { +- _description =3D params['file']; +- await super.generatePage(params); +- } finally { +- _description =3D null; +- } +- } +-} +- +-class CommunicationsPage extends DiagnosticPageWithNav { +- CommunicationsPage(DiagnosticsSite site) +- : super(site, 'communications', 'Communications', +- description: +- 'Latency statistics for analysis server communications.'); +- +- @override +- void generateContent(Map params) { +- void writeRow(List data, {List classes}) { +- buf.write(""); +- for (int i =3D 0; i < data.length; i++) { +- String c =3D classes =3D=3D null ? null : classes[i]; +- if (c !=3D null) { +- buf.write('${escape(data[i])}'); +- } else { +- buf.write('${escape(data[i])}'); +- } +- } +- buf.writeln(""); +- } +- +- buf.writeln('
'); +- +- ServerPerformance perf =3D server.performanceAfterStartup; +- if (perf !=3D null) { +- buf.writeln('
'); +- h3('Current'); +- +- int requestCount =3D perf.requestCount; +- int averageLatency =3D +- requestCount > 0 ? (perf.requestLatency ~/ requestCount) : 0; +- int maximumLatency =3D perf.maxLatency; +- double slowRequestPercent =3D +- requestCount > 0 ? (perf.slowRequestCount / requestCount) : 0.0; +- +- buf.write(''); +- writeRow([printInteger(requestCount), 'requests'], +- classes: ["right", null]); +- writeRow([printMilliseconds(averageLatency), 'average latency'], +- classes: ["right", null]); +- writeRow([printMilliseconds(maximumLatency), 'maximum latency'], +- classes: ["right", null]); +- writeRow([printPercentage(slowRequestPercent), '> 150 ms latency'], +- classes: ["right", null]); +- buf.write('
'); +- +- String time =3D server.uptime.toString(); +- if (time.contains('.')) { +- time =3D time.substring(0, time.indexOf('.')); +- } +- buf.writeln(writeOption('Uptime', time)); +- +- buf.write('
'); +- } +- +- buf.writeln('
'); +- h3('Startup'); +- perf =3D server.performanceDuringStartup; +- +- int requestCount =3D perf.requestCount; +- int averageLatency =3D +- requestCount > 0 ? (perf.requestLatency ~/ requestCount) : 0; +- int maximumLatency =3D perf.maxLatency; +- double slowRequestPercent =3D +- requestCount > 0 ? (perf.slowRequestCount / requestCount) : 0.0; +- +- buf.write(''); +- writeRow([printInteger(requestCount), 'requests'], +- classes: ["right", null]); +- writeRow([printMilliseconds(averageLatency), 'average latency'], +- classes: ["right", null]); +- writeRow([printMilliseconds(maximumLatency), 'maximum latency'], +- classes: ["right", null]); +- writeRow([printPercentage(slowRequestPercent), '> 150 ms latency'], +- classes: ["right", null]); +- buf.write('
'); +- +- if (server.performanceAfterStartup !=3D null) { +- int startupTime =3D +- server.performanceAfterStartup.startTime - perf.startTime; +- buf.writeln( +- writeOption('Initial analysis time', printMilliseconds(startupT= ime))); +- } +- buf.write('
'); +- +- buf.write('
'); +- } +-} +- +-class CompletionPage extends DiagnosticPageWithNav { +- CompletionPage(DiagnosticsSite site) +- : super(site, 'completion', 'Code Completion', +- description: 'Latency statistics for code completion.'); +- +- @override +- void generateContent(Map params) { +- CompletionDomainHandler completionDomain =3D server.handlers +- .firstWhere((handler) =3D> handler is CompletionDomainHandler); +- +- List completions =3D +- completionDomain.performanceList.items.toList(); +- +- if (completions.isEmpty) { +- blankslate('No completions recorded.'); +- return; +- } +- +- int fastCount =3D +- completions.where((c) =3D> c.elapsedInMilliseconds <=3D 100).leng= th; +- p('${completions.length} results; ${printPercentage( +- fastCount / completions.length)} within 100ms.'); +- +- // draw a chart +- buf.writeln( +- '
'); +- StringBuffer rowData =3D new StringBuffer(); +- for (int i =3D completions.length - 1; i >=3D 0; i--) { +- // [' ', 101.5] +- if (rowData.isNotEmpty) { +- rowData.write(','); +- } +- rowData.write("[' ', ${completions[i].elapsedInMilliseconds}]"); +- } +- buf.writeln(''' +- +-'''); +- +- // emit the data as a table +- buf.writeln(''); +- buf.writeln( +- '= '); +- for (CompletionPerformance completion in completions) { +- buf.writeln('' +- '' +- '' +- '' +- '' +- ''); +- } +- buf.writeln('
TimeResultsSourceSnippet
${printMilliseconds( +- completion.elapsedInMilliseconds)}${completion.suggestionCount}${escape(completion.source.shortName)}${escape(completion.snippet)}
'); +- } +-} +- +-class ContextsPage extends DiagnosticPageWithNav { +- ContextsPage(DiagnosticsSite site) +- : super(site, 'contexts', 'Contexts', +- description: +- 'An analysis context defines the options and the set of s= ources being analyzed.'); +- +- String get navDetail =3D> printInteger(server.driverMap.length); +- +- String describe(AnalysisOptionsImpl options) { +- StringBuffer b =3D new StringBuffer(); +- +- b.write( +- writeOption('Analyze function bodies', options.analyzeFunctionBod= ies)); +- b.write(writeOption( +- 'Enable strict call checks', options.enableStrictCallChecks)); +- b.write(writeOption('Enable super mixins', options.enableSuperMixins)= ); +- b.write(writeOption('Generate dart2js hints', options.dart2jsHint)); +- b.write(writeOption( +- 'Generate errors in implicit files', options.generateImplicitErro= rs)); +- b.write( +- writeOption('Generate errors in SDK files', options.generateSdkEr= rors)); +- b.write(writeOption('Generate hints', options.hint)); +- b.write(writeOption('Preserve comments', options.preserveComments)); +- b.write(writeOption('Strong mode', options.strongMode)); +- b.write(writeOption('Strong mode hints', options.strongModeHints)); +- +- return b.toString(); +- } +- +- @override +- void generateContent(Map params) { +- Map driverMap =3D server.driverMap; +- if (driverMap.isEmpty) { +- blankslate('No contexts.'); +- return; +- } +- +- String contextPath =3D params['context']; +- List folders =3D driverMap.keys.toList(); +- folders +- .sort((first, second) =3D> first.shortName.compareTo(second.short= Name)); +- Folder folder =3D +- folders.firstWhere((f) =3D> f.path =3D=3D contextPath, orElse: ()= =3D> null); +- +- if (folder =3D=3D null) { +- folder =3D folders.first; +- contextPath =3D folder.path; +- } +- +- AnalysisDriver driver =3D driverMap[folder]; +- +- buf.writeln('
'); +- buf.writeln(''); +- buf.writeln('
'); +- +- buf.writeln(writeOption('Context location', escape(contextPath))); +- buf.writeln(writeOption('Analysis options path', +- escape(driver.contextRoot.optionsFilePath ?? 'none'))); +- +- buf.writeln('
'); +- +- buf.writeln('
'); +- h3('Analysis options'); +- p(describe(driver.analysisOptions), raw: true); +- buf.writeln( +- writeOption('Has .packages file', folder.getChild('.packages').ex= ists)); +- buf.writeln(writeOption( +- 'Has pubspec.yaml file', folder.getChild('pubspec.yaml').exists)); +- buf.writeln('
'); +- +- buf.writeln('
'); +- DartSdk sdk =3D driver?.sourceFactory?.dartSdk; +- AnalysisOptionsImpl sdkOptions =3D sdk?.context?.analysisOptions; +- if (sdkOptions !=3D null) { +- h3('SDK analysis options'); +- p(describe(sdkOptions), raw: true); +- +- if (sdk is FolderBasedDartSdk) { +- p(writeOption('Use summaries', sdk.useSummary), raw: true); +- } +- } +- buf.writeln('
'); +- +- buf.writeln('
'); +- +- h3('Lints'); +- p(driver.analysisOptions.lintRules.map((l) =3D> l.name).join(', ')); +- +- h3('Error processors'); +- p(driver.analysisOptions.errorProcessors +- .map((e) =3D> e.description) +- .join(', ')); +- +- h3('Plugins'); +- p(driver.analysisOptions.enabledPluginNames.join(', ')); +- +- List priorityFiles =3D driver.priorityFiles; +- List addedFiles =3D driver.addedFiles.toList(); +- List implicitFiles =3D +- driver.knownFiles.difference(driver.addedFiles).toList(); +- addedFiles.sort(); +- implicitFiles.sort(); +- +- String lenCounter(List list) { +- return '${list +- .length}'; +- } +- +- h3('Context files'); +- +- void writeFile(String file) { +- String astPath =3D '/ast?file=3D${Uri.encodeQueryComponent(file)}'; +- String elementPath =3D '/element?file=3D${Uri.encodeQueryComponent(= file)}'; +- +- buf.write(file); +- buf.writeln('
ast'); +- buf.write(' '); +- buf.writeln('element'); +- } +- +- h4('Priority files ${lenCounter(priorityFiles)}', raw: true); +- ul(priorityFiles, writeFile, classes: 'scroll-table'); +- +- h4('Added files ${lenCounter(addedFiles)}', raw: true); +- ul(addedFiles, writeFile, classes: 'scroll-table'); +- +- h4('Implicit files ${lenCounter(implicitFiles)}', raw: true); +- ul(implicitFiles, writeFile, classes: 'scroll-table'); +- +- SourceFactory sourceFactory =3D driver.sourceFactory; +- if (sourceFactory is SourceFactoryImpl) { +- h3('Resolvers'); +- for (UriResolver resolver in sourceFactory.resolvers) { +- h4(resolver.runtimeType.toString()); +- buf.write('

'); +- if (resolver is DartUriResolver) { +- DartSdk sdk =3D resolver.dartSdk; +- buf.write(' (sdk =3D '); +- buf.write(sdk.runtimeType); +- if (sdk is FolderBasedDartSdk) { +- buf.write(' (path =3D '); +- buf.write(sdk.directory.path); +- buf.write(')'); +- } else if (sdk is EmbedderSdk) { +- buf.write(' (map =3D '); +- writeMap(sdk.urlMappings); +- buf.write(')'); +- } +- buf.write(')'); +- } else if (resolver is SdkExtUriResolver) { +- buf.write(' (map =3D '); +- writeMap(resolver.urlMappings); +- buf.write(')'); +- } else if (resolver is PackageMapUriResolver) { +- writeMap(resolver.packageMap); +- } +- buf.write('

'); +- } +- } +- } +- +- void writeList(List list) { +- buf.writeln('[${list.join(', ')}]'); +- } +- +- void writeMap(Map map) { +- List keys =3D map.keys.toList(); +- keys.sort(); +- int length =3D keys.length; +- buf.write('{'); +- for (int i =3D 0; i < length; i++) { +- buf.write('
'); +- String key =3D keys[i]; +- V value =3D map[key]; +- buf.write(key); +- buf.write(' =3D '); +- if (value is List) { +- writeList(value); +- } else { +- buf.write(value); +- } +- buf.write(','); +- } +- buf.write('
}'); +- } +-} +- +-/// A page with a proscriptive notion of layout. +-abstract class DiagnosticPage extends Page { +- final Site site; +- +- DiagnosticPage(this.site, String id, String title, {String description}) +- : super(id, title, description: description); +- +- bool get isNavPage =3D> false; +- +- AnalysisServer get server =3D> +- (site as DiagnosticsSite).socketServer.analysisServer; +- +- Future generateContainer(Map params) async { +- buf.writeln('
'); +- buf.writeln('
'); +- h1(title, classes: 'page-title'); +- await asyncDiv(() async { +- p(description); +- await generateContent(params); +- }, classes: 'markdown-body'); +- buf.writeln('
'); +- buf.writeln('
'); +- } +- +- void generateContent(Map params); +- +- void generateFooter() { +- buf.writeln(''' +-
+- Dart ${site.title} SDK $_sdkVersion +-
+-'''); +- } +- +- void generateHeader() { +- buf.writeln(''' +-
+-
+- +- +- ${site.title} Diagnostics +- +- +- +-
+-
+-'''); +- } +- +- Future generatePage(Map params) async { +- buf.writeln(''); +- buf.write(''); +- buf.write(''); +- buf.write(''); +- buf.writeln('${site.title}'); +- buf.writeln(''); +- buf.writeln(''); +- buf.writeln(''); +- buf.writeln(''); +- buf.writeln(''); +- +- buf.writeln(''); +- generateHeader(); +- buf.writeln('
'); +- await generateContainer(params); +- generateFooter(); +- buf.writeln('
'); // div.container +- buf.writeln(''); +- buf.writeln(''); +- } +-} +- +-abstract class DiagnosticPageWithNav extends DiagnosticPage { +- DiagnosticPageWithNav(Site site, String id, String title, +- {String description}) +- : super(site, id, title, description: description); +- +- bool get isNavPage =3D> true; +- +- String get navDetail =3D> null; +- +- bool get showInNav =3D> true; +- +- Future generateContainer(Map params) async { +- buf.writeln('
'); +- +- bool shouldShowInNav(Page page) { +- return page is DiagnosticPageWithNav && page.showInNav; +- } +- +- buf.writeln('
'); +- buf.writeln(''); +- buf.writeln('
'); +- +- buf.writeln('
'); +- h1(title, classes: 'page-title'); +- await asyncDiv(() async { +- p(description); +- await generateContent(params); +- }, classes: 'markdown-body'); +- buf.writeln('
'); +- +- buf.writeln('
'); +- } +-} +- +-class DiagnosticsSite extends Site implements AbstractGetHandler { +- /// An object that can handle either a WebSocket connection or a connec= tion +- /// to the client over stdio. +- SocketServer socketServer; +- +- /// The last few lines printed. +- List lastPrintedLines =3D []; +- +- DiagnosticsSite(this.socketServer, this.lastPrintedLines) +- : super('Analysis Server') { +- pages.add(new CompletionPage(this)); +- pages.add(new CommunicationsPage(this)); +- pages.add(new ContextsPage(this)); +- pages.add(new EnvironmentVariablesPage(this)); +- pages.add(new ExceptionsPage(this)); +- pages.add(new InstrumentationPage(this)); +- pages.add(new OverlaysPage(this)); +- pages.add(new PluginsPage(this)); +- pages.add(new ProfilePage(this)); +- pages.add(new SubscriptionsPage(this)); +- +- ProcessProfiler profiler =3D ProcessProfiler.getProfilerForPlatform(); +- if (profiler !=3D null) { +- pages.add(new MemoryAndCpuPage(this, profiler)); +- } +- +- pages.sort(((Page a, Page b) =3D> +- a.title.toLowerCase().compareTo(b.title.toLowerCase()))); +- +- // Add the status page at the beginning. +- pages.insert(0, new StatusPage(this)); +- +- // Add non-nav pages. +- pages.add(new FeedbackPage(this)); +- pages.add(new AstPage(this)); +- pages.add(new ElementModelPage(this)); +- } +- +- String get customCss =3D> kCustomCss; +- +- Page createExceptionPage(String message, StackTrace trace) =3D> +- new ExceptionPage(this, message, trace); +- +- Page createUnknownPage(String unknownPath) =3D> +- new NotFoundPage(this, unknownPath); +-} +- +-class ElementModelPage extends DiagnosticPageWithNav { +- String _description; +- +- ElementModelPage(DiagnosticsSite site) +- : super(site, 'element', 'Element model', +- description: 'The element model for a file.'); +- +- @override +- String get description =3D> _description ?? super.description; +- +- @override +- bool get showInNav =3D> false; +- +- @override +- Future generateContent(Map params) async { +- String path =3D params['file']; +- if (path =3D=3D null) { +- p('No file path provided.'); +- return; +- } +- AnalysisDriver driver =3D server.getAnalysisDriver(path); +- if (driver =3D=3D null) { +- p('The file ${escape(path)} is not being analyzed.', +- raw: true); +- return; +- } +- AnalysisResult result =3D await driver.getResult(path); +- if (result =3D=3D null) { +- p( +- 'An element model could not be produced for the file ${es= cape( +- path)}.', +- raw: true); +- return; +- } +- +- ElementWriter writer =3D new ElementWriter(buf); +- result.unit.element.accept(writer); +- } +- +- @override +- Future generatePage(Map params) async { +- try { +- _description =3D params['file']; +- await super.generatePage(params); +- } finally { +- _description =3D null; +- } +- } +-} +- +-class EnvironmentVariablesPage extends DiagnosticPageWithNav { +- EnvironmentVariablesPage(DiagnosticsSite site) +- : super(site, 'environment', 'Environment Variables', +- description: +- 'System environment variables as seen from the analysis s= erver.'); +- +- @override +- void generateContent(Map params) { +- buf.writeln(''); +- buf.writeln(''); +- for (String key in Platform.environment.keys.toList()..sort()) { +- String value =3D Platform.environment[key]; +- buf.writeln(''); +- } +- buf.writeln('
VariableValue
${escape(key)}${escape(value)}
'); +- } +-} +- +-class ExceptionPage extends DiagnosticPage { +- final StackTrace trace; +- +- ExceptionPage(Site site, String message, this.trace) +- : super(site, '', '500 Oops', description: message); +- +- void generateContent(Map params) { +- p(trace.toString(), style: 'white-space: pre'); +- } +-} +- +-class ExceptionsPage extends DiagnosticPageWithNav { +- ExceptionsPage(DiagnosticsSite site) +- : super(site, 'exceptions', 'Exceptions', +- description: 'Exceptions from the analysis server.'); +- +- Iterable get exceptions =3D> server.exceptions.items; +- +- String get navDetail =3D> printInteger(exceptions.length); +- +- @override +- void generateContent(Map params) { +- if (exceptions.isEmpty) { +- blankslate('No exceptions encountered!'); +- } else { +- for (ServerException ex in exceptions) { +- h3('Exception ${ex.exception}'); +- p('${escape(ex.message)}
${writeOption('fatal', ex.fatal)}', +- raw: true); +- pre(() { +- buf.writeln('${escape(ex.stackTrace.toString())}'); +- }, classes: "scroll-table"); +- } +- } +- } +-} +- +-class FeedbackPage extends DiagnosticPage { +- FeedbackPage(DiagnosticsSite site) +- : super(site, 'feedback', 'Feedback', +- description: 'Providing feedback and filing issues.'); +- +- @override +- void generateContent(Map params) { +- final String issuesUrl =3D 'https://github.com/dart-lang/sdk/issues'; +- p( +- 'To file issues or feature requests, see our ' +- 'bug tracker. When filing an issue, = please describe:', +- raw: true, +- ); +- ul([ +- 'what you were doing', +- 'what occured', +- 'what you think the expected behavior should have been', +- ], (line) =3D> buf.writeln(line)); +- +- List ideInfo =3D []; +- if (server.options.clientId !=3D null) { +- ideInfo.add(server.options.clientId); +- } +- if (server.options.clientVersion !=3D null) { +- ideInfo.add(server.options.clientVersion); +- } +- String ideText =3D ideInfo.map((str) =3D> '$str').join('= , '); +- +- p('Other data to include:'); +- ul([ +- "the IDE you are using and it's version${ideText.isEmpty +- ? '' +- : ' ($ideText)'}", +- 'the Dart SDK version (${escape(_sdkVersion)})', +- 'your operating system (${escape( +- Platform.operatingSystem)})', +- ], (line) =3D> buf.writeln(line)); +- +- p('Thanks!'); +- } +-} +- +-class InstrumentationPage extends DiagnosticPageWithNav { +- InstrumentationPage(DiagnosticsSite site) +- : super(site, 'instrumentation', 'Instrumentation', +- description: +- 'Verbose instrumentation data from the analysis server.'); +- +- @override +- void generateContent(Map params) { +- p( +- 'Instrumentation can be enabled by starting the analysis server w= ith the ' +- '--instrumentation-log-file=3Dpath/to/file flag.', +- raw: true); +- +- if (!AnalysisEngine.instance.instrumentationService.isActive) { +- blankslate('Instrumentation not active.'); +- return; +- } +- +- h3('Instrumentation'); +- +- p('Instrumentation active.'); +- +- InstrumentationServer instrumentation =3D +- AnalysisEngine.instance.instrumentationService.instrumentationSer= ver; +- String description =3D instrumentation.describe; +- HtmlEscape htmlEscape =3D new HtmlEscape(HtmlEscapeMode.ELEMENT); +- description =3D htmlEscape.convert(description); +- // Convert http(s): references to hyperlinks. +- final RegExp urlRegExp =3D new RegExp(r'[http|https]+:\/*(\S+)'); +- description =3D description.replaceAllMapped(urlRegExp, (Match match)= { +- return '${match.group(1)}'; +- }); +- p(description.replaceAll('\n', '
'), raw: true); +- } +-} +- +-class MemoryAndCpuPage extends DiagnosticPageWithNav { +- final ProcessProfiler profiler; +- +- MemoryAndCpuPage(DiagnosticsSite site, this.profiler) +- : super(site, 'memory', 'Memory and CPU Usage', +- description: 'Memory and CPU usage for the analysis server.'); +- +- DiagnosticDomainHandler get diagnosticDomain { +- return server.handlers +- .firstWhere((handler) =3D> handler is DiagnosticDomainHandler); +- } +- +- @override +- void generateContent(Map params) { +- UsageInfo usage =3D profiler.getProcessUsageSync(pid); +- if (usage !=3D null) { +- buf.writeln( +- writeOption('CPU', printPercentage(usage.cpuPercentage / 100.0)= )); +- buf.writeln( +- writeOption('Memory', '${printInteger(usage.memoryMB.round())} = MB')); +- } else { +- p('Error retreiving the memory and cpu usage information.'); +- } +- } +-} +- +-class NotFoundPage extends DiagnosticPage { +- final String path; +- +- NotFoundPage(Site site, this.path) +- : super(site, '', '404 Not found', description: "'$path' not found.= "); +- +- void generateContent(Map params) {} +-} +- +-class OverlaysPage extends DiagnosticPageWithNav { +- OverlaysPage(DiagnosticsSite site) +- : super(site, 'overlays', 'Overlays', +- description: 'Editing overlays - unsaved file changes.'); +- +- @override +- void generateContent(Map params) { +- FileContentOverlay overlays =3D server.fileContentOverlay; +- List paths =3D overlays.paths.toList()..sort(); +- +- String overlayPath =3D params['overlay']; +- if (overlayPath !=3D null) { +- p(overlayPath); +- +- if (overlays[overlayPath] !=3D null) { +- buf.write('
');
+-        buf.write(overlays[overlayPath]);
+-        buf.writeln('
'); +- } else { +- p('${escape(overlayPath)} not found.', raw: true); +- } +- +- return; +- } +- +- if (paths.isEmpty) { +- blankslate('No overlays.'); +- } else { +- String lenCounter(List list) { +- return '${list +- .length}'; +- } +- +- h3('Overlays ${lenCounter(paths)}', raw: true); +- ul(paths, (String overlayPath) { +- String uri =3D '$path?overlay=3D${Uri.encodeQueryComponent(overla= yPath)}'; +- buf.writeln('${escape(overlayPath)}'); +- }); +- } +- } +-} +- +-// TODO(devoncarew): We're not currently tracking the time spent in speci= fic +-// lints by default (analysisOptions / driverOptions enableTiming) +-class PluginsPage extends DiagnosticPageWithNav { +- PluginsPage(DiagnosticsSite site) +- : super(site, 'plugins', 'Plugins', description: 'Plugins in use.'); +- +- @override +- void generateContent(Map params) { +- h3('Analysis plugins'); +- List analysisPlugins =3D server.pluginManager.plugins; +- +- if (analysisPlugins.isEmpty) { +- blankslate('No known analysis plugins.'); +- } else { +- for (PluginInfo plugin in analysisPlugins) { +- // TODO(brianwilkerson) Sort the plugins by name. +- String id =3D plugin.pluginId; +- PluginData data =3D plugin.data; +- +- List components =3D pathPackage.split(id); +- int length =3D components.length; +- String name; +- if (length =3D=3D 0) { +- name =3D 'unknown plugin'; +- } else if (length > 2) { +- name =3D components[length - 3]; +- } else { +- name =3D components[length - 1]; +- } +- h4(name); +- p('path: $id'); +- if (data.name =3D=3D null) { +- if (plugin.exception !=3D null) { +- p('not running'); +- pre(() { +- buf.write(plugin.exception); +- }); +- } else { +- p('not running for unknown reason'); +- } +- } else { +- p('name: ${data.name}'); +- p('version: ${data.version}'); +- p('Associated contexts:'); +- Set contexts =3D plugin.contextRoots; +- if (contexts.isEmpty) { +- blankslate('none'); +- } else { +- ul(contexts.toList(), (ContextRoot root) { +- buf.writeln(root.root); +- }); +- } +- } +- } +- } +- } +-} +- +-class ProfilePage extends DiagnosticPageWithNav { +- ProfilePage(DiagnosticsSite site) +- : super(site, 'profile', 'Profiling Info', +- description: 'Profiling performance tag data.'); +- +- @override +- void generateContent(Map params) { +- h3('Profiling performance tag data'); +- +- // prepare sorted tags +- List tags =3D PerformanceTag.all.toList(); +- tags.remove(ServerPerformanceStatistics.idle); +- tags.remove(PerformanceTag.unknown); +- tags.removeWhere((tag) =3D> tag.elapsedMs =3D=3D 0); +- tags.sort((a, b) =3D> b.elapsedMs - a.elapsedMs); +- +- // print total time +- int totalTime =3D +- tags.fold(0, (int a, PerformanceTag tag) =3D> a + tag.elapse= dMs); +- p('Total measured time: ${printMilliseconds(totalTime)}'); +- +- // draw a pie chart +- String rowData =3D +- tags.map((tag) =3D> "['${tag.label}', ${tag.elapsedMs}]").join(',= '); +- buf.writeln( +- '
'); +- buf.writeln(''' +- +-'''); +- +- // write out a table +- void _writeRow(List data, {bool header: false}) { +- buf.write(''); +- if (header) { +- for (String d in data) { +- buf.write('$d'); +- } +- } else { +- buf.write('${data[0]}'); +- +- for (String d in data.sublist(1)) { +- buf.write('$d'); +- } +- } +- buf.writeln(''); +- } +- +- buf.write(''); +- _writeRow(['Tag name', 'Time (in ms)', 'Percent'], header: true); +- void writeRow(PerformanceTag tag) { +- double percent =3D tag.elapsedMs / totalTime; +- _writeRow([ +- tag.label, +- printMilliseconds(tag.elapsedMs), +- printPercentage(percent) +- ]); +- } +- +- tags.forEach(writeRow); +- buf.write('
'); +- +- if (_showLints) { +- h3('Lint rule timings'); +- List rules =3D Registry.ruleRegistry.rules.toList(); +- int totalLintTime =3D rules.fold(0, +- (sum, rule) =3D> sum + lintRegistry.getTimer(rule).elapsedMilli= seconds); +- p('Total time spent in lints: ${printMilliseconds(totalLintTime)}'); +- +- rules.sort((first, second) { +- int firstTime =3D lintRegistry.getTimer(first).elapsedMillisecond= s; +- int secondTime =3D lintRegistry.getTimer(second).elapsedMilliseco= nds; +- if (firstTime =3D=3D secondTime) { +- return first.lintCode.name.compareTo(second.lintCode.name); +- } +- return secondTime - firstTime; +- }); +- buf.write(''); +- _writeRow(['Lint code', 'Time (in ms)'], header: true); +- for (var rule in rules) { +- int time =3D lintRegistry.getTimer(rule).elapsedMilliseconds; +- _writeRow([rule.lintCode.name, printMilliseconds(time)]); +- } +- buf.write('
'); +- } +- } +-} +- +-class StatusPage extends DiagnosticPageWithNav { +- StatusPage(DiagnosticsSite site) +- : super(site, 'status', 'Status', +- description: +- 'General status and diagnostics for the analysis server.'= ); +- +- @override +- void generateContent(Map params) { +- buf.writeln('
'); +- +- buf.writeln('
'); +- h3('Status'); +- buf.writeln(writeOption('Instrumentation enabled', +- AnalysisEngine.instance.instrumentationService.isActive)); +- buf.writeln(writeOption('Server process ID', pid)); +- buf.writeln('
'); +- +- buf.writeln('
'); +- h3('Versions'); +- buf.writeln(writeOption('Analysis server version', AnalysisServer.VER= SION)); +- buf.writeln(writeOption('Dart SDK', Platform.version)); +- buf.writeln('
'); +- +- buf.writeln('
'); +- +- List lines =3D (site as DiagnosticsSite).lastPrintedLines; +- if (lines.isNotEmpty) { +- h3('Debug output'); +- p(lines.join('\n'), style: 'white-space: pre'); +- } +- } +-} +- +-class SubscriptionsPage extends DiagnosticPageWithNav { +- SubscriptionsPage(DiagnosticsSite site) +- : super(site, 'subscriptions', 'Subscriptions', +- description: 'Registered subscriptions to analysis server eve= nts.'); +- +- @override +- void generateContent(Map params) { +- // server domain +- h3('Server domain subscriptions'); +- ul(ServerService.VALUES, (item) { +- if (server.serverServices.contains(item)) { +- buf.write('$item (has subscriptions)'); +- } else { +- buf.write('$item (no subscriptions)'); +- } +- }); +- +- // analysis domain +- h3('Analysis domain subscriptions'); +- for (AnalysisService service in AnalysisService.VALUES) { +- buf.writeln('${service.name}
'); +- ul(server.analysisServices[service] ?? [], (item) { +- buf.write('$item'); +- }); +- } +- +- // execution domain +- ExecutionDomainHandler domain =3D server.handlers.firstWhere( +- (handler) =3D> handler is ExecutionDomainHandler, +- orElse: () =3D> null); +- +- h3('Execution domain'); +- ul(ExecutionService.VALUES, (item) { +- if (domain.onFileAnalyzed !=3D null) { +- buf.write('$item (has subscriptions)'); +- } else { +- buf.write('$item (no subscriptions)'); +- } +- }); +- } +-} +diff --git a/pkg/analysis_server/lib/src/status/element_writer.dart b/pkg/= analysis_server/lib/src/status/element_writer.dart +deleted file mode 100644 +index 8299ef9d7a1..00000000000 +--- a/pkg/analysis_server/lib/src/status/element_writer.dart ++++ /dev/null +@@ -1,179 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:collection'; +-import 'dart:convert'; +- +-import 'package:analysis_server/src/status/tree_writer.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +-import 'package:analyzer/src/dart/element/element.dart'; +- +-/** +- * A visitor that will produce an HTML representation of an element struc= ture. +- */ +-class ElementWriter extends GeneralizingElementVisitor with TreeWriter { +- /** +- * Initialize a newly created element writer to write the HTML represen= tation +- * of visited elements on the given [buffer]. +- */ +- ElementWriter(StringBuffer buffer) { +- this.buffer =3D buffer; +- } +- +- @override +- void visitElement(Element element) { +- _writeElement(element); +- writeProperties(_computeProperties(element)); +- indentLevel++; +- try { +- element.visitChildren(this); +- } finally { +- indentLevel--; +- } +- } +- +- /** +- * Write a representation of the properties of the given [node] to the = buffer. +- */ +- Map _computeProperties(Element element) { +- Map properties =3D new HashMap(); +- +- properties['metadata'] =3D element.metadata; +- properties['nameOffset'] =3D element.nameOffset; +- if (element is ClassElement) { +- properties['hasNonFinalField'] =3D element.hasNonFinalField; +- properties['hasReferenceToSuper'] =3D element.hasReferenceToSuper; +- properties['hasStaticMember'] =3D element.hasStaticMember; +- properties['interfaces'] =3D element.interfaces; +- properties['isAbstract'] =3D element.isAbstract; +- properties['isEnum'] =3D element.isEnum; +- properties['isMixinApplication'] =3D element.isMixinApplication; +- properties['isOrInheritsProxy'] =3D element.isOrInheritsProxy; +- properties['isProxy'] =3D element.isProxy; +- properties['isValidMixin'] =3D element.isValidMixin; +- properties['mixins'] =3D element.mixins; +- properties['supertype'] =3D element.supertype; +- } +- if (element is ClassMemberElement) { +- properties['isStatic'] =3D element.isStatic; +- } +- if (element is CompilationUnitElement) { +- properties['hasLoadLibraryFunction'] =3D element.hasLoadLibraryFunc= tion; +- properties['source'] =3D element.source; +- } +- if (element is ConstFieldElementImpl) { +- properties['evaluationResult'] =3D element.evaluationResult; +- } +- if (element is ConstLocalVariableElementImpl) { +- properties['evaluationResult'] =3D element.evaluationResult; +- } +- if (element is ConstTopLevelVariableElementImpl) { +- properties['evaluationResult'] =3D element.evaluationResult; +- } +- if (element is ConstructorElement) { +- properties['isConst'] =3D element.isConst; +- properties['isDefaultConstructor'] =3D element.isDefaultConstructor; +- properties['isFactory'] =3D element.isFactory; +- properties['redirectedConstructor'] =3D element.redirectedConstruct= or; +- } +- if (element is ExecutableElement) { +- properties['hasImplicitReturnType'] =3D element.hasImplicitReturnTy= pe; +- properties['isAbstract'] =3D element.isAbstract; +- properties['isAsynchronous'] =3D element.isAsynchronous; +- properties['isExternal'] =3D element.isExternal; +- properties['isGenerator'] =3D element.isGenerator; +- properties['isOperator'] =3D element.isOperator; +- properties['isStatic'] =3D element.isStatic; +- properties['isSynchronous'] =3D element.isSynchronous; +- properties['returnType'] =3D element.returnType; +- properties['type'] =3D element.type; +- } +- if (element is ExportElement) { +- properties['combinators'] =3D element.combinators; +- properties['library'] =3D element.library; +- } +- if (element is FieldElement) { +- properties['isEnumConstant'] =3D element.isEnumConstant; +- } +- if (element is FieldFormalParameterElement) { +- properties['field'] =3D element.field; +- } +- if (element is FunctionElement) { +- properties['isEntryPoint'] =3D element.isEntryPoint; +- } +- if (element is FunctionTypedElement) { +- properties['returnType'] =3D element.returnType; +- properties['type'] =3D element.type; +- } +- if (element is ImportElement) { +- properties['combinators'] =3D element.combinators; +- properties['isDeferred'] =3D element.isDeferred; +- properties['library'] =3D element.library; +- } +- if (element is LibraryElement) { +- properties['definingCompilationUnit'] =3D element.definingCompilati= onUnit; +- properties['entryPoint'] =3D element.entryPoint; +- properties['hasExtUri'] =3D element.hasExtUri; +- properties['hasLoadLibraryFunction'] =3D element.hasLoadLibraryFunc= tion; +- properties['isBrowserApplication'] =3D element.isBrowserApplication; +- properties['isDartAsync'] =3D element.isDartAsync; +- properties['isDartCore'] =3D element.isDartCore; +- properties['isInSdk'] =3D element.isInSdk; +- } +- if (element is LocalElement) { +- properties['visibleRange'] =3D element.visibleRange; +- } +- if (element is ParameterElement) { +- properties['defaultValueCode'] =3D element.defaultValueCode; +- properties['isInitializingFormal'] =3D element.isInitializingFormal; +- properties['parameterKind'] =3D element.parameterKind; +- } +- if (element is PropertyAccessorElement) { +- properties['isGetter'] =3D element.isGetter; +- properties['isSetter'] =3D element.isSetter; +- } +- if (element is PropertyInducingElement) { +- properties['isStatic'] =3D element.isStatic; +- properties['propagatedType'] =3D element.propagatedType; +- } +- if (element is TypeDefiningElement) { +- properties['type'] =3D element.type; +- } +- if (element is TypeParameterElement) { +- properties['bound'] =3D element.bound; +- } +- if (element is TypeParameterizedElement) { +- properties['typeParameters'] =3D element.typeParameters; +- } +- if (element is VariableElement) { +- properties['constantValue'] =3D element.constantValue; +- properties['hasImplicitType'] =3D element.hasImplicitType; +- properties['isConst'] =3D element.isConst; +- properties['isFinal'] =3D element.isFinal; +- properties['isStatic'] =3D element.isStatic; +- properties['type'] =3D element.type; +- } +- +- return properties; +- } +- +- /** +- * Write a representation of the given [node] to the buffer. +- */ +- void _writeElement(Element element) { +- indent(); +- if (element.isSynthetic) { +- buffer.write(''); +- } +- buffer.write(HTML_ESCAPE.convert(element.toString())); +- if (element.isSynthetic) { +- buffer.write(''); +- } +- buffer.write(' ('); +- buffer.write(element.runtimeType); +- buffer.write(')'); +- buffer.write('
'); +- } +-} +diff --git a/pkg/analysis_server/lib/src/status/pages.dart b/pkg/analysis_= server/lib/src/status/pages.dart +deleted file mode 100644 +index 1d85eccc9f4..00000000000 +--- a/pkg/analysis_server/lib/src/status/pages.dart ++++ /dev/null +@@ -1,189 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:intl/intl.dart'; +- +-final NumberFormat numberFormat =3D new NumberFormat.decimalPattern(); +- +-String escape(String text) =3D> text =3D=3D null ? '' : HTML_ESCAPE.conve= rt(text); +- +-String printInteger(int value) =3D> numberFormat.format(value); +- +-String printMilliseconds(num value) =3D> '${numberFormat.format(value)} m= s'; +- +-String printPercentage(num value) =3D> '${(value * 100).toStringAsFixed(1= )}%'; +- +-/// An entity that knows how to serve itself over http. +-abstract class Page { +- final StringBuffer buf =3D new StringBuffer(); +- +- final String id; +- final String title; +- final String description; +- +- Page(this.id, this.title, {this.description}); +- +- String get path =3D> '/$id'; +- +- Future asyncDiv(void gen(), {String classes}) async { +- if (classes !=3D null) { +- buf.writeln('
'); +- } else { +- buf.writeln('
'); +- } +- await gen(); +- buf.writeln('
'); +- } +- +- void blankslate(String str) { +- div(() =3D> buf.writeln(str), classes: 'blankslate'); +- } +- +- void div(void gen(), {String classes}) { +- if (classes !=3D null) { +- buf.writeln('
'); +- } else { +- buf.writeln('
'); +- } +- gen(); +- buf.writeln('
'); +- } +- +- Future generate(Map params) async { +- buf.clear(); +- await generatePage(params); +- return buf.toString(); +- } +- +- void generatePage(Map params); +- +- void h1(String text, {String classes}) { +- if (classes !=3D null) { +- buf.writeln('

${escape(text)}

'); +- } else { +- buf.writeln('

${escape(text)}

'); +- } +- } +- +- void h2(String text) { +- buf.writeln('

${escape(text)}

'); +- } +- +- void h3(String text, {bool raw: false}) { +- buf.writeln('

${raw ? text : escape(text)}

'); +- } +- +- void h4(String text, {bool raw: false}) { +- buf.writeln('

${raw ? text : escape(text)}

'); +- } +- +- void inputList(Iterable items, void gen(T item)) { +- buf.writeln(''); +- } +- +- bool isCurrentPage(String pathToTest) =3D> path =3D=3D pathToTest; +- +- void p(String text, {String style, bool raw: false, String classes}) { +- String c =3D classes =3D=3D null ? '' : ' class=3D"$classes"'; +- +- if (style !=3D null) { +- buf.writeln('${raw ? text : escape(text)}

= '); +- } else { +- buf.writeln('${raw ? text : escape(text)}

'); +- } +- } +- +- void pre(void gen(), {String classes}) { +- if (classes !=3D null) { +- buf.write('
');
+-    } else {
+-      buf.write('
');
+-    }
+-    gen();
+-    buf.writeln('
'); +- } +- +- void ul(Iterable items, void gen(T item), {String classes}) { +- buf.writeln(''); +- for (T item in items) { +- buf.write('
  • '); +- gen(item); +- buf.write('
  • '); +- } +- buf.writeln(''); +- } +-} +- +-/// Contains a collection of Pages. +-abstract class Site { +- final String title; +- List pages =3D []; +- +- Site(this.title); +- +- String get customCss =3D> ''; +- +- Page createExceptionPage(String message, StackTrace trace); +- +- Page createUnknownPage(String unknownPath); +- +- Future handleGetRequest(HttpRequest request) async { +- try { +- String path =3D request.uri.path; +- +- if (path =3D=3D '/') { +- respondRedirect(request, pages.first.path); +- return; +- } +- +- for (Page page in pages) { +- if (page.path =3D=3D path) { +- HttpResponse response =3D request.response; +- response.headers.contentType =3D ContentType.HTML; +- response.write(await page.generate(request.uri.queryParameters)= ); +- response.close(); +- return; +- } +- } +- +- await respond(request, createUnknownPage(path), HttpStatus.NOT_FOUN= D); +- } catch (e, st) { +- try { +- await respond(request, createExceptionPage('$e', st), +- HttpStatus.INTERNAL_SERVER_ERROR); +- } catch (e, st) { +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.INTERNAL_SERVER_ERROR; +- response.headers.contentType =3D ContentType.TEXT; +- response.write('$e\n\n$st'); +- response.close(); +- } +- } +- } +- +- Future respond(HttpRequest request, Page page, +- [int code =3D HttpStatus.OK]) async { +- HttpResponse response =3D request.response; +- response.statusCode =3D code; +- response.headers.contentType =3D ContentType.HTML; +- response.write(await page.generate(request.uri.queryParameters)); +- response.close(); +- } +- +- void respondRedirect(HttpRequest request, String pathFragment) { +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.MOVED_TEMPORARILY; +- response.redirect(request.uri.resolve(pathFragment)); +- } +-} +diff --git a/pkg/analysis_server/lib/src/status/tree_writer.dart b/pkg/ana= lysis_server/lib/src/status/tree_writer.dart +deleted file mode 100644 +index e6b45709578..00000000000 +--- a/pkg/analysis_server/lib/src/status/tree_writer.dart ++++ /dev/null +@@ -1,123 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/src/dart/element/element.dart'; +-import 'package:analyzer/src/generated/constant.dart'; +-import 'package:analyzer/src/generated/source.dart'; +- +-/** +- * Utility methods that can be mixed in to classes that produce an HTML +- * representation of a tree structure. +- */ +-abstract class TreeWriter { +- /** +- * The buffer on which the HTML is to be written. +- */ +- StringBuffer buffer; +- +- /** +- * The current level of indentation. +- */ +- int indentLevel =3D 0; +- +- /** +- * A list containing the exceptions that were caught while attempting t= o write +- * out the tree structure. +- */ +- List exceptions =3D []; +- +- void indent([int extra =3D 0]) { +- for (int i =3D 0; i < indentLevel; i++) { +- buffer.write('┊   '); +- } +- if (extra > 0) { +- buffer.write('┊   '); +- for (int i =3D 1; i < extra; i++) { +- buffer.write('     '); +- } +- } +- } +- +- /** +- * Write a representation of the given [properties] to the buffer. +- */ +- void writeProperties(Map properties) { +- List propertyNames =3D properties.keys.toList(); +- propertyNames.sort(); +- for (String propertyName in propertyNames) { +- writeProperty(propertyName, properties[propertyName]); +- } +- } +- +- /** +- * Write the [value] of the property with the given [name]. +- */ +- void writeProperty(String name, Object value) { +- if (value !=3D null) { +- indent(2); +- buffer.write('$name =3D '); +- _writePropertyValue(value, indentLevel); +- buffer.write('
    '); +- } +- } +- +- String _toString(Object value) { +- try { +- if (value is Source) { +- return 'Source (uri=3D"${value.uri}", path=3D"${value.fullName}")= '; +- } else if (value is ElementAnnotationImpl) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write(_toString(value.element)); +- EvaluationResultImpl result =3D value.evaluationResult; +- if (result =3D=3D null) { +- buffer.write(': no result'); +- } else { +- buffer.write(': value =3D '); +- buffer.write(result.value); +- buffer.write('; errors =3D '); +- buffer.write(result.errors); +- } +- return buffer.toString(); +- } else { +- return value.toString(); +- } +- } catch (exception, stackTrace) { +- exceptions.add(new CaughtException(exception, stackTrace)); +- } +- return null; +- } +- +- /** +- * Write the [value] of the property with the given [name]. +- */ +- void _writePropertyValue(Object value, int baseIndent) { +- if (value is List) { +- if (value.isEmpty) { +- buffer.write('[]'); +- } else { +- int elementIndent =3D baseIndent + 2; +- buffer.write('[
    '); +- for (Object element in value) { +- indent(elementIndent); +- _writePropertyValue(element, elementIndent); +- buffer.write('
    '); +- } +- indent(baseIndent); +- buffer.write(']'); +- } +- } else { +- String valueString =3D _toString(value); +- if (valueString =3D=3D null) { +- buffer.write(''); +- buffer.write(HTML_ESCAPE.convert(value.runtimeType.toString())); +- buffer.write(''); +- } else { +- buffer.write(HTML_ESCAPE.convert(valueString)); +- } +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/utilities/documentation.dart b/pk= g/analysis_server/lib/src/utilities/documentation.dart +deleted file mode 100644 +index 2cc837e0b56..00000000000 +--- a/pkg/analysis_server/lib/src/utilities/documentation.dart ++++ /dev/null +@@ -1,67 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-String getDartDocSummary(String str) { +- if (str =3D=3D null) { +- return null; +- } +- List lines =3D str.split('\n'); +- StringBuffer sb =3D new StringBuffer(); +- bool firstLine =3D true; +- for (String line in lines) { +- if (sb.length !=3D 0 && line.isEmpty) { +- return sb.toString(); +- } +- if (!firstLine) { +- sb.write('\n'); +- } +- firstLine =3D false; +- sb.write(line); +- } +- return sb.toString(); +-} +- +-/** +- * Converts [str] from a Dart Doc string with slashes and stars to a plai= n text +- * representation of the comment. +- */ +-String removeDartDocDelimiters(String str) { +- if (str =3D=3D null) { +- return null; +- } +- // remove /** */ +- if (str.startsWith('/**')) { +- str =3D str.substring(3); +- } +- if (str.endsWith("*/")) { +- str =3D str.substring(0, str.length - 2); +- } +- str =3D str.trim(); +- // remove leading '* ' and '/// ' +- List lines =3D str.split('\n'); +- StringBuffer sb =3D new StringBuffer(); +- bool firstLine =3D true; +- for (String line in lines) { +- line =3D line.trim(); +- if (line.startsWith("*")) { +- line =3D line.substring(1); +- if (line.startsWith(" ")) { +- line =3D line.substring(1); +- } +- } else if (line.startsWith("///")) { +- line =3D line.substring(3); +- if (line.startsWith(" ")) { +- line =3D line.substring(1); +- } +- } +- if (!firstLine) { +- sb.write('\n'); +- } +- firstLine =3D false; +- sb.write(line); +- } +- str =3D sb.toString(); +- // done +- return str; +-} +diff --git a/pkg/analysis_server/lib/src/utilities/flutter.dart b/pkg/anal= ysis_server/lib/src/utilities/flutter.dart +deleted file mode 100644 +index b49c372a7f6..00000000000 +--- a/pkg/analysis_server/lib/src/utilities/flutter.dart ++++ /dev/null +@@ -1,267 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/change_builder/change_builder_d= art.dart'; +- +-const _WIDGET_NAME =3D "Widget"; +-const _WIDGET_URI =3D "package:flutter/src/widgets/framework.dart"; +- +-void convertChildToChildren( +- InstanceCreationExpression childArg, +- NamedExpression namedExp, +- String eol, +- Function getNodeText, +- Function getLinePrefix, +- Function getIndent, +- Function getText, +- Function _addInsertEdit, +- Function _addRemoveEdit, +- Function _addReplaceEdit, +- Function rangeNode) { +- int childLoc =3D namedExp.offset + 'child'.length; +- _addInsertEdit(childLoc, 'ren'); +- int listLoc =3D childArg.offset; +- String childArgSrc =3D getNodeText(childArg); +- if (!childArgSrc.contains(eol)) { +- _addInsertEdit(listLoc, '['); +- _addInsertEdit(listLoc + childArg.length, ']'); +- } else { +- int newlineLoc =3D childArgSrc.lastIndexOf(eol); +- if (newlineLoc =3D=3D childArgSrc.length) { +- newlineLoc -=3D 1; +- } +- String indentOld =3D getLinePrefix(childArg.offset + 1 + newlineLoc); +- String indentNew =3D '$indentOld${getIndent(1)}'; +- // The separator includes 'child:' but that has no newlines. +- String separator =3D +- getText(namedExp.offset, childArg.offset - namedExp.offset); +- String prefix =3D separator.contains(eol) ? "" : "$eol$indentNew"; +- if (prefix.isEmpty) { +- _addInsertEdit(namedExp.offset + 'child:'.length, ' ['); +- _addRemoveEdit(new SourceRange(childArg.offset - 2, 2)); +- } else { +- _addInsertEdit(listLoc, '['); +- } +- String newChildArgSrc =3D childArgSrc.replaceAll( +- new RegExp("^$indentOld", multiLine: true), "$indentNew"); +- newChildArgSrc =3D "$prefix$newChildArgSrc,$eol$indentOld]"; +- _addReplaceEdit(rangeNode(childArg), newChildArgSrc); +- } +-} +- +-void convertChildToChildren2( +- DartFileEditBuilder builder, +- InstanceCreationExpression childArg, +- NamedExpression namedExp, +- String eol, +- Function getNodeText, +- Function getLinePrefix, +- Function getIndent, +- Function getText, +- Function rangeNode) { +- int childLoc =3D namedExp.offset + 'child'.length; +- builder.addSimpleInsertion(childLoc, 'ren'); +- int listLoc =3D childArg.offset; +- String childArgSrc =3D getNodeText(childArg); +- if (!childArgSrc.contains(eol)) { +- builder.addSimpleInsertion(listLoc, '['); +- builder.addSimpleInsertion(listLoc + childArg.length, ']'); +- } else { +- int newlineLoc =3D childArgSrc.lastIndexOf(eol); +- if (newlineLoc =3D=3D childArgSrc.length) { +- newlineLoc -=3D 1; +- } +- String indentOld =3D getLinePrefix(childArg.offset + 1 + newlineLoc); +- String indentNew =3D '$indentOld${getIndent(1)}'; +- // The separator includes 'child:' but that has no newlines. +- String separator =3D +- getText(namedExp.offset, childArg.offset - namedExp.offset); +- String prefix =3D separator.contains(eol) ? "" : "$eol$indentNew"; +- if (prefix.isEmpty) { +- builder.addSimpleInsertion( +- namedExp.offset + 'child:'.length, ' ['); +- builder.addDeletion(new SourceRange(childArg.offset - 2, 2)); +- } else { +- builder.addSimpleInsertion(listLoc, '['); +- } +- String newChildArgSrc =3D childArgSrc.replaceAll( +- new RegExp("^$indentOld", multiLine: true), "$indentNew"); +- newChildArgSrc =3D "$prefix$newChildArgSrc,$eol$indentOld]"; +- builder.addSimpleReplacement(rangeNode(childArg), newChildArgSrc); +- } +-} +- +-/** +- * Return the named expression representing the 'child' argument of the g= iven +- * [newExpr], or null if none. +- */ +-NamedExpression findChildArgument(InstanceCreationExpression newExpr) =3D> +- newExpr.argumentList.arguments.firstWhere( +- (arg) =3D> arg is NamedExpression && arg.name.label.name =3D=3D '= child', +- orElse: () =3D> null); +- +-/** +- * Return the Flutter instance creation expression that is the value of t= he +- * 'child' argument of the given [newExpr], or null if none. +- */ +-InstanceCreationExpression findChildWidget(InstanceCreationExpression new= Expr) { +- NamedExpression child =3D findChildArgument(newExpr); +- return getChildWidget(child); +-} +- +-/** +- * If the given [node] is a simple identifier, find the named expression = whose +- * name is the given [name] that is an argument to a Flutter instance cre= ation +- * expression. Return null if any condition cannot be satisfied. +- */ +-NamedExpression findNamedExpression(AstNode node, String name) { +- if (node is! SimpleIdentifier) { +- return null; +- } +- SimpleIdentifier namedArg =3D node; +- NamedExpression namedExp; +- if (namedArg.parent is Label && namedArg.parent.parent is NamedExpressi= on) { +- namedExp =3D namedArg.parent.parent; +- if (namedArg.name !=3D name || namedExp.expression =3D=3D null) { +- return null; +- } +- } else { +- return null; +- } +- if (namedExp.parent?.parent is! InstanceCreationExpression) { +- return null; +- } +- InstanceCreationExpression newExpr =3D namedExp.parent.parent; +- if (newExpr =3D=3D null || !isWidgetCreation(newExpr)) { +- return null; +- } +- return namedExp; +-} +- +-ListLiteral getChildList(NamedExpression child) { +- if (child.expression is ListLiteral) { +- ListLiteral list =3D child.expression; +- if (list.elements.isEmpty || +- list.elements.every((element) =3D> +- element is InstanceCreationExpression && +- isWidgetCreation(element))) { +- return list; +- } +- } +- return null; +-} +- +-/** +- * Return the Flutter instance creation expression that is the value of t= he +- * given [child], or null if none. If [strict] is true, require the value= to +- * also have a 'child' argument. +- */ +-InstanceCreationExpression getChildWidget(NamedExpression child, +- [bool strict =3D false]) { +- if (child?.expression is InstanceCreationExpression) { +- InstanceCreationExpression childNewExpr =3D child.expression; +- if (isWidgetCreation(childNewExpr)) { +- if (!strict || (findChildArgument(childNewExpr) !=3D null)) { +- return childNewExpr; +- } +- } +- } +- return null; +-} +- +-/** +- * Return the presentation for the given Flutter `Widget` creation [node]. +- */ +-String getWidgetPresentationText(InstanceCreationExpression node) { +- ClassElement element =3D node.staticElement?.enclosingElement; +- if (!isWidget(element)) { +- return null; +- } +- List arguments =3D node.argumentList.arguments; +- if (_isExactWidget( +- element, 'Icon', 'package:flutter/src/widgets/icon.dart')) { +- if (arguments.isNotEmpty) { +- String text =3D arguments[0].toString(); +- String arg =3D shorten(text, 32); +- return 'Icon($arg)'; +- } else { +- return 'Icon'; +- } +- } +- if (_isExactWidget( +- element, 'Text', 'package:flutter/src/widgets/text.dart')) { +- if (arguments.isNotEmpty) { +- String text =3D arguments[0].toString(); +- String arg =3D shorten(text, 32); +- return 'Text($arg)'; +- } else { +- return 'Text'; +- } +- } +- return element.name; +-} +- +-/** +- * Return the instance creation expression that surrounds the given +- * [node], if any, else null. The [node] may be the instance creation +- * expression itself or the identifier that names the constructor. +- */ +-InstanceCreationExpression identifyNewExpression(AstNode node) { +- InstanceCreationExpression newExpr; +- if (node is SimpleIdentifier) { +- if (node.parent is ConstructorName && +- node.parent.parent is InstanceCreationExpression) { +- newExpr =3D node.parent.parent; +- } else if (node.parent?.parent is ConstructorName && +- node.parent.parent?.parent is InstanceCreationExpression) { +- newExpr =3D node.parent.parent.parent; +- } +- } else if (node is InstanceCreationExpression) { +- newExpr =3D node; +- } +- return newExpr; +-} +- +-/** +- * Return `true` if the given [element] has the Flutter class `Widget` as +- * a superclass. +- */ +-bool isWidget(ClassElement element) { +- if (element =3D=3D null) { +- return false; +- } +- for (InterfaceType type in element.allSupertypes) { +- if (type.name =3D=3D _WIDGET_NAME) { +- Uri uri =3D type.element.source.uri; +- if (uri.toString() =3D=3D _WIDGET_URI) { +- return true; +- } +- } +- } +- return false; +-} +- +-/** +- * Return `true` if the given [expr] is a constructor invocation for a +- * class that has the Flutter class `Widget` as a superclass. +- */ +-bool isWidgetCreation(InstanceCreationExpression expr) { +- ClassElement element =3D expr.staticElement?.enclosingElement; +- return isWidget(element); +-} +- +-/** +- * Return `true` if the given [element] is the exact [type] defined in the +- * file with the given [uri]. +- */ +-bool _isExactWidget(ClassElement element, String type, String uri) { +- return element !=3D null && +- element.name =3D=3D type && +- element.source.uri.toString() =3D=3D uri; +-} +diff --git a/pkg/analysis_server/lib/src/utilities/null_string_sink.dart b= /pkg/analysis_server/lib/src/utilities/null_string_sink.dart +deleted file mode 100644 +index 27fef3a0682..00000000000 +--- a/pkg/analysis_server/lib/src/utilities/null_string_sink.dart ++++ /dev/null +@@ -1,13 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * A string sink that ignores everything written to it. +- */ +-class NullStringSink implements StringSink { +- void write(Object obj) {} +- void writeAll(Iterable objects, [String separator =3D ""]) {} +- void writeCharCode(int charCode) {} +- void writeln([Object obj =3D ""]) {} +-} +diff --git a/pkg/analysis_server/lib/src/utilities/profiling.dart b/pkg/an= alysis_server/lib/src/utilities/profiling.dart +deleted file mode 100644 +index 7e2e49bc626..00000000000 +--- a/pkg/analysis_server/lib/src/utilities/profiling.dart ++++ /dev/null +@@ -1,89 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-/// A class that can return memory and cpu usage information for a given +-/// process. +-abstract class ProcessProfiler { +- ProcessProfiler._(); +- +- Future getProcessUsage(int processId); +- +- UsageInfo getProcessUsageSync(int processId); +- +- /// Return a [ProcessProfiler] instance suitable for the current host +- /// platform. This can return `null` if we're not able to gather memory= and +- /// cpu information for the current platform. +- static ProcessProfiler getProfilerForPlatform() { +- if (Platform.isLinux || Platform.isMacOS) { +- return new _PosixProcessProfiler(); +- } +- +- // Not a supported platform. +- return null; +- } +-} +- +-class UsageInfo { +- /// A number between 0.0 and 100.0 * the number of host CPUs (but typic= ally +- /// never more than slightly above 100.0). +- final double cpuPercentage; +- +- /// The process memory usage in kilobytes. +- final int memoryKB; +- +- UsageInfo(this.cpuPercentage, this.memoryKB); +- +- double get memoryMB =3D> memoryKB / 1024; +- +- String toString() =3D> '$cpuPercentage% ${memoryMB.toStringAsFixed(1)}M= B'; +-} +- +-class _PosixProcessProfiler extends ProcessProfiler { +- static final RegExp stringSplitRegExp =3D new RegExp(r'\s+'); +- +- _PosixProcessProfiler() : super._(); +- +- @override +- Future getProcessUsage(int processId) { +- try { +- // Execution time is typically 2-4ms. +- Future future =3D +- Process.run('ps', ['-o', '%cpu=3D,rss=3D', processId.toString()= ]); +- return future.then((ProcessResult result) { +- if (result.exitCode !=3D 0) { +- return new Future.value(null); +- } +- +- return new Future.value(_parse(result.stdout)); +- }); +- } catch (e) { +- return new Future.error(e); +- } +- } +- +- UsageInfo getProcessUsageSync(int processId) { +- try { +- // Execution time is typically 2-4ms. +- ProcessResult result =3D +- Process.runSync('ps', ['-o', '%cpu=3D,rss=3D', processId.toStri= ng()]); +- return result.exitCode =3D=3D 0 ? _parse(result.stdout) : null; +- } catch (e) { +- return null; +- } +- } +- +- UsageInfo _parse(String psResults) { +- try { +- // " 0.0 378940" +- String line =3D psResults.split('\n').first.trim(); +- List values =3D line.split(stringSplitRegExp); +- return new UsageInfo(double.parse(values[0]), int.parse(values[1])); +- } catch (e) { +- return null; +- } +- } +-} +diff --git a/pkg/analysis_server/lib/src/watch_manager.dart b/pkg/analysis= _server/lib/src/watch_manager.dart +deleted file mode 100644 +index 8a3fc97d809..00000000000 +--- a/pkg/analysis_server/lib/src/watch_manager.dart ++++ /dev/null +@@ -1,285 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:core'; +- +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:watcher/watcher.dart'; +- +-/** +- * A function called when a watch [event] associated with a watched resou= rce is +- * received. The list of [tokens] will contain all of the tokens associat= ed with +- * folders containing (or the same as) the watched resource. +- */ +-typedef void HandleWatchEvent(WatchEvent event, List tokens); +- +-/** +- * An object that manages a collections of folders that need to be watche= d in +- * order to ensure that we are watching the minimum number of folders. +- * +- * Each folder can be watched multiple times. In order to differentiate b= etween +- * the watch requests, each watch request has a *token* associated with i= t. The +- * tokens that are used must correctly implement both [=3D=3D] and [hashC= ode]. +- */ +-class WatchManager { +- /** +- * The resource provider used to convert paths to resources. +- */ +- final ResourceProvider provider; +- +- /** +- * The function that is invoked when a watch event is received. +- */ +- final HandleWatchEvent handleWatchEvent; +- +- /** +- * A node representing the (conceptual) root of all other folders. +- */ +- final WatchNode rootNode =3D new WatchNode(null); +- +- /** +- * A table mapping the folders that are being watched to the nodes +- * representing those folders. +- */ +- final Map> _watchedFolders =3D +- new HashMap>(); +- +- /** +- * Initialize a newly created watch manager to use the resource [provid= er] to +- * convert file paths to resources and to call the [handleWatchEvent] f= unction +- * to notify the owner of the manager when resources have been changed. +- */ +- WatchManager(this.provider, this.handleWatchEvent); +- +- /** +- * Record the fact that we are now watching the given [folder], and ass= ociate +- * that folder with the given [token]. If the folder is already being w= atched +- * and is already associated with the token, then this request is effec= tively +- * ignored. +- */ +- void addFolder(Folder folder, T token) { +- WatchNode folderNode =3D _watchedFolders[folder]; +- // +- // If the folder was already being watched, just record the new token. +- // +- if (folderNode !=3D null) { +- folderNode.tokens.add(token); +- return; +- } +- // +- // Otherwise, add the folder to the tree. +- // +- folderNode =3D new WatchNode(folder); +- _watchedFolders[folder] =3D folderNode; +- folderNode.tokens.add(token); +- WatchNode parentNode =3D rootNode.insert(folderNode); +- // +- // If we are not watching a folder that contains the folder, then cre= ate a +- // subscription for it. +- // +- if (parentNode =3D=3D rootNode) { +- folderNode.subscription =3D folder.changes.listen(_handleWatchEvent= ); +- // +- // Any nodes that became children of the newly added folder would h= ave +- // been top-level folders and would have been watched. We need to c= ancel +- // their subscriptions. +- // +- for (WatchNode childNode in folderNode.children) { +- assert(childNode.subscription !=3D null); +- if (childNode.subscription !=3D null) { +- childNode.subscription.cancel(); +- childNode.subscription =3D null; +- } +- } +- } +- } +- +- /** +- * Record that we are no longer watching the given [folder] with the gi= ven +- * [token]. +- * +- * Throws a [StateError] if the folder is not be watched or is not asso= ciated +- * with the given token. +- */ +- void removeFolder(Folder folder, T token) { +- WatchNode folderNode =3D _watchedFolders[folder]; +- if (folderNode =3D=3D null) { +- assert(false); +- return; +- } +- Set tokens =3D folderNode.tokens; +- if (!tokens.remove(token)) { +- assert(false); +- } +- // +- // If this was the last token associated with this folder, then remov= e the +- // folder from the tree. +- // +- if (tokens.isEmpty) { +- // +- // If the folder was a top-level folder, then we need to create +- // subscriptions for all of its children and cancel its subscriptio= n. +- // +- if (folderNode.subscription !=3D null) { +- for (WatchNode childNode in folderNode.children) { +- assert(childNode.subscription =3D=3D null); +- childNode.subscription =3D +- childNode.folder.changes.listen(_handleWatchEvent); +- } +- folderNode.subscription.cancel(); +- folderNode.subscription =3D null; +- } +- folderNode.delete(); +- _watchedFolders.remove(folder); +- } +- } +- +- /** +- * Dispatch the given event by finding all of the tokens that contain t= he +- * resource and invoke the [handleWatchEvent] function. +- */ +- void _handleWatchEvent(WatchEvent event) { +- String path =3D event.path; +- List tokens =3D []; +- WatchNode parent =3D rootNode.findParent(path); +- while (parent !=3D rootNode) { +- tokens.addAll(parent.tokens); +- parent =3D parent.parent; +- } +- if (tokens.isNotEmpty) { +- handleWatchEvent(event, tokens); +- } +- } +-} +- +-/** +- * The information kept by a [WatchManager] about a single folder that is= being +- * watched. +- * +- * Watch nodes form a tree in which one node is a child of another node i= f the +- * child's folder is contained in the parent's folder and none of the fol= ders +- * between the parent's folder and the child's folder are being watched. +- */ +-class WatchNode { +- /** +- * The folder for which information is being maintained. This is `null`= for +- * the unique "root" node that maintains references to all of the top-l= evel +- * folders being watched. +- */ +- final Folder folder; +- +- /** +- * The parent of this node. +- */ +- WatchNode parent; +- +- /** +- * The information for the children of this node. +- */ +- final List> _children =3D >[]; +- +- /** +- * The tokens that were used to register interest in watching this fold= er. +- */ +- final Set tokens =3D new HashSet(); +- +- /** +- * The subscription being used to watch the folder, or `null` if the fo= lder +- * is being watched as part of a containing folder (in other words, if = the +- * parent is not the special "root"). +- */ +- StreamSubscription subscription; +- +- /** +- * Initialize a newly created node to represent the given [folder]. +- */ +- WatchNode(this.folder); +- +- /** +- * Return a list containing the children of this node. +- */ +- Iterable> get children =3D> _children; +- +- /** +- * Remove this node from the tree of watched folders. +- */ +- void delete() { +- if (parent !=3D null) { +- parent._removeChild(this); +- parent =3D null; +- } +- } +- +- /** +- * Return the highest node reachable from this node that contains the g= iven +- * [filePath]. If no other node is found, return this node, even if thi= s node +- * does not contain the path. +- */ +- WatchNode findParent(String filePath) { +- if (_children =3D=3D null) { +- return this; +- } +- for (WatchNode childNode in _children) { +- if (childNode.folder.isOrContains(filePath)) { +- return childNode.findParent(filePath); +- } +- } +- return this; +- } +- +- /** +- * Insert the given [node] into the tree of watched folders, either as = a child +- * of this node or as a descendent of one of this node's children. Retu= rn the +- * immediate parent of the newly added node. +- */ +- WatchNode insert(WatchNode node) { +- WatchNode parentNode =3D findParent(node.folder.path); +- parentNode._addChild(node, true); +- return parentNode; +- } +- +- @override +- String toString() =3D> 'WatchNode (' +- 'folder =3D ${folder =3D=3D null ? '' : folder.path}, ' +- 'tokens =3D $tokens, ' +- 'subscription =3D ${subscription =3D=3D null ? 'null' : 'non-null'}= )'; +- +- /** +- * Add the given [newChild] as an immediate child of this node. +- * +- * If [checkChildren] is `true`, check to see whether any of the previo= usly +- * existing children of this node should now be children of the new chi= ld, and +- * if so, move them. +- */ +- void _addChild(WatchNode newChild, bool checkChildren) { +- if (checkChildren) { +- Folder folder =3D newChild.folder; +- for (int i =3D _children.length - 1; i >=3D 0; i--) { +- WatchNode existingChild =3D _children[i]; +- if (folder.contains(existingChild.folder.path)) { +- newChild._addChild(existingChild, false); +- _children.removeAt(i); +- } +- } +- } +- newChild.parent =3D this; +- _children.add(newChild); +- } +- +- /** +- * Remove the given [node] from the list of children of this node. Any +- * children of the [node] will become children of this node. +- */ +- void _removeChild(WatchNode child) { +- _children.remove(child); +- Iterable> grandchildren =3D child.children; +- for (WatchNode grandchild in grandchildren) { +- grandchild.parent =3D this; +- _children.add(grandchild); +- } +- child._children.clear(); +- } +-} +diff --git a/pkg/analysis_server/lib/starter.dart b/pkg/analysis_server/li= b/starter.dart +deleted file mode 100644 +index cca06dab3a8..00000000000 +--- a/pkg/analysis_server/lib/starter.dart ++++ /dev/null +@@ -1,49 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/server/driver.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/plugin/resolver_provider.dart'; +- +-/** +- * An object that can be used to start an analysis server. This class exi= sts so +- * that clients can configure an analysis server before starting it. +- * +- * Clients may not extend, implement or mix-in this class. +- */ +-abstract class ServerStarter { +- /** +- * Initialize a newly created starter to start up an analysis server. +- */ +- factory ServerStarter() =3D Driver; +- +- /** +- * Set the file resolver provider used to override the way file URI's +- * are resolved in some contexts. The provider should return `null` if = the +- * default file resolution scheme should be used instead. +- */ +- void set fileResolverProvider(ResolverProvider provider); +- +- /** +- * Set the instrumentation [server] that is to be used by the analysis = server. +- */ +- void set instrumentationServer(InstrumentationServer server); +- +- /** +- * Set the package resolver provider used to override the way package U= RI's +- * are resolved in some contexts. The provider should return `null` if = the +- * default package resolution scheme should be used instead. +- */ +- void set packageResolverProvider(ResolverProvider provider); +- +- /** +- * Use the given command-line [arguments] to start this server. +- * +- * At least temporarily returns AnalysisServer so that consumers of the +- * starter API can then use the server, this is done as a stopgap for t= he +- * angular plugin until the official plugin API is finished. +- */ +- AnalysisServer start(List arguments); +-} +diff --git a/pkg/analysis_server/pubspec.yaml b/pkg/analysis_server/pubspe= c.yaml +deleted file mode 100644 +index 5a920345285..00000000000 +--- a/pkg/analysis_server/pubspec.yaml ++++ /dev/null +@@ -1,27 +0,0 @@ +-name: analysis_server +-version: 0.1.1-dev +-author: Dart Team +-description: A server that performs analysis of Dart code over character = streams using JSON-RPC encoded information. +-homepage: http://www.dartlang.org +-environment: +- sdk: '>=3D1.12.0 <2.0.0' +-dependencies: +- analyzer: ^0.30.0 +- args: '>=3D0.13.0 <0.14.0' +- dart_style: '^1.0.6' +- intl: ^0.15.0 +- isolate: '>=3D0.2.2 <2.0.0' +- linter: ^0.1.16 +- logging: any +- package_config: '>=3D0.1.5 <2.0.0' +- path: any +- plugin: ^0.2.0 +- telemetry: ^0.0.1 +- usage: ^3.2.0+1 +- watcher: any +- yaml: any +-dev_dependencies: +- html: any +- test_reflective_loader: ^0.1.0 +- mockito: ^2.0.2 +- test: ^0.12.17 +diff --git a/pkg/analysis_server/test/abstract_context.dart b/pkg/analysis= _server/test/abstract_context.dart +deleted file mode 100644 +index 850f2ca7d1d..00000000000 +--- a/pkg/analysis_server/test/abstract_context.dart ++++ /dev/null +@@ -1,172 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/dart/element/visitor.dart'; +-import 'package:analyzer/exception/exception.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/file_state.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/engine.dart' as engine; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source_io.dart'; +-import 'package:front_end/byte_store.dart'; +-import 'package:front_end/src/base/performance_logger.dart'; +- +-import 'mock_sdk.dart'; +- +-/** +- * Finds an [Element] with the given [name]. +- */ +-Element findChildElement(Element root, String name, [ElementKind kind]) { +- Element result =3D null; +- root.accept(new _ElementVisitorFunctionWrapper((Element element) { +- if (element.name !=3D name) { +- return; +- } +- if (kind !=3D null && element.kind !=3D kind) { +- return; +- } +- result =3D element; +- })); +- return result; +-} +- +-/** +- * A function to be called for every [Element]. +- */ +-typedef void _ElementVisitorFunction(Element element); +- +-class AbstractContextTest { +- MemoryResourceProvider provider; +- DartSdk sdk; +- Map> packageMap; +- UriResolver resourceResolver; +- +- StringBuffer _logBuffer =3D new StringBuffer(); +- FileContentOverlay _fileContentOverlay =3D new FileContentOverlay(); +- AnalysisDriver _driver; +- +- AnalysisDriver get driver =3D> _driver; +- +- Source addMetaPackageSource() =3D> addPackageSource('meta', 'meta.dart'= , r''' +-library meta; +- +-const Required required =3D const Required(); +- +-class Required { +- final String reason; +- const Required([this.reason]); +-} +-'''); +- +- Source addPackageSource(String packageName, String filePath, String con= tent) { +- packageMap[packageName] =3D [(newFolder('/pubcache/$packageName/lib')= )]; +- File file =3D newFile('/pubcache/$packageName/lib/$filePath', content= ); +- return file.createSource(); +- } +- +- Source addSource(String path, String content, [Uri uri]) { +- if (path.startsWith('/')) { +- path =3D provider.convertPath(path); +- } +- File file =3D newFile(path, content); +- Source source =3D file.createSource(uri); +- driver.addFile(path); +- driver.changeFile(path); +- _fileContentOverlay[path] =3D content; +- return source; +- } +- +- File newFile(String path, [String content]) =3D> +- provider.newFile(provider.convertPath(path), content ?? ''); +- +- Folder newFolder(String path) =3D> +- provider.newFolder(provider.convertPath(path)); +- +- void processRequiredPlugins() { +- AnalysisEngine.instance.processRequiredPlugins(); +- } +- +- Future resolveLibraryUnit(Source source) async { +- return (await driver.getResult(source.fullName))?.unit; +- } +- +- void setUp() { +- processRequiredPlugins(); +- setupResourceProvider(); +- sdk =3D new MockSdk(resourceProvider: provider); +- resourceResolver =3D new ResourceUriResolver(provider); +- packageMap =3D new Map>(); +- PackageMapUriResolver packageResolver =3D +- new PackageMapUriResolver(provider, packageMap); +- SourceFactory sourceFactory =3D new SourceFactory( +- [new DartUriResolver(sdk), packageResolver, resourceResolver]); +- PerformanceLog log =3D new PerformanceLog(_logBuffer); +- AnalysisDriverScheduler scheduler =3D new AnalysisDriverScheduler(log= ); +- _driver =3D new AnalysisDriver( +- scheduler, +- log, +- provider, +- new MemoryByteStore(), +- _fileContentOverlay, +- null, +- sourceFactory, +- new AnalysisOptionsImpl()..strongMode =3D true); +- scheduler.start(); +- AnalysisEngine.instance.logger =3D PrintLogger.instance; +- } +- +- void setupResourceProvider() { +- provider =3D new MemoryResourceProvider(); +- } +- +- void tearDown() { +- provider =3D null; +- AnalysisEngine.instance.clearCaches(); +- AnalysisEngine.instance.logger =3D null; +- } +-} +- +-/** +- * Instances of the class [PrintLogger] print all of the errors. +- */ +-class PrintLogger implements Logger { +- static final Logger instance =3D new PrintLogger(); +- +- @override +- void logError(String message, [CaughtException exception]) { +- print(message); +- if (exception !=3D null) { +- print(exception); +- } +- } +- +- @override +- void logInformation(String message, [CaughtException exception]) { +- print(message); +- if (exception !=3D null) { +- print(exception); +- } +- } +-} +- +-/** +- * Wraps the given [_ElementVisitorFunction] into an instance of +- * [engine.GeneralizingElementVisitor]. +- */ +-class _ElementVisitorFunctionWrapper extends GeneralizingElementVisitor { +- final _ElementVisitorFunction function; +- _ElementVisitorFunctionWrapper(this.function); +- visitElement(Element element) { +- function(element); +- super.visitElement(element); +- } +-} +diff --git a/pkg/analysis_server/test/abstract_single_unit.dart b/pkg/anal= ysis_server/test/abstract_single_unit.dart +deleted file mode 100644 +index 86601445dfe..00000000000 +--- a/pkg/analysis_server/test/abstract_single_unit.dart ++++ /dev/null +@@ -1,144 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/visitor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/ast/utilities.dart'; +-import 'package:analyzer/src/dart/error/hint_codes.dart'; +-import 'package:analyzer/src/generated/java_engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:test/test.dart'; +- +-import 'abstract_context.dart'; +- +-class AbstractSingleUnitTest extends AbstractContextTest { +- bool verifyNoTestUnitErrors =3D true; +- +- String testCode; +- String testFile =3D '/test.dart'; +- Source testSource; +- CompilationUnit testUnit; +- CompilationUnitElement testUnitElement; +- LibraryElement testLibraryElement; +- +- void addTestSource(String code, [Uri uri]) { +- testCode =3D code; +- testSource =3D addSource(testFile, code, uri); +- } +- +- Element findElement(String name, [ElementKind kind]) { +- return findChildElement(testUnitElement, name, kind); +- } +- +- int findEnd(String search) { +- return findOffset(search) + search.length; +- } +- +- /** +- * Returns the [SimpleIdentifier] at the given search pattern. +- */ +- SimpleIdentifier findIdentifier(String search) { +- return findNodeAtString(search, (node) =3D> node is SimpleIdentifier); +- } +- +- /** +- * Search the [testUnit] for the [LocalVariableElement] with the given = [name]. +- * Fail if there is not exactly one such variable. +- */ +- LocalVariableElement findLocalVariable(String name) { +- var finder =3D new _ElementsByNameFinder(name); +- testUnit.accept(finder); +- List localVariables =3D +- finder.elements.where((e) =3D> e is LocalVariableElement).toList(= ); +- expect(localVariables, hasLength(1)); +- return localVariables[0]; +- } +- +- AstNode findNodeAtOffset(int offset, [Predicate predicate]) { +- AstNode result =3D new NodeLocator(offset).searchWithin(testUnit); +- if (result !=3D null && predicate !=3D null) { +- result =3D result.getAncestor(predicate); +- } +- return result; +- } +- +- AstNode findNodeAtString(String search, [Predicate predicate])= { +- int offset =3D findOffset(search); +- return findNodeAtOffset(offset, predicate); +- } +- +- Element findNodeElementAtString(String search, +- [Predicate predicate]) { +- AstNode node =3D findNodeAtString(search, predicate); +- if (node =3D=3D null) { +- return null; +- } +- return ElementLocator.locate(node); +- } +- +- int findOffset(String search) { +- int offset =3D testCode.indexOf(search); +- expect(offset, isNonNegative, reason: "Not found '$search' in\n$testC= ode"); +- return offset; +- } +- +- int getLeadingIdentifierLength(String search) { +- int length =3D 0; +- while (length < search.length) { +- int c =3D search.codeUnitAt(length); +- if (c >=3D 'a'.codeUnitAt(0) && c <=3D 'z'.codeUnitAt(0)) { +- length++; +- continue; +- } +- if (c >=3D 'A'.codeUnitAt(0) && c <=3D 'Z'.codeUnitAt(0)) { +- length++; +- continue; +- } +- if (c >=3D '0'.codeUnitAt(0) && c <=3D '9'.codeUnitAt(0)) { +- length++; +- continue; +- } +- break; +- } +- return length; +- } +- +- Future resolveTestUnit(String code) async { +- addTestSource(code); +- AnalysisResult result =3D await driver.getResult(testFile); +- testUnit =3D result.unit; +- if (verifyNoTestUnitErrors) { +- expect(result.errors.where((AnalysisError error) { +- return error.errorCode !=3D HintCode.DEAD_CODE && +- error.errorCode !=3D HintCode.UNUSED_CATCH_CLAUSE && +- error.errorCode !=3D HintCode.UNUSED_CATCH_STACK && +- error.errorCode !=3D HintCode.UNUSED_ELEMENT && +- error.errorCode !=3D HintCode.UNUSED_FIELD && +- error.errorCode !=3D HintCode.UNUSED_IMPORT && +- error.errorCode !=3D HintCode.UNUSED_LOCAL_VARIABLE; +- }), isEmpty); +- } +- testUnitElement =3D testUnit.element; +- testLibraryElement =3D testUnitElement.library; +- } +-} +- +-class _ElementsByNameFinder extends RecursiveAstVisitor { +- final String name; +- final List elements =3D []; +- +- _ElementsByNameFinder(this.name); +- +- @override +- visitSimpleIdentifier(SimpleIdentifier node) { +- if (node.name =3D=3D name && node.inDeclarationContext()) { +- elements.add(node.staticElement); +- } +- } +-} +diff --git a/pkg/analysis_server/test/analysis/get_errors_test.dart b/pkg/= analysis_server/test/analysis/get_errors_test.dart +deleted file mode 100644 +index 431f5ed7651..00000000000 +--- a/pkg/analysis_server/test/analysis/get_errors_test.dart ++++ /dev/null +@@ -1,150 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetErrorsTest); +- }); +-} +- +-@reflectiveTest +-class GetErrorsTest extends AbstractAnalysisTest { +- static const String requestId =3D 'test-getError'; +- +- @override +- void setUp() { +- super.setUp(); +- server.handlers =3D [ +- new AnalysisDomainHandler(server), +- ]; +- createProject(); +- } +- +- test_afterAnalysisComplete() async { +- addTestFile(''' +-main() { +- print(42) +-} +-'''); +- await waitForTasksFinished(); +- List errors =3D await _getErrors(testFile); +- expect(errors, hasLength(1)); +- } +- +- test_errorInPart() async { +- String libPath =3D '$testFolder/main.dart'; +- String partPath =3D '$testFolder/main_part.dart'; +- addFile(libPath, r''' +-library main; +-part 'main_part.dart'; +-class A {} +-'''); +- addFile(partPath, r''' +-part of main; +-class A {} +-'''); +- await waitForTasksFinished(); +- { +- List libErrors =3D await _getErrors(libPath); +- expect(libErrors, isEmpty); +- } +- { +- List partErrors =3D await _getErrors(partPath); +- expect(partErrors, hasLength(1)); +- } +- } +- +- @failingTest +- test_fileDoesNotExist() { +- // Broken under the new driver. +- String file =3D '$projectPath/doesNotExist.dart'; +- return _checkInvalid(file); +- } +- +- @failingTest +- test_fileWithoutContext() { +- // Broken under the new driver. +- String file =3D '/outside.dart'; +- addFile(file, ''' +-main() { +- print(42); +-} +-'''); +- return _checkInvalid(file); +- } +- +- test_hasErrors() async { +- addTestFile(''' +-main() { +- print(42) +-} +-'''); +- List errors =3D await _getErrors(testFile); +- expect(errors, hasLength(1)); +- { +- AnalysisError error =3D errors[0]; +- expect(error.severity, AnalysisErrorSeverity.ERROR); +- expect(error.type, AnalysisErrorType.SYNTACTIC_ERROR); +- expect(error.location.file, testFile); +- expect(error.location.startLine, 2); +- } +- } +- +- test_noErrors() async { +- addTestFile(''' +-main() { +- print(42); +-} +-'''); +- List errors =3D await _getErrors(testFile); +- expect(errors, isEmpty); +- } +- +- @failingTest +- test_removeContextAfterRequest() async { +- // Broken under the new driver. +- addTestFile(''' +-main() { +- print(42) +-} +-'''); +- // handle the request synchronously +- Request request =3D _createGetErrorsRequest(testFile); +- server.handleRequest(request); +- // remove context, causes sending an "invalid file" error +- resourceProvider.deleteFolder(projectPath); +- // wait for an error response +- Response response =3D await serverChannel.waitForResponse(request); +- expect(response.error, isNotNull); +- expect(response.error.code, RequestErrorCode.GET_ERRORS_INVALID_FILE); +- } +- +- Future _checkInvalid(String file) async { +- Request request =3D _createGetErrorsRequest(file); +- Response response =3D await serverChannel.sendRequest(request); +- expect(response.error, isNotNull); +- expect(response.error.code, RequestErrorCode.GET_ERRORS_INVALID_FILE); +- } +- +- Request _createGetErrorsRequest(String file) { +- return new AnalysisGetErrorsParams(file).toRequest(requestId); +- } +- +- Future> _getErrors(String file) async { +- Request request =3D _createGetErrorsRequest(file); +- Response response =3D await serverChannel.sendRequest(request); +- return new AnalysisGetErrorsResult.fromResponse(response).errors; +- } +-} +diff --git a/pkg/analysis_server/test/analysis/get_hover_test.dart b/pkg/a= nalysis_server/test/analysis/get_hover_test.dart +deleted file mode 100644 +index 64cb212a4ea..00000000000 +--- a/pkg/analysis_server/test/analysis/get_hover_test.dart ++++ /dev/null +@@ -1,562 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisHoverTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisHoverTest extends AbstractAnalysisTest { +- Future prepareHover(String search) { +- int offset =3D findOffset(search); +- return prepareHoverAt(offset); +- } +- +- Future prepareHoverAt(int offset) async { +- await waitForTasksFinished(); +- Request request =3D +- new AnalysisGetHoverParams(testFile, offset).toRequest('0'); +- Response response =3D await waitResponse(request); +- var result =3D new AnalysisGetHoverResult.fromResponse(response); +- List hovers =3D result.hovers; +- return hovers.isNotEmpty ? hovers.first : null; +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- test_class() async { +- addTestFile(''' +-class A {} +-class I1 {} +-class I2 {} +-class M1 {} +-class M2 {} +-class B extends A with M1, M2 implements I1, I2 {} +-'''); +- HoverInformation hover =3D await prepareHover('B'); +- expect( +- hover.elementDescription, +- 'class B extends A with M1, M2 ' +- 'implements I1, I2'); +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- } +- +- test_class_abstract() async { +- addTestFile(''' +-class A {} +-abstract class B extends A {} +-'''); +- HoverInformation hover =3D await prepareHover('B extends'); +- expect(hover.elementDescription, 'abstract class B extends A'); +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- } +- +- test_dartdoc_clunky() async { +- addTestFile(''' +-library my.library; +-/** +- * doc aaa +- * doc bbb +- */ +-main() { +-} +-'''); +- HoverInformation hover =3D await prepareHover('main() {'); +- expect(hover.dartdoc, '''doc aaa\ndoc bbb'''); +- } +- +- test_dartdoc_elegant() async { +- addTestFile(''' +-library my.library; +-/// doc aaa +-/// doc bbb +-main() { +-} +-'''); +- HoverInformation hover =3D await prepareHover('main() {'); +- expect(hover.dartdoc, '''doc aaa\ndoc bbb'''); +- } +- +- test_dartdoc_inherited_methodByMethod_fromInterface() async { +- addTestFile(''' +-class A { +- /// my doc +- m() {} // in A +-} +- +-class B implements A { +- m() {} // in B +-} +-'''); +- HoverInformation hover =3D await prepareHover('m() {} // in B'); +- expect(hover.dartdoc, '''my doc\n\nCopied from `A`.'''); +- } +- +- test_dartdoc_inherited_methodByMethod_fromSuper_direct() async { +- addTestFile(''' +-class A { +- /// my doc +- m() {} // in A +-} +- +-class B extends A { +- m() {} // in B +-} +-'''); +- HoverInformation hover =3D await prepareHover('m() {} // in B'); +- expect(hover.dartdoc, '''my doc\n\nCopied from `A`.'''); +- } +- +- test_dartdoc_inherited_methodByMethod_fromSuper_indirect() async { +- addTestFile(''' +-class A { +- /// my doc +- m() {} +-} +-class B extends A { +- m() {} +-} +-class C extends B { +- m() {} // in C +-}'''); +- HoverInformation hover =3D await prepareHover('m() {} // in C'); +- expect(hover.dartdoc, '''my doc\n\nCopied from `A`.'''); +- } +- +- test_dartdoc_inherited_methodByMethod_preferSuper() async { +- addTestFile(''' +-class A { +- /// my doc +- m() {} +-} +-class B extends A { +-} +-class I { +- // wrong doc +- m() {} +-} +-class C extends B implements I { +- m() {} // in C +-}'''); +- HoverInformation hover =3D await prepareHover('m() {} // in C'); +- expect(hover.dartdoc, '''my doc\n\nCopied from `A`.'''); +- } +- +- test_enum() async { +- addTestFile(''' +-enum MyEnum {AAA, BBB, CCC} +-'''); +- HoverInformation hover =3D await prepareHover('MyEnum'); +- expect(hover.elementDescription, 'enum MyEnum'); +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- } +- +- test_expression_function() async { +- addTestFile(''' +-library my.library; +-/// doc aaa +-/// doc bbb +-List fff(int a, String b) { +-} +-'''); +- HoverInformation hover =3D await prepareHover('fff(int a'); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.containingClassDescription, isNull); +- expect(hover.dartdoc, '''doc aaa\ndoc bbb'''); +- expect(hover.elementDescription, 'fff(int a, String b) =E2=86=92 List= '); +- expect(hover.elementKind, 'function'); +- // types +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_expression_literal_noElement() async { +- addTestFile(''' +-main() { +- foo(123); +-} +-foo(Object myParameter) {} +-'''); +- HoverInformation hover =3D await prepareHover('123'); +- // literal, no Element +- expect(hover.containingClassDescription, isNull); +- expect(hover.elementDescription, isNull); +- expect(hover.elementKind, isNull); +- // types +- expect(hover.staticType, 'int'); +- expect(hover.propagatedType, isNull); +- // parameter +- expect(hover.parameter, 'Object myParameter'); +- } +- +- test_expression_method() async { +- addTestFile(''' +-library my.library; +-class A { +- /// doc aaa +- /// doc bbb +- List mmm(int a, String b) { +- } +-} +-'''); +- HoverInformation hover =3D await prepareHover('mmm(int a'); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.containingClassDescription, 'A'); +- expect(hover.dartdoc, '''doc aaa\ndoc bbb'''); +- expect(hover.elementDescription, 'mmm(int a, String b) =E2=86=92 List= '); +- expect(hover.elementKind, 'method'); +- // types +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_expression_method_deprecated() async { +- addTestFile(''' +-class A { +- @deprecated +- static void test() {} +-} +-main() { +- A.test(); +-} +-'''); +- HoverInformation hover =3D await prepareHover('test();'); +- // element +- expect(hover.containingLibraryPath, testFile); +- expect(hover.elementDescription, 'test() =E2=86=92 void'); +- expect(hover.elementKind, 'method'); +- expect(hover.isDeprecated, isTrue); +- } +- +- test_expression_method_invocation() async { +- addTestFile(''' +-library my.library; +-class A { +- List mmm(int a, String b) { +- } +-} +-main(A a) { +- a.mmm(42, 'foo'); +-} +-'''); +- HoverInformation hover =3D await prepareHover('mm(42, '); +- // range +- expect(hover.offset, findOffset('mmm(42, ')); +- expect(hover.length, 'mmm'.length); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.elementDescription, 'mmm(int a, String b) =E2=86=92 List= '); +- expect(hover.elementKind, 'method'); +- expect(hover.isDeprecated, isFalse); +- // types +- expect(hover.staticType, '(int, String) =E2=86=92 List'); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_expression_method_invocation_genericMethod() async { +- addTestFile(''' +-library my.library; +- +-abstract class Stream { +- Stream transform(StreamTransformer streamTransformer); +-} +-abstract class StreamTransformer {} +- +-f(Stream s) { +- s.transform(null); +-} +-'''); +- HoverInformation hover =3D await prepareHover('nsform(n'); +- // range +- expect(hover.offset, findOffset('transform(n')); +- expect(hover.length, 'transform'.length); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.elementDescription, +- 'Stream.transform(StreamTransformer streamTransformer)= =E2=86=92 Stream'); +- expect(hover.elementKind, 'method'); +- expect(hover.isDeprecated, isFalse); +- // types +- expect(hover.staticType, +- '(StreamTransformer) =E2=86=92 Stream'); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_expression_parameter() async { +- addTestFile(''' +-library my.library; +-class A { +- /// The method documentation. +- m(int p) { +- } +-} +-'''); +- HoverInformation hover =3D await prepareHover('p) {'); +- // element +- expect(hover.containingLibraryName, isNull); +- expect(hover.containingLibraryPath, isNull); +- expect(hover.containingClassDescription, isNull); +- expect(hover.dartdoc, 'The method documentation.'); +- expect(hover.elementDescription, 'int p'); +- expect(hover.elementKind, 'parameter'); +- // types +- expect(hover.staticType, 'int'); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_expression_parameter_fieldFormal_declaration() async { +- addTestFile(''' +-class A { +- /// The field documentation. +- final int fff; +- A({this.fff}); +-} +-main() { +- new A(fff: 42); +-} +-'''); +- HoverInformation hover =3D await prepareHover('fff});'); +- expect(hover.containingLibraryName, isNull); +- expect(hover.containingLibraryPath, isNull); +- expect(hover.containingClassDescription, isNull); +- expect(hover.dartdoc, 'The field documentation.'); +- expect(hover.elementDescription, '{int fff}'); +- expect(hover.elementKind, 'parameter'); +- expect(hover.staticType, 'int'); +- } +- +- test_expression_parameter_fieldFormal_use() async { +- addTestFile(''' +-class A { +- /// The field documentation. +- final int fff; +- A({this.fff}); +-} +-main() { +- new A(fff: 42); +-} +-'''); +- HoverInformation hover =3D await prepareHover('fff: 42'); +- expect(hover.containingLibraryName, isNull); +- expect(hover.containingLibraryPath, isNull); +- expect(hover.containingClassDescription, isNull); +- expect(hover.dartdoc, 'The field documentation.'); +- expect(hover.elementDescription, '{int fff}'); +- expect(hover.elementKind, 'parameter'); +- expect(hover.staticType, 'int'); +- } +- +- test_expression_syntheticGetter_invocation() async { +- addTestFile(''' +-library my.library; +-class A { +- /// doc aaa +- /// doc bbb +- String fff; +-} +-main(A a) { +- print(a.fff); +-} +-'''); +- HoverInformation hover =3D await prepareHover('fff);'); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.containingClassDescription, 'A'); +- expect(hover.dartdoc, '''doc aaa\ndoc bbb'''); +- expect(hover.elementDescription, 'String fff'); +- expect(hover.elementKind, 'field'); +- // types +- expect(hover.staticType, 'String'); +- expect(hover.propagatedType, isNull); +- } +- +- test_expression_variable_hasPropagatedType() async { +- addTestFile(''' +-library my.library; +-main() { +- var vvv =3D 123; +- print(vvv); +-} +-'''); +- HoverInformation hover =3D await prepareHover('vvv);'); +- // element +- expect(hover.containingLibraryName, isNull); +- expect(hover.containingLibraryPath, isNull); +- expect(hover.containingClassDescription, isNull); +- expect(hover.dartdoc, isNull); +- expect(hover.elementDescription, 'dynamic vvv'); +- expect(hover.elementKind, 'local variable'); +- // types +- expect(hover.staticType, 'dynamic'); +- expect(hover.propagatedType, 'int'); +- } +- +- test_expression_variable_inMethod() async { +- addTestFile(''' +-library my.library; +-class A { +- m() { +- num vvv =3D 42; +- } +-} +-'''); +- HoverInformation hover =3D await prepareHover('vvv =3D 42'); +- // element +- expect(hover.containingLibraryName, isNull); +- expect(hover.containingLibraryPath, isNull); +- expect(hover.containingClassDescription, isNull); +- expect(hover.dartdoc, isNull); +- expect(hover.elementDescription, 'num vvv'); +- expect(hover.elementKind, 'local variable'); +- // types +- expect(hover.staticType, 'num'); +- expect(hover.propagatedType, 'int'); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_instanceCreation_implicit() async { +- addTestFile(''' +-library my.library; +-class A { +-} +-main() { +- new A(); +-} +-'''); +- HoverInformation hover =3D await prepareHover('new A'); +- // range +- expect(hover.offset, findOffset('new A')); +- expect(hover.length, 'new A()'.length); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.dartdoc, isNull); +- expect(hover.elementDescription, 'A() =E2=86=92 A'); +- expect(hover.elementKind, 'constructor'); +- // types +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- test_instanceCreation_implicit_withTypeArgument() async { +- addTestFile(''' +-library my.library; +-class A {} +-main() { +- new A(); +-} +-'''); +- void onConstructor(HoverInformation hover) { +- // range +- expect(hover.offset, findOffset('new A')); +- expect(hover.length, 'new A()'.length); +- // element +- expect(hover.containingLibraryName, 'my.library'); +- expect(hover.containingLibraryPath, testFile); +- expect(hover.dartdoc, isNull); +- expect(hover.elementDescription, 'A() =E2=86=92 A'); +- expect(hover.elementKind, 'constructor'); +- // types +- expect(hover.staticType, isNull); +- expect(hover.propagatedType, isNull); +- // no parameter +- expect(hover.parameter, isNull); +- } +- +- { +- HoverInformation hover =3D await prepareHover('new A'); +- onConstructor(hover); +- } +- { +- HoverInformation hover =3D await prepareHover('A()'); +- onConstructor(hover); +- } +- { +- HoverInformation hover =3D await prepareHover('String>'); +- expect(hover.offset, findOffset('String>')); +- expect(hover.length, 'String'.length); +- expect(hover.elementKind, 'class'); +- } +- } +- +- test_instanceCreation_named() async { +- addTestFile(''' +-library my.library; +-class A { +- /// my doc +- A.named() {} +-} +-main() { +- new A.named(); +-} +-'''); +- void onConstructor(HoverInformation hover) { +- // range +- expect(hover.offset, findOffset('new A')); +- expect(hover.length, 'new A.named()'.length); +- // element +- expect(hover.dartdoc, 'my doc'); +- expect(hover.elementDescription, 'A.named() =E2=86=92 A'); +- expect(hover.elementKind, 'constructor'); +- } +- +- { +- HoverInformation hover =3D await prepareHover('new A'); +- onConstructor(hover); +- } +- { +- HoverInformation hover =3D await prepareHover('named();'); +- onConstructor(hover); +- } +- } +- +- test_noHoverInfo() async { +- addTestFile(''' +-library my.library; +-main() { +- // nothing +-} +-'''); +- HoverInformation hover =3D await prepareHover('nothing'); +- expect(hover, isNull); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/get_navigation_test.dart b/= pkg/analysis_server/test/analysis/get_navigation_test.dart +deleted file mode 100644 +index 6df117964a3..00000000000 +--- a/pkg/analysis_server/test/analysis/get_navigation_test.dart ++++ /dev/null +@@ -1,250 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'notification_navigation_test.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetNavigationTest); +- }); +-} +- +-@reflectiveTest +-class GetNavigationTest extends AbstractNavigationTest { +- static const String requestId =3D 'test-getNavigation'; +- +- @override +- void setUp() { +- generateSummaryFiles =3D true; +- super.setUp(); +- server.handlers =3D [ +- new AnalysisDomainHandler(server), +- ]; +- createProject(); +- } +- +- test_beforeAnalysisComplete() async { +- addTestFile(''' +-main() { +- var test =3D 0; +- print(test); +-} +-'''); +- await _getNavigation(testFile, testCode.indexOf('test);'), 0); +- assertHasRegion('test);'); +- assertHasTarget('test =3D 0'); +- } +- +- test_fileDoesNotExist() async { +- String file =3D '$projectPath/doesNotExist.dart'; +- Request request =3D _createGetNavigationRequest(file, 0, 100); +- Response response =3D await serverChannel.sendRequest(request); +- expect(response.error, isNull); +- expect(response.result['files'], isEmpty); +- expect(response.result['targets'], isEmpty); +- expect(response.result['regions'], isEmpty); +- } +- +- test_fileOutsideOfRoot() async { +- testFile =3D '/outside.dart'; +- addTestFile(''' +-main() { +- var test =3D 0; +- print(test); +-} +-'''); +- await _getNavigation(testFile, testCode.indexOf('test);'), 0); +- assertHasRegion('test);'); +- assertHasTarget('test =3D 0'); +- } +- +- test_importDirective() async { +- addTestFile(''' +-import 'dart:math'; +- +-main() { +-}'''); +- await waitForTasksFinished(); +- await _getNavigation(testFile, 0, 17); +- expect(regions, hasLength(1)); +- assertHasRegionString("'dart:math'"); +- expect(testTargets, hasLength(1)); +- expect(testTargets[0].kind, ElementKind.LIBRARY); +- } +- +- test_importKeyword() async { +- addTestFile(''' +-import 'dart:math'; +- +-main() { +-}'''); +- await waitForTasksFinished(); +- await _getNavigation(testFile, 0, 1); +- expect(regions, hasLength(1)); +- assertHasRegionString("'dart:math'"); +- expect(testTargets, hasLength(1)); +- expect(testTargets[0].kind, ElementKind.LIBRARY); +- } +- +- test_importUri() async { +- addTestFile(''' +-import 'dart:math'; +- +-main() { +-}'''); +- await waitForTasksFinished(); +- await _getNavigation(testFile, 7, 11); +- expect(regions, hasLength(1)); +- assertHasRegionString("'dart:math'"); +- expect(testTargets, hasLength(1)); +- expect(testTargets[0].kind, ElementKind.LIBRARY); +- } +- +- test_multipleRegions() async { +- addTestFile(''' +-main() { +- var aaa =3D 1; +- var bbb =3D 2; +- var ccc =3D 3; +- var ddd =3D 4; +- print(aaa + bbb + ccc + ddd); +-} +-'''); +- await waitForTasksFinished(); +- // request navigation +- String navCode =3D ' + bbb + '; +- await _getNavigation(testFile, testCode.indexOf(navCode), navCode.len= gth); +- // verify +- { +- assertHasRegion('aaa +'); +- assertHasTarget('aaa =3D 1'); +- } +- { +- assertHasRegion('bbb +'); +- assertHasTarget('bbb =3D 2'); +- } +- { +- assertHasRegion('ccc +'); +- assertHasTarget('ccc =3D 3'); +- } +- assertNoRegionAt('ddd)'); +- } +- +- test_operator_index() async { +- addTestFile(''' +-class A { +- A operator [](index) =3D> null; +- operator []=3D(index, A value) {} +-} +-main() { +- var a =3D new A(); +- a[0] // []; +- a[1] =3D 1; // []=3D; +- a[2] +=3D 2; +-} +-'''); +- await waitForTasksFinished(); +- { +- String search =3D '[0'; +- await _getNavigation(testFile, testCode.indexOf(search), 1); +- assertHasOperatorRegion(search, 1, '[](index)', 2); +- } +- { +- String search =3D '] // []'; +- await _getNavigation(testFile, testCode.indexOf(search), 1); +- assertHasOperatorRegion(search, 1, '[](index)', 2); +- } +- { +- String search =3D '[1'; +- await _getNavigation(testFile, testCode.indexOf(search), 1); +- assertHasOperatorRegion(search, 1, '[]=3D(index', 3); +- } +- { +- String search =3D '] =3D 1'; +- await _getNavigation(testFile, testCode.indexOf(search), 1); +- assertHasOperatorRegion(search, 1, '[]=3D(index', 3); +- } +- { +- String search =3D '[2'; +- await _getNavigation(testFile, testCode.indexOf(search), 1); +- assertHasOperatorRegion(search, 1, '[]=3D(index', 3); +- } +- { +- String search =3D '] +=3D 2'; +- await _getNavigation(testFile, testCode.indexOf(search), 1); +- assertHasOperatorRegion(search, 1, '[]=3D(index', 3); +- } +- } +- +- test_removeContextAfterRequest() async { +- addTestFile(''' +-main() { +- var test =3D 0; +- print(test); +-} +-'''); +- // handle the request synchronously +- Request request =3D +- _createGetNavigationRequest(testFile, testCode.indexOf('test);'),= 0); +- server.handleRequest(request); +- // remove context, causes sending an "invalid file" error +- { +- Folder projectFolder =3D resourceProvider.getResource(projectPath); +- server.contextManager.callbacks.removeContext(projectFolder, []); +- } +- // wait for an error response +- Response response =3D await serverChannel.waitForResponse(request); +- expect(response.error, isNotNull); +- expect(response.error.code, RequestErrorCode.GET_NAVIGATION_INVALID_F= ILE); +- } +- +- test_zeroLength_end() async { +- addTestFile(''' +-main() { +- var test =3D 0; +- print(test); +-} +-'''); +- await waitForTasksFinished(); +- await _getNavigation(testFile, testCode.indexOf(');'), 0); +- assertHasRegion('test);'); +- assertHasTarget('test =3D 0'); +- } +- +- test_zeroLength_start() async { +- addTestFile(''' +-main() { +- var test =3D 0; +- print(test); +-} +-'''); +- await waitForTasksFinished(); +- await _getNavigation(testFile, testCode.indexOf('test);'), 0); +- assertHasRegion('test);'); +- assertHasTarget('test =3D 0'); +- } +- +- Request _createGetNavigationRequest(String file, int offset, int length= ) { +- return new AnalysisGetNavigationParams(file, offset, length) +- .toRequest(requestId); +- } +- +- _getNavigation(String file, int offset, int length) async { +- Request request =3D _createGetNavigationRequest(file, offset, length); +- Response response =3D await serverChannel.sendRequest(request); +- AnalysisGetNavigationResult result =3D +- new AnalysisGetNavigationResult.fromResponse(response); +- targetFiles =3D result.files; +- targets =3D result.targets; +- regions =3D result.regions; +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_analysis_optio= ns_test.dart b/pkg/analysis_server/test/analysis/notification_analysis_opti= ons_test.dart +deleted file mode 100644 +index 4293c6cf41a..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_analysis_options_test= .dart ++++ /dev/null +@@ -1,334 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart' +- hide AnalysisOptions; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:linter/src/rules.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(NewAnalysisOptionsFileNotificationTest); +- defineReflectiveTests(OldAnalysisOptionsFileNotificationTest); +- }); +-} +- +-abstract class AnalysisOptionsFileNotificationTest +- extends AbstractAnalysisTest { +- Map> filesErrors =3D {}; +- +- final testSource =3D ''' +-main() { +- var x =3D ''; +- int y =3D x; // Not assignable in strong-mode +- print(y); +-}'''; +- +- List get errors =3D> filesErrors[testFile]; +- +- List get optionsFileErrors =3D> filesErrors[optionsFileP= ath]; +- +- String get optionsFilePath; +- +- List get testFileErrors =3D> filesErrors[testFile]; +- +- void addOptionsFile(String contents) { +- addFile(optionsFilePath, contents); +- } +- +- void deleteFile(String filePath) { +- resourceProvider.deleteFile(filePath); +- } +- +- @override +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ERRORS) { +- var decoded =3D new AnalysisErrorsParams.fromNotification(notificat= ion); +- filesErrors[decoded.file] =3D decoded.errors; +- } +- } +- +- void setAnalysisRoot() { +- Request request =3D +- new AnalysisSetAnalysisRootsParams([projectPath], []).toRequest('= 0'); +- handleSuccessfulRequest(request); +- } +- +- void setStrongMode(bool isSet) { +- addOptionsFile(''' +-analyzer: +- strong-mode: $isSet +-'''); +- } +- +- @override +- void setUp() { +- generateSummaryFiles =3D true; +- registerLintRules(); +- super.setUp(); +- server.handlers =3D [new AnalysisDomainHandler(server)]; +- } +- +- @override +- void tearDown() { +- filesErrors[optionsFilePath] =3D []; +- filesErrors[testFile] =3D []; +- super.tearDown(); +- } +- +- test_error_filter() async { +- addOptionsFile(''' +-analyzer: +- errors: +- unused_local_variable: ignore +-'''); +- +- addTestFile(''' +-main() { +- String unused =3D ""; +-} +-'''); +- +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- // Verify options file. +- // TODO(brianwilkerson) Implement options file analysis in the new dr= iver. +-// expect(optionsFileErrors, isNotNull); +-// expect(optionsFileErrors, isEmpty); +- +- // Verify test file. +- expect(testFileErrors, isNotNull); +- expect(testFileErrors, isEmpty); +- } +- +- test_error_filter_removed() async { +- addOptionsFile(''' +-analyzer: +- errors: +- unused_local_variable: ignore +-'''); +- +- addTestFile(''' +-main() { +- String unused =3D ""; +-} +-'''); +- +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- // Verify options file. +- // TODO(brianwilkerson) Implement options file analysis in the new dr= iver. +-// expect(optionsFileErrors, isNotNull); +-// expect(optionsFileErrors, isEmpty); +- +- // Verify test file. +- expect(testFileErrors, isNotNull); +- expect(testFileErrors, isEmpty); +- +- addOptionsFile(''' +-analyzer: +- errors: +- # unused_local_variable: ignore +-'''); +- +- await pumpEventQueue(); +- await waitForTasksFinished(); +- +- // Verify options file. +- // TODO(brianwilkerson) Implement options file analysis in the new dr= iver. +-// expect(optionsFileErrors, isEmpty); +- +- // Verify test file. +- expect(testFileErrors, hasLength(1)); +- } +- +- test_lint_options_changes() async { +- addOptionsFile(''' +-linter: +- rules: +- - camel_case_types +- - constant_identifier_names +-'''); +- +- addTestFile(testSource); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- verifyLintsEnabled(['camel_case_types', 'constant_identifier_names']); +- +- addOptionsFile(''' +-linter: +- rules: +- - camel_case_types +-'''); +- +- await pumpEventQueue(); +- await waitForTasksFinished(); +- +- verifyLintsEnabled(['camel_case_types']); +- } +- +- test_lint_options_unsupported() async { +- addOptionsFile(''' +-linter: +- rules: +- - unsupported +-'''); +- +- addTestFile(testSource); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- // TODO(brianwilkerson) Implement options file analysis in the new dr= iver. +-// expect(optionsFileErrors, hasLength(1)); +-// expect(optionsFileErrors.first.severity, AnalysisErrorSeverity.WARN= ING); +-// expect(optionsFileErrors.first.type, AnalysisErrorType.STATIC_WARNI= NG); +- } +- +- test_options_file_added() async { +- addTestFile(testSource); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- // Verify strong-mode disabled. +- verifyStrongMode(enabled: false); +- +- // Clear errors. +- filesErrors[testFile] =3D []; +- +- // Add options file with strong mode enabled. +- setStrongMode(true); +- +- await pumpEventQueue(); +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: true); +- } +- +- test_options_file_parse_error() async { +- addOptionsFile(''' +-; #bang +-'''); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- // TODO(brianwilkerson) Implement options file analysis in the new dr= iver. +-// expect(optionsFileErrors, hasLength(1)); +-// expect(optionsFileErrors.first.severity, AnalysisErrorSeverity.ERRO= R); +-// expect(optionsFileErrors.first.type, AnalysisErrorType.COMPILE_TIME= _ERROR); +- } +- +- test_options_file_removed() async { +- setStrongMode(true); +- +- addTestFile(testSource); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: true); +- +- // Clear errors. +- filesErrors[testFile] =3D []; +- +- deleteFile(optionsFilePath); +- +- await pumpEventQueue(); +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: false); +- } +- +- test_strong_mode_changed_off() async { +- setStrongMode(true); +- +- addTestFile(testSource); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: true); +- +- // Clear errors. +- filesErrors[testFile] =3D []; +- +- setStrongMode(false); +- +- await pumpEventQueue(); +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: false); +- } +- +- test_strong_mode_changed_on() async { +- setStrongMode(false); +- +- addTestFile(testSource); +- setAnalysisRoot(); +- +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: false); +- +- setStrongMode(true); +- +- await pumpEventQueue(); +- await waitForTasksFinished(); +- +- verifyStrongMode(enabled: true); +- } +- +- void verifyLintsEnabled(List lints) { +- AnalysisOptions options =3D analysisOptions; +- expect(options.lint, true); +- var rules =3D options.lintRules.map((rule) =3D> rule.name); +- expect(rules, unorderedEquals(lints)); +- } +- +- verifyStrongMode({bool enabled}) { +- // Verify strong-mode enabled. +- expect(analysisOptions.strongMode, enabled); +- +- if (enabled) { +- // Should produce a type warning. +- expect(errors.map((error) =3D> error.type), +- unorderedEquals([AnalysisErrorType.STATIC_TYPE_WARNING])); +- } else { +- // Should only produce a hint. +- expect(errors.map((error) =3D> error.type), +- unorderedEquals([AnalysisErrorType.HINT])); +- } +- } +-} +- +-@reflectiveTest +-class NewAnalysisOptionsFileNotificationTest +- extends AnalysisOptionsFileNotificationTest { +- @override +- String get optionsFilePath =3D> '$projectPath/analysis_options.yaml'; +-} +- +-@reflectiveTest +-class OldAnalysisOptionsFileNotificationTest +- extends AnalysisOptionsFileNotificationTest { +- @override +- String get optionsFilePath =3D> '$projectPath/.analysis_options'; +-} +diff --git a/pkg/analysis_server/test/analysis/notification_analyzedFiles_= test.dart b/pkg/analysis_server/test/analysis/notification_analyzedFiles_te= st.dart +deleted file mode 100644 +index c7a11964eaa..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_analyzedFiles_test.da= rt ++++ /dev/null +@@ -1,133 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationAnalyzedFilesTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNotificationAnalyzedFilesTest extends AbstractAnalysisTest { +- List analyzedFiles; +- bool analyzedFilesReceived =3D false; +- +- void assertHasFile(String filePath) { +- expect(analyzedFilesReceived, isTrue); +- expect(analyzedFiles, contains(filePath)); +- } +- +- void assertHasNoFile(String filePath) { +- expect(analyzedFilesReceived, isTrue); +- expect(analyzedFiles, isNot(contains(filePath))); +- } +- +- Future prepareAnalyzedFiles() async { +- addGeneralAnalysisSubscription(GeneralAnalysisService.ANALYZED_FILES); +- await pumpEventQueue(); +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ANALYZED_FILES) { +- AnalysisAnalyzedFilesParams params =3D +- new AnalysisAnalyzedFilesParams.fromNotification(notification); +- analyzedFilesReceived =3D true; +- analyzedFiles =3D params.directories; +- } +- } +- +- void setUp() { +- generateSummaryFiles =3D true; +- super.setUp(); +- createProject(); +- } +- +- test_afterAnalysis() async { +- addTestFile(''' +-class A {} +-'''); +- await waitForTasksFinished(); +- await prepareAnalyzedFiles(); +- assertHasFile(testFile); +- } +- +- test_beforeAnalysis() async { +- addTestFile(''' +-class A {} +-'''); +- await prepareAnalyzedFiles(); +- assertHasFile(testFile); +- } +- +- test_beforeAnalysis_excludeYamlFiles() async { +- File yamlFile =3D resourceProvider +- .getFolder(projectPath) +- .getChildAssumingFile('sample.yaml'); +- yamlFile.writeAsStringSync(''); +- addTestFile(''' +-class A {} +-'''); +- await prepareAnalyzedFiles(); +- assertHasFile(testFile); +- assertHasNoFile(yamlFile.path); +- } +- +- test_insignificant_change() async { +- // Making a change that doesn't affect the set of reachable files sho= uld +- // not trigger the notification to be re-sent. +- addTestFile('class A {}'); +- await prepareAnalyzedFiles(); +- expect(analyzedFilesReceived, isTrue); +- +- analyzedFilesReceived =3D false; +- modifyTestFile('class B {}'); +- await prepareAnalyzedFiles(); +- expect(analyzedFilesReceived, isFalse); +- } +- +- test_resubscribe_no_changes() async { +- // Unsubscribing and resubscribing should cause the notification to be +- // re-sent, even if nothing has changed. +- addTestFile('class A {}'); +- await prepareAnalyzedFiles(); +- expect(analyzedFilesReceived, isTrue); +- +- unsubscribeAnalyzedFiles(); +- analyzedFilesReceived =3D false; +- +- await prepareAnalyzedFiles(); +- expect(analyzedFilesReceived, isTrue); +- assertHasFile(testFile); +- } +- +- test_significant_change() async { +- // Making a change that *does* affect the set of reachable files shou= ld +- // trigger the notification to be re-sent. +- addTestFile('class A {}'); +- addFile('/foo.dart', 'library foo;'); +- await prepareAnalyzedFiles(); +- expect(analyzedFilesReceived, isTrue); +- +- analyzedFilesReceived =3D false; +- modifyTestFile('import "/foo.dart";'); +- await prepareAnalyzedFiles(); +- assertHasFile('/foo.dart'); +- } +- +- void unsubscribeAnalyzedFiles() { +- removeGeneralAnalysisSubscription(GeneralAnalysisService.ANALYZED_FIL= ES); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_closingLabels_= test.dart b/pkg/analysis_server/test/analysis/notification_closingLabels_te= st.dart +deleted file mode 100644 +index c99d004fa44..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_closingLabels_test.da= rt ++++ /dev/null +@@ -1,101 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(_AnalysisNotificationClosingLabelsTest); +- }); +-} +- +-@reflectiveTest +-class _AnalysisNotificationClosingLabelsTest extends AbstractAnalysisTest= { +- static const sampleCode =3D ''' +-Widget build(BuildContext context) { +- return /*1*/new Row( +- children: /*2*/[ +- new Text('a'), +- new Text('b'), +- ]/*/2*/, +- )/*/1*/; +-} +-'''; +- +- static final expectedResults =3D [ +- new ClosingLabel(51, 96, "Row"), +- new ClosingLabel(79, 57, "[]") +- ]; +- +- List lastLabels; +- +- Completer _labelsReceived; +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_CLOSING_LABELS) { +- var params =3D +- new AnalysisClosingLabelsParams.fromNotification(notification); +- if (params.file =3D=3D testFile) { +- lastLabels =3D params.labels; +- _labelsReceived.complete(null); +- } +- } else if (notification.event =3D=3D SERVER_NOTIFICATION_ERROR) { +- var params =3D new ServerErrorParams.fromNotification(notification); +- throw "${params.message}\n${params.stackTrace}"; +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- void subscribeForLabels() { +- addAnalysisSubscription(AnalysisService.CLOSING_LABELS, testFile); +- } +- +- test_afterAnalysis() async { +- addTestFile(sampleCode); +- await waitForTasksFinished(); +- expect(lastLabels, isNull); +- +- await waitForLabels(() =3D> subscribeForLabels()); +- +- expect(lastLabels, expectedResults); +- } +- +- test_afterUpdate() async { +- addTestFile(''); +- // Currently required to get notifications on updates +- setPriorityFiles([testFile]); +- +- // Before subscribing, we shouldn't have had any labels. +- await waitForTasksFinished(); +- expect(lastLabels, isNull); +- +- // With no content, there should be zero labels. +- await waitForLabels(() =3D> subscribeForLabels()); +- expect(lastLabels, hasLength(0)); +- +- // With sample code there will be labels. +- await waitForLabels(() =3D> modifyTestFile(sampleCode)); +- +- expect(lastLabels, expectedResults); +- } +- +- Future waitForLabels(action()) { +- _labelsReceived =3D new Completer(); +- action(); +- return _labelsReceived.future; +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_errors_test.da= rt b/pkg/analysis_server/test/analysis/notification_errors_test.dart +deleted file mode 100644 +index 904a0e4cc44..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_errors_test.dart ++++ /dev/null +@@ -1,146 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/context_manager.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/lint/linter.dart'; +-import 'package:analyzer/src/services/lint.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:linter/src/rules.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(NotificationErrorsTest); +- }); +-} +- +-@reflectiveTest +-class NotificationErrorsTest extends AbstractAnalysisTest { +- Map> filesErrors =3D {}; +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ERRORS) { +- var decoded =3D new AnalysisErrorsParams.fromNotification(notificat= ion); +- filesErrors[decoded.file] =3D decoded.errors; +- } +- } +- +- @override +- void setUp() { +- generateSummaryFiles =3D true; +- registerLintRules(); +- super.setUp(); +- server.handlers =3D [ +- new AnalysisDomainHandler(server), +- ]; +- } +- +- test_importError() async { +- createProject(); +- +- addTestFile(''' +-import 'does_not_exist.dart'; +-'''); +- await waitForTasksFinished(); +- await pumpEventQueue(); +- List errors =3D filesErrors[testFile]; +- // Verify that we are generating only 1 error for the bad URI. +- // https://github.com/dart-lang/sdk/issues/23754 +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.severity, AnalysisErrorSeverity.ERROR); +- expect(error.type, AnalysisErrorType.COMPILE_TIME_ERROR); +- expect(error.message, startsWith("Target of URI doesn't exist")); +- } +- +- test_lintError() async { +- var camelCaseTypesLintName =3D 'camel_case_types'; +- +- addFile('$projectPath/.analysis_options', ''' +-linter: +- rules: +- - $camelCaseTypesLintName +-'''); +- +- addTestFile('class a { }'); +- +- Request request =3D +- new AnalysisSetAnalysisRootsParams([projectPath], []).toRequest('= 0'); +- handleSuccessfulRequest(request); +- +- await waitForTasksFinished(); +- List lints; +- AnalysisDriver testDriver =3D (server.contextManager as ContextManage= rImpl) +- .getContextInfoFor(resourceProvider.getFolder(projectPath)) +- .analysisDriver; +- lints =3D testDriver.analysisOptions.lintRules; +- // Registry should only contain single lint rule. +- expect(lints, hasLength(1)); +- LintRule lint =3D lints.first as LintRule; +- expect(lint.name, camelCaseTypesLintName); +- // Verify lint error result. +- List errors =3D filesErrors[testFile]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.location.file, '/project/bin/test.dart'); +- expect(error.severity, AnalysisErrorSeverity.INFO); +- expect(error.type, AnalysisErrorType.LINT); +- expect(error.message, lint.description); +- } +- +- test_notInAnalysisRoot() async { +- createProject(); +- String otherFile =3D '/other.dart'; +- addFile(otherFile, 'UnknownType V;'); +- addTestFile(''' +-import '/other.dart'; +-main() { +- print(V); +-} +-'''); +- await waitForTasksFinished(); +- expect(filesErrors[otherFile], isNull); +- } +- +- test_ParserError() async { +- createProject(); +- addTestFile('library lib'); +- await waitForTasksFinished(); +- await pumpEventQueue(); +- List errors =3D filesErrors[testFile]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.location.file, '/project/bin/test.dart'); +- expect(error.location.offset, isPositive); +- expect(error.location.length, isNonNegative); +- expect(error.severity, AnalysisErrorSeverity.ERROR); +- expect(error.type, AnalysisErrorType.SYNTACTIC_ERROR); +- expect(error.message, isNotNull); +- } +- +- test_StaticWarning() async { +- createProject(); +- addTestFile(''' +-main() { +- print(UNKNOWN); +-} +-'''); +- await waitForTasksFinished(); +- await pumpEventQueue(); +- List errors =3D filesErrors[testFile]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.severity, AnalysisErrorSeverity.WARNING); +- expect(error.type, AnalysisErrorType.STATIC_WARNING); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_highlights_tes= t.dart b/pkg/analysis_server/test/analysis/notification_highlights_test.dart +deleted file mode 100644 +index ceabbceb2ec..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_highlights_test.dart ++++ /dev/null +@@ -1,960 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationHighlightsTest); +- defineReflectiveTests(HighlightTypeTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNotificationHighlightsTest extends AbstractAnalysisTest { +- List regions; +- +- Completer _resultsAvailable =3D new Completer(); +- +- void assertHasRawRegion(HighlightRegionType type, int offset, int lengt= h) { +- for (HighlightRegion region in regions) { +- if (region.offset =3D=3D offset && +- region.length =3D=3D length && +- region.type =3D=3D type) { +- return; +- } +- } +- fail('Expected to find (offset=3D$offset; length=3D$length; type=3D$t= ype) in\n' +- '${regions.join('\n')}'); +- } +- +- void assertHasRegion(HighlightRegionType type, String search, +- [int length =3D -1]) { +- int offset =3D findOffset(search); +- length =3D findRegionLength(search, length); +- assertHasRawRegion(type, offset, length); +- } +- +- void assertHasStringRegion(HighlightRegionType type, String str) { +- int offset =3D findOffset(str); +- int length =3D str.length; +- assertHasRawRegion(type, offset, length); +- } +- +- void assertNoRawRegion(HighlightRegionType type, int offset, int length= ) { +- for (HighlightRegion region in regions) { +- if (region.offset =3D=3D offset && +- region.length =3D=3D length && +- region.type =3D=3D type) { +- fail( +- 'Not expected to find (offset=3D$offset; length=3D$length; ty= pe=3D$type) in\n' +- '${regions.join('\n')}'); +- } +- } +- } +- +- void assertNoRegion(HighlightRegionType type, String search, +- [int length =3D -1]) { +- int offset =3D findOffset(search); +- length =3D findRegionLength(search, length); +- assertNoRawRegion(type, offset, length); +- } +- +- int findRegionLength(String search, int length) { +- if (length =3D=3D -1) { +- length =3D 0; +- while (length < search.length) { +- int c =3D search.codeUnitAt(length); +- if (length =3D=3D 0 && c =3D=3D '@'.codeUnitAt(0)) { +- length++; +- continue; +- } +- if (!(c >=3D 'a'.codeUnitAt(0) && c <=3D 'z'.codeUnitAt(0) || +- c >=3D 'A'.codeUnitAt(0) && c <=3D 'Z'.codeUnitAt(0) || +- c >=3D '0'.codeUnitAt(0) && c <=3D '9'.codeUnitAt(0))) { +- break; +- } +- length++; +- } +- } +- return length; +- } +- +- Future prepareHighlights() { +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, testFile); +- return _resultsAvailable.future; +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_HIGHLIGHTS) { +- var params =3D new AnalysisHighlightsParams.fromNotification(notifi= cation); +- if (params.file =3D=3D testFile) { +- regions =3D params.regions; +- _resultsAvailable.complete(null); +- } +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- test_ANNOTATION_hasArguments() async { +- addTestFile(''' +-class AAA { +- const AAA(a, b, c); +-} +-@AAA(1, 2, 3) main() {} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ANNOTATION, '@AAA(', '@AAA('.leng= th); +- assertHasRegion(HighlightRegionType.ANNOTATION, ') main', ')'.length); +- } +- +- test_ANNOTATION_noArguments() async { +- addTestFile(''' +-const AAA =3D 42; +-@AAA main() {} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ANNOTATION, '@AAA'); +- } +- +- test_BUILT_IN_abstract() async { +- addTestFile(''' +-abstract class A {}; +-abstract class B =3D Object with A; +-main() { +- var abstract =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'abstract class A'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'abstract class B'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'abstract =3D 42'); +- } +- +- test_BUILT_IN_as() async { +- addTestFile(''' +-import 'dart:math' as math; +-main() { +- p as int; +- var as =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'as math'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'as int'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'as =3D 42'); +- } +- +- test_BUILT_IN_async() async { +- addTestFile(''' +-fa() async {} +-fb() async* {} +-main() { +- bool async =3D false; +-} +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'async'); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'async*'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'async =3D false'); +- } +- +- test_BUILT_IN_await() async { +- addTestFile(''' +-main() async { +- await 42; +- await for (var item in []) { +- print(item); +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'await 42'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'await for'); +- } +- +- test_BUILT_IN_deferred() async { +- addTestFile(''' +-import 'dart:math' deferred as math; +-main() { +- var deferred =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'deferred as math'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'deferred =3D 42'); +- } +- +- test_BUILT_IN_export() async { +- addTestFile(''' +-export "dart:math"; +-main() { +- var export =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'export "dart:'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'export =3D 42'); +- } +- +- test_BUILT_IN_external() async { +- addTestFile(''' +-class A { +- external A(); +- external aaa(); +-} +-external main() { +- var external =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'external A()'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'external aaa()'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'external main()'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'external =3D 42'); +- } +- +- test_BUILT_IN_factory() async { +- addTestFile(''' +-class A { +- factory A() =3D> null; +-} +-main() { +- var factory =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'factory A()'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'factory =3D 42'); +- } +- +- test_BUILT_IN_get() async { +- addTestFile(''' +-get aaa =3D> 1; +-class A { +- get bbb =3D> 2; +-} +-main() { +- var get =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'get aaa =3D>'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'get bbb =3D>'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'get =3D 42'); +- } +- +- test_BUILT_IN_hide() async { +- addTestFile(''' +-import 'foo.dart' hide Foo; +-main() { +- var hide =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'hide Foo'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'hide =3D 42'); +- } +- +- test_BUILT_IN_implements() async { +- addTestFile(''' +-class A {} +-class B implements A {} +-main() { +- var implements =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'implements A {}'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'implements =3D 42'); +- } +- +- test_BUILT_IN_import() async { +- addTestFile(''' +-import "foo.dart"; +-main() { +- var import =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'import "'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'import =3D 42'); +- } +- +- test_BUILT_IN_library() async { +- addTestFile(''' +-library lib; +-main() { +- var library =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'library lib;'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'library =3D 42'); +- } +- +- test_BUILT_IN_native() async { +- addTestFile(''' +-class A native "A_native" {} +-class B { +- bbb() native "bbb_native"; +-} +-main() { +- var native =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'native "A_'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'native "bbb_'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'native =3D 42'); +- } +- +- test_BUILT_IN_on() async { +- addTestFile(''' +-main() { +- try { +- } on int catch (e) { +- } +- var on =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'on int'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'on =3D 42'); +- } +- +- test_BUILT_IN_operator() async { +- addTestFile(''' +-class A { +- operator +(x) =3D> null; +-} +-main() { +- var operator =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'operator +('); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'operator =3D 42'); +- } +- +- test_BUILT_IN_part() async { +- addTestFile(''' +-part "my_part.dart"; +-main() { +- var part =3D 42; +-}'''); +- addFile('/project/bin/my_part.dart', 'part of lib;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'part "my_'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'part =3D 42'); +- } +- +- test_BUILT_IN_partOf() async { +- addTestFile(''' +-part of lib; +-main() { +- var part =3D 1; +- var of =3D 2; +-}'''); +- _addLibraryForTestPart(); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'part of', 'part of'.le= ngth); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'part =3D 1'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'of =3D 2'); +- } +- +- test_BUILT_IN_set() async { +- addTestFile(''' +-set aaa(x) {} +-class A +- set bbb(x) {} +-} +-main() { +- var set =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'set aaa('); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'set bbb('); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'set =3D 42'); +- } +- +- test_BUILT_IN_show() async { +- addTestFile(''' +-import 'foo.dart' show Foo; +-main() { +- var show =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'show Foo'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'show =3D 42'); +- } +- +- test_BUILT_IN_static() async { +- addTestFile(''' +-class A { +- static aaa; +- static bbb() {} +-} +-main() { +- var static =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'static aaa;'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'static bbb()'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'static =3D 42'); +- } +- +- test_BUILT_IN_sync() async { +- addTestFile(''' +-fa() sync {} +-fb() sync* {} +-main() { +- bool sync =3D false; +-} +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'sync'); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'sync*'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'sync =3D false'); +- } +- +- test_BUILT_IN_typedef() async { +- addTestFile(''' +-typedef A(); +-main() { +- var typedef =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'typedef A();'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'typedef =3D 42'); +- } +- +- test_BUILT_IN_yield() async { +- addTestFile(''' +-main() async* { +- yield 42; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'yield 42'); +- } +- +- test_BUILT_IN_yieldStar() async { +- addTestFile(''' +-main() async* { +- yield* []; +-} +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'yield*'); +- } +- +- test_CLASS() async { +- addTestFile(''' +-class AAA {} +-AAA aaa; +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.CLASS, 'AAA {}'); +- assertHasRegion(HighlightRegionType.CLASS, 'AAA aaa'); +- } +- +- test_CLASS_notDynamic() async { +- addTestFile(''' +-dynamic f() {} +-'''); +- await prepareHighlights(); +- assertNoRegion(HighlightRegionType.CLASS, 'dynamic f()'); +- } +- +- test_CLASS_notVoid() async { +- addTestFile(''' +-void f() {} +-'''); +- await prepareHighlights(); +- assertNoRegion(HighlightRegionType.CLASS, 'void f()'); +- } +- +- test_COMMENT() async { +- addTestFile(''' +-/** +- * documentation comment +- */ +-void main() { +- // end-of-line comment +- my_function(1); +-} +- +-void my_function(String a) { +- /* block comment */ +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.COMMENT_DOCUMENTATION, '/**', 32); +- assertHasRegion(HighlightRegionType.COMMENT_END_OF_LINE, '//', 22); +- assertHasRegion(HighlightRegionType.COMMENT_BLOCK, '/* b', 19); +- } +- +- test_CONSTRUCTOR() async { +- addTestFile(''' +-class AAA { +- AAA() {} +- AAA.name(p) {} +-} +-main() { +- new AAA(); +- new AAA.name(42); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.CONSTRUCTOR, 'name(p)'); +- assertHasRegion(HighlightRegionType.CONSTRUCTOR, 'name(42)'); +- assertNoRegion(HighlightRegionType.CONSTRUCTOR, 'AAA() {}'); +- assertNoRegion(HighlightRegionType.CONSTRUCTOR, 'AAA();'); +- } +- +- test_DIRECTIVE() async { +- addTestFile(''' +-library lib; +-import 'dart:math'; +-export 'dart:math'; +-part 'part.dart'; +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "library lib;"); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "import 'dart:ma= th';"); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "export 'dart:ma= th';"); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "part 'part.dart= ';"); +- } +- +- test_DIRECTIVE_partOf() async { +- addTestFile(''' +-part of lib; +-'''); +- _addLibraryForTestPart(); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "part of lib;"); +- } +- +- test_DYNAMIC_TYPE() async { +- addTestFile(''' +-f() {} +-main(p) { +- print(p); +- var v1 =3D f(); +- int v2; +- var v3 =3D v2; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.DYNAMIC_TYPE, 'p)'); +- assertHasRegion(HighlightRegionType.DYNAMIC_TYPE, 'v1 =3D'); +- assertNoRegion(HighlightRegionType.DYNAMIC_TYPE, 'v2;'); +- assertNoRegion(HighlightRegionType.DYNAMIC_TYPE, 'v3 =3D'); +- } +- +- test_ENUM() async { +- addTestFile(''' +-enum MyEnum {A, B, C} +-MyEnum value; +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ENUM, 'MyEnum {'); +- assertHasRegion(HighlightRegionType.ENUM, 'MyEnum value;'); +- } +- +- test_ENUM_CONSTANT() async { +- addTestFile(''' +-enum MyEnum {AAA, BBB} +-main() { +- print(MyEnum.AAA); +- print(MyEnum.BBB); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'AAA, '); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'BBB}'); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'AAA);'); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'BBB);'); +- } +- +- test_FIELD() async { +- addTestFile(''' +-class A { +- int aaa =3D 1; +- int bbb =3D 2; +- A([this.bbb =3D 3]); +-} +-main(A a) { +- a.aaa =3D 4; +- a.bbb =3D 5; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.FIELD, 'aaa =3D 1'); +- assertHasRegion(HighlightRegionType.FIELD, 'bbb =3D 2'); +- assertHasRegion(HighlightRegionType.FIELD, 'bbb =3D 3'); +- assertHasRegion(HighlightRegionType.FIELD, 'aaa =3D 4'); +- assertHasRegion(HighlightRegionType.FIELD, 'bbb =3D 5'); +- } +- +- test_FIELD_STATIC() async { +- addTestFile(''' +-class A { +- static aaa =3D 1; +- static get bbb =3D> null; +- static set ccc(x) {} +-} +-main() { +- A.aaa =3D 2; +- A.bbb; +- A.ccc =3D 3; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.FIELD_STATIC, 'aaa =3D 1'); +- assertHasRegion(HighlightRegionType.FIELD_STATIC, 'aaa =3D 2'); +- assertHasRegion(HighlightRegionType.FIELD_STATIC, 'bbb;'); +- assertHasRegion(HighlightRegionType.FIELD_STATIC, 'ccc =3D 3'); +- } +- +- test_FUNCTION() async { +- addTestFile(''' +-fff(p) {} +-main() { +- fff(42); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.FUNCTION_DECLARATION, 'fff(p) {}'= ); +- assertHasRegion(HighlightRegionType.FUNCTION, 'fff(42)'); +- } +- +- test_FUNCTION_TYPE_ALIAS() async { +- addTestFile(''' +-typedef FFF(p); +-main(FFF fff) { +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.FUNCTION_TYPE_ALIAS, 'FFF(p)'); +- assertHasRegion(HighlightRegionType.FUNCTION_TYPE_ALIAS, 'FFF fff)'); +- } +- +- test_GETTER_DECLARATION() async { +- addTestFile(''' +-get aaa =3D> null; +-class A { +- get bbb =3D> null; +-} +-main(A a) { +- aaa; +- a.bbb; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.GETTER_DECLARATION, 'aaa =3D> nul= l'); +- assertHasRegion(HighlightRegionType.GETTER_DECLARATION, 'bbb =3D> nul= l'); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_VARIABLE, 'aaa;'); +- assertHasRegion(HighlightRegionType.FIELD, 'bbb;'); +- } +- +- test_IDENTIFIER_DEFAULT() async { +- addTestFile(''' +-main() { +- aaa =3D 42; +- bbb(84); +- CCC ccc; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'aaa =3D 42'); +- assertHasRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'bbb(84)'); +- assertHasRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'CCC ccc'); +- } +- +- test_IMPORT_PREFIX() async { +- addTestFile(''' +-import 'dart:math' as ma; +-main() { +- ma.max(1, 2); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.IMPORT_PREFIX, 'ma;'); +- assertHasRegion(HighlightRegionType.IMPORT_PREFIX, 'ma.max'); +- } +- +- test_KEYWORD() async { +- addTestFile(''' +-main() { +- assert(true); +- for (;;) break; +- switch (0) { +- case 0: break; +- default: break; +- } +- try {} catch (e) {} +- const v1 =3D 0; +- for (;;) continue; +- do {} while (true); +- if (true) {} else {} +- var v2 =3D false; +- final v3 =3D 1; +- try {} finally {} +- for (var v4 in []) {} +- v3 is int; +- new A(); +- try {} catch (e) {rethrow;} +- var v5 =3D true; +- while (true) {} +-} +-class A {} +-class B extends A { +- B() : super(); +- m() { +- return this; +- } +-} +-class C =3D Object with A; +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.KEYWORD, 'assert(true)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'for (;;)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'for (var v4 in'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'break;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'case 0:'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'catch (e) {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'class A {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'const v1'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'continue;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'default:'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'do {} while'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'if (true)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'false;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'final v3 =3D'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'finally {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'in []'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'is int'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'new A();'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'rethrow;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'return this'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'super();'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'switch (0)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'this;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'true;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'try {'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'while (true) {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'while (true);'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'with A;'); +- } +- +- test_KEYWORD_void() async { +- addTestFile(''' +-void main() { +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.KEYWORD, 'void main()'); +- } +- +- test_LABEL() async { +- addTestFile(''' +-main() { +-myLabel: +- while (true) { +- break myLabel; +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LABEL, 'myLabel:'); +- assertHasRegion(HighlightRegionType.LABEL, 'myLabel;'); +- } +- +- test_LITERAL_BOOLEAN() async { +- addTestFile('var V =3D true;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LITERAL_BOOLEAN, 'true;'); +- } +- +- test_LITERAL_DOUBLE() async { +- addTestFile('var V =3D 4.2;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LITERAL_DOUBLE, '4.2;', '4.2'.len= gth); +- } +- +- test_LITERAL_INTEGER() async { +- addTestFile('var V =3D 42;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LITERAL_INTEGER, '42;'); +- } +- +- test_LITERAL_LIST() async { +- addTestFile('var V =3D [1, 2, 3];'); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.LITERAL_LIST, '[1, 2, = 3]'); +- } +- +- test_LITERAL_MAP() async { +- addTestFile("var V =3D const {1: 'a', 2: 'b', 3: 'c'};"); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.LITERAL_MAP, +- "const {1: 'a', 2: 'b', 3: 'c'}"); +- } +- +- test_LITERAL_STRING() async { +- addTestFile('var V =3D "abc";'); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.LITERAL_STRING, '"abc";', '"abc"'.length); +- } +- +- test_LOCAL_VARIABLE() async { +- addTestFile(''' +-main() { +- int vvv =3D 0; +- vvv; +- vvv =3D 1; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LOCAL_VARIABLE_DECLARATION, 'vvv = =3D 0'); +- assertHasRegion(HighlightRegionType.LOCAL_VARIABLE, 'vvv;'); +- assertHasRegion(HighlightRegionType.LOCAL_VARIABLE, 'vvv =3D 1;'); +- } +- +- test_METHOD() async { +- addTestFile(''' +-class A { +- aaa() {} +- static bbb() {} +-} +-main(A a) { +- a.aaa(); +- a.aaa; +- A.bbb(); +- A.bbb; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.METHOD_DECLARATION, 'aaa() {}'); +- assertHasRegion(HighlightRegionType.METHOD_DECLARATION_STATIC, 'bbb()= {}'); +- assertHasRegion(HighlightRegionType.METHOD, 'aaa();'); +- assertHasRegion(HighlightRegionType.METHOD, 'aaa;'); +- assertHasRegion(HighlightRegionType.METHOD_STATIC, 'bbb();'); +- assertHasRegion(HighlightRegionType.METHOD_STATIC, 'bbb;'); +- } +- +- test_METHOD_bestType() async { +- addTestFile(''' +-main(p) { +- if (p is List) { +- p.add(null); +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.METHOD, 'add(null)'); +- } +- +- test_PARAMETER() async { +- addTestFile(''' +-main(int p) { +- p; +- p =3D 42; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.PARAMETER, 'p) {'); +- assertHasRegion(HighlightRegionType.PARAMETER, 'p;'); +- assertHasRegion(HighlightRegionType.PARAMETER, 'p =3D 42'); +- } +- +- test_SETTER_DECLARATION() async { +- addTestFile(''' +-set aaa(x) {} +-class A { +- set bbb(x) {} +-} +-main(A a) { +- aaa =3D 1; +- a.bbb =3D 2; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.SETTER_DECLARATION, 'aaa(x)'); +- assertHasRegion(HighlightRegionType.SETTER_DECLARATION, 'bbb(x)'); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_VARIABLE, 'aaa =3D 1'); +- assertHasRegion(HighlightRegionType.FIELD, 'bbb =3D 2'); +- } +- +- test_TOP_LEVEL_VARIABLE() async { +- addTestFile(''' +-const VVV =3D 0; +-@VVV // annotation +-main() { +- print(VVV); +- VVV =3D 1; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_VARIABLE, 'VVV =3D 0'); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_VARIABLE, 'VVV // annotation'); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_VARIABLE, 'VVV);'); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_VARIABLE, 'VVV =3D 1'); +- } +- +- test_TYPE_NAME_DYNAMIC() async { +- addTestFile(''' +-dynamic main() { +- dynamic =3D 42; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.TYPE_NAME_DYNAMIC, 'dynamic main(= )'); +- assertNoRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'dynamic main(= )'); +- assertNoRegion(HighlightRegionType.TYPE_NAME_DYNAMIC, 'dynamic =3D 42= '); +- } +- +- test_TYPE_PARAMETER() async { +- addTestFile(''' +-class A { +- T fff; +- T mmm(T p) =3D> null; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T> {'); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T fff;'); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T mmm('); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T p)'); +- } +- +- void _addLibraryForTestPart() { +- addFile('$testFolder/my_lib.dart', ''' +-library lib; +-part 'test.dart'; +- '''); +- } +-} +- +-@reflectiveTest +-class HighlightTypeTest { +- void test_constructor() { +- expect(HighlightRegionType.CLASS, +- new HighlightRegionType(HighlightRegionType.CLASS.name)); +- } +- +- void test_toString() { +- expect(HighlightRegionType.CLASS.toString(), 'HighlightRegionType.CLA= SS'); +- } +- +- void test_valueOf_unknown() { +- expect(() { +- new HighlightRegionType('no-such-type'); +- }, throwsException); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_highlights_tes= t2.dart b/pkg/analysis_server/test/analysis/notification_highlights_test2.d= art +deleted file mode 100644 +index df9b59d7835..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_highlights_test2.dart ++++ /dev/null +@@ -1,1111 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationHighlightsTest); +- defineReflectiveTests(HighlightTypeTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNotificationHighlightsTest extends AbstractAnalysisTest { +- List regions; +- +- Completer _resultsAvailable =3D new Completer(); +- +- void assertHasRawRegion(HighlightRegionType type, int offset, int lengt= h) { +- for (HighlightRegion region in regions) { +- if (region.offset =3D=3D offset && +- region.length =3D=3D length && +- region.type =3D=3D type) { +- return; +- } +- } +- fail('Expected to find (offset=3D$offset; length=3D$length; type=3D$t= ype) in\n' +- '${regions.join('\n')}'); +- } +- +- void assertHasRegion(HighlightRegionType type, String search, +- [int length =3D -1]) { +- int offset =3D findOffset(search); +- length =3D findRegionLength(search, length); +- assertHasRawRegion(type, offset, length); +- } +- +- void assertHasStringRegion(HighlightRegionType type, String str) { +- int offset =3D findOffset(str); +- int length =3D str.length; +- assertHasRawRegion(type, offset, length); +- } +- +- void assertNoRawRegion(HighlightRegionType type, int offset, int length= ) { +- for (HighlightRegion region in regions) { +- if (region.offset =3D=3D offset && +- region.length =3D=3D length && +- region.type =3D=3D type) { +- fail( +- 'Not expected to find (offset=3D$offset; length=3D$length; ty= pe=3D$type) in\n' +- '${regions.join('\n')}'); +- } +- } +- } +- +- void assertNoRegion(HighlightRegionType type, String search, +- [int length =3D -1]) { +- int offset =3D findOffset(search); +- length =3D findRegionLength(search, length); +- assertNoRawRegion(type, offset, length); +- } +- +- int findRegionLength(String search, int length) { +- if (length =3D=3D -1) { +- length =3D 0; +- while (length < search.length) { +- int c =3D search.codeUnitAt(length); +- if (length =3D=3D 0 && c =3D=3D '@'.codeUnitAt(0)) { +- length++; +- continue; +- } +- if (!(c >=3D 'a'.codeUnitAt(0) && c <=3D 'z'.codeUnitAt(0) || +- c >=3D 'A'.codeUnitAt(0) && c <=3D 'Z'.codeUnitAt(0) || +- c >=3D '0'.codeUnitAt(0) && c <=3D '9'.codeUnitAt(0))) { +- break; +- } +- length++; +- } +- } +- return length; +- } +- +- Future prepareHighlights() { +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, testFile); +- return _resultsAvailable.future; +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_HIGHLIGHTS) { +- var params =3D new AnalysisHighlightsParams.fromNotification(notifi= cation); +- if (params.file =3D=3D testFile) { +- regions =3D params.regions; +- _resultsAvailable.complete(null); +- } +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- server.options.useAnalysisHighlight2 =3D true; +- createProject(); +- } +- +- test_ANNOTATION_hasArguments() async { +- addTestFile(''' +-class AAA { +- const AAA(a, b, c); +-} +-@AAA(1, 2, 3) main() {} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ANNOTATION, '@AAA(', '@AAA('.leng= th); +- assertHasRegion(HighlightRegionType.ANNOTATION, ') main', ')'.length); +- } +- +- test_ANNOTATION_noArguments() async { +- addTestFile(''' +-const AAA =3D 42; +-@AAA main() {} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ANNOTATION, '@AAA'); +- } +- +- test_BUILT_IN_abstract() async { +- addTestFile(''' +-abstract class A {}; +-abstract class B =3D Object with A; +-main() { +- var abstract =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'abstract class A'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'abstract class B'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'abstract =3D 42'); +- } +- +- test_BUILT_IN_as() async { +- addTestFile(''' +-import 'dart:math' as math; +-main() { +- p as int; +- var as =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'as math'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'as int'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'as =3D 42'); +- } +- +- test_BUILT_IN_async() async { +- addTestFile(''' +-fa() async {} +-fb() async* {} +-main() { +- bool async =3D false; +-} +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'async'); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'async*'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'async =3D false'); +- } +- +- test_BUILT_IN_await() async { +- addTestFile(''' +-main() async { +- await 42; +- await for (var item in []) { +- print(item); +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'await 42'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'await for'); +- } +- +- test_BUILT_IN_deferred() async { +- addTestFile(''' +-import 'dart:math' deferred as math; +-main() { +- var deferred =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'deferred as math'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'deferred =3D 42'); +- } +- +- test_BUILT_IN_export() async { +- addTestFile(''' +-export "dart:math"; +-main() { +- var export =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'export "dart:'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'export =3D 42'); +- } +- +- test_BUILT_IN_external() async { +- addTestFile(''' +-class A { +- external A(); +- external aaa(); +-} +-external main() { +- var external =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'external A()'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'external aaa()'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'external main()'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'external =3D 42'); +- } +- +- test_BUILT_IN_factory() async { +- addTestFile(''' +-class A { +- factory A() =3D> null; +-} +-main() { +- var factory =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'factory A()'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'factory =3D 42'); +- } +- +- test_BUILT_IN_get() async { +- addTestFile(''' +-get aaa =3D> 1; +-class A { +- get bbb =3D> 2; +-} +-main() { +- var get =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'get aaa =3D>'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'get bbb =3D>'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'get =3D 42'); +- } +- +- test_BUILT_IN_hide() async { +- addTestFile(''' +-import 'foo.dart' hide Foo; +-main() { +- var hide =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'hide Foo'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'hide =3D 42'); +- } +- +- test_BUILT_IN_implements() async { +- addTestFile(''' +-class A {} +-class B implements A {} +-main() { +- var implements =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'implements A {}'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'implements =3D 42'); +- } +- +- test_BUILT_IN_import() async { +- addTestFile(''' +-import "foo.dart"; +-main() { +- var import =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'import "'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'import =3D 42'); +- } +- +- test_BUILT_IN_library() async { +- addTestFile(''' +-library lib; +-main() { +- var library =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'library lib;'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'library =3D 42'); +- } +- +- test_BUILT_IN_native() async { +- addTestFile(''' +-class A native "A_native" {} +-class B { +- bbb() native "bbb_native"; +-} +-main() { +- var native =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'native "A_'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'native "bbb_'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'native =3D 42'); +- } +- +- test_BUILT_IN_on() async { +- addTestFile(''' +-main() { +- try { +- } on int catch (e) { +- } +- var on =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'on int'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'on =3D 42'); +- } +- +- test_BUILT_IN_operator() async { +- addTestFile(''' +-class A { +- operator +(x) =3D> null; +-} +-main() { +- var operator =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'operator +('); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'operator =3D 42'); +- } +- +- test_BUILT_IN_part() async { +- addTestFile(''' +-part "my_part.dart"; +-main() { +- var part =3D 42; +-}'''); +- addFile('/project/bin/my_part.dart', 'part of lib;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'part "my_'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'part =3D 42'); +- } +- +- test_BUILT_IN_partOf() async { +- addTestFile(''' +-part of lib; +-main() { +- var part =3D 1; +- var of =3D 2; +-}'''); +- _addLibraryForTestPart(); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'part of', 'part of'.le= ngth); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'part =3D 1'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'of =3D 2'); +- } +- +- test_BUILT_IN_set() async { +- addTestFile(''' +-set aaa(x) {} +-class A +- set bbb(x) {} +-} +-main() { +- var set =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'set aaa('); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'set bbb('); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'set =3D 42'); +- } +- +- test_BUILT_IN_show() async { +- addTestFile(''' +-import 'foo.dart' show Foo; +-main() { +- var show =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'show Foo'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'show =3D 42'); +- } +- +- test_BUILT_IN_static() async { +- addTestFile(''' +-class A { +- static aaa; +- static bbb() {} +-} +-main() { +- var static =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'static aaa;'); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'static bbb()'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'static =3D 42'); +- } +- +- test_BUILT_IN_sync() async { +- addTestFile(''' +-fa() sync {} +-fb() sync* {} +-main() { +- bool sync =3D false; +-} +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'sync'); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'sync*'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'sync =3D false'); +- } +- +- test_BUILT_IN_typedef() async { +- addTestFile(''' +-typedef A(); +-main() { +- var typedef =3D 42; +-}'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'typedef A();'); +- assertNoRegion(HighlightRegionType.BUILT_IN, 'typedef =3D 42'); +- } +- +- test_BUILT_IN_yield() async { +- addTestFile(''' +-main() async* { +- yield 42; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.BUILT_IN, 'yield 42'); +- } +- +- test_BUILT_IN_yieldStar() async { +- addTestFile(''' +-main() async* { +- yield* []; +-} +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.BUILT_IN, 'yield*'); +- } +- +- test_CLASS() async { +- addTestFile(''' +-class AAA {} +-AAA aaa; +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.CLASS, 'AAA {}'); +- assertHasRegion(HighlightRegionType.CLASS, 'AAA aaa'); +- } +- +- test_CLASS_notDynamic() async { +- addTestFile(''' +-dynamic f() {} +-'''); +- await prepareHighlights(); +- assertNoRegion(HighlightRegionType.CLASS, 'dynamic f()'); +- } +- +- test_CLASS_notVoid() async { +- addTestFile(''' +-void f() {} +-'''); +- await prepareHighlights(); +- assertNoRegion(HighlightRegionType.CLASS, 'void f()'); +- } +- +- test_COMMENT() async { +- addTestFile(''' +-/** +- * documentation comment +- */ +-void main() { +- // end-of-line comment +- my_function(1); +-} +- +-void my_function(String a) { +- /* block comment */ +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.COMMENT_DOCUMENTATION, '/**', 32); +- assertHasRegion(HighlightRegionType.COMMENT_END_OF_LINE, '//', 22); +- assertHasRegion(HighlightRegionType.COMMENT_BLOCK, '/* b', 19); +- } +- +- test_CONSTRUCTOR() async { +- addTestFile(''' +-class AAA { +- AAA() {} +- AAA.name(p) {} +-} +-main() { +- new AAA(); +- new AAA.name(42); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.CONSTRUCTOR, 'name(p)'); +- assertHasRegion(HighlightRegionType.CONSTRUCTOR, 'name(42)'); +- assertNoRegion(HighlightRegionType.CONSTRUCTOR, 'AAA() {}'); +- assertNoRegion(HighlightRegionType.CONSTRUCTOR, 'AAA();'); +- } +- +- test_DIRECTIVE() async { +- addTestFile(''' +-library lib; +-import 'dart:math'; +-export 'dart:math'; +-part 'part.dart'; +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "library lib;"); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "import 'dart:ma= th';"); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "export 'dart:ma= th';"); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "part 'part.dart= ';"); +- } +- +- test_DIRECTIVE_partOf() async { +- addTestFile(''' +-part of lib; +-'''); +- _addLibraryForTestPart(); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.DIRECTIVE, "part of lib;"); +- } +- +- test_DYNAMIC_LOCAL_VARIABLE() async { +- addTestFile(''' +-f() {} +-main(p) { +- var v =3D f(); +- v; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_DECLARATION, 'v =3D f(= )'); +- assertHasRegion(HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_REFERENCE,= 'v;'); +- } +- +- test_DYNAMIC_PARAMETER() async { +- addTestFile(''' +-main(p) { +- print(p); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.DYNAMIC_PARAMETER_DECLARATION, 'p= )'); +- assertHasRegion(HighlightRegionType.DYNAMIC_PARAMETER_REFERENCE, 'p);= '); +- } +- +- test_DYNAMIC_VARIABLE_field() async { +- addTestFile(''' +-class A { +- var f; +- m() { +- f =3D 1; +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_DECLARATION, 'f;'); +- assertHasRegion(HighlightRegionType.INSTANCE_SETTER_REFERENCE, 'f =3D= 1'); +- } +- +- test_ENUM() async { +- addTestFile(''' +-enum MyEnum {A, B, C} +-MyEnum value; +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ENUM, 'MyEnum {'); +- assertHasRegion(HighlightRegionType.ENUM, 'MyEnum value;'); +- } +- +- test_ENUM_CONSTANT() async { +- addTestFile(''' +-enum MyEnum {AAA, BBB} +-main() { +- print(MyEnum.AAA); +- print(MyEnum.BBB); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'AAA, '); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'BBB}'); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'AAA);'); +- assertHasRegion(HighlightRegionType.ENUM_CONSTANT, 'BBB);'); +- } +- +- test_FUNCTION_TYPE_ALIAS() async { +- addTestFile(''' +-typedef FFF(p); +-main(FFF fff) { +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.FUNCTION_TYPE_ALIAS, 'FFF(p)'); +- assertHasRegion(HighlightRegionType.FUNCTION_TYPE_ALIAS, 'FFF fff)'); +- } +- +- test_GETTER() async { +- addTestFile(''' +-get aaa =3D> null; +-class A { +- get bbb =3D> null; +- static get ccc =3D> null; +-} +-main(A a) { +- aaa; +- a.bbb; +- A.ccc; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_GETTER_DECLARATION, 'aaa =3D> null'= ); +- assertHasRegion( +- HighlightRegionType.INSTANCE_GETTER_DECLARATION, 'bbb =3D> null'); +- assertHasRegion( +- HighlightRegionType.STATIC_GETTER_DECLARATION, 'ccc =3D> null'); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_GETTER_REFERENCE, 'aaa;= '); +- assertHasRegion(HighlightRegionType.INSTANCE_GETTER_REFERENCE, 'bbb;'= ); +- assertHasRegion(HighlightRegionType.STATIC_GETTER_REFERENCE, 'ccc;'); +- } +- +- test_IDENTIFIER_DEFAULT() async { +- addTestFile(''' +-main() { +- aaa =3D 42; +- bbb(84); +- CCC ccc; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'aaa =3D 42'); +- assertHasRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'bbb(84)'); +- assertHasRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'CCC ccc'); +- } +- +- test_IMPORT_PREFIX() async { +- addTestFile(''' +-import 'dart:math' as ma; +-main() { +- ma.max(1, 2); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.IMPORT_PREFIX, 'ma;'); +- assertHasRegion(HighlightRegionType.IMPORT_PREFIX, 'ma.max'); +- } +- +- test_INSTANCE_FIELD() async { +- addTestFile(''' +-class A { +- int aaa =3D 1; +- int bbb =3D 2; +- A([this.bbb =3D 3]); +-} +-main(A a) { +- a.aaa =3D 4; +- a.bbb =3D 5; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_DECLARATION, 'aaa = =3D 1'); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_DECLARATION, 'bbb = =3D 2'); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_REFERENCE, 'bbb = =3D 3'); +- assertHasRegion(HighlightRegionType.INSTANCE_SETTER_REFERENCE, 'aaa = =3D 4'); +- assertHasRegion(HighlightRegionType.INSTANCE_SETTER_REFERENCE, 'bbb = =3D 5'); +- } +- +- test_INSTANCE_FIELD_dynamic() async { +- addTestFile(''' +-class A { +- var f; +- A(this.f); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_DECLARATION, 'f;'); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_REFERENCE, 'f);'); +- } +- +- test_KEYWORD() async { +- addTestFile(''' +-main() { +- assert(true); +- for (;;) break; +- switch (0) { +- case 0: break; +- default: break; +- } +- try {} catch (e) {} +- const v1 =3D 0; +- for (;;) continue; +- do {} while (true); +- if (true) {} else {} +- var v2 =3D false; +- final v3 =3D 1; +- try {} finally {} +- for (var v4 in []) {} +- v3 is int; +- new A(); +- try {} catch (e) {rethrow;} +- var v5 =3D true; +- while (true) {} +-} +-class A {} +-class B extends A { +- B() : super(); +- m() { +- return this; +- } +-} +-class C =3D Object with A; +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.KEYWORD, 'assert(true)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'for (;;)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'for (var v4 in'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'break;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'case 0:'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'catch (e) {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'class A {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'const v1'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'continue;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'default:'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'do {} while'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'if (true)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'false;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'final v3 =3D'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'finally {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'in []'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'is int'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'new A();'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'rethrow;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'return this'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'super();'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'switch (0)'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'this;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'true;'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'try {'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'while (true) {}'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'while (true);'); +- assertHasRegion(HighlightRegionType.KEYWORD, 'with A;'); +- } +- +- test_KEYWORD_void() async { +- addTestFile(''' +-void main() { +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.KEYWORD, 'void main()'); +- } +- +- test_LABEL() async { +- addTestFile(''' +-main() { +-myLabel: +- while (true) { +- break myLabel; +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LABEL, 'myLabel:'); +- assertHasRegion(HighlightRegionType.LABEL, 'myLabel;'); +- } +- +- test_LIBRARY_NAME_libraryDirective() async { +- addTestFile(''' +-library my.lib.name; +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.LIBRARY_NAME, 'my.lib.name'= ); +- } +- +- test_LIBRARY_NAME_partOfDirective() async { +- _addLibraryForTestPart(); +- addTestFile(''' +-part of my.lib.name; +-'''); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.LIBRARY_NAME, 'my.lib.name'= ); +- } +- +- test_LITERAL_BOOLEAN() async { +- addTestFile('var V =3D true;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LITERAL_BOOLEAN, 'true;'); +- } +- +- test_LITERAL_DOUBLE() async { +- addTestFile('var V =3D 4.2;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LITERAL_DOUBLE, '4.2;', '4.2'.len= gth); +- } +- +- test_LITERAL_INTEGER() async { +- addTestFile('var V =3D 42;'); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LITERAL_INTEGER, '42;'); +- } +- +- test_LITERAL_LIST() async { +- addTestFile('var V =3D [1, 2, 3];'); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.LITERAL_LIST, '[1, 2, = 3]'); +- } +- +- test_LITERAL_MAP() async { +- addTestFile("var V =3D const {1: 'a', 2: 'b', 3: 'c'};"); +- await prepareHighlights(); +- assertHasStringRegion(HighlightRegionType.LITERAL_MAP, +- "const {1: 'a', 2: 'b', 3: 'c'}"); +- } +- +- test_LITERAL_STRING() async { +- addTestFile('var V =3D "abc";'); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.LITERAL_STRING, '"abc";', '"abc"'.length); +- } +- +- test_LOCAL_FUNCTION() async { +- addTestFile(''' +-main() { +- fff() {} +- fff(); +- fff; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LOCAL_FUNCTION_DECLARATION, 'fff(= ) {}'); +- assertHasRegion(HighlightRegionType.LOCAL_FUNCTION_REFERENCE, 'fff();= '); +- assertHasRegion(HighlightRegionType.LOCAL_FUNCTION_REFERENCE, 'fff;'); +- } +- +- test_LOCAL_VARIABLE() async { +- addTestFile(''' +-main() { +- int vvv =3D 0; +- vvv; +- vvv =3D 1; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.LOCAL_VARIABLE_DECLARATION, 'vvv = =3D 0'); +- assertHasRegion(HighlightRegionType.LOCAL_VARIABLE_REFERENCE, 'vvv;'); +- assertHasRegion(HighlightRegionType.LOCAL_VARIABLE_REFERENCE, 'vvv = =3D 1;'); +- } +- +- test_METHOD() async { +- addTestFile(''' +-class A { +- aaa() {} +- static bbb() {} +-} +-main(A a) { +- a.aaa(); +- a.aaa; +- A.bbb(); +- A.bbb; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.INSTANCE_METHOD_DECLARATION, 'aaa() {}'); +- assertHasRegion(HighlightRegionType.STATIC_METHOD_DECLARATION, 'bbb()= {}'); +- assertHasRegion(HighlightRegionType.INSTANCE_METHOD_REFERENCE, 'aaa()= ;'); +- assertHasRegion(HighlightRegionType.INSTANCE_METHOD_REFERENCE, 'aaa;'= ); +- assertHasRegion(HighlightRegionType.STATIC_METHOD_REFERENCE, 'bbb();'= ); +- assertHasRegion(HighlightRegionType.STATIC_METHOD_REFERENCE, 'bbb;'); +- } +- +- test_METHOD_bestType() async { +- addTestFile(''' +-main(p) { +- if (p is List) { +- p.add(null); +- } +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.INSTANCE_METHOD_REFERENCE, 'add(n= ull)'); +- } +- +- test_PARAMETER() async { +- addTestFile(''' +-main(int p) { +- p; +- p =3D 42; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.PARAMETER_DECLARATION, 'p) {'); +- assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'p;'); +- assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'p =3D 42'); +- } +- +- test_PARAMETER_named() async { +- addTestFile(''' +-class C { +- final int aaa; +- C({this.aaa, int bbb}); +-} +-main() { +- new C(aaa: 1, bbb: 2); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.INSTANCE_FIELD_REFERENCE, 'aaa,'); +- assertHasRegion(HighlightRegionType.PARAMETER_DECLARATION, 'bbb}'); +- assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'aaa: 1'); +- assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'bbb: 2'); +- } +- +- test_SETTER_DECLARATION() async { +- addTestFile(''' +-set aaa(x) {} +-class A { +- set bbb(x) {} +- static set ccc(x) {} +-} +-main(A a) { +- aaa =3D 1; +- a.bbb =3D 2; +- A.ccc =3D 3; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_SETTER_DECLARATION, 'aa= a(x)'); +- assertHasRegion(HighlightRegionType.INSTANCE_SETTER_DECLARATION, 'bbb= (x)'); +- assertHasRegion(HighlightRegionType.STATIC_SETTER_DECLARATION, 'ccc(x= )'); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_SETTER_REFERENCE, 'aaa = =3D 1'); +- assertHasRegion(HighlightRegionType.INSTANCE_SETTER_REFERENCE, 'bbb = =3D 2'); +- assertHasRegion(HighlightRegionType.STATIC_SETTER_REFERENCE, 'ccc =3D= 3'); +- } +- +- test_STATIC_FIELD() async { +- addTestFile(''' +-class A { +- static aaa =3D 1; +- static get bbb =3D> null; +- static set ccc(x) {} +-} +-main() { +- A.aaa =3D 2; +- A.bbb; +- A.ccc =3D 3; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.STATIC_FIELD_DECLARATION, 'aaa = =3D 1'); +- assertHasRegion(HighlightRegionType.STATIC_SETTER_REFERENCE, 'aaa =3D= 2'); +- assertHasRegion(HighlightRegionType.STATIC_GETTER_REFERENCE, 'bbb;'); +- assertHasRegion(HighlightRegionType.STATIC_SETTER_REFERENCE, 'ccc =3D= 3'); +- } +- +- test_TOP_LEVEL_FUNCTION() async { +- addTestFile(''' +-fff(p) {} +-main() { +- fff(42); +-} +-'''); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_FUNCTION_DECLARATION, 'fff(p) {}'); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_FUNCTION_REFERENCE, 'fff(42)'); +- } +- +- test_TOP_LEVEL_VARIABLE() async { +- addTestFile(''' +-const V1 =3D 1; +-var V2 =3D 2; +-@V1 // annotation +-main() { +- print(V1); +- V2 =3D 3; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_VARIABLE_DECLARATION, 'V1 =3D 1'); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_VARIABLE_DECLARATION, 'V2 =3D 2'); +- assertHasRegion( +- HighlightRegionType.TOP_LEVEL_GETTER_REFERENCE, 'V1 // annotation= '); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_GETTER_REFERENCE, 'V1);= '); +- assertHasRegion(HighlightRegionType.TOP_LEVEL_SETTER_REFERENCE, 'V2 = =3D 3'); +- } +- +- test_TYPE_NAME_DYNAMIC() async { +- addTestFile(''' +-dynamic main() { +- dynamic =3D 42; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.TYPE_NAME_DYNAMIC, 'dynamic main(= )'); +- assertNoRegion(HighlightRegionType.IDENTIFIER_DEFAULT, 'dynamic main(= )'); +- assertNoRegion(HighlightRegionType.TYPE_NAME_DYNAMIC, 'dynamic =3D 42= '); +- } +- +- test_TYPE_PARAMETER() async { +- addTestFile(''' +-class A { +- T fff; +- T mmm(T p) =3D> null; +-} +-'''); +- await prepareHighlights(); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T> {'); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T fff;'); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T mmm('); +- assertHasRegion(HighlightRegionType.TYPE_PARAMETER, 'T p)'); +- } +- +- test_UNRESOLVED_INSTANCE_MEMBER_REFERENCE_dynamicVarTarget() async { +- addTestFile(''' +-main(p) { +- p.aaa; +- p.aaa++; +- p.aaa +=3D 0; +- ++p.aaa; // ++ +- p.aaa =3D 0; +- p.bbb(0); +- ''.length.ccc().ddd(); +-} +-'''); +- await prepareHighlights(); +- HighlightRegionType type =3D +- HighlightRegionType.UNRESOLVED_INSTANCE_MEMBER_REFERENCE; +- assertHasRegion(type, 'aaa'); +- assertHasRegion(type, 'aaa++'); +- assertHasRegion(type, 'aaa +=3D 0'); +- assertHasRegion(type, 'aaa; // ++'); +- assertHasRegion(type, 'aaa =3D'); +- assertHasRegion(type, 'bbb('); +- assertHasRegion(type, 'ddd()'); +- } +- +- test_UNRESOLVED_INSTANCE_MEMBER_REFERENCE_nonDynamicTarget() async { +- addTestFile(''' +-import 'dart:math' as math; +-main(String str) { +- new Object().aaa(); +- math.bbb(); +- str.ccc(); +-} +-class A { +- m() { +- unresolved(1); +- this.unresolved(2); +- super.unresolved(3); +- } +-} +-'''); +- await prepareHighlights(); +- HighlightRegionType type =3D HighlightRegionType.IDENTIFIER_DEFAULT; +- assertHasRegion(type, 'aaa()'); +- assertHasRegion(type, 'bbb()'); +- assertHasRegion(type, 'ccc()'); +- assertHasRegion(type, 'unresolved(1)'); +- assertHasRegion(type, 'unresolved(2)'); +- assertHasRegion(type, 'unresolved(3)'); +- } +- +- void _addLibraryForTestPart() { +- addFile('$testFolder/my_lib.dart', ''' +-library lib; +-part 'test.dart'; +- '''); +- } +-} +- +-@reflectiveTest +-class HighlightTypeTest { +- void test_constructor() { +- expect(HighlightRegionType.CLASS, +- new HighlightRegionType(HighlightRegionType.CLASS.name)); +- } +- +- void test_toString() { +- expect(HighlightRegionType.CLASS.toString(), 'HighlightRegionType.CLA= SS'); +- } +- +- void test_valueOf_unknown() { +- expect(() { +- new HighlightRegionType('no-such-type'); +- }, throwsException); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_implemented_te= st.dart b/pkg/analysis_server/test/analysis/notification_implemented_test.d= art +deleted file mode 100644 +index cc80eb999cd..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_implemented_test.dart ++++ /dev/null +@@ -1,431 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationImplementedTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNotificationImplementedTest extends AbstractAnalysisTest { +- List implementedClasses; +- List implementedMembers; +- +- /** +- * Validates that there is an [ImplementedClass] at the offset of [sear= ch]. +- * +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertHasImplementedClass(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- if (implementedClasses =3D=3D null) { +- fail('No notification of impemented classes was received'); +- } +- for (ImplementedClass clazz in implementedClasses) { +- if (clazz.offset =3D=3D offset && clazz.length =3D=3D length) { +- return; +- } +- } +- fail('Expect to find an implemented class at $offset' +- ' in $implementedClasses'); +- } +- +- /** +- * Validates that there is an [ImplementedClass] at the offset of [sear= ch]. +- * +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertHasImplementedMember(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- if (implementedMembers =3D=3D null) { +- fail('No notification of impemented members was received'); +- } +- for (ImplementedMember member in implementedMembers) { +- if (member.offset =3D=3D offset && member.length =3D=3D length) { +- return; +- } +- } +- fail('Expect to find an implemented member at $offset' +- ' in $implementedMembers'); +- } +- +- /** +- * Validates that there is no an [ImplementedClass] at the offset of [s= earch]. +- * +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertNoImplementedMember(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- if (implementedMembers =3D=3D null) { +- fail('No notification of impemented members was received'); +- } +- for (ImplementedMember member in implementedMembers) { +- if (member.offset =3D=3D offset) { +- fail('Unexpected implemented member at $offset' +- ' in $implementedMembers'); +- } +- } +- } +- +- /** +- * Subscribe for `IMPLEMENTED` and wait for the notification. +- */ +- Future prepareImplementedElements() { +- subscribeForImplemented(); +- return waitForImplementedElements(); +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_IMPLEMENTED) { +- var params =3D new AnalysisImplementedParams.fromNotification(notif= ication); +- if (params.file =3D=3D testFile) { +- implementedClasses =3D params.classes; +- implementedMembers =3D params.members; +- } +- } +- } +- +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- void subscribeForImplemented() { +- setPriorityFiles([testFile]); +- addAnalysisSubscription(AnalysisService.IMPLEMENTED, testFile); +- } +- +- test_afterAnalysis() async { +- addTestFile(''' +-class A {} +-class B extends A {} +-'''); +- await waitForTasksFinished(); +- await prepareImplementedElements(); +- assertHasImplementedClass('A {'); +- } +- +- test_afterIncrementalResolution() async { +- subscribeForImplemented(); +- addTestFile(''' +-class A {} +-class B extends A {} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedClass('A {'); +- // add a space +- implementedClasses =3D null; +- testCode =3D ''' +-class A {} +-class B extends A {} +-'''; +- server.updateContent('1', {testFile: new AddContentOverlay(testCode)}= ); +- await waitForImplementedElements(); +- assertHasImplementedClass('A {'); +- } +- +- test_class_extended() async { +- addTestFile(''' +-class A {} +-class B extends A {} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedClass('A {'); +- } +- +- test_class_implemented() async { +- addTestFile(''' +-class A {} +-class B implements A {} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedClass('A {'); +- } +- +- test_class_mixed() async { +- addTestFile(''' +-class A {} +-class B =3D Object with A; +-'''); +- await prepareImplementedElements(); +- assertHasImplementedClass('A {'); +- } +- +- test_field_withField() async { +- addTestFile(''' +-class A { +- int f; // A +-} +-class B extends A { +- int f; +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f; // A'); +- } +- +- test_field_withGetter() async { +- addTestFile(''' +-class A { +- int f; // A +-} +-class B extends A { +- get f =3D> null; +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f; // A'); +- } +- +- test_field_withSetter() async { +- addTestFile(''' +-class A { +- int f; // A +-} +-class B extends A { +- void set f(_) {} +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f; // A'); +- } +- +- test_getter_withField() async { +- addTestFile(''' +-class A { +- get f =3D> null; // A +-} +-class B extends A { +- int f; +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f =3D> null; // A'); +- } +- +- test_getter_withGetter() async { +- addTestFile(''' +-class A { +- get f =3D> null; // A +-} +-class B extends A { +- get f =3D> null; +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f =3D> null; // A'); +- } +- +- test_method_withMethod() async { +- addTestFile(''' +-class A { +- m() {} // A +-} +-class B extends A { +- m() {} // B +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('m() {} // A'); +- assertNoImplementedMember('m() {} // B'); +- } +- +- test_method_withMethod_indirectSubclass() async { +- addTestFile(''' +-class A { +- m() {} // A +-} +-class B extends A { +-} +-class C extends A { +- m() {} +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('m() {} // A'); +- } +- +- test_method_withMethod_private_differentLib() async { +- addFile('$testFolder/lib.dart', r''' +-import 'test.dart'; +-class B extends A { +- void _m() {} +-} +-'''); +- addTestFile(''' +-class A { +- _m() {} // A +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('_m() {} // A'); +- } +- +- test_method_withMethod_private_sameLibrary() async { +- addTestFile(''' +-class A { +- _m() {} // A +-} +-class B extends A { +- _m() {} // B +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('_m() {} // A'); +- assertNoImplementedMember('_m() {} // B'); +- } +- +- test_method_withMethod_wasAbstract() async { +- addTestFile(''' +-abstract class A { +- m(); // A +-} +-class B extends A { +- m() {} +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('m(); // A'); +- } +- +- test_setter_withField() async { +- addTestFile(''' +-class A { +- set f(_) {} // A +-} +-class B extends A { +- int f; +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f(_) {} // A'); +- } +- +- test_setter_withSetter() async { +- addTestFile(''' +-class A { +- set f(_) {} // A +-} +-class B extends A { +- set f(_) {} // B +-} +-'''); +- await prepareImplementedElements(); +- assertHasImplementedMember('f(_) {} // A'); +- } +- +- test_static_field_instanceStatic() async { +- addTestFile(''' +-class A { +- int F =3D 0; +-} +-class B extends A { +- static int F =3D 1; +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('F =3D 0'); +- } +- +- test_static_field_staticInstance() async { +- addTestFile(''' +-class A { +- static int F =3D 0; +-} +-class B extends A { +- int F =3D 1; +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('F =3D 0'); +- } +- +- test_static_field_staticStatic() async { +- addTestFile(''' +-class A { +- static int F =3D 0; +-} +-class B extends A { +- static int F =3D 1; +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('F =3D 0'); +- } +- +- test_static_method_instanceStatic() async { +- addTestFile(''' +-class A { +- int m() =3D> 0; +-} +-class B extends A { +- static int m() =3D> 1; +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('m() =3D> 0'); +- } +- +- test_static_method_staticInstance() async { +- addTestFile(''' +-class A { +- static int m() =3D> 0; +-} +-class B extends A { +- int m() =3D> 1; +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('m() =3D> 0'); +- } +- +- test_static_method_staticStatic() async { +- addTestFile(''' +-class A { +- static int m() =3D> 0; +-} +-class B extends A { +- static int m() =3D> 1; +-} +-'''); +- await prepareImplementedElements(); +- assertNoImplementedMember('m() =3D> 0'); +- } +- +- Future waitForImplementedElements() { +- Future waitForNotification(int times) { +- if (times =3D=3D 0 || implementedClasses !=3D null) { +- return new Future.value(); +- } +- return new Future.delayed( +- new Duration(milliseconds: 1), () =3D> waitForNotification(time= s - 1)); +- } +- +- return waitForNotification(30000); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_navigation_tes= t.dart b/pkg/analysis_server/test/analysis/notification_navigation_test.dart +deleted file mode 100644 +index f57c6715326..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_navigation_test.dart ++++ /dev/null +@@ -1,1031 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationNavigationTest); +- }); +-} +- +-class AbstractNavigationTest extends AbstractAnalysisTest { +- List regions; +- List targets; +- List targetFiles; +- +- NavigationRegion testRegion; +- List testTargetIndexes; +- List testTargets; +- NavigationTarget testTarget; +- +- /** +- * Validates that there is a target in [testTargetIndexes] with [file], +- * at [offset] and with the given [length]. +- */ +- void assertHasFileTarget(String file, int offset, int length) { +- for (NavigationTarget target in testTargets) { +- if (targetFiles[target.fileIndex] =3D=3D file && +- target.offset =3D=3D offset && +- target.length =3D=3D length) { +- testTarget =3D target; +- return; +- } +- } +- fail( +- 'Expected to find target (file=3D$file; offset=3D$offset; length= =3D$length) in\n' +- '$testRegion in\n' +- '${testTargets.join('\n')}'); +- } +- +- void assertHasOperatorRegion(String regionSearch, int regionLength, +- String targetSearch, int targetLength) { +- assertHasRegion(regionSearch, regionLength); +- assertHasTarget(targetSearch, targetLength); +- } +- +- /** +- * Validates that there is a region at the offset of [search] in [testF= ile]. +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertHasRegion(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- findRegion(offset, length, true); +- } +- +- /** +- * Validates that there is a region at the offset of [search] in [testF= ile] +- * with the given [length] or the length of [search]. +- */ +- void assertHasRegionString(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D search.length; +- } +- findRegion(offset, length, true); +- } +- +- /** +- * Validates that there is an identifier region at [regionSearch] with = target +- * at [targetSearch]. +- */ +- void assertHasRegionTarget(String regionSearch, String targetSearch) { +- assertHasRegion(regionSearch); +- assertHasTarget(targetSearch); +- } +- +- /** +- * Validates that there is a target in [testTargets] with [testFile], = at the +- * offset of [search] in [testFile], and with the given [length] or the= length +- * of an leading identifier in [search]. +- */ +- void assertHasTarget(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- assertHasFileTarget(testFile, offset, length); +- } +- +- /** +- * Validates that there is a target in [testTargets] with [testFile], = at the +- * offset of [str] in [testFile], and with the length of [str]. +- */ +- void assertHasTargetString(String str) { +- assertHasTarget(str, str.length); +- } +- +- /** +- * Validates that there is no a region at [search] and with the given +- * [length]. +- */ +- void assertNoRegion(String search, int length) { +- int offset =3D findOffset(search); +- findRegion(offset, length, false); +- } +- +- /** +- * Validates that there is no a region at [search] with any length. +- */ +- void assertNoRegionAt(String search) { +- int offset =3D findOffset(search); +- findRegion(offset, -1, false); +- } +- +- /** +- * Validates that there is no a region for [search] string. +- */ +- void assertNoRegionString(String search) { +- int offset =3D findOffset(search); +- int length =3D search.length; +- findRegion(offset, length, false); +- } +- +- void assertRegionsSorted() { +- int lastEnd =3D -1; +- for (NavigationRegion region in regions) { +- int offset =3D region.offset; +- if (offset < lastEnd) { +- fail('$lastEnd was expected to be > $offset in\n' + regions.join(= '\n')); +- } +- lastEnd =3D offset + region.length; +- } +- } +- +- /** +- * Finds the navigation region with the given [offset] and [length]. +- * If [length] is `-1`, then it is ignored. +- * +- * If [exists] is `true`, then fails if such region does not exist. +- * Otherwise remembers this it into [testRegion]. +- * Also fills [testTargets] with its targets. +- * +- * If [exists] is `false`, then fails if such region exists. +- */ +- void findRegion(int offset, int length, bool exists) { +- for (NavigationRegion region in regions) { +- if (region.offset =3D=3D offset && +- (length =3D=3D -1 || region.length =3D=3D length)) { +- if (exists =3D=3D false) { +- fail('Not expected to find (offset=3D$offset; length=3D$length)= in\n' +- '${regions.join('\n')}'); +- } +- testRegion =3D region; +- testTargetIndexes =3D region.targets; +- testTargets =3D testTargetIndexes.map((i) =3D> targets[i]).toList= (); +- return; +- } +- } +- if (exists =3D=3D true) { +- fail('Expected to find (offset=3D$offset; length=3D$length) in\n' +- '${regions.join('\n')}'); +- } +- } +-} +- +-@reflectiveTest +-class AnalysisNotificationNavigationTest extends AbstractNavigationTest { +- Completer _resultsAvailable =3D new Completer(); +- +- Future prepareNavigation() async { +- addAnalysisSubscription(AnalysisService.NAVIGATION, testFile); +- await _resultsAvailable.future; +- assertRegionsSorted(); +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_NAVIGATION) { +- var params =3D new AnalysisNavigationParams.fromNotification(notifi= cation); +- if (params.file =3D=3D testFile) { +- regions =3D params.regions; +- targets =3D params.targets; +- targetFiles =3D params.files; +- _resultsAvailable.complete(null); +- } +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- test_afterAnalysis() async { +- addTestFile(''' +-class AAA {} +-AAA aaa; +-'''); +- await waitForTasksFinished(); +- await prepareNavigation(); +- assertHasRegionTarget('AAA aaa;', 'AAA {}'); +- } +- +- test_annotationConstructor_implicit() async { +- addTestFile(''' +-class A { +-} +-@A() +-main() { +-} +-'''); +- await prepareNavigation(); +- assertHasRegionString('A()', 'A'.length); +- assertHasTarget('A {'); +- } +- +- test_annotationConstructor_importPrefix() async { +- addFile('$testFolder/my_annotation.dart', r''' +-library an; +-class MyAnnotation { +- const MyAnnotation(); +- const MyAnnotation.named(); +-} +-'''); +- addTestFile(''' +-import 'my_annotation.dart' as man; +-@man.MyAnnotation() +-@man.MyAnnotation.named() +-main() { +-} +-'''); +- await prepareNavigation(); +- assertHasRegion('MyAnnotation()'); +- assertHasRegion('MyAnnotation.named()'); +- assertHasRegion('named()'); +- { +- assertHasRegion('man.MyAnnotation()'); +- assertHasTarget('man;'); +- } +- { +- assertHasRegion('man.MyAnnotation.named()'); +- assertHasTarget('man;'); +- } +- } +- +- test_annotationConstructor_named() async { +- addTestFile(''' +-class A { +- const A.named(p); +-} +-@A.named(0) +-main() { +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('A.named(0)'); +- assertHasTarget('named(p);'); +- } +- { +- assertHasRegion('named(0)'); +- assertHasTarget('named(p);'); +- } +- } +- +- test_annotationConstructor_unnamed() async { +- addTestFile(''' +-class A { +- const A(); +-} +-@A() +-main() { +-} +-'''); +- await prepareNavigation(); +- assertHasRegionString('A()', 'A'.length); +- assertHasTarget('A();', 0); +- } +- +- test_annotationField() async { +- addTestFile(''' +-const myan =3D new Object(); +-@myan // ref +-main() { +-} +-'''); +- await prepareNavigation(); +- assertHasRegion('myan // ref'); +- assertHasTarget('myan =3D new Object();'); +- } +- +- test_annotationField_importPrefix() async { +- addFile('$testFolder/mayn.dart', r''' +-library an; +-const myan =3D new Object(); +-'''); +- addTestFile(''' +-import 'mayn.dart' as man; +-@man.myan // ref +-main() { +-} +-'''); +- await prepareNavigation(); +- assertHasRegion('myan // ref'); +- } +- +- test_class_fromSDK() async { +- addTestFile(''' +-int V =3D 42; +-'''); +- await prepareNavigation(); +- assertHasRegion('int V'); +- int targetIndex =3D testTargetIndexes[0]; +- NavigationTarget target =3D targets[targetIndex]; +- expect(target.startLine, greaterThan(0)); +- expect(target.startColumn, greaterThan(0)); +- } +- +- test_constructor_named() async { +- addTestFile(''' +-class A { +- A.named(BBB p) {} +-} +-class BBB {} +-'''); +- await prepareNavigation(); +- // has region for complete "A.named" +- assertHasRegionString('A.named'); +- assertHasTarget('named(BBB'); +- // no separate regions for "A" and "named" +- assertNoRegion('A.named(', 'A'.length); +- assertNoRegion('named(', 'named'.length); +- // validate that we don't forget to resolve parameters +- assertHasRegionTarget('BBB p', 'BBB {}'); +- } +- +- test_constructor_unnamed() async { +- addTestFile(''' +-class A { +- A(BBB p) {} +-} +-class BBB {} +-'''); +- await prepareNavigation(); +- // has region for complete "A.named" +- assertHasRegion("A(BBB"); +- assertHasTarget("A(BBB", 0); +- // validate that we don't forget to resolve parameters +- assertHasRegionTarget('BBB p', 'BBB {}'); +- } +- +- test_factoryRedirectingConstructor_implicit() async { +- addTestFile(''' +-class A { +- factory A() =3D B; +-} +-class B { +-} +-'''); +- await prepareNavigation(); +- assertHasRegion('B;'); +- assertHasTarget('B {'); +- } +- +- test_factoryRedirectingConstructor_implicit_withTypeArgument() async { +- addTestFile(''' +-class A {} +-class B { +- factory B() =3D C; +-} +-class C {} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('C'); +- assertHasTarget('C {'); +- } +- { +- assertHasRegion('A>;'); +- assertHasTarget('A {'); +- } +- } +- +- test_factoryRedirectingConstructor_named() async { +- addTestFile(''' +-class A { +- factory A() =3D B.named; +-} +-class B { +- B.named(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegionString('B.named;', 'B'.length); +- assertHasTarget('named();'); +- } +- { +- assertHasRegionString('named;', 'named'.length); +- assertHasTarget('named();'); +- } +- } +- +- test_factoryRedirectingConstructor_named_withTypeArgument() async { +- addTestFile(''' +-class A {} +-class B { +- factory B.named() =3D C.named; +-} +-class C { +- C.named() {} +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('C'); +- assertHasTarget('named() {}'); +- } +- { +- assertHasRegion('A>.named'); +- assertHasTarget('A {'); +- } +- { +- assertHasRegion('named;', 'named'.length); +- assertHasTarget('named() {}'); +- } +- } +- +- test_factoryRedirectingConstructor_unnamed() async { +- addTestFile(''' +-class A { +- factory A() =3D B; +-} +-class B { +- B() {} +-} +-'''); +- await prepareNavigation(); +- assertHasRegion('B;'); +- assertHasTarget('B() {}', 0); +- } +- +- test_factoryRedirectingConstructor_unnamed_withTypeArgument() async { +- addTestFile(''' +-class A {} +-class B { +- factory B() =3D C; +-} +-class C { +- C() {} +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('C'); +- assertHasTarget('C() {}', 0); +- } +- { +- assertHasRegion('A>;'); +- assertHasTarget('A {'); +- } +- } +- +- test_factoryRedirectingConstructor_unresolved() async { +- addTestFile(''' +-class A { +- factory A() =3D B; +-} +-'''); +- await prepareNavigation(); +- // don't check regions, but there should be no exceptions +- } +- +- test_fieldFormalParameter() async { +- addTestFile(''' +-class AAA { +- int fff =3D 123; +- AAA(this.fff); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('fff);', 'fff =3D 123'); +- } +- +- test_fieldFormalParameter_unresolved() async { +- addTestFile(''' +-class AAA { +- AAA(this.fff); +-} +-'''); +- await prepareNavigation(); +- assertNoRegion('fff);', 3); +- } +- +- test_identifier_resolved() async { +- addTestFile(''' +-class AAA {} +-main() { +- AAA aaa =3D null; +- print(aaa); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('AAA aaa', 'AAA {}'); +- assertHasRegionTarget('aaa);', 'aaa =3D null'); +- assertHasRegionTarget('main() {', 'main() {'); +- } +- +- test_identifier_unresolved() async { +- addTestFile(''' +-main() { +- print(vvv); +-} +-'''); +- await prepareNavigation(); +- assertNoRegionString('vvv'); +- } +- +- test_identifier_whenStrayImportDirective() async { +- addTestFile(''' +-main() { +- int aaa =3D 42; +- print(aaa); +-} +-import 'dart:math'; +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('aaa);', 'aaa =3D 42'); +- } +- +- test_inComment() async { +- addTestFile(''' +-class FirstClass {} +-class SecondClass { +- /** +- * Return a [FirstClass] object equivalent to this object in every othe= r way. +- */ +- convert() { +- return new FirstClass(); +- } +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('FirstClass]', 'FirstClass {'); +- assertHasRegionTarget('FirstClass(', 'FirstClass {'); +- } +- +- test_instanceCreation_implicit() async { +- addTestFile(''' +-class A { +-} +-main() { +- new A(); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionString('A()', 'A'.length); +- assertHasTarget('A {'); +- } +- +- test_instanceCreation_implicit_withTypeArgument() async { +- addTestFile(''' +-class A {} +-class B {} +-main() { +- new B(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('B', 'B'.length); +- assertHasTarget('B {'); +- } +- { +- assertHasRegion('A>();', 'A'.length); +- assertHasTarget('A {'); +- } +- } +- +- test_instanceCreation_named() async { +- addTestFile(''' +-class A { +- A.named() {} +-} +-main() { +- new A.named(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegionString('A.named();', 'A'.length); +- assertHasTarget('named() {}'); +- } +- { +- assertHasRegionString('named();', 'named'.length); +- assertHasTarget('named() {}'); +- } +- } +- +- test_instanceCreation_named_withTypeArgument() async { +- addTestFile(''' +-class A {} +-class B { +- B.named() {} +-} +-main() { +- new B.named(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegionString('B', 'B'.length); +- assertHasTarget('named() {}'); +- } +- { +- assertHasRegion('A>.named'); +- assertHasTarget('A {'); +- } +- { +- assertHasRegion('named();', 'named'.length); +- assertHasTarget('named() {}'); +- } +- } +- +- test_instanceCreation_unnamed() async { +- addTestFile(''' +-class A { +- A() {} +-} +-main() { +- new A(); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionString('A();', 'A'.length); +- assertHasTarget('A() {}', 0); +- } +- +- test_instanceCreation_unnamed_withTypeArgument() async { +- addTestFile(''' +-class A {} +-class B { +- B() {} +-} +-main() { +- new B(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegionString('B();', 'B'.length); +- assertHasTarget('B() {}', 0); +- } +- { +- assertHasRegion('A>();'); +- assertHasTarget('A {'); +- } +- } +- +- test_instanceCreation_withImportPrefix_named() async { +- addTestFile(''' +-import 'dart:async' as ppp; +-main() { +- new ppp.Future.value(42); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('ppp.'); +- assertHasTarget('ppp;'); +- } +- assertHasRegion('Future.value'); +- assertHasRegion('value(42)'); +- } +- +- test_library() async { +- addTestFile(''' +-library my.lib; +-'''); +- await prepareNavigation(); +- assertHasRegionString('my.lib'); +- assertHasTargetString('my.lib'); +- } +- +- test_multiplyDefinedElement() async { +- addFile('$projectPath/bin/libA.dart', 'library A; int TEST =3D 1;'); +- addFile('$projectPath/bin/libB.dart', 'library B; int TEST =3D 2;'); +- addTestFile(''' +-import 'libA.dart'; +-import 'libB.dart'; +-main() { +- TEST; +-} +-'''); +- await prepareNavigation(); +- assertNoRegionAt('TEST'); +- } +- +- test_operator_arithmetic() async { +- addTestFile(''' +-class A { +- A operator +(other) =3D> null; +- A operator -() =3D> null; +- A operator -(other) =3D> null; +- A operator *(other) =3D> null; +- A operator /(other) =3D> null; +-} +-main() { +- var a =3D new A(); +- a - 1; +- a + 2; +- -a; // unary +- --a; +- ++a; +- a--; // mm +- a++; // pp +- a -=3D 3; +- a +=3D 4; +- a *=3D 5; +- a /=3D 6; +-} +-'''); +- await prepareNavigation(); +- assertHasOperatorRegion('- 1', 1, '-(other) =3D> null', 1); +- assertHasOperatorRegion('+ 2', 1, '+(other) =3D> null', 1); +- assertHasOperatorRegion('-a; // unary', 1, '-() =3D> null', 1); +- assertHasOperatorRegion('--a;', 2, '-(other) =3D> null', 1); +- assertHasOperatorRegion('++a;', 2, '+(other) =3D> null', 1); +- assertHasOperatorRegion('--; // mm', 2, '-(other) =3D> null', 1); +- assertHasOperatorRegion('++; // pp', 2, '+(other) =3D> null', 1); +- assertHasOperatorRegion('-=3D 3', 2, '-(other) =3D> null', 1); +- assertHasOperatorRegion('+=3D 4', 2, '+(other) =3D> null', 1); +- assertHasOperatorRegion('*=3D 5', 2, '*(other) =3D> null', 1); +- assertHasOperatorRegion('/=3D 6', 2, '/(other) =3D> null', 1); +- } +- +- test_operator_index() async { +- addTestFile(''' +-class A { +- A operator +(other) =3D> null; +-} +-class B { +- A operator [](index) =3D> null; +- operator []=3D(index, A value) {} +-} +-main() { +- var b =3D new B(); +- b[0] // []; +- b[1] =3D 1; // []=3D; +- b[2] +=3D 2; +-} +-'''); +- await prepareNavigation(); +- assertHasOperatorRegion('[0', 1, '[](index)', 2); +- assertHasOperatorRegion('] // []', 1, '[](index)', 2); +- assertHasOperatorRegion('[1', 1, '[]=3D(index,', 3); +- assertHasOperatorRegion('] =3D 1;', 1, '[]=3D(index,', 3); +- assertHasOperatorRegion('[2', 1, '[]=3D(index,', 3); +- assertHasOperatorRegion('] +=3D 2;', 1, '[]=3D(index,', 3); +- assertHasOperatorRegion('+=3D 2;', 2, '+(other)', 1); +- } +- +- test_partOf() async { +- var libCode =3D 'library lib; part "test.dart";'; +- var libFile =3D addFile('$projectPath/bin/lib.dart', libCode); +- addTestFile('part of lib;'); +- await prepareNavigation(); +- assertHasRegionString('lib'); +- assertHasFileTarget(libFile, libCode.indexOf('lib;'), 'lib'.length); +- } +- +- test_redirectingConstructorInvocation() async { +- addTestFile(''' +-class A { +- A() {} +- A.foo() : this(); +- A.bar() : this.foo(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegion('this();'); +- assertHasTarget('A() {}', 0); +- } +- { +- assertHasRegion('this.foo'); +- assertHasTarget('foo() :'); +- } +- { +- assertHasRegion('foo();'); +- assertHasTarget('foo() :'); +- } +- } +- +- test_string_export() async { +- var libCode =3D 'library lib;'; +- var libFile =3D addFile('$projectPath/bin/lib.dart', libCode); +- addTestFile('export "lib.dart";'); +- await prepareNavigation(); +- assertHasRegionString('"lib.dart"'); +- assertHasFileTarget(libFile, libCode.indexOf('lib;'), 'lib'.length); +- } +- +- test_string_export_unresolvedUri() async { +- addTestFile('export "no.dart";'); +- await prepareNavigation(); +- assertNoRegionString('"no.dart"'); +- } +- +- test_string_import() async { +- var libCode =3D 'library lib;'; +- var libFile =3D addFile('$projectPath/bin/lib.dart', libCode); +- addTestFile('import "lib.dart";'); +- await prepareNavigation(); +- assertHasRegionString('"lib.dart"'); +- assertHasFileTarget(libFile, libCode.indexOf('lib;'), 'lib'.length); +- } +- +- test_string_import_noUri() async { +- addTestFile('import ;'); +- await prepareNavigation(); +- assertNoRegionAt('import ;'); +- } +- +- test_string_import_unresolvedUri() async { +- addTestFile('import "no.dart";'); +- await prepareNavigation(); +- assertNoRegionString('"no.dart"'); +- } +- +- test_string_part() async { +- var unitCode =3D 'part of lib; f() {}'; +- var unitFile =3D addFile('$projectPath/bin/test_unit.dart', unitCode); +- addTestFile(''' +-library lib; +-part "test_unit.dart"; +-'''); +- await prepareNavigation(); +- assertHasRegionString('"test_unit.dart"'); +- assertHasFileTarget(unitFile, 0, 0); +- } +- +- test_string_part_unresolvedUri() async { +- addTestFile(''' +-library lib; +-part "test_unit.dart"; +-'''); +- await prepareNavigation(); +- assertNoRegionString('"test_unit.dart"'); +- } +- +- test_superConstructorInvocation() async { +- addTestFile(''' +-class A { +- A() {} +- A.named() {} +-} +-class B extends A { +- B() : super(); +- B.named() : super.named(); +-} +-'''); +- await prepareNavigation(); +- { +- assertHasRegionString('super'); +- assertHasTarget('A() {}', 0); +- } +- { +- assertHasRegion('super.named'); +- assertHasTarget('named() {}'); +- } +- { +- assertHasRegion('named();'); +- assertHasTarget('named() {}'); +- } +- } +- +- test_superConstructorInvocation_synthetic() async { +- addTestFile(''' +-class A { +-} +-class B extends A { +- B() : super(); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionString('super'); +- assertHasTarget('A {'); +- } +- +- test_targetElement() async { +- addTestFile(''' +-class AAA {} +-main() { +- AAA aaa =3D null; +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('AAA aaa', 'AAA {}'); +- expect(testTarget.kind, ElementKind.CLASS); +- } +- +- test_type_dynamic() async { +- addTestFile(''' +-main() { +- dynamic v =3D null; +-} +-'''); +- await prepareNavigation(); +- assertNoRegionAt('dynamic'); +- } +- +- test_type_void() async { +- addTestFile(''' +-void main() { +-} +-'''); +- await prepareNavigation(); +- assertNoRegionAt('void'); +- } +- +- test_var_declaredVariable() async { +- addTestFile(''' +-class C {} +-f(List items) { +- for (var item in items) {} +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('var', 'C {}'); +- expect(testTarget.kind, ElementKind.CLASS); +- } +- +- test_var_localVariable_multiple_inferred_different() async { +- addTestFile(''' +-class A {} +-class B {} +-void f() { +- var a =3D new A(), b =3D new B(); +-} +-'''); +- await prepareNavigation(); +- assertNoRegionAt('var'); +- } +- +- test_var_localVariable_multiple_inferred_same() async { +- addTestFile(''' +-class C {} +-void f() { +- var a =3D new C(), b =3D new C(); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('var', 'C {}'); +- expect(testTarget.kind, ElementKind.CLASS); +- } +- +- test_var_localVariable_single_inferred() async { +- addTestFile(''' +-class C {} +-f() { +- var c =3D new C(); +-} +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('var', 'C {}'); +- expect(testTarget.kind, ElementKind.CLASS); +- } +- +- test_var_localVariable_single_notInferred() async { +- addTestFile(''' +-f() { +- var x; +-} +-'''); +- await prepareNavigation(); +- assertNoRegionAt('var'); +- } +- +- test_var_topLevelVariable_multiple_inferred_different() async { +- addTestFile(''' +-class A {} +-class B {} +-var a =3D new A(), b =3D new B(); +-'''); +- await prepareNavigation(); +- assertNoRegionAt('var'); +- } +- +- test_var_topLevelVariable_multiple_inferred_same() async { +- addTestFile(''' +-class C {} +-var a =3D new C(), b =3D new C(); +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('var', 'C {}'); +- expect(testTarget.kind, ElementKind.CLASS); +- } +- +- test_var_topLevelVariable_single_inferred() async { +- addTestFile(''' +-class C {} +-var c =3D new C(); +-'''); +- await prepareNavigation(); +- assertHasRegionTarget('var', 'C {}'); +- expect(testTarget.kind, ElementKind.CLASS); +- } +- +- test_var_topLevelVariable_single_notInferred() async { +- addTestFile(''' +-var x; +-'''); +- await prepareNavigation(); +- assertNoRegionAt('var'); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_occurrences_te= st.dart b/pkg/analysis_server/test/analysis/notification_occurrences_test.d= art +deleted file mode 100644 +index df66d76d1eb..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_occurrences_test.dart ++++ /dev/null +@@ -1,257 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationOccurrencesTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNotificationOccurrencesTest extends AbstractAnalysisTest { +- List occurrencesList; +- Occurrences testOccurrences; +- +- Completer _resultsAvailable =3D new Completer(); +- +- /** +- * Asserts that there is an offset of [search] in [testOccurrences]. +- */ +- void assertHasOffset(String search) { +- int offset =3D findOffset(search); +- expect(testOccurrences.offsets, contains(offset)); +- } +- +- /** +- * Validates that there is a region at the offset of [search] in [testF= ile]. +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertHasRegion(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- findRegion(offset, length, true); +- } +- +- /** +- * Finds an [Occurrences] with the given [offset] and [length]. +- * +- * If [exists] is `true`, then fails if such [Occurrences] does not exi= st. +- * Otherwise remembers this it into [testOccurrences]. +- * +- * If [exists] is `false`, then fails if such [Occurrences] exists. +- */ +- void findRegion(int offset, int length, [bool exists]) { +- for (Occurrences occurrences in occurrencesList) { +- if (occurrences.length !=3D length) { +- continue; +- } +- for (int occurrenceOffset in occurrences.offsets) { +- if (occurrenceOffset =3D=3D offset) { +- if (exists =3D=3D false) { +- fail('Not expected to find (offset=3D$offset; length=3D$lengt= h) in\n' +- '${occurrencesList.join('\n')}'); +- } +- testOccurrences =3D occurrences; +- return; +- } +- } +- } +- if (exists =3D=3D true) { +- fail('Expected to find (offset=3D$offset; length=3D$length) in\n' +- '${occurrencesList.join('\n')}'); +- } +- } +- +- Future prepareOccurrences() { +- addAnalysisSubscription(AnalysisService.OCCURRENCES, testFile); +- return _resultsAvailable.future; +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_OCCURRENCES) { +- var params =3D new AnalysisOccurrencesParams.fromNotification(notif= ication); +- if (params.file =3D=3D testFile) { +- occurrencesList =3D params.occurrences; +- _resultsAvailable.complete(null); +- } +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- test_afterAnalysis() async { +- addTestFile(''' +-main() { +- var vvv =3D 42; +- print(vvv); +-} +-'''); +- await waitForTasksFinished(); +- await prepareOccurrences(); +- assertHasRegion('vvv =3D'); +- expect(testOccurrences.element.kind, ElementKind.LOCAL_VARIABLE); +- expect(testOccurrences.element.name, 'vvv'); +- assertHasOffset('vvv =3D 42'); +- assertHasOffset('vvv);'); +- } +- +- test_field() async { +- addTestFile(''' +-class A { +- int fff; +- A(this.fff); // constructor +- main() { +- fff =3D 42; +- print(fff); // print +- } +-} +-'''); +- await prepareOccurrences(); +- assertHasRegion('fff;'); +- expect(testOccurrences.element.kind, ElementKind.FIELD); +- assertHasOffset('fff); // constructor'); +- assertHasOffset('fff =3D 42;'); +- assertHasOffset('fff); // print'); +- } +- +- test_field_unresolved() async { +- addTestFile(''' +-class A { +- A(this.noSuchField); +-} +-'''); +- // no checks for occurrences, just ensure that there is no NPE +- await prepareOccurrences(); +- } +- +- test_localVariable() async { +- addTestFile(''' +-main() { +- var vvv =3D 42; +- vvv +=3D 5; +- print(vvv); +-} +-'''); +- await prepareOccurrences(); +- assertHasRegion('vvv =3D'); +- expect(testOccurrences.element.kind, ElementKind.LOCAL_VARIABLE); +- expect(testOccurrences.element.name, 'vvv'); +- assertHasOffset('vvv =3D 42'); +- assertHasOffset('vvv +=3D 5'); +- assertHasOffset('vvv);'); +- } +- +- test_memberField() async { +- addTestFile(''' +-class A { +- T fff; +-} +-main() { +- var a =3D new A(); +- var b =3D new A(); +- a.fff =3D 1; +- b.fff =3D 2; +-} +-'''); +- await prepareOccurrences(); +- assertHasRegion('fff;'); +- expect(testOccurrences.element.kind, ElementKind.FIELD); +- assertHasOffset('fff =3D 1;'); +- assertHasOffset('fff =3D 2;'); +- } +- +- test_memberMethod() async { +- addTestFile(''' +-class A { +- T mmm() {} +-} +-main() { +- var a =3D new A(); +- var b =3D new A(); +- a.mmm(); // a +- b.mmm(); // b +-} +-'''); +- await prepareOccurrences(); +- assertHasRegion('mmm() {}'); +- expect(testOccurrences.element.kind, ElementKind.METHOD); +- assertHasOffset('mmm(); // a'); +- assertHasOffset('mmm(); // b'); +- } +- +- test_topLevelVariable() async { +- addTestFile(''' +-var VVV =3D 1; +-main() { +- VVV =3D 2; +- print(VVV); +-} +-'''); +- await prepareOccurrences(); +- assertHasRegion('VVV =3D 1;'); +- expect(testOccurrences.element.kind, ElementKind.TOP_LEVEL_VARIABLE); +- assertHasOffset('VVV =3D 2;'); +- assertHasOffset('VVV);'); +- } +- +- test_type_class() async { +- addTestFile(''' +-main() { +- int a =3D 1; +- int b =3D 2; +- int c =3D 3; +-} +-int VVV =3D 4; +-'''); +- await prepareOccurrences(); +- assertHasRegion('int a'); +- expect(testOccurrences.element.kind, ElementKind.CLASS); +- expect(testOccurrences.element.name, 'int'); +- assertHasOffset('int a'); +- assertHasOffset('int b'); +- assertHasOffset('int c'); +- assertHasOffset('int VVV'); +- } +- +- test_type_dynamic() async { +- addTestFile(''' +-main() { +- dynamic a =3D 1; +- dynamic b =3D 2; +-} +-dynamic V =3D 3; +-'''); +- await prepareOccurrences(); +- int offset =3D findOffset('dynamic a'); +- findRegion(offset, 'dynamic'.length, false); +- } +- +- test_type_void() async { +- addTestFile(''' +-void main() { +-} +-'''); +- await prepareOccurrences(); +- int offset =3D findOffset('void main()'); +- findRegion(offset, 'void'.length, false); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_outline_test.d= art b/pkg/analysis_server/test/analysis/notification_outline_test.dart +deleted file mode 100644 +index f3e6f4f34d7..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_outline_test.dart ++++ /dev/null +@@ -1,135 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(_AnalysisNotificationOutlineTest); +- }); +-} +- +-@reflectiveTest +-class _AnalysisNotificationOutlineTest extends AbstractAnalysisTest { +- FileKind fileKind; +- String libraryName; +- Outline outline; +- +- Completer _outlineReceived =3D new Completer(); +- Completer _highlightsReceived =3D new Completer(); +- +- Future prepareOutline() { +- addAnalysisSubscription(AnalysisService.OUTLINE, testFile); +- return _outlineReceived.future; +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_OUTLINE) { +- var params =3D new AnalysisOutlineParams.fromNotification(notificat= ion); +- if (params.file =3D=3D testFile) { +- fileKind =3D params.kind; +- libraryName =3D params.libraryName; +- outline =3D params.outline; +- _outlineReceived.complete(null); +- } +- } +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_HIGHLIGHTS) { +- var params =3D new AnalysisHighlightsParams.fromNotification(notifi= cation); +- if (params.file =3D=3D testFile) { +- _highlightsReceived?.complete(null); +- _highlightsReceived =3D null; +- } +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- test_afterAnalysis() async { +- addTestFile(''' +-class AAA { +-} +-class BBB { +-} +-'''); +- await waitForTasksFinished(); +- expect(outline, isNull); +- await prepareOutline(); +- Outline unitOutline =3D outline; +- List outlines =3D unitOutline.children; +- expect(outlines, hasLength(2)); +- } +- +- test_libraryName_hasLibraryDirective() async { +- addTestFile(''' +-library my.lib; +-'''); +- await prepareOutline(); +- expect(fileKind, FileKind.LIBRARY); +- expect(libraryName, 'my.lib'); +- } +- +- @failingTest +- test_libraryName_hasLibraryPartOfDirectives() async { +- // This appears to have broken with the move to the new analysis driv= er. +- addTestFile(''' +-part of lib.in.part.of; +-library my.lib; +-'''); +- await prepareOutline(); +- expect(fileKind, FileKind.LIBRARY); +- expect(libraryName, 'my.lib'); +- } +- +- test_libraryName_hasPartOfDirective() async { +- addTestFile(''' +-part of my.lib; +-'''); +- await prepareOutline(); +- expect(fileKind, FileKind.PART); +- expect(libraryName, 'my.lib'); +- } +- +- test_libraryName_noDirectives() async { +- addTestFile(''' +-class A {} +-'''); +- await prepareOutline(); +- expect(fileKind, FileKind.LIBRARY); +- expect(libraryName, isNull); +- } +- +- test_subscribeWhenCachedResultIsAvailable() async { +- // https://github.com/dart-lang/sdk/issues/30238 +- // We need to get notifications for new subscriptions even when the +- // file is a priority file, and there is a cached result available. +- addTestFile(''' +-class A {} +-class B {} +-'''); +- +- // Make the file a priority one and subscribe for other notification. +- // This will pre-cache the analysis result for the file. +- setPriorityFiles([testFile]); +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, testFile); +- await _highlightsReceived.future; +- +- // Now subscribe for outline notification, we must get it even though +- // the result which is used is pre-cached, and not a newly computed. +- await prepareOutline(); +- expect(outline.children, hasLength(2)); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/notification_overrides_test= .dart b/pkg/analysis_server/test/analysis/notification_overrides_test.dart +deleted file mode 100644 +index 10abe239f0e..00000000000 +--- a/pkg/analysis_server/test/analysis/notification_overrides_test.dart ++++ /dev/null +@@ -1,577 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNotificationOverridesTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNotificationOverridesTest extends AbstractAnalysisTest { +- List overridesList; +- Override override; +- +- Completer _resultsAvailable =3D new Completer(); +- +- /** +- * Asserts that there is an overridden interface [OverriddenMember] at = the +- * offset of [search] in [override]. +- */ +- void assertHasInterfaceMember(String search) { +- int offset =3D findOffset(search); +- for (OverriddenMember member in override.interfaceMembers) { +- if (member.element.location.offset =3D=3D offset) { +- return; +- } +- } +- fail('Expect to find an overridden interface members at $offset in ' +- '${override.interfaceMembers.join('\n')}'); +- } +- +- /** +- * Validates that there is an [Override] at the offset of [search]. +- * +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertHasOverride(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- findOverride(offset, length, true); +- } +- +- /** +- * Asserts that there is an overridden superclass [OverriddenMember] at= the +- * offset of [search] in [override]. +- */ +- void assertHasSuperElement(String search) { +- int offset =3D findOffset(search); +- OverriddenMember member =3D override.superclassMember; +- expect(member.element.location.offset, offset); +- } +- +- /** +- * Asserts that there are no overridden members from interfaces. +- */ +- void assertNoInterfaceMembers() { +- expect(override.interfaceMembers, isNull); +- } +- +- /** +- * Validates that there is no [Override] at the offset of [search]. +- * +- * If [length] is not specified explicitly, then length of an identifier +- * from [search] is used. +- */ +- void assertNoOverride(String search, [int length =3D -1]) { +- int offset =3D findOffset(search); +- if (length =3D=3D -1) { +- length =3D findIdentifierLength(search); +- } +- findOverride(offset, length, false); +- } +- +- /** +- * Asserts that there are no overridden member from the superclass. +- */ +- void assertNoSuperMember() { +- expect(override.superclassMember, isNull); +- } +- +- /** +- * Finds an [Override] with the given [offset] and [length]. +- * +- * If [exists] is `true`, then fails if such [Override] does not exist. +- * Otherwise remembers this it into [override]. +- * +- * If [exists] is `false`, then fails if such [Override] exists. +- */ +- void findOverride(int offset, int length, [bool exists]) { +- for (Override override in overridesList) { +- if (override.offset =3D=3D offset && override.length =3D=3D length)= { +- if (exists =3D=3D false) { +- fail('Not expected to find (offset=3D$offset; length=3D$length)= in\n' +- '${overridesList.join('\n')}'); +- } +- this.override =3D override; +- return; +- } +- } +- if (exists =3D=3D true) { +- fail('Expected to find (offset=3D$offset; length=3D$length) in\n' +- '${overridesList.join('\n')}'); +- } +- } +- +- Future prepareOverrides() { +- addAnalysisSubscription(AnalysisService.OVERRIDES, testFile); +- return _resultsAvailable.future; +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_OVERRIDES) { +- var params =3D new AnalysisOverridesParams.fromNotification(notific= ation); +- if (params.file =3D=3D testFile) { +- overridesList =3D params.overrides; +- _resultsAvailable.complete(null); +- } +- } +- } +- +- void setUp() { +- super.setUp(); +- createProject(); +- } +- +- test_afterAnalysis() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B implements A { +- m() {} // in B +-} +-'''); +- await waitForTasksFinished(); +- await prepareOverrides(); +- assertHasOverride('m() {} // in B'); +- assertNoSuperMember(); +- assertHasInterfaceMember('m() {} // in A'); +- } +- +- test_BAD_fieldByMethod() async { +- addTestFile(''' +-class A { +- int fff; // in A +-} +-class B extends A { +- fff() {} // in B +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff() {} // in B'); +- } +- +- test_BAD_getterByMethod() async { +- addTestFile(''' +-class A { +- get fff =3D> null; +-} +-class B extends A { +- fff() {} +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff() {}'); +- } +- +- test_BAD_getterBySetter() async { +- addTestFile(''' +-class A { +- get fff =3D> null; +-} +-class B extends A { +- set fff(x) {} +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff(x) {}'); +- } +- +- test_BAD_methodByField() async { +- addTestFile(''' +-class A { +- fff() {} // in A +-} +-class B extends A { +- int fff; // in B +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff; // in B'); +- } +- +- test_BAD_methodByGetter() async { +- addTestFile(''' +-class A { +- fff() {} +-} +-class B extends A { +- int get fff =3D> null; +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff =3D> null'); +- } +- +- test_BAD_methodBySetter() async { +- addTestFile(''' +-class A { +- fff(x) {} // A +-} +-class B extends A { +- set fff(x) {} // B +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff(x) {} // B'); +- } +- +- test_BAD_privateByPrivate_inDifferentLib() async { +- addFile('$testFolder/lib.dart', r''' +-class A { +- void _m() {} +-} +-'''); +- addTestFile(''' +-import 'lib.dart'; +-class B extends A { +- void _m() {} // in B +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('_m() {} // in B'); +- } +- +- test_BAD_setterByGetter() async { +- addTestFile(''' +-class A { +- set fff(x) {} +-} +-class B extends A { +- get fff =3D> null; +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff =3D> null;'); +- } +- +- test_BAD_setterByMethod() async { +- addTestFile(''' +-class A { +- set fff(x) {} // A +-} +-class B extends A { +- fff(x) {} // B +-} +-'''); +- await prepareOverrides(); +- assertNoOverride('fff(x) {} // B'); +- } +- +- test_definedInInterface_ofInterface() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B implements A {} +-class C implements B { +- m() {} // in C +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in C'); +- assertNoSuperMember(); +- assertHasInterfaceMember('m() {} // in A'); +- } +- +- test_definedInInterface_ofSuper() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B implements A {} +-class C extends B { +- m() {} // in C +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in C'); +- assertNoSuperMember(); +- assertHasInterfaceMember('m() {} // in A'); +- } +- +- test_interface_method_direct_multiple() async { +- addTestFile(''' +-class IA { +- m() {} // in IA +-} +-class IB { +- m() {} // in IB +-} +-class A implements IA, IB { +- m() {} // in A +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in A'); +- assertNoSuperMember(); +- assertHasInterfaceMember('m() {} // in IA'); +- assertHasInterfaceMember('m() {} // in IB'); +- } +- +- test_interface_method_direct_single() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B implements A { +- m() {} // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in B'); +- assertNoSuperMember(); +- assertHasInterfaceMember('m() {} // in A'); +- } +- +- test_interface_method_indirect_single() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B extends A { +-} +-class C implements B { +- m() {} // in C +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in C'); +- assertNoSuperMember(); +- assertHasInterfaceMember('m() {} // in A'); +- } +- +- test_interface_stopWhenFound() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B extends A { +- m() {} // in B +-} +-class C implements B { +- m() {} // in C +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in C'); +- expect(override.interfaceMembers, hasLength(2)); +- assertHasInterfaceMember('m() {} // in B'); +- } +- +- test_mix_sameMethod() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-abstract class B extends A { +-} +-class C extends A implements A { +- m() {} // in C +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in C'); +- assertHasSuperElement('m() {} // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_mix_sameMethod_Object_hashCode() async { +- addTestFile(''' +-class A {} +-abstract class B {} +-class C extends A implements A { +- int get hashCode =3D> 42; +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('hashCode =3D> 42;'); +- expect(override.superclassMember, isNotNull); +- expect(override.interfaceMembers, isNull); +- } +- +- test_staticMembers() async { +- addTestFile(''' +-class A { +- static int F =3D 0; +- static void M() {} +- static int get G =3D> 0; +- static void set S(int v) {} +-} +-class B extends A { +- static int F =3D 0; +- static void M() {} +- static int get G =3D> 0; +- static void set S(int v) {} +-} +-'''); +- await prepareOverrides(); +- expect(overridesList, isEmpty); +- } +- +- test_super_fieldByField() async { +- addTestFile(''' +-class A { +- int fff; // in A +-} +-class B extends A { +- int fff; // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('fff; // in B'); +- assertHasSuperElement('fff; // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_fieldByGetter() async { +- addTestFile(''' +-class A { +- int fff; // in A +-} +-class B extends A { +- get fff =3D> 0; // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('fff =3D> 0; // in B'); +- assertHasSuperElement('fff; // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_fieldBySetter() async { +- addTestFile(''' +-class A { +- int fff; // in A +-} +-class B extends A { +- set fff(x) {} // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('fff(x) {} // in B'); +- assertHasSuperElement('fff; // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_getterByField() async { +- addTestFile(''' +-class A { +- get fff =3D> 0; // in A +- set fff(x) {} // in A +-} +-class B extends A { +- int fff; // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('fff; // in B'); +- assertHasSuperElement('fff =3D> 0; // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_getterByGetter() async { +- addTestFile(''' +-class A { +- get fff =3D> 0; // in A +-} +-class B extends A { +- get fff =3D> 0; // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('fff =3D> 0; // in B'); +- assertHasSuperElement('fff =3D> 0; // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_method_direct() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B extends A { +- m() {} // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in B'); +- assertHasSuperElement('m() {} // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_method_indirect() async { +- addTestFile(''' +-class A { +- m() {} // in A +-} +-class B extends A { +-} +-class C extends B { +- m() {} // in C +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('m() {} // in C'); +- assertHasSuperElement('m() {} // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_method_privateByPrivate() async { +- addTestFile(''' +-class A { +- _m() {} // in A +-} +-class B extends A { +- _m() {} // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('_m() {} // in B'); +- assertHasSuperElement('_m() {} // in A'); +- assertNoInterfaceMembers(); +- } +- +- test_super_method_superTypeCycle() async { +- addTestFile(''' +-class A extends B { +- m() {} // in A +-} +-class B extends A { +- m() {} // in B +-} +-'''); +- await prepareOverrides(); +- // must finish +- } +- +- test_super_setterBySetter() async { +- addTestFile(''' +-class A { +- set fff(x) {} // in A +-} +-class B extends A { +- set fff(x) {} // in B +-} +-'''); +- await prepareOverrides(); +- assertHasOverride('fff(x) {} // in B'); +- assertHasSuperElement('fff(x) {} // in A'); +- assertNoInterfaceMembers(); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/reanalyze_test.dart b/pkg/a= nalysis_server/test/analysis/reanalyze_test.dart +deleted file mode 100644 +index c78dd97f87c..00000000000 +--- a/pkg/analysis_server/test/analysis/reanalyze_test.dart ++++ /dev/null +@@ -1,75 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ReanalyzeTest); +- }); +-} +- +-@reflectiveTest +-class ReanalyzeTest extends AbstractAnalysisTest { +- Map> filesErrors =3D {}; +- +- Completer _resultsAvailable =3D new Completer(); +- +- @override +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ERRORS) { +- var decoded =3D new AnalysisErrorsParams.fromNotification(notificat= ion); +- filesErrors[decoded.file] =3D decoded.errors; +- _resultsAvailable.complete(null); +- } +- } +- +- test_reanalyze() { +- createProject(); +- Map drivers =3D server.driverMap; +- expect(drivers, hasLength(1)); +- Request request =3D new Request("0", ANALYSIS_REQUEST_REANALYZE); +- handleSuccessfulRequest(request); +- drivers =3D server.driverMap; +- expect(drivers, hasLength(1)); +- } +- +- test_reanalyze_with_overlay() async { +- createProject(); +- resourceProvider.newFolder(testFolder); +- resourceProvider.newFile(testFile, 'main() {}'); +- // Update the content with an overlay that contains a syntax error. +- server.updateContent('1', {testFile: new AddContentOverlay('main() {'= )}); +- await _resultsAvailable.future; +- // Verify that the syntax error was detected. +- { +- List errors =3D filesErrors[testFile]; +- expect(errors, hasLength(1)); +- } +- // Remove testFile from filesErrors so that we'll notice when the fil= e is +- // re-analyzed. +- filesErrors.remove(testFile); +- // Reanalyze. +- _resultsAvailable =3D new Completer(); +- server.reanalyze(null); +- await _resultsAvailable.future; +- // The file should have been reanalyzed. +- expect(filesErrors, contains(testFile)); +- // Verify that the syntax error is present (this indicates that the +- // content introduced by the call to updateContent is still in effect= ). +- { +- List errors =3D filesErrors[testFile]; +- expect(errors, hasLength(1)); +- } +- } +-} +diff --git a/pkg/analysis_server/test/analysis/set_priority_files_test.dar= t b/pkg/analysis_server/test/analysis/set_priority_files_test.dart +deleted file mode 100644 +index 1de25bf77ee..00000000000 +--- a/pkg/analysis_server/test/analysis/set_priority_files_test.dart ++++ /dev/null +@@ -1,131 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetPriorityFilesTest); +- }); +-} +- +-@reflectiveTest +-class SetPriorityFilesTest extends AbstractAnalysisTest { +- @override +- void setUp() { +- super.setUp(); +- server.handlers =3D [ +- new AnalysisDomainHandler(server), +- ]; +- createProject(); +- } +- +- test_fileDoesNotExist() async { +- String file =3D '$projectPath/doesNotExist.dart'; +- Response response =3D await _setPriorityFile(file); +- expect(response, isResponseSuccess('0')); +- } +- +- test_fileInAnalysisRoot() async { +- addTestFile(''); +- // set priority files +- Response response =3D await _setPriorityFile(testFile); +- expect(response, isResponseSuccess('0')); +- // verify +- _verifyPriorityFiles(testFile); +- } +- +- test_fileInSdk() async { +- addTestFile(''); +- // set priority files +- String filePath =3D '/lib/convert/convert.dart'; +- Response response =3D await _setPriorityFile(filePath); +- expect(response, isResponseSuccess('0')); +- // verify +- _verifyPriorityFiles(filePath); +- } +- +- test_fileNotInAnalysisRoot() async { +- String path =3D '/other/file.dart'; +- addFile(path, ''); +- await _setPriorityFile(path); +- _verifyPriorityFiles(path); +- } +- +- test_ignoredInAnalysisOptions() async { +- String sampleFile =3D '$projectPath/samples/sample.dart'; +- addFile('$projectPath/.analysis_options', r''' +-analyzer: +- exclude: +- - 'samples/**' +-'''); +- addFile(sampleFile, ''); +- // attempt to set priority file +- await _setPriorityFile(sampleFile); +- _verifyPriorityFiles(sampleFile); +- } +- +- test_ignoredInAnalysisOptions_inChildContext() async { +- addFile('$projectPath/.packages', ''); +- addFile('$projectPath/child/.packages', ''); +- String sampleFile =3D '$projectPath/child/samples/sample.dart'; +- addFile('$projectPath/child/.analysis_options', r''' +-analyzer: +- exclude: +- - 'samples/**' +-'''); +- addFile(sampleFile, ''); +- // attempt to set priority file +- await _setPriorityFile(sampleFile); +- _verifyPriorityFiles(sampleFile); +- } +- +- test_ignoredInAnalysisOptions_inRootContext() async { +- addFile('$projectPath/.packages', ''); +- addFile('$projectPath/child/.packages', ''); +- String sampleFile =3D '$projectPath/child/samples/sample.dart'; +- addFile('$projectPath/.analysis_options', r''' +-analyzer: +- exclude: +- - 'child/samples/**' +-'''); +- addFile(sampleFile, ''); +- // attempt to set priority file +- await _setPriorityFile(sampleFile); +- _verifyPriorityFiles(sampleFile); +- } +- +- test_sentToPlugins() async { +- addTestFile(''); +- // set priority files +- Response response =3D await _setPriorityFile(testFile); +- expect(response, isResponseSuccess('0')); +- // verify +- plugin.AnalysisSetPriorityFilesParams params =3D +- pluginManager.analysisSetPriorityFilesParams; +- expect(params, isNotNull); +- expect(params.files, [testFile]); +- } +- +- _setPriorityFile(String file) async { +- Request request =3D +- new AnalysisSetPriorityFilesParams([file]).toRequest('0'); +- return await serverChannel.sendRequest(request); +- } +- +- void _verifyPriorityFiles(String path) { +- AnalysisDriver driver =3D server.getAnalysisDriver(path); +- List prioritySources =3D driver.priorityFiles; +- expect(prioritySources, [path]); +- } +-} +diff --git a/pkg/analysis_server/test/analysis/test_all.dart b/pkg/analysi= s_server/test/analysis/test_all.dart +deleted file mode 100644 +index 76e1f5b6061..00000000000 +--- a/pkg/analysis_server/test/analysis/test_all.dart ++++ /dev/null +@@ -1,51 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'get_errors_test.dart' as get_errors_test; +-import 'get_hover_test.dart' as get_hover_test; +-import 'get_navigation_test.dart' as get_navigation_test; +-import 'notification_analysis_options_test.dart' +- as notification_analysis_options_test; +-import 'notification_analyzedFiles_test.dart' +- as notification_analyzedFiles_test; +-import 'notification_closingLabels_test.dart' +- as notification_closingLabels_test; +-import 'notification_errors_test.dart' as notification_errors_test; +-import 'notification_highlights_test.dart' as notification_highlights_tes= t; +-import 'notification_highlights_test2.dart' as notification_highlights_te= st2; +-import 'notification_implemented_test.dart' as notification_implemented_t= est; +-import 'notification_navigation_test.dart' as notification_navigation_tes= t; +-import 'notification_occurrences_test.dart' as notification_occurrences_t= est; +-import 'notification_outline_test.dart' as notification_outline_test; +-import 'notification_overrides_test.dart' as notification_overrides_test; +-import 'reanalyze_test.dart' as reanalyze_test; +-import 'set_priority_files_test.dart' as set_priority_files_test; +-import 'update_content_test.dart' as update_content_test; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- defineReflectiveSuite(() { +- get_errors_test.main(); +- get_hover_test.main(); +- get_navigation_test.main(); +- notification_analysis_options_test.main(); +- notification_analyzedFiles_test.main(); +- notification_closingLabels_test.main(); +- notification_errors_test.main(); +- notification_highlights_test.main(); +- notification_highlights_test2.main(); +- notification_implemented_test.main(); +- notification_navigation_test.main(); +- notification_occurrences_test.main(); +- notification_outline_test.main(); +- notification_overrides_test.main(); +- reanalyze_test.main(); +- set_priority_files_test.main(); +- update_content_test.main(); +- }, name: 'analysis'); +-} +diff --git a/pkg/analysis_server/test/analysis/update_content_test.dart b/= pkg/analysis_server/test/analysis/update_content_test.dart +deleted file mode 100644 +index f2733f8e1e1..00000000000 +--- a/pkg/analysis_server/test/analysis/update_content_test.dart ++++ /dev/null +@@ -1,266 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(UpdateContentTest); +- }); +-} +- +-@reflectiveTest +-class UpdateContentTest extends AbstractAnalysisTest { +- Map> filesErrors =3D {}; +- int serverErrorCount =3D 0; +- int navigationCount =3D 0; +- +- @override +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ERRORS) { +- var decoded =3D new AnalysisErrorsParams.fromNotification(notificat= ion); +- String _format(AnalysisError e) =3D> +- "${e.location.startLine}: ${e.message}"; +- filesErrors[decoded.file] =3D decoded.errors.map(_format).toList(); +- } +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_NAVIGATION) { +- navigationCount++; +- } +- if (notification.event =3D=3D SERVER_NOTIFICATION_ERROR) { +- serverErrorCount++; +- } +- } +- +- test_illegal_ChangeContentOverlay() { +- // It should be illegal to send a ChangeContentOverlay for a file that +- // doesn't have an overlay yet. +- createProject(); +- addTestFile('library foo;'); +- String id =3D 'myId'; +- try { +- server.updateContent(id, { +- testFile: new ChangeContentOverlay([new SourceEdit(8, 3, 'bar')]) +- }); +- fail('Expected an exception to be thrown'); +- } on RequestFailure catch (e) { +- expect(e.response.id, id); +- expect(e.response.error.code, RequestErrorCode.INVALID_OVERLAY_CHAN= GE); +- } +- } +- +- test_multiple_contexts() async { +- String fooPath =3D '/project1/foo.dart'; +- resourceProvider.newFile(fooPath, ''' +-library foo; +-import '../project2/baz.dart'; +-main() { f(); }'''); +- String barPath =3D '/project2/bar.dart'; +- resourceProvider.newFile(barPath, ''' +-library bar; +-import 'baz.dart'; +-main() { f(); }'''); +- String bazPath =3D '/project2/baz.dart'; +- resourceProvider.newFile(bazPath, ''' +-library baz; +-f(int i) {} +-'''); +- Request request =3D +- new AnalysisSetAnalysisRootsParams(['/project1', '/project2'], []) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- { +- await server.onAnalysisComplete; +- // Files foo.dart and bar.dart should both have errors, since they = both +- // call f() with the wrong number of arguments. +- expect(filesErrors[fooPath], hasLength(1)); +- expect(filesErrors[barPath], hasLength(1)); +- // Overlay the content of baz.dart to eliminate the errors. +- server.updateContent('1', { +- bazPath: new AddContentOverlay(''' +-library baz; +-f() {} +-''') +- }); +- } +- { +- await server.onAnalysisComplete; +- // The overlay should have been propagated to both contexts, causin= g both +- // foo.dart and bar.dart to be reanalyzed and found to be free of e= rrors. +- expect(filesErrors[fooPath], isEmpty); +- expect(filesErrors[barPath], isEmpty); +- } +- } +- +- @failingTest +- test_overlay_addPreviouslyImported() async { +- // The list of errors doesn't include errors for '/project/target.dar= t'. +- Folder project =3D resourceProvider.newFolder('/project'); +- handleSuccessfulRequest( +- new AnalysisSetAnalysisRootsParams([project.path], []).toRequest(= '0')); +- +- server.updateContent('1', +- {'/project/main.dart': new AddContentOverlay('import "target.dart= ";')}); +- await server.onAnalysisComplete; +- expect(filesErrors, { +- '/project/main.dart': ["1: Target of URI doesn't exist: 'target.dar= t'."], +- '/project/target.dart': [] +- }); +- +- server.updateContent('1', +- {'/project/target.dart': new AddContentOverlay('import "none.dart= ";')}); +- await server.onAnalysisComplete; +- expect(filesErrors, { +- '/project/main.dart': ["1: Unused import."], +- '/project/target.dart': ["1: Target of URI doesn't exist: 'none.dar= t'."], +- '/project/none.dart': [] +- }); +- } +- +- test_overlayOnly() async { +- String filePath =3D '/User/project1/test.dart'; +- Folder folder1 =3D resourceProvider.newFolder('/User/project1'); +- Folder folder2 =3D resourceProvider.newFolder('/User/project2'); +- Request request =3D +- new AnalysisSetAnalysisRootsParams([folder1.path, folder2.path], = []) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- // exactly 2 contexts +- expect(server.driverMap, hasLength(2)); +- AnalysisDriver driver1 =3D server.driverMap[folder1]; +- AnalysisDriver driver2 =3D server.driverMap[folder2]; +- // no sources +- expect(_getUserSources(driver1), isEmpty); +- expect(_getUserSources(driver2), isEmpty); +- // add an overlay - new Source in context1 +- server.updateContent('1', {filePath: new AddContentOverlay('')}); +- { +- List paths =3D _getUserSources(driver1); +- expect(paths, hasLength(1)); +- expect(paths[0], filePath); +- } +- expect(_getUserSources(driver2), isEmpty); +- // remove the overlay - no sources +- server.updateContent('2', {filePath: new RemoveContentOverlay()}); +- // The file isn't removed from the list of added sources. +-// expect(_getUserSources(driver1), isEmpty); +- expect(_getUserSources(driver2), isEmpty); +- } +- +- @failingTest +- test_sendNoticesAfterNopChange() async { +- // The errors are empty on the last line. +- createProject(); +- addTestFile(''); +- await server.onAnalysisComplete; +- // add an overlay +- server.updateContent( +- '1', {testFile: new AddContentOverlay('main() {} main() {}')}); +- await server.onAnalysisComplete; +- // clear errors and make a no-op change +- filesErrors.clear(); +- server.updateContent('2', { +- testFile: new ChangeContentOverlay([new SourceEdit(0, 4, 'main')]) +- }); +- await server.onAnalysisComplete; +- // errors should have been resent +- expect(filesErrors, isNotEmpty); +- } +- +- @failingTest +- test_sendNoticesAfterNopChange_flushedUnit() async { +- // The list of errors is empty on the last line. +- createProject(); +- addTestFile(''); +- await server.onAnalysisComplete; +- // add an overlay +- server.updateContent( +- '1', {testFile: new AddContentOverlay('main() {} main() {}')}); +- await server.onAnalysisComplete; +- // clear errors and make a no-op change +- filesErrors.clear(); +- server.updateContent('2', { +- testFile: new ChangeContentOverlay([new SourceEdit(0, 4, 'main')]) +- }); +- await server.onAnalysisComplete; +- // errors should have been resent +- expect(filesErrors, isNotEmpty); +- } +- +- test_sentToPlugins() { +- String filePath =3D '/project/target.dart'; +- String fileContent =3D 'import "none.dart";'; +- // +- // Add +- // +- handleSuccessfulRequest(new AnalysisUpdateContentParams( +- {filePath: new AddContentOverlay(fileContent= )}) +- .toRequest('0')); +- plugin.AnalysisUpdateContentParams params =3D +- pluginManager.analysisUpdateContentParams; +- expect(params, isNotNull); +- Map files =3D params.files; +- expect(files, hasLength(1)); +- Object overlay =3D files[filePath]; +- expect(overlay, new isInstanceOf()); +- plugin.AddContentOverlay addOverlay =3D overlay; +- expect(addOverlay.content, fileContent); +- // +- // Change +- // +- pluginManager.analysisUpdateContentParams =3D null; +- handleSuccessfulRequest(new AnalysisUpdateContentParams({ +- filePath: new ChangeContentOverlay( +- [new SourceEdit(8, 1, "'"), new SourceEdit(18, 1, "= '")]) +- }).toRequest('1')); +- params =3D pluginManager.analysisUpdateContentParams; +- expect(params, isNotNull); +- files =3D params.files; +- expect(files, hasLength(1)); +- overlay =3D files[filePath]; +- expect(overlay, new isInstanceOf()); +- plugin.ChangeContentOverlay changeOverlay =3D overlay; +- expect(changeOverlay.edits, hasLength(2)); +- // +- // Remove +- // +- pluginManager.analysisUpdateContentParams =3D null; +- handleSuccessfulRequest(new AnalysisUpdateContentParams( +- {filePath: new RemoveContentOverlay()}) +- .toRequest('2')); +- params =3D pluginManager.analysisUpdateContentParams; +- expect(params, isNotNull); +- files =3D params.files; +- expect(files, hasLength(1)); +- overlay =3D files[filePath]; +- expect(overlay, new isInstanceOf()); +- } +- +-// CompilationUnit _getTestUnit() { +-// ContextSourcePair pair =3D server.getContextSourcePair(testFile); +-// AnalysisContext context =3D pair.context; +-// Source source =3D pair.source; +-// return context.getResolvedCompilationUnit2(source, source); +-// } +- +- List _getUserSources(AnalysisDriver driver) { +- List sources =3D []; +- driver.addedFiles.forEach((path) { +- if (path.startsWith('/User/')) { +- sources.add(path); +- } +- }); +- return sources; +- } +-} +diff --git a/pkg/analysis_server/test/analysis_abstract.dart b/pkg/analysi= s_server/test/analysis_abstract.dart +deleted file mode 100644 +index 2546cd894e3..00000000000 +--- a/pkg/analysis_server/test/analysis_abstract.dart ++++ /dev/null +@@ -1,367 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart' +- hide AnalysisOptions; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analyzer/context/context_root.dart' as analyzer; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart' as p= lugin; +-import 'package:plugin/manager.dart'; +-import 'package:test/test.dart'; +-import 'package:watcher/watcher.dart'; +- +-import 'mock_sdk.dart'; +-import 'mocks.dart'; +- +-int findIdentifierLength(String search) { +- int length =3D 0; +- while (length < search.length) { +- int c =3D search.codeUnitAt(length); +- if (!(c >=3D 'a'.codeUnitAt(0) && c <=3D 'z'.codeUnitAt(0) || +- c >=3D 'A'.codeUnitAt(0) && c <=3D 'Z'.codeUnitAt(0) || +- c >=3D '0'.codeUnitAt(0) && c <=3D '9'.codeUnitAt(0) || +- c =3D=3D '_'.codeUnitAt(0))) { +- break; +- } +- length++; +- } +- return length; +-} +- +-/** +- * An abstract base for all 'analysis' domain tests. +- */ +-class AbstractAnalysisTest { +- bool generateSummaryFiles =3D false; +- MockServerChannel serverChannel; +- MemoryResourceProvider resourceProvider; +- MockPackageMapProvider packageMapProvider; +- TestPluginManager pluginManager; +- AnalysisServer server; +- RequestHandler handler; +- +- final List serverErrors =3D []; +- final List generalServices =3D +- []; +- final Map> analysisSubscriptions =3D {}; +- +- String projectPath; +- String testFolder; +- String testFile; +- String testCode; +- +- AbstractAnalysisTest(); +- +- AnalysisDomainHandler get analysisHandler =3D> server.handlers +- .singleWhere((handler) =3D> handler is AnalysisDomainHandler); +- +- AnalysisOptions get analysisOptions =3D> testDiver.analysisOptions; +- +- AnalysisDriver get testDiver =3D> server.getAnalysisDriver(testFile); +- +- void addAnalysisSubscription(AnalysisService service, String file) { +- // add file to subscription +- var files =3D analysisSubscriptions[service]; +- if (files =3D=3D null) { +- files =3D []; +- analysisSubscriptions[service] =3D files; +- } +- files.add(file); +- // set subscriptions +- Request request =3D new AnalysisSetSubscriptionsParams(analysisSubscr= iptions) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- } +- +- String addFile(String path, String content) { +- path =3D resourceProvider.convertPath(path); +- resourceProvider.newFile(path, content); +- return path; +- } +- +- void addGeneralAnalysisSubscription(GeneralAnalysisService service) { +- generalServices.add(service); +- Request request =3D new AnalysisSetGeneralSubscriptionsParams(general= Services) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- } +- +- String addTestFile(String content) { +- addFile(testFile, content); +- this.testCode =3D content; +- return testFile; +- } +- +- AnalysisServer createAnalysisServer() { +- // +- // Process plugins +- // +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- // +- // Create an SDK in the mock file system. +- // +- new MockSdk( +- generateSummaryFiles: generateSummaryFiles, +- resourceProvider: resourceProvider); +- // +- // Create server +- // +- AnalysisServerOptions options =3D new AnalysisServerOptions(); +- return new AnalysisServer( +- serverChannel, +- resourceProvider, +- packageMapProvider, +- options, +- new DartSdkManager(resourceProvider.convertPath('/'), true), +- InstrumentationService.NULL_SERVICE); +- } +- +- /** +- * Creates a project `/project`. +- */ +- void createProject({Map packageRoots}) { +- resourceProvider.newFolder(projectPath); +- Request request =3D new AnalysisSetAnalysisRootsParams([projectPath],= [], +- packageRoots: packageRoots) +- .toRequest('0'); +- handleSuccessfulRequest(request, handler: analysisHandler); +- } +- +- /** +- * Returns the offset of [search] in [testCode]. +- * Fails if not found. +- */ +- int findFileOffset(String path, String search) { +- File file =3D resourceProvider.getResource(path) as File; +- String code =3D file.createSource().contents.data; +- int offset =3D code.indexOf(search); +- expect(offset, isNot(-1), reason: '"$search" in\n$code'); +- return offset; +- } +- +- /** +- * Returns the offset of [search] in [testCode]. +- * Fails if not found. +- */ +- int findOffset(String search) { +- int offset =3D testCode.indexOf(search); +- expect(offset, isNot(-1)); +- return offset; +- } +- +- /** +- * Validates that the given [request] is handled successfully. +- */ +- Response handleSuccessfulRequest(Request request, {RequestHandler handl= er}) { +- handler ??=3D this.handler; +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess(request.id)); +- return response; +- } +- +- String modifyTestFile(String content) { +- String path =3D resourceProvider.convertPath(testFile); +- resourceProvider.updateFile(path, content); +- this.testCode =3D content; +- return testFile; +- } +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D SERVER_NOTIFICATION_ERROR) { +- var params =3D new ServerErrorParams.fromNotification(notification); +- serverErrors.add(params); +- } +- } +- +- void removeGeneralAnalysisSubscription(GeneralAnalysisService service) { +- generalServices.remove(service); +- Request request =3D new AnalysisSetGeneralSubscriptionsParams(general= Services) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- } +- +- void setPriorityFiles(List files) { +- var request =3D new AnalysisSetPriorityFilesParams(files).toRequest('= 0'); +- handleSuccessfulRequest(request); +- } +- +- void setUp() { +- serverChannel =3D new MockServerChannel(); +- resourceProvider =3D new MemoryResourceProvider(); +- projectPath =3D resourceProvider.convertPath('/project'); +- testFolder =3D resourceProvider.convertPath('/project/bin'); +- testFile =3D resourceProvider.convertPath('/project/bin/test.dart'); +- packageMapProvider =3D new MockPackageMapProvider(); +- pluginManager =3D new TestPluginManager(); +- server =3D createAnalysisServer(); +- server.pluginManager =3D pluginManager; +- handler =3D analysisHandler; +- // listen for notifications +- Stream notificationStream =3D +- serverChannel.notificationController.stream; +- notificationStream.listen((Notification notification) { +- processNotification(notification); +- }); +- } +- +- void tearDown() { +- server.done(); +- handler =3D null; +- server =3D null; +- resourceProvider =3D null; +- serverChannel =3D null; +- } +- +- /** +- * Returns a [Future] that completes when the server's analysis is comp= lete. +- */ +- Future waitForTasksFinished() { +- return server.onAnalysisComplete; +- } +- +- /** +- * Completes with a successful [Response] for the given [request]. +- * Otherwise fails. +- */ +- Future waitResponse(Request request) async { +- return serverChannel.sendRequest(request); +- } +-} +- +-/** +- * A plugin manager that simulates broadcasting requests to plugins by +- * hard-coding the responses. +- */ +-class TestPluginManager implements PluginManager { +- plugin.AnalysisSetPriorityFilesParams analysisSetPriorityFilesParams; +- plugin.AnalysisSetSubscriptionsParams analysisSetSubscriptionsParams; +- plugin.AnalysisUpdateContentParams analysisUpdateContentParams; +- plugin.RequestParams broadcastedRequest; +- Map> broadcastResults; +- +- @override +- String get byteStorePath { +- fail('Unexpected invocation of byteStorePath'); +- return null; +- } +- +- @override +- InstrumentationService get instrumentationService { +- fail('Unexpected invocation of instrumentationService'); +- return null; +- } +- +- @override +- NotificationManager get notificationManager { +- fail('Unexpected invocation of notificationManager'); +- return null; +- } +- +- @override +- List get plugins { +- fail('Unexpected invocation of plugins'); +- return null; +- } +- +- @override +- ResourceProvider get resourceProvider { +- fail('Unexpected invocation of resourceProvider'); +- return null; +- } +- +- @override +- String get sdkPath { +- fail('Unexpected invocation of sdkPath'); +- return null; +- } +- +- @override +- Future addPluginToContextRoot( +- analyzer.ContextRoot contextRoot, String path) async { +- fail('Unexpected invocation of addPluginToContextRoot'); +- return null; +- } +- +- @override +- Map> broadcastRequest( +- plugin.RequestParams params, +- {analyzer.ContextRoot contextRoot}) { +- broadcastedRequest =3D params; +- return broadcastResults ?? >{}; +- } +- +- @override +- Future>> broadcastWatchEvent( +- WatchEvent watchEvent) async { +- return >[]; +- } +- +- @override +- List pathsFor(String pluginPath) { +- fail('Unexpected invocation of pathsFor'); +- return null; +- } +- +- @override +- List pluginsForContextRoot(analyzer.ContextRoot contextRoot= ) { +- fail('Unexpected invocation of pluginsForContextRoot'); +- return null; +- } +- +- @override +- void recordPluginFailure(String hostPackageName, String message) { +- fail('Unexpected invocation of recordPluginFailure'); +- } +- +- @override +- void removedContextRoot(analyzer.ContextRoot contextRoot) { +- fail('Unexpected invocation of removedContextRoot'); +- } +- +- @override +- Future restartPlugins() async { +- // Nothing to restart. +- return null; +- } +- +- @override +- void setAnalysisSetPriorityFilesParams( +- plugin.AnalysisSetPriorityFilesParams params) { +- analysisSetPriorityFilesParams =3D params; +- } +- +- @override +- void setAnalysisSetSubscriptionsParams( +- plugin.AnalysisSetSubscriptionsParams params) { +- analysisSetSubscriptionsParams =3D params; +- } +- +- @override +- void setAnalysisUpdateContentParams( +- plugin.AnalysisUpdateContentParams params) { +- analysisUpdateContentParams =3D params; +- } +- +- @override +- Future> stopAll() async { +- fail('Unexpected invocation of stopAll'); +- return null; +- } +-} +diff --git a/pkg/analysis_server/test/analysis_server_test.dart b/pkg/anal= ysis_server/test/analysis_server_test.dart +deleted file mode 100644 +index 31c8a50253e..00000000000 +--- a/pkg/analysis_server/test/analysis_server_test.dart ++++ /dev/null +@@ -1,210 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/domain_server.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:plugin/manager.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'mock_sdk.dart'; +-import 'mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisServerTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisServerTest { +- MockServerChannel channel; +- AnalysisServer server; +- MemoryResourceProvider resourceProvider; +- MockPackageMapProvider packageMapProvider; +- +- /** +- * Test that having multiple analysis contexts analyze the same file do= esn't +- * cause that file to receive duplicate notifications when it's modifie= d. +- */ +- Future do_not_test_no_duplicate_notifications() async { +- // Subscribe to STATUS so we'll know when analysis is done. +- server.serverServices =3D [ServerService.STATUS].toSet(); +- resourceProvider.newFolder('/foo'); +- resourceProvider.newFolder('/bar'); +- resourceProvider.newFile('/foo/foo.dart', 'import "../bar/bar.dart";'= ); +- File bar =3D resourceProvider.newFile('/bar/bar.dart', 'library bar;'= ); +- server.setAnalysisRoots('0', ['/foo', '/bar'], [], {}); +- Map> subscriptions =3D +- >{}; +- for (AnalysisService service in AnalysisService.VALUES) { +- subscriptions[service] =3D [bar.path].toSet(); +- } +- // The following line causes the isolate to continue running even tho= ugh the +- // test completes. +- server.setAnalysisSubscriptions(subscriptions); +- await server.onAnalysisComplete; +- expect(server.statusAnalyzing, isFalse); +- channel.notificationsReceived.clear(); +- server.updateContent( +- '0', {bar.path: new AddContentOverlay('library bar; void f() {}')= }); +- await server.onAnalysisComplete; +- expect(server.statusAnalyzing, isFalse); +- expect(channel.notificationsReceived, isNotEmpty); +- Set notificationTypesReceived =3D new Set(); +- for (Notification notification in channel.notificationsReceived) { +- String notificationType =3D notification.event; +- switch (notificationType) { +- case 'server.status': +- case 'analysis.errors': +- // It's normal for these notifications to be sent multiple time= s. +- break; +- case 'analysis.outline': +- // It's normal for this notification to be sent twice. +- // TODO(paulberry): why? +- break; +- default: +- if (!notificationTypesReceived.add(notificationType)) { +- fail('Notification type $notificationType received more than = once'); +- } +- break; +- } +- } +- } +- +- void processRequiredPlugins() { +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- } +- +- void setUp() { +- processRequiredPlugins(); +- channel =3D new MockServerChannel(); +- resourceProvider =3D new MemoryResourceProvider(); +- // Create an SDK in the mock file system. +- new MockSdk(resourceProvider: resourceProvider); +- packageMapProvider =3D new MockPackageMapProvider(); +- server =3D new AnalysisServer( +- channel, +- resourceProvider, +- packageMapProvider, +- new AnalysisServerOptions(), +- new DartSdkManager('/', false), +- InstrumentationService.NULL_SERVICE); +- } +- +- Future test_echo() { +- server.handlers =3D [new EchoHandler()]; +- var request =3D new Request('my22', 'echo'); +- return channel.sendRequest(request).then((Response response) { +- expect(response.id, equals('my22')); +- expect(response.error, isNull); +- }); +- } +- +- Future test_serverStatusNotifications() { +- server.serverServices.add(ServerService.STATUS); +- resourceProvider.newFolder('/pkg'); +- resourceProvider.newFolder('/pkg/lib'); +- resourceProvider.newFile('/pkg/lib/test.dart', 'class C {}'); +- server.setAnalysisRoots('0', ['/pkg'], [], {}); +- // Pump the event queue to make sure the server has finished any +- // analysis. +- return pumpEventQueue().then((_) { +- List notifications =3D channel.notificationsReceived; +- expect(notifications, isNotEmpty); +- // expect at least one notification indicating analysis is in progr= ess +- expect(notifications.any((Notification notification) { +- if (notification.event =3D=3D SERVER_NOTIFICATION_STATUS) { +- var params =3D new ServerStatusParams.fromNotification(notifica= tion); +- if (params.analysis !=3D null) { +- return params.analysis.isAnalyzing; +- } +- } +- return false; +- }), isTrue); +- // the last notification should indicate that analysis is complete +- Notification notification =3D notifications[notifications.length - = 1]; +- var params =3D new ServerStatusParams.fromNotification(notification= ); +- expect(params.analysis.isAnalyzing, isFalse); +- }); +- } +- +- test_setAnalysisSubscriptions_fileInIgnoredFolder_newOptions() async { +- String path =3D '/project/samples/sample.dart'; +- resourceProvider.newFile(path, ''); +- resourceProvider.newFile('/project/analysis_options.yaml', r''' +-analyzer: +- exclude: +- - 'samples/**' +-'''); +- server.setAnalysisRoots('0', ['/project'], [], {}); +- server.setAnalysisSubscriptions(>{ +- AnalysisService.NAVIGATION: new Set.from([path]) +- }); +- // the file is excluded, so no navigation notification +- await server.onAnalysisComplete; +- expect(channel.notificationsReceived.any((notification) { +- return notification.event =3D=3D ANALYSIS_NOTIFICATION_NAVIGATION; +- }), isFalse); +- } +- +- test_setAnalysisSubscriptions_fileInIgnoredFolder_oldOptions() async { +- String path =3D '/project/samples/sample.dart'; +- resourceProvider.newFile(path, ''); +- resourceProvider.newFile('/project/.analysis_options', r''' +-analyzer: +- exclude: +- - 'samples/**' +-'''); +- server.setAnalysisRoots('0', ['/project'], [], {}); +- server.setAnalysisSubscriptions(>{ +- AnalysisService.NAVIGATION: new Set.from([path]) +- }); +- // the file is excluded, so no navigation notification +- await server.onAnalysisComplete; +- expect(channel.notificationsReceived.any((notification) { +- return notification.event =3D=3D ANALYSIS_NOTIFICATION_NAVIGATION; +- }), isFalse); +- } +- +- Future test_shutdown() { +- server.handlers =3D [new ServerDomainHandler(server)]; +- var request =3D new Request('my28', SERVER_REQUEST_SHUTDOWN); +- return channel.sendRequest(request).then((Response response) { +- expect(response.id, equals('my28')); +- expect(response.error, isNull); +- }); +- } +- +- Future test_unknownRequest() { +- server.handlers =3D [new EchoHandler()]; +- var request =3D new Request('my22', 'randomRequest'); +- return channel.sendRequest(request).then((Response response) { +- expect(response.id, equals('my22')); +- expect(response.error, isNotNull); +- }); +- } +-} +- +-class EchoHandler implements RequestHandler { +- @override +- Response handleRequest(Request request) { +- if (request.method =3D=3D 'echo') { +- return new Response(request.id, result: {'echo': true}); +- } +- return null; +- } +-} +diff --git a/pkg/analysis_server/test/benchmarks_test.dart b/pkg/analysis_= server/test/benchmarks_test.dart +deleted file mode 100644 +index 4cd4a46426a..00000000000 +--- a/pkg/analysis_server/test/benchmarks_test.dart ++++ /dev/null +@@ -1,76 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file.=3D> defineTes= ts(); +- +-/// This tests the benchmarks in benchmark/benchmark.test, and ensures th= at our +-/// benchmarks can run. +- +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +- +-void main() =3D> defineTests(); +- +-void defineTests() { +- group('benchmarks', () { +- final List benchmarks =3D _listBenchmarks(); +- +- test('can list', () { +- expect(benchmarks, isNotEmpty); +- }); +- +- for (String benchmarkId in benchmarks) { +- test(benchmarkId, () { +- ProcessResult r =3D Process.runSync( +- Platform.resolvedExecutable, +- [ +- path.join('benchmark', 'benchmarks.dart'), +- 'run', +- '--repeat=3D1', +- '--quick', +- benchmarkId +- ], +- workingDirectory: _serverSourcePath, +- ); +- expect(r.exitCode, 0, +- reason: 'exit: ${r.exitCode}\n${r.stdout}\n${r.stderr}'); +- }); +- +- test('$benchmarkId-preview-dart-2', () { +- ProcessResult r =3D Process.runSync( +- Platform.resolvedExecutable, +- [ +- path.join('benchmark', 'benchmarks.dart'), +- 'run', +- '--repeat=3D1', +- '--quick', +- '--preview-dart-2', +- benchmarkId +- ], +- workingDirectory: _serverSourcePath, +- ); +- expect(r.exitCode, 0, +- reason: 'exit: ${r.exitCode}\n${r.stdout}\n${r.stderr}'); +- }); +- } +- }); +-} +- +-List _listBenchmarks() { +- ProcessResult result =3D Process.runSync( +- Platform.resolvedExecutable, +- [path.join('benchmark', 'benchmarks.dart'), 'list', '--machine'], +- workingDirectory: _serverSourcePath, +- ); +- Map m =3D JSON.decode(result.stdout); +- List benchmarks =3D m['benchmarks']; +- return benchmarks.map((b) =3D> b['id']).toList(); +-} +- +-String get _serverSourcePath { +- String script =3D Platform.script.toFilePath(windows: Platform.isWindow= s); +- String pkgPath =3D path.normalize(path.join(path.dirname(script), '..',= '..')); +- return path.join(pkgPath, 'analysis_server'); +-} +diff --git a/pkg/analysis_server/test/channel/byte_stream_channel_test.dar= t b/pkg/analysis_server/test/channel/byte_stream_channel_test.dart +deleted file mode 100644 +index 4395c7ab08d..00000000000 +--- a/pkg/analysis_server/test/channel/byte_stream_channel_test.dart ++++ /dev/null +@@ -1,272 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/src/channel/byte_stream_channel.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:mockito/mockito.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ByteStreamClientChannelTest); +- defineReflectiveTests(ByteStreamServerChannelTest); +- }); +-} +- +-@reflectiveTest +-class ByteStreamClientChannelTest { +- ByteStreamClientChannel channel; +- +- /** +- * Sink that may be used to deliver data to the channel, as though it's +- * coming from the server. +- */ +- IOSink inputSink; +- +- /** +- * Sink through which the channel delivers data to the server. +- */ +- IOSink outputSink; +- +- /** +- * Stream of lines sent back to the client by the channel. +- */ +- Stream outputLineStream; +- +- void setUp() { +- var inputStream =3D new StreamController>(); +- inputSink =3D new IOSink(inputStream); +- var outputStream =3D new StreamController>(); +- outputLineStream =3D outputStream.stream +- .transform((new Utf8Codec()).decoder) +- .transform(new LineSplitter()); +- outputSink =3D new IOSink(outputStream); +- channel =3D new ByteStreamClientChannel(inputStream.stream, outputSin= k); +- } +- +- test_close() { +- bool doneCalled =3D false; +- bool closeCalled =3D false; +- // add listener so that outputSink will trigger done/close futures +- outputLineStream.listen((_) {/* no-op */}); +- outputSink.done.then((_) { +- doneCalled =3D true; +- }); +- channel.close().then((_) { +- closeCalled =3D true; +- }); +- return pumpEventQueue().then((_) { +- expect(doneCalled, isTrue); +- expect(closeCalled, isTrue); +- }); +- } +- +- test_listen_notification() { +- List notifications =3D []; +- channel.notificationStream.forEach((n) =3D> notifications.add(n)); +- inputSink.writeln('{"event":"server.connected"}'); +- return pumpEventQueue().then((_) { +- expect(notifications.length, equals(1)); +- expect(notifications[0].event, equals('server.connected')); +- }); +- } +- +- test_listen_response() { +- List responses =3D []; +- channel.responseStream.forEach((n) =3D> responses.add(n)); +- inputSink.writeln('{"id":"72"}'); +- return pumpEventQueue().then((_) { +- expect(responses.length, equals(1)); +- expect(responses[0].id, equals('72')); +- }); +- } +- +- test_sendRequest() { +- int assertCount =3D 0; +- Request request =3D new Request('72', 'foo.bar'); +- outputLineStream.first.then((line) =3D> JSON.decode(line)).then((json= ) { +- expect(json[Request.ID], equals('72')); +- expect(json[Request.METHOD], equals('foo.bar')); +- inputSink.writeln('{"id":"73"}'); +- inputSink.writeln('{"id":"72"}'); +- assertCount++; +- }); +- channel.sendRequest(request).then((Response response) { +- expect(response.id, equals('72')); +- assertCount++; +- }); +- return pumpEventQueue().then((_) =3D> expect(assertCount, equals(2))); +- } +-} +- +-@reflectiveTest +-class ByteStreamServerChannelTest { +- ByteStreamServerChannel channel; +- +- /** +- * Sink that may be used to deliver data to the channel, as though it's +- * coming from the client. +- */ +- IOSink inputSink; +- +- /** +- * Stream of lines sent back to the client by the channel. +- */ +- Stream outputLineStream; +- +- /** +- * Stream of requests received from the channel via [listen()]. +- */ +- Stream requestStream; +- +- /** +- * Stream of errors received from the channel via [listen()]. +- */ +- Stream errorStream; +- +- /** +- * Future which is completed when then [listen()] reports [onDone]. +- */ +- Future doneFuture; +- +- void setUp() { +- StreamController> inputStream =3D new StreamController>(); +- inputSink =3D new IOSink(inputStream); +- StreamController> outputStream =3D +- new StreamController>(); +- outputLineStream =3D outputStream.stream +- .transform((new Utf8Codec()).decoder) +- .transform(new LineSplitter()); +- IOSink outputSink =3D new IOSink(outputStream); +- channel =3D new ByteStreamServerChannel( +- inputStream.stream, outputSink, InstrumentationService.NULL_SERVI= CE); +- StreamController requestStreamController =3D +- new StreamController(); +- requestStream =3D requestStreamController.stream; +- StreamController errorStreamController =3D new StreamController(); +- errorStream =3D errorStreamController.stream; +- Completer doneCompleter =3D new Completer(); +- doneFuture =3D doneCompleter.future; +- channel.listen((Request request) { +- requestStreamController.add(request); +- }, onError: (error) { +- errorStreamController.add(error); +- }, onDone: () { +- doneCompleter.complete(); +- }); +- } +- +- test_closed() { +- return inputSink +- .close() +- .then((_) =3D> channel.closed.timeout(new Duration(seconds: 1))); +- } +- +- test_listen_invalidJson() { +- inputSink.writeln('{"id":'); +- return inputSink +- .flush() +- .then((_) =3D> outputLineStream.first.timeout(new Duration(second= s: 1))) +- .then((String response) { +- var jsonResponse =3D new JsonCodec().decode(response); +- expect(jsonResponse, isMap); +- expect(jsonResponse, contains('error')); +- expect(jsonResponse['error'], isNotNull); +- }); +- } +- +- test_listen_invalidRequest() { +- inputSink.writeln('{"id":"0"}'); +- return inputSink +- .flush() +- .then((_) =3D> outputLineStream.first.timeout(new Duration(second= s: 1))) +- .then((String response) { +- var jsonResponse =3D new JsonCodec().decode(response); +- expect(jsonResponse, isMap); +- expect(jsonResponse, contains('error')); +- expect(jsonResponse['error'], isNotNull); +- }); +- } +- +- test_listen_streamDone() { +- return inputSink +- .close() +- .then((_) =3D> doneFuture.timeout(new Duration(seconds: 1))); +- } +- +- test_listen_streamError() { +- var error =3D new Error(); +- inputSink.addError(error); +- return inputSink +- .flush() +- .then((_) =3D> errorStream.first.timeout(new Duration(seconds: 1)= )) +- .then((var receivedError) { +- expect(receivedError, same(error)); +- }); +- } +- +- test_listen_wellFormedRequest() { +- inputSink.writeln('{"id":"0","method":"server.version"}'); +- return inputSink +- .flush() +- .then((_) =3D> requestStream.first.timeout(new Duration(seconds: = 1))) +- .then((Request request) { +- expect(request.id, equals("0")); +- expect(request.method, equals("server.version")); +- }); +- } +- +- test_sendNotification() { +- channel.sendNotification(new Notification('foo')); +- return outputLineStream.first +- .timeout(new Duration(seconds: 1)) +- .then((String notification) { +- var jsonNotification =3D new JsonCodec().decode(notification); +- expect(jsonNotification, isMap); +- expect(jsonNotification, contains('event')); +- expect(jsonNotification['event'], equals('foo')); +- }); +- } +- +- test_sendNotification_exceptionInSink() async { +- // This IOSink asynchronously throws an exception on any writeln(). +- var outputSink =3D new _IOSinkMock(); +- when(outputSink.writeln(any)).thenAnswer((answer) { +- new Timer(new Duration(milliseconds: 10), () { +- throw '42'; +- }); +- }); +- +- var channel =3D new ByteStreamServerChannel( +- null, outputSink, InstrumentationService.NULL_SERVICE); +- +- // Attempt to send a notification. +- channel.sendNotification(new Notification('foo')); +- +- // An exception was thrown, it did not leak, but the channel was clos= ed. +- await channel.closed; +- } +- +- test_sendResponse() { +- channel.sendResponse(new Response('foo')); +- return outputLineStream.first +- .timeout(new Duration(seconds: 1)) +- .then((String response) { +- var jsonResponse =3D new JsonCodec().decode(response); +- expect(jsonResponse, isMap); +- expect(jsonResponse, contains('id')); +- expect(jsonResponse['id'], equals('foo')); +- }); +- } +-} +- +-class _IOSinkMock extends Mock implements IOSink {} +diff --git a/pkg/analysis_server/test/channel/test_all.dart b/pkg/analysis= _server/test/channel/test_all.dart +deleted file mode 100644 +index ce5e85a3ace..00000000000 +--- a/pkg/analysis_server/test/channel/test_all.dart ++++ /dev/null +@@ -1,16 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test/test.dart'; +- +-import 'byte_stream_channel_test.dart' as byte_stream_channel_test; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- group('computer', () { +- byte_stream_channel_test.main(); +- }); +-} +diff --git a/pkg/analysis_server/test/completion_test.dart b/pkg/analysis_= server/test/completion_test.dart +deleted file mode 100644 +index e6201b5ce65..00000000000 +--- a/pkg/analysis_server/test/completion_test.dart ++++ /dev/null +@@ -1,2517 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:test/test.dart'; +- +-import 'completion_test_support.dart'; +- +-main() { +- CompletionTestBuilder builder =3D new CompletionTestBuilder(); +- builder.buildAll(); +-} +- +-/** +- * A builder that builds the completion tests. +- */ +-class CompletionTestBuilder { +- /** +- * Number of tests that have been built that are expected to pass. +- */ +- int expectedPassCount =3D 0; +- +- /** +- * Number of tests that have been built that are expected to fail. +- */ +- int expectedFailCount =3D 0; +- +- void buildAll() { +- buildNumberedTests(); +- buildCommentSnippetTests(); +- buildCompletionTests(); +- buildOtherTests(); +- buildLibraryTests(); +- int testCount =3D expectedPassCount + expectedFailCount; +- print( +- 'Total $testCount tests, of which $expectedFailCount are expected= to fail.'); +- } +- +- void buildCommentSnippetTests() { +- buildTests('testCommentSnippets001', ''' +-class X {static final num MAX =3D 0;num yc,xc;mth() {xc =3D yc =3D MA!1X;= x!2c.abs();num f =3D M!3AX;}}''', +- ["1+MAX", "2+xc", "3+MAX"]); +- +- buildTests('testCommentSnippets002', ''' +-class Y {String x=3D'hi';mth() {x.l!1ength;int n =3D 0;x!2.codeUnitAt(n!3= );}}''', +- ["1+length", "2+x", "3+n"]); +- +- buildTests('testCommentSnippets004', ''' +-class A {!1int x; !2mth() {!3int y =3D this.!5x!6;}}class B{}''', +- ["1+A", "2+B", "3+x", "3-y", "5+mth", "6+x"]); +- +- buildTests('testCommentSnippets005', ''' +-class Date { static Date JUN, JUL;}class X { m() { return Da!1te.JU!2L; }= }''', +- ["1+Date", "2+JUN", "2+JUL"]); +- +- buildTests('testCommentSnippets007', ''' +-class C {mth(Map x, !1) {}mtf(!2, Map x) {}m() {for (in!3t i=3D0; i<5; i+= +); A!4 x;}}class int{}class Arrays{}''', +- ["1+bool", "2+bool", "3+int", "4+Arrays"]); +- +- buildTests('testCommentSnippets008', ''' +-class Date{}final num M =3D Dat!1''', ["1+Date"]); +- +- // space, char, eol are important +- buildTests( +- 'testCommentSnippets009', +- ''' +-class Maps{}class x extends!5 !2M!3 !4implements!6 !1\n{}''', +- [ +- "1+Map", +- "2+Maps", +- "3+Maps", +- "4-Maps", +- "4+implements", +- "5-Maps", +- "6-Map", +- "6+implements" +- ], +- failingTests: '46'); +- +- // space, char, eol are important +- buildTests('testCommentSnippets010', ''' +-class x implements !1{}''', ["1+Map"]); +- +- // space, char, eol are important +- buildTests('testCommentSnippets011', ''' +-class x implements M!1{}''', ["1+Map"]); +- +- // space, char, eol are important +- buildTests('testCommentSnippets012', ''' +-class x implements M!1\n{}''', ["1+Map"]); +- +- buildTests('testCommentSnippets013', ''' +-class x !2{!1}!3''', ["1+num", "2-num", "3+num"]); +- +- // trailing space is important +- buildTests('testCommentSnippets014', ''' +-typedef n!1 ;''', ["1+num"]); +- +- buildTests('testCommentSnippets015', ''' +-class D {f(){} g(){f!1(f!2);}}''', ["1+f", "2+f"]); +- +- buildTests('testCommentSnippets016', ''' +-class F {m() { m(); !1}}''', ["1+m"]); +- +- buildTests('testCommentSnippets017', ''' +-class F {var x =3D !1false;}''', ["1+true"]); +- +- buildTests('testCommentSnippets018', ''' +-class Map{}class Arrays{}class C{ m(!1){} n(!2 x, q)''', +- ["1+Map", "1-void", "1-null", "2+Arrays", "2-void", "2-nu= ll"]); +- +- buildTests('testCommentSnippets019', ''' +-class A{m(){Object x;x.!1/**/clear()''', ["1+toString"]); +- +- buildTests('testCommentSnippets020', ''' +-classMap{}class tst {var newt;void newf(){}test() {var newz;new!1/**/;}}'= '', +- ["1+newt", "1+newf", "1+newz", "1-Map"]); +- +- buildTests('testCommentSnippets021', ''' +-class Map{}class tst {var newt;void newf(){}test() {var newz;new !1/**/;}= }''', +- ["1+Map", "1-newt"]); +- +- buildTests('testCommentSnippets022', ''' +-class Map{}class F{m(){new !1;}}''', ["1+Map"]); +- +- buildTests('testCommentSnippets022a', ''' +-class Map{}class F{m(){new !1''', ["1+Map"]); +- +- buildTests('testCommentSnippets022b', ''' +-class Map{factory Map.qq(){return null;}}class F{m(){new Map.!1qq();}}''', +- ["1+qq"]); +- +- buildTests('testCommentSnippets023', ''' +-class X {X c; X(this.!1c!3) : super() {c.!2}}''', +- ["1+c", "2+c", "3+c"]); +- +- buildTests('testCommentSnippets024', ''' +-class q {m(Map q){var x;m(!1)}n(){var x;n(!2)}}''', ["1+x", "2+x"= ]); +- +- buildTests('testCommentSnippets025', ''' +-class q {num m() {var q; num x=3D!1 q!3 + !2/**/;}}''', +- ["1+q", "2+q", "3+q"]); +- +- buildTests('testCommentSnippets026', ''' +-class List{}class a implements !1{}''', ["1+List"]); +- +- buildTests('testCommentSnippets027', ''' +-class String{}class List{}class test {}''', +- ["1+List", "2+String", "2-List"]); +- +- buildTests('testCommentSnippets028', ''' +-class String{}class List{}class DateTime{}typedef T Y(List = input);''', +- ["1+DateTime", "1+String"]); +- +- buildTests('testCommentSnippets029', ''' +-interface A default B {}''', +- ["1+DateTime", "2+List"]); +- +- buildTests( +- 'testCommentSnippets030', +- ''' +-class Bar {const Bar(!1T!2 k);T!3 m(T!4 a, T!5 b){}final T= !6 f =3D null;}''', +- ["1+T", "2+T", "3+T", "4+T", "5+T", "6+T"], +- failingTests: '123456'); +- +- buildTests( +- 'testCommentSnippets031', +- ''' +-class Bar {m(x){if (x is !1) return;if (x is!!!2)}}''', +- ["1+Bar", "1+T", "2+T", "2+Bar"], +- failingTests: '12'); +- +- buildTests( +- 'testCommentSnippets032', +- ''' +-class Fit{}class Bar {const !2F!1ara();}''', +- ["1+Fit", "1+Fara", "1-Bar", "2+Fit"], +- failingTests: '1'); +- +- // Type propagation +- buildTests('testCommentSnippets033', ''' +-class List{add(){}length(){}}t1() {var x;if (x is List) {x.!1add(3);}}''', +- ["1+add", "1+length"]); +- +- // Type propagation +- buildTests('testCommentSnippets035', ''' +-class List{clear(){}length(){}}t3() {var x=3Dnew List(), y=3Dx.!1length()= ;x.!2clear();}''', +- ["1+length", "2+clear"]); +- +- buildTests('testCommentSnippets036', ''' +-class List{}t3() {var x=3Dnew List!1}''', ["1+List"]); +- +- buildTests('testCommentSnippets037', ''' +-class List{factory List.from(){}}t3() {var x=3Dnew List.!1}''', +- ["1+from"]); +- +- buildTests('testCommentSnippets038', ''' +-f(){int xa; String s =3D '\$x!1';}''', ["1+xa"]); +- +- buildTests('testCommentSnippets038a', ''' +-int xa; String s =3D '\$x!1\'''', ["1+xa"]); +- +- buildTests('testCommentSnippets039', ''' +-f(){int xa; String s =3D '\$!1';}''', ["1+xa"]); +- +- buildTests('testCommentSnippets039a', ''' +-int xa; String s =3D '\$!1\'''', ["1+xa"]); +- +- buildTests('testCommentSnippets040', ''' +-class List{add(){}}class Map{}class X{m(){List list; list.!1 Map map;}}''= ', +- ["1+add"]); +- +- buildTests('testCommentSnippets041', ''' +-class List{add(){}length(){}}class X{m(){List list; list.!1 zox();}}''', +- ["1+add"]); +- +- buildTests('testCommentSnippets042', ''' +-class DateTime{static const int WED=3D3;int get day;}fd(){DateTime d=3Dne= w DateTime.now();d.!1WED!2;}''', +- ["1+day", "2-WED"]); +- +- buildTests('testCommentSnippets043', ''' +-class L{var k;void.!1}''', ["1-k"]); +- +- buildTests('testCommentSnippets044', ''' +-class List{}class XXX {XXX.fisk();}main() {main(); new !1}}''', +- ["1+List", "1+XXX.fisk"]); +- +- buildTests('testCommentSnippets047', ''' +-f(){int x;int y=3D!1;}''', ["1+x"]); +- +- buildTests('testCommentSnippets048', ''' +-import 'dart:convert' as json;f() {var x=3Dnew js!1}''', ["1+json= "]); +- +- buildTests('testCommentSnippets049', ''' +-import 'dart:convert' as json; +-import 'dart:convert' as jxx; +-class JsonDecoderX{} +-f1() {var x=3Dnew !2j!1s!3}''', [ +- "1+json", +- "1+jxx", +- "2+json", +- "2+jxx", +- "2-JsonDecoder", +- "3+json", +- "3-jxx" +- ]); +- +- buildTests('testCommentSnippets050', ''' +-class xdr { +- xdr(); +- const xdr.a(a,b,c); +- xdr.b(); +- f() =3D> 3; +-} +-class xa{} +-k() { +- new x!1dr().f(); +- const x!2dr.!3a(1, 2, 3); +-}''', [ +- "1+xdr", +- "1+xa", +- "1+xdr.a", +- "1+xdr.b", +- "2+xa", // suggest default constructor +- "2+xdr", // suggest normal constructor +- "2+xdr.a", +- "2+xdr.b", // suggest named constructor +- "3+b", // suggest named constructor +- "3+a" +- ]); +- +- // Type propagation. +- buildTests('testCommentSnippets051', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void r() { +- var v; +- if (v is String) { +- v.!1length; +- v.!2getKeys; +- } +-}''', ["1+length", "2-getKeys"]); +- +- // Type propagation. +- buildTests('testCommentSnippets052', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void r() { +- List values =3D ['a','b','c']; +- for (var v in values) { +- v.!1toUpperCase; +- v.!2getKeys; +- } +-}''', ["1+toUpperCase", "2-getKeys"]); +- +- // Type propagation. +- buildTests('testCommentSnippets053', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void r() { +- var v; +- while (v is String) { +- v.!1toUpperCase; +- v.!2getKeys; +- } +-}''', ["1+toUpperCase", "2-getKeys"]); +- +- buildTests('testCommentSnippets054', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void r() { +- var v; +- for (; v is String; v.!1isEmpty) { +- v.!2toUpperCase; +- v.!3getKeys; +- } +-}''', ["1+isEmpty", "2+toUpperCase", "3-getKeys"]); +- +- buildTests('testCommentSnippets055', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void r() { +- String v; +- if (v is Object) { +- v.!1toUpperCase; +- } +-}''', ["1+toUpperCase"]); +- +- // Type propagation. +- buildTests('testCommentSnippets056', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void f(var v) { +- if (v is!! String) { +- return; +- } +- v.!1toUpperCase; +-}''', ["1+toUpperCase"]); +- +- // Type propagation. +- buildTests('testCommentSnippets057', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void f(var v) { +- if ((v as String).!2length =3D=3D 0) { +- v.!1toUpperCase; +- } +-}''', ["1+toUpperCase", "2+length"]); +- +- buildTests( +- 'testCommentSnippets058', +- ''' +-typedef vo!2id callback(int k); +-void x(callback q){} +-void r() { +- callback v; +- x(!1); +-}''', +- ["1+v", "2+void"], +- failingTests: '2'); +- +- buildTests('testCommentSnippets059', ''' +-f(){((int x) =3D> x+4).!1call(1);}''', ["1-call"]); +- +- buildTests('testCommentSnippets060', ''' +-class Map{} +-abstract class MM extends Map{factory MM() =3D> new Map();} +-class Z { +- MM x; +- f() { +- x!1 +- } +-}''', ["1+x", "1-x[]"]); +- +- buildTests('testCommentSnippets061', ''' +-class A{m(){!1f(3);!2}}n(){!3f(3);!4}f(x)=3D>x*3;''', +- ["1+f", "1+n", "2+f", "2+n", "3+f", "3+n", "4+f", "4+n"]); +- +- // Type propagation. +- buildTests('testCommentSnippets063', ''' +-class String{int length(){} String toUpperCase(){} bool isEmpty(){}}class= Map{getKeys(){}} +-void r(var v) { +- v.!1toUpperCase; +- assert(v is String); +- v.!2toUpperCase; +-}''', ["1-toUpperCase", "2+toUpperCase"]); +- +- buildTests('testCommentSnippets064', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.!9h()..!1a()..!2b().!7g(); +- x.!8j..!3b()..!4c..!6c..!5a(); +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', [ +- "1+a", +- "2+b", +- "1-g", +- "2-h", +- "3+b", +- "4+c", +- "5+a", +- "6+c", +- "7+g", +- "8+j", +- "9+h" +- ]); +- +- buildTests('testCommentSnippets065', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.h()..!1; +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', ["1+a"]); +- +- buildTests('testCommentSnippets066', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.h()..a()..!1; +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', ["1+b"]); +- +- buildTests('testCommentSnippets067', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.h()..a()..c..!1; +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', ["1+b"]); +- +- buildTests('testCommentSnippets068', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.j..b()..c..!1; +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', ["1+c"]); +- +- buildTests('testCommentSnippets069', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.j..b()..!1; +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', ["1+c"]); +- +- buildTests('testCommentSnippets070', ''' +-class Spline { +- Line c; +- Spline a() { +- return this; +- } +- Line b() { +- return null; +- } +- Spline f() { +- Line x =3D new Line(); +- x.j..!1; +- } +-} +-class Line { +- Spline j; +- Line g() { +- return this; +- } +- Spline h() { +- return null; +- } +-}''', ["1+b"]); +- +- buildTests('testCommentSnippets072', ''' +-class X { +- int _p; +- set p(int x) =3D> _p =3D x; +-} +-f() { +- X x =3D new X(); +- x.!1p =3D 3; +-}''', ["1+p"]); +- +- buildTests('testCommentSnippets073', ''' +-class X { +- m() { +- JSON.stri!1; +- X f =3D null; +- } +-} +-class JSON { +- static stringify() {} +-}''', ["1+stringify"]); +- +- buildTests('testCommentSnippets074', ''' +-class X { +- m() { +- _x!1 +- } +- _x1(){} +-}''', ["1+_x1"]); +- +- buildTests('testCommentSnippets075', ''' +-p(x)=3D>0;var E;f(q)=3D>!1p(!2E);''', ["1+p", "2+E"]); +- +- buildTests('testCommentSnippets076', ''' +-class Map{}class List{}class int{}main() {var m=3Dnew Map>,List>();}''', +- ["1+List", "2+int", "3+int"]); +- +- buildTests('testCommentSnippets076a', ''' +-class Map{}class List{}class int{}main() {var m=3Dnew Map>,List>();}''', +- ["1+List", "2+int", "3+int"]); +- +- buildTests('testCommentSnippets077', ''' +-class FileMode { +- static const READ =3D const FileMode._internal(0); +- static const WRITE =3D const FileMode._internal(1); +- static const APPEND =3D const FileMode._internal(2); +- const FileMode._internal(int this._mode); +- factory FileMode._internal1(int this._mode); +- factory FileMode(_mode); +- final int _mode; +-} +-class File { +- factory File(String path) =3D> null; +- factory File.fromPath(Path path) =3D> null; +-} +-f() =3D> new Fil!1''', [ +- "1+File", +- "1+File.fromPath", +- "1+FileMode", +- "1+FileMode._internal1", +- "1+FileMode._internal" +- ]); +- +- buildTests('testCommentSnippets078', ''' +-class Map{static from()=3D>null;clear(){}}void main() { Map.!1 }''', +- ["1+from", "1-clear"]); // static method, instance method +- +- buildTests('testCommentSnippets079', ''' +-class Map{static from()=3D>null;clear(){}}void main() { Map s; s.!1 }''', +- ["1-from", "1+clear"]); // static method, instance method +- +- buildTests('testCommentSnippets080', ''' +-class RuntimeError{var message;}void main() { RuntimeError.!1 }''', +- ["1-message"]); // field +- +- buildTests( +- 'testCommentSnippets081', +- ''' +-class Foo {this.!1}''', +- ["1-Object"], +- failingTests: '1'); +- +- buildTests('testCommentSnippets082', ''' +- class HttpRequest {} +- class HttpResponse {} +- main() { +- var v =3D (HttpRequest req, HttpResp!1) +- }''', ["1+HttpResponse"]); +- +- buildTests('testCommentSnippets083', ''' +-main() {(.!1)}''', ["1-toString"]); +- +- buildTests('testCommentSnippets083a', ''' +-main() { .!1 }''', ["1-toString"]); +- +- buildTests('testCommentSnippets083b', ''' +-main() { null.!1 }''', ["1+toString"]); +- +- buildTests('testCommentSnippets085', ''' +-class List{}class Map{}class Z extends List with !1Ma!2p {}''', +- ["1+List", "1+Map", "2+Map", "2-List"]); +- +- buildTests( +- 'testCommentSnippets086', +- ''' +-class Q{f(){xy() {!2};x!1y();}}''', +- ["1+xy", "2+f", "2-xy"], +- failingTests: '2'); +- +- buildTests('testCommentSnippets087', ''' +-class Map{}class Q extends Object with !1Map {}''', +- ["1+Map", "1-HashMap"]); +- +- buildTests('testCommentSnippets088', ''' +-class A { +- int f; +- B m(){} +-} +-class B extends A { +- num f; +- A m(){} +-} +-class Z { +- B q; +- f() {q.!1} +-}''', ["1+f", "1+m"]); // f->num, m()->A +- +- buildTests( +- 'testCommentSnippets089', +- ''' +-class Q { +- fqe() { +- xya() { +- xyb() { +- !1 +- } +- !3 xyb(); +- }; +- xza() { +- !2 +- } +- xya(); +- !4 xza(); +- } +- fqi() { +- !5 +- } +-}''', +- [ +- "1+fqe", +- "1+fqi", +- "1+Q", +- "1-xya", +- "1-xyb", +- "1-xza", +- "2+fqe", +- "2+fqi", +- "2+Q", +- "2-xya", +- "2-xyb", +- "2-xza", +- "3+fqe", +- "3+fqi", +- "3+Q", +- "3-xya", +- "3+xyb", +- "3-xza", +- "4+fqe", +- "4+fqi", +- "4+Q", +- "4+xya", +- "4-xyb", +- "4+xza", +- "5+fqe", +- "5+fqi", +- "5+Q", +- "5-xya", +- "5-xyb", +- "5-xza" +- ], +- failingTests: '123'); +- +- buildTests('testCommentSnippets090', ''' +-class X { f() { var a =3D 'x'; a.!1 }}''', ["1+length"]); +- } +- +- void buildCompletionTests() { +- buildTests('testCompletion_alias_field', ''' +-typedef int fnint(int k); fn!1int x;''', ["1+fnint"]); +- +- buildTests( +- 'testCompletion_annotation_argumentList', +- ''' +-class AAA {", +- const AAA({int aaa, int bbb});", +-}", +-", +-@AAA(!1) +-main() { +-}''', +- [ +- "1+AAA" /*":" + ProposalKind.ARGUMENT_LIST*/, +- "1+aaa", +- "1+bbb" +- ], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_annotation_topLevelVar', +- ''' +-const fooConst =3D null; +-final fooNotConst =3D null; +-const bar =3D null; +- +-@foo!1 +-main() { +-}''', +- ["1+fooConst", "1-fooNotConst", "1-bar"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_annotation_type', +- ''' +-class AAA { +- const AAA({int a, int b}); +- const AAA.nnn(int c, int d); +-} +-@AAA!1 +-main() { +-}''', +- [ +- "1+AAA" /*":" + ProposalKind.CONSTRUCTOR*/, +- "1+AAA.nnn" /*":" + ProposalKind.CONSTRUCTOR*/ +- ], +- failingTests: '1'); +- +- buildTests('testCompletion_annotation_type_inClass_withoutMember', ''' +-class AAA { +- const AAA(); +-} +- +-class C { +- @A!1 +-}''', ["1+AAA" /*":" + ProposalKind.CONSTRUCTOR*/]); +- +- buildTests('testCompletion_argument_typeName', ''' +-class Enum { +- static Enum FOO =3D new Enum(); +-} +-f(Enum e) {} +-main() { +- f(En!1); +-}''', ["1+Enum"]); +- +- buildTests('testCompletion_arguments_ignoreEmpty', ''' +-class A { +- test() {} +-} +-main(A a) { +- a.test(!1); +-}''', ["1-test"]); +- +- buildTests('testCompletion_as_asIdentifierPrefix', ''' +-main(p) { +- var asVisible; +- var v =3D as!1; +-}''', ["1+asVisible"]); +- +- buildTests('testCompletion_as_asPrefixedIdentifierStart', ''' +-class A { +- var asVisible; +-} +- +-main(A p) { +- var v =3D p.as!1; +-}''', ["1+asVisible"]); +- +- buildTests('testCompletion_as_incompleteStatement', ''' +-class MyClass {} +-main(p) { +- var justSomeVar; +- var v =3D p as !1 +-}''', ["1+MyClass", "1-justSomeVar"]); +- +- buildTests('testCompletion_cascade', ''' +-class A { +- aaa() {} +-} +- +- +-main(A a) { +- a..!1 aaa(); +-}''', ["1+aaa", "1-main"]); +- +- buildTests('testCompletion_combinator_afterComma', ''' +-import 'dart:math' show cos, !1;''', +- ["1+PI", "1+sin", "1+Random", "1-String"]); +- +- buildTests('testCompletion_combinator_ended', ''' +-import 'dart:math' show !1;"''', +- ["1+PI", "1+sin", "1+Random", "1-String"]); +- +- buildTests('testCompletion_combinator_export', ''' +-export 'dart:math' show !1;"''', +- ["1+PI", "1+sin", "1+Random", "1-String"]); +- +- buildTests('testCompletion_combinator_hide', ''' +-import 'dart:math' hide !1;"''', +- ["1+PI", "1+sin", "1+Random", "1-String"]); +- +- buildTests('testCompletion_combinator_notEnded', ''' +-import 'dart:math' show !1"''', +- ["1+PI", "1+sin", "1+Random", "1-String"]); +- +- buildTests('testCompletion_combinator_usePrefix', ''' +-import 'dart:math' show s!1"''', +- ["1+sin", "1+sqrt", "1-cos", "1-String"]); +- +- buildTests( +- 'testCompletion_constructor_field', +- ''' +-class X { X(this.field); int f!1ield;}''', +- ["1+field"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_constructorArguments_showOnlyCurrent', +- ''' +-class A { +- A.first(int p); +- A.second(double p); +-} +-main() { +- new A.first(!1); +-}''', +- ["1+A.first", "1-A.second"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_constructorArguments_whenPrefixedType', +- ''' +-import 'dart:math' as m; +-main() { +- new m.Random(!1); +-}''', +- ["1+Random:ARGUMENT_LIST"], +- failingTests: '1'); +- +- buildTests('testCompletion_dartDoc_reference_forClass', ''' +-/** +- * [int!1] +- * [method!2] +- */ +-class AAA { +- methodA() {} +-}''', ["1+int", "1-method", "2+methodA", "2-int"]); +- +- buildTests('testCompletion_dartDoc_reference_forConstructor', ''' +-class A { +- /** +- * [aa!1] +- * [int!2] +- * [method!3] +- */ +- A.named(aaa, bbb) {} +- methodA() {} +-}''', ["1+aaa", "1-bbb", "2+int", "2-double", "3+methodA"]); +- +- buildTests( +- 'testCompletion_dartDoc_reference_forFunction', +- ''' +-/** +- * [aa!1] +- * [int!2] +- * [function!3] +- */ +-functionA(aaa, bbb) {} +-functionB() {}''', +- [ +- "1+aaa", +- "1-bbb", +- "2+int", +- "2-double", +- "3+functionA", +- "3+functionB", +- "3-int" +- ], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_dartDoc_reference_forFunctionTypeAlias', +- ''' +-/** +- * [aa!1] +- * [int!2] +- * [Function!3] +- */ +-typedef FunctionA(aaa, bbb) {} +-typedef FunctionB() {}''', +- [ +- "1+aaa", +- "1-bbb", +- "2+int", +- "2-double", +- "3+FunctionA", +- "3+FunctionB", +- "3-int" +- ], +- failingTests: '1'); +- +- buildTests('testCompletion_dartDoc_reference_forMethod', ''' +-class A { +- /** +- * [aa!1] +- * [int!2] +- * [method!3] +- */ +- methodA(aaa, bbb) {} +- methodB() {} +-}''', [ +- "1+aaa", +- "1-bbb", +- "2+int", +- "2-double", +- "3+methodA", +- "3+methodB", +- "3-int" +- ]); +- +- buildTests('testCompletion_dartDoc_reference_incomplete', ''' +-/** +- * [doubl!1 some text +- * other text +- */ +-class A {} +-/** +- * [!2 some text +- * other text +- */ +-class B {} +-/** +- * [!3] some text +- */ +-class C {}''', [ +- "1+double", +- "1-int", +- "2+int", +- "2+String", +- "3+int", +- "3+String" +- ]); +- +- buildTests('testCompletion_double_inFractionPart', ''' +-main() { +- 1.0!1 +-}''', ["1-abs", "1-main"]); +- +- buildTests('testCompletion_enum', ''' +-enum MyEnum {A, B, C} +-main() { +- MyEnum.!1; +-}''', ["1+values", "1+A", "1+B", "1+C"]); +- +- buildTests('testCompletion_exactPrefix_hasHigherRelevance', ''' +-var STR; +-main(p) { +- var str; +- str!1; +- STR!2; +- Str!3; +-}''', [ +- "1+str" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 1)*/, +- "1+STR" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 0)*/, +- "2+STR" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 1)*/, +- "2+str" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 0)*/, +- "3+String" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 1)= */, +- "3+STR" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 0)*/, +- "3+str" /*",rel=3D" + (CompletionProposal.RELEVANCE_DEFAULT + 0)*/ +- ]); +- +- buildTests('testCompletion_export_dart', ''' +-import 'dart:math +-import 'dart:_chrome +-import 'dart:_collection.dev +-export 'dart:!1''', [ +- "1+dart:core", +- "1+dart:math", +- "1-dart:_chrome", +- "1-dart:_collection.dev" +- ]); +- +- buildTests( +- 'testCompletion_export_noStringLiteral_noSemicolon', +- ''' +-import !1 +- +-class A {}''', +- ["1+'dart:!';", "1+'package:!';"], +- failingTests: '1'); +- +- buildTests('testCompletion_forStmt_vars', ''' +-class int{}class Foo { mth() { for (in!1t i =3D 0; i!2 < 5; i!3++); }}''', +- ["1+int", "2+i", "3+i"]); +- +- buildTests('testCompletion_function', ''' +-class Foo { int boo =3D 7; mth() { PNGS.sort((String a, Str!1) =3D> a.com= pareTo(b)); }}''', +- ["1+String"]); +- +- buildTests('testCompletion_function_partial', ''' +-class Foo { int boo =3D 7; mth() { PNGS.sort((String a, Str!1)); }}''', +- ["1+String"]); +- +- buildTests( +- 'testCompletion_functionTypeParameter_namedArgument', +- ''' +-typedef FFF(a, b, {x1, x2, y}); +-main(FFF fff) { +- fff(1, 2, !1)!2; +-}''', +- ["1+x1", "2-x2"], +- failingTests: '1'); +- +- buildTests('testCompletion_ifStmt_field1', ''' +-class Foo { int myField =3D 7; mth() { if (!1) {}}}''', ["1+myFie= ld"]); +- +- buildTests('testCompletion_ifStmt_field1a', ''' +-class Foo { int myField =3D 7; mth() { if (!1) }}''', ["1+myField= "]); +- +- buildTests('testCompletion_ifStmt_field2', ''' +-class Foo { int myField =3D 7; mth() { if (m!1) {}}}''', ["1+myFi= eld"]); +- +- buildTests('testCompletion_ifStmt_field2a', ''' +-class Foo { int myField =3D 7; mth() { if (m!1) }}''', ["1+myFiel= d"]); +- +- buildTests('testCompletion_ifStmt_field2b', ''' +-class Foo { myField =3D 7; mth() { if (m!1) {}}}''', ["1+myField"= ]); +- +- buildTests('testCompletion_ifStmt_localVar', ''' +-class Foo { mth() { int value =3D 7; if (v!1) {}}}''', ["1+value"= ]); +- +- buildTests('testCompletion_ifStmt_localVara', ''' +-class Foo { mth() { value =3D 7; if (v!1) {}}}''', ["1-value"]); +- +- buildTests('testCompletion_ifStmt_topLevelVar', ''' +-int topValue =3D 7; class Foo { mth() { if (t!1) {}}}''', ["1+top= Value"]); +- +- buildTests('testCompletion_ifStmt_topLevelVara', ''' +-topValue =3D 7; class Foo { mth() { if (t!1) {}}}''', ["1+topValu= e"]); +- +- buildTests( +- 'testCompletion_ifStmt_unionType_nonStrict', +- ''' +-class A { a() =3D> null; x() =3D> null} +-class B { a() =3D> null; y() =3D> null} +-void main() { +- var x; +- var c; +- if(c) { +- x =3D new A(); +- } else { +- x =3D new B(); +- } +- x.!1; +-}''', +- ["1+a", "1+x", "1+y"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_ifStmt_unionType_strict', +- ''' +-class A { a() =3D> null; x() =3D> null} +-class B { a() =3D> null; y() =3D> null} +-void main() { +- var x; +- var c; +- if(c) { +- x =3D new A(); +- } else { +- x =3D new B(); +- } +- x.!1; +-}''', +- ["1+a", "1-x", "1-y"], +- failingTests: '1'); +- +- buildTests('testCompletion_import', ''' +-import '!1';''', ["1+dart:!", "1+package:!"]); +- +- buildTests('testCompletion_import_dart', ''' +-import 'dart:math +-import 'dart:_chrome +-import 'dart:_collection.dev +-import 'dart:!1''', [ +- "1+dart:core", +- "1+dart:math", +- "1-dart:_chrome", +- "1-dart:_collection.dev" +- ]); +- +- buildTests('testCompletion_import_hasStringLiteral_noSemicolon', ''' +-import '!1' +- +-class A {}''', ["1+dart:!", "1+package:!"]); +- +- buildTests( +- 'testCompletion_import_noSpace', +- ''' +-import!1''', +- ["1+ 'dart:!';", "1+ 'package:!';"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_import_noStringLiteral', +- ''' +-import !1;''', +- ["1+'dart:!'", "1+'package:!'"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_import_noStringLiteral_noSemicolon', +- ''' +-import !1 +- +-class A {}''', +- ["1+'dart:!';", "1+'package:!';"], +- failingTests: '1'); +- +- buildTests('testCompletion_incompleteClassMember', ''' +-class A { +- Str!1 +- final f =3D null; +-}''', ["1+String", "1-bool"]); +- +- buildTests('testCompletion_incompleteClosure_parameterType', ''' +-f1(cb(String s)) {} +-f2(String s) {} +-main() { +- f1((Str!1)); +- f2((Str!2)); +-}''', ["1+String", "1-bool", "2+String", "2-bool"]); +- +- buildTests( +- 'testCompletion_inPeriodPeriod', +- ''' +-main(String str) { +- 1 < str.!1.length; +- 1 + str.!2.length; +- 1 + 2 * str.!3.length; +-}''', +- ["1+codeUnits", "2+codeUnits", "3+codeUnits"], +- failingTests: '123'); +- +- // no checks, but no exceptions +- buildTests('testCompletion_instanceCreation_unresolved', ''' +-class A { +-} +-main() { +- new NoSuchClass(!1); +- new A.noSuchConstructor(!2); +-}''', ["1+int", "2+int"]); +- +- buildTests( +- 'testCompletion_import_lib', +- ''' +-import '!1''', +- ["1+my_lib.dart"], +- extraFiles: {"/my_lib.dart": ""}, +- failingTests: '1'); +- +- buildTests('testCompletion_is', ''' +-class MyClass {} +-main(p) { +- var isVariable; +- if (p is MyCla!1) {} +- var v1 =3D p is MyCla!2; +- var v2 =3D p is !3; +- var v2 =3D p is!4; +-}''', [ +- "1+MyClass", +- "2+MyClass", +- "3+MyClass", +- "3-v1", +- "4+is", +- "4-isVariable" +- ]); +- +- buildTests('testCompletion_is_asIdentifierStart', ''' +-main(p) { +- var isVisible; +- var v1 =3D is!1; +- var v2 =3D is!2 +-}''', ["1+isVisible", "2+isVisible"]); +- +- buildTests('testCompletion_is_asPrefixedIdentifierStart', ''' +-class A { +- var isVisible; +-} +- +-main(A p) { +- var v1 =3D p.is!1; +- var v2 =3D p.is!2 +-}''', ["1+isVisible", "2+isVisible"]); +- +- buildTests('testCompletion_is_incompleteStatement1', ''' +-class MyClass {} +-main(p) { +- var justSomeVar; +- var v =3D p is !1 +-}''', ["1+MyClass", "1-justSomeVar"]); +- +- buildTests('testCompletion_is_incompleteStatement2', ''' +-class MyClass {} +-main(p) { +- var isVariable; +- var v =3D p is!1 +-}''', ["1+is", "1-isVariable"]); +- +- buildTests('testCompletion_keyword_in', ''' +-class Foo { int input =3D 7; mth() { if (in!1) {}}}''', ["1+input= "]); +- +- buildTests('testCompletion_keyword_syntheticIdentifier', ''' +-main() { +- var caseVar; +- var otherVar; +- var v =3D case!1 +-}''', ["1+caseVar", "1-otherVar"]); +- +- buildTests('testCompletion_libraryIdentifier_atEOF', ''' +-library int.!1''', ["1-parse", "1-bool"]); +- +- buildTests('testCompletion_libraryIdentifier_notEOF', ''' +-library int.!1''', ["1-parse", "1-bool"]); +- +- buildTests( +- 'testCompletion_methodRef_asArg_incompatibleFunctionType', +- ''' +-foo( f(int p) ) {} +-class Functions { +- static myFuncInt(int p) {} +- static myFuncDouble(double p) {} +-} +-bar(p) {} +-main(p) { +- foo( Functions.!1; ); +-}''', +- [ +- "1+myFuncInt" /*":" + ProposalKind.METHOD_NAME*/, +- "1-myFuncDouble" /*":" + ProposalKind.METHOD_NAME*/ +- ], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_methodRef_asArg_notFunctionType', +- ''' +-foo( f(int p) ) {} +-class Functions { +- static myFunc(int p) {} +-} +-bar(p) {} +-main(p) { +- foo( (int p) =3D> Functions.!1; ); +-}''', +- [ +- "1+myFunc" /*":" + ProposalKind.METHOD*/, +- "1-myFunc" /*":" + ProposalKind.METHOD_NAME*/ +- ], +- failingTests: '1'); +- +- buildTests('testCompletion_methodRef_asArg_ofFunctionType', ''' +-foo( f(int p) ) {} +-class Functions { +- static int myFunc(int p) {} +-} +-main(p) { +- foo(Functions.!1); +-}''', [ +- "1+myFunc" /*":" + ProposalKind.METHOD*/, +- "1+myFunc" /*":" + ProposalKind.METHOD_NAME*/ +- ]); +- +- buildTests('testCompletion_namedArgument_alreadyUsed', ''' +-func({foo}) {} main() { func(foo: 0, fo!1); }''', ["1-foo"]); +- +- buildTests( +- 'testCompletion_namedArgument_constructor', +- ''' +-class A {A({foo, bar}) {}} main() { new A(fo!1); }''', +- ["1+foo", "1-bar"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_namedArgument_empty', +- ''' +-func({foo, bar}) {} main() { func(!1); }''', +- [ +- "1+foo" /*":" + ProposalKind.NAMED_ARGUMENT*/, +- "1-foo" /*":" + ProposalKind.OPTIONAL_ARGUMENT*/ +- ], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_namedArgument_function', +- ''' +-func({foo, bar}) {} main() { func(fo!1); }''', +- ["1+foo", "1-bar"], +- failingTests: '1'); +- +- buildTests('testCompletion_namedArgument_notNamed', ''' +-func([foo]) {} main() { func(fo!1); }''', ["1-foo"]); +- +- buildTests('testCompletion_namedArgument_unresolvedFunction', ''' +-main() { func(fo!1); }''', ["1-foo"]); +- +- buildTests('testCompletion_newMemberType1', ''' +-class Collection{}class List extends Collection{}class Foo { !1 }''', +- ["1+Collection", "1+List"]); +- +- buildTests('testCompletion_newMemberType2', ''' +-class Collection{}class List extends Collection{}class Foo {!1}''', +- ["1+Collection", "1+List"]); +- +- buildTests('testCompletion_newMemberType3', ''' +-class Collection{}class List extends Collection{}class Foo {L!1}''', +- ["1-Collection", "1+List"]); +- +- buildTests('testCompletion_newMemberType4', ''' +-class Collection{}class List extends Collection{}class Foo {C!1}''', +- ["1+Collection", "1-List"]); +- +- buildTests( +- 'testCompletion_positionalArgument_constructor', +- ''' +-class A { +- A([foo, bar]); +-} +-main() { +- new A(!1); +- new A(0, !2); +-}''', +- [ +- "1+foo" /*":" + ProposalKind.OPTIONAL_ARGUMENT*/, +- "1-bar", +- "2-foo", +- "2+bar" /*":" +- + ProposalKind.OPTIONAL_ARGUMENT*/ +- ], +- failingTests: '12'); +- +- buildTests( +- 'testCompletion_positionalArgument_function', +- ''' +-func([foo, bar]) {} +-main() { +- func(!1); +- func(0, !2); +-}''', +- [ +- "1+foo" /*":" + ProposalKind.OPTIONAL_ARGUMENT*/, +- "1-bar", +- "2-foo", +- "2+bar" /*":" +- + ProposalKind.OPTIONAL_ARGUMENT*/ +- ], +- failingTests: '12'); +- +- buildTests( +- 'testCompletion_preferStaticType', +- ''' +-class A { +- foo() {} +-} +-class B extends A { +- bar() {} +-} +-main() { +- A v =3D new B(); +- v.!1 +-}''', +- [ +- "1+foo", +- "1-bar,potential=3Dfalse,declaringType=3DB", +- "1+bar,potential=3Dtrue,declaringType=3DB" +- ], +- failingTests: '1'); +- +- buildTests('testCompletion_privateElement_sameLibrary_constructor', '= '' +-class A { +- A._c(); +- A.c(); +-} +-main() { +- new A.!1 +-}''', ["1+_c", "1+c"]); +- +- buildTests('testCompletion_privateElement_sameLibrary_member', ''' +-class A { +- _m() {} +- m() {} +-} +-main(A a) { +- a.!1 +-}''', ["1+_m", "1+m"]); +- +- buildTests('testCompletion_propertyAccess_whenClassTarget', ''' +-class A { +- static int FIELD; +- int field; +-} +-main() { +- A.!1 +-}''', ["1+FIELD", "1-field"]); +- +- buildTests('testCompletion_propertyAccess_whenClassTarget_excludeSupe= r', ''' +-class A { +- static int FIELD_A; +- static int methodA() {} +-} +-class B extends A { +- static int FIELD_B; +- static int methodB() {} +-} +-main() { +- B.!1; +-}''', ["1+FIELD_B", "1-FIELD_A", "1+methodB", "1-methodA"]); +- +- buildTests('testCompletion_propertyAccess_whenInstanceTarget', ''' +-class A { +- static int FIELD; +- int fieldA; +-} +-class B { +- A a; +-} +-class C extends A { +- int fieldC; +-} +-main(B b, C c) { +- b.a.!1; +- c.!2; +-}''', ["1-FIELD", "1+fieldA", "2+fieldC", "2+fieldA"]); +- +- buildTests('testCompletion_return_withIdentifierPrefix', ''' +-f() { var vvv =3D 42; return v!1 }''', ["1+vvv"]); +- +- buildTests('testCompletion_return_withoutExpression', ''' +-f() { var vvv =3D 42; return !1 }''', ["1+vvv"]); +- +- buildTests('testCompletion_staticField1', ''' +-class num{}class Sunflower {static final n!2um MAX_D =3D 300;nu!3m xc, yc= ;Sun!4flower() {x!Xc =3D y!Yc =3D MA!1 }}''', +- ["1+MAX_D", "X+xc", "Y+yc", "2+num", "3+num", "4+Sunflowe= r"]); +- +- buildTests('testCompletion_super_superType', ''' +-class A { +- var fa; +- ma() {} +-} +-class B extends A { +- var fb; +- mb() {} +- main() { +- super.!1 +- } +-}''', ["1+fa", "1-fb", "1+ma", "1-mb"]); +- +- buildTests( +- 'testCompletion_superConstructorInvocation_noNamePrefix', +- ''' +-class A { +- A.fooA(); +- A.fooB(); +- A.bar(); +-} +-class B extends A { +- B() : super.!1 +-}''', +- ["1+fooA", "1+fooB", "1+bar"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_superConstructorInvocation_withNamePrefix', +- ''' +-class A { +- A.fooA(); +- A.fooB(); +- A.bar(); +-} +-class B extends A { +- B() : super.f!1 +-}''', +- ["1+fooA", "1+fooB", "1-bar"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_this_bad_inConstructorInitializer', +- ''' +-class A { +- var f; +- A() : f =3D this.!1; +-}''', +- ["1-toString"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_this_bad_inFieldDeclaration', +- ''' +-class A { +- var f =3D this.!1; +-}''', +- ["1-toString"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_this_bad_inStaticMethod', +- ''' +-class A { +- static m() { +- this.!1; +- } +-}''', +- ["1-toString"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_this_bad_inTopLevelFunction', +- ''' +-main() { +- this.!1; +-}''', +- ["1-toString"], +- failingTests: '1'); +- +- buildTests( +- 'testCompletion_this_bad_inTopLevelVariableDeclaration', +- ''' +-var v =3D this.!1;''', +- ["1-toString"], +- failingTests: '1'); +- +- buildTests('testCompletion_this_OK_inConstructorBody', ''' +-class A { +- var f; +- m() {} +- A() { +- this.!1; +- } +-}''', ["1+f", "1+m"]); +- +- buildTests('testCompletion_this_OK_localAndSuper', ''' +-class A { +- var fa; +- ma() {} +-} +-class B extends A { +- var fb; +- mb() {} +- main() { +- this.!1 +- } +-}''', ["1+fa", "1+fb", "1+ma", "1+mb"]); +- +- buildTests('testCompletion_topLevelField_init2', ''' +-class DateTime{static var JUN;}final num M =3D Dat!1eTime.JUN;''', +- ["1+DateTime", "1-void"]); +- +- buildTests('testCompletion_while', ''' +-class Foo { int boo =3D 7; mth() { while (b!1) {} }}''', ["1+boo"= ]); +- } +- +- void buildLibraryTests() { +- Map sources =3D new HashMap(); +- +- buildTests('test_export_ignoreIfThisLibraryExports', ''' +-export 'dart:math'; +-libFunction() {}; +-main() { +- !1 +-}''', ["1-cos", "1+libFunction"]); +- +- sources.clear(); +- sources["/lib.dart"] =3D ''' +-library lib; +-export 'dart:math' hide sin; +-libFunction() {};'''; +- buildTests( +- 'test_export_showIfImportLibraryWithExport', +- ''' +-import 'lib.dart' as p; +-main() { +- p.!1 +-}''', +- ["1+cos", "1-sin", "1+libFunction"], +- extraFiles: sources, +- failingTests: '1'); +- +- buildTests( +- 'test_importPrefix_hideCombinator', +- ''' +-import 'dart:math' as math hide PI; +-main() { +- math.!1 +-}''', +- ["1-PI", "1+LN10"], +- failingTests: '1'); +- +- buildTests( +- 'test_importPrefix_showCombinator', +- ''' +-import 'dart:math' as math show PI; +-main() { +- math.!1 +-}''', +- ["1+PI", "1-LN10"], +- failingTests: '1'); +- +- sources.clear(); +- sources["/lib.dart"] =3D ''' +-library lib +-class _A +- foo() {} +- +-class A extends _A { +-}'''; +- buildTests( +- 'test_memberOfPrivateClass_otherLibrary', +- ''' +-import 'lib.dart'; +-main(A a) { +- a.!1 +-}''', +- ["1+foo"], +- extraFiles: sources, +- failingTests: '1'); +- +- sources.clear(); +- sources["/lib.dart"] =3D ''' +-library lib; +-class A { +- A.c(); +- A._c(); +-}'''; +- buildTests( +- 'test_noPrivateElement_otherLibrary_constructor', +- ''' +-import 'lib.dart'; +-main() { +- new A.!1 +-}''', +- ["1-_c", "1+c"], +- failingTests: '1'); +- +- sources.clear(); +- sources["/lib.dart"] =3D ''' +-library lib; +-class A { +- var f; +- var _f; +-}'''; +- buildTests( +- 'test_noPrivateElement_otherLibrary_member', +- ''' +- import 'lib.dart'; +- main(A a) { +- a.!1 +- }''', +- ["1-_f", "1+f"], +- extraFiles: sources, +- failingTests: '1'); +- +- sources.clear(); +- sources["/firth.dart"] =3D ''' +-library firth; +-class SerializationException { +- const SerializationException(); +-}'''; +- buildTests( +- 'testLibrary001', +- ''' +-import 'firth.dart'; +-main() { +-throw new Seria!1lizationException();}''', +- ["1+SerializationException"], +- extraFiles: sources, +- failingTests: '1'); +- +- // Type propagation. +- // TODO Include corelib analysis (this works in the editor) +- buildTests( +- 'testLibrary002', +- '''t2() {var q=3D[0],z=3Dq.!1length;q.!2clear();}''', +- ["1+length", "1+isEmpty", "2+clear"], +- failingTests: '1'); +- +- // TODO Include corelib analysis +- buildTests('testLibrary003', '''class X{var q; f() {q.!1a!2}}''', +- ["1+end", "2+abs", "2-end"], +- failingTests: '12'); +- +- // TODO Include corelib analysis +- // Resolving dart:html takes between 2.5s and 30s; json, about 0.12s +- buildTests('testLibrary004', ''' +- library foo; +- import 'dart:convert' as json; +- class JsonDecoderX{} +- f1() {var x=3Dnew json.!1} +- f2() {var x=3Dnew json.JsonDe!2} +- f3() {var x=3Dnew json.JsonDecoder!3}''', [ +- "1+JsonDecoder", +- "1-JsonDecoderX", +- "2+JsonDecoder", +- "2-JsonDecoderX", +- "3+JsonDecoder", +- "3-JsonDecoderX" +- ]); +- +- // TODO Enable after type propagation is implemented. Not yet. +- // TODO Include corelib analysis +- buildTests('testLibrary005', +- '''var PHI;main(){PHI=3D5.3;PHI.abs().!1 Object x;}''', [= "1+abs"], +- failingTests: '1'); +- +- // Exercise import and export handling. +- // Libraries are defined in partial order of increasing dependency. +- sources.clear(); +- sources["/exp2a.dart"] =3D ''' +-library exp2a; +-e2a() {}'''; +- sources["/exp1b.dart"] =3D ''' +-library exp1b;", +-e1b() {}'''; +- sources["/exp1a.dart"] =3D ''' +-library exp1a;", +-export 'exp1b.dart';", +-e1a() {}'''; +- sources["/imp1.dart"] =3D ''' +-library imp1; +-export 'exp1a.dart'; +-i1() {}'''; +- sources["/imp2.dart"] =3D ''' +-library imp2; +-export 'exp2a.dart'; +-i2() {}'''; +- buildTests( +- 'testLibrary006', +- ''' +-import 'imp1.dart'; +-import 'imp2.dart'; +-main() {!1 +- i1(); +- i2(); +- e1a(); +- e1b(); +- e2a(); +-}''', +- ["1+i1", "1+i2", "1+e1a", "1+e2a", "1+e1b"], +- extraFiles: sources, +- failingTests: '1'); +- +- // Exercise import and export handling. +- // Libraries are defined in partial order of increasing dependency. +- sources.clear(); +- sources["/l1.dart"] =3D ''' +-library l1; +-var _l1t; var l1t;'''; +- buildTests( +- 'testLibrary007', +- ''' +-import 'l1.dart'; +-main() { +- var x =3D l!1 +- var y =3D _!2 +-}''', +- ["1+l1t", "1-_l1t", "2-_l1t"], +- extraFiles: sources, +- failingTests: '1'); +- +- // Check private library exclusion +- sources.clear(); +- sources["/public.dart"] =3D ''' +-library public; +-class NonPrivate { +- void publicMethod() { +- } +-}'''; +- sources["/private.dart"] =3D ''' +-library _private; +-import 'public.dart'; +-class Private extends NonPrivate { +- void privateMethod() { +- } +-}'''; +- buildTests( +- 'testLibrary008', +- ''' +-import 'private.dart'; +-import 'public.dart'; +-class Test { +- void test() { +- NonPrivate x =3D new NonPrivate(); +- x.!1 //publicMethod but not privateMethod should appear +- } +-}''', +- ["1-privateMethod", "1+publicMethod"], +- extraFiles: sources, +- failingTests: '1'); +- +- // Exercise library prefixes. +- sources.clear(); +- sources["/lib.dart"] =3D ''' +-library lib; +-int X =3D 1; +-void m(){} +-class Y {}'''; +- buildTests( +- 'testLibrary009', +- ''' +-import 'lib.dart' as Q; +-void a() { +- var x =3D Q.!1 +-} +-void b() { +- var x =3D [Q.!2] +-} +-void c() { +- var x =3D new List([Q.!3]) +-} +-void d() { +- new Q.!4 +-}''', +- [ +- "1+X", +- "1+m", +- "1+Y", +- "2+X", +- "2+m", +- "2+Y", +- "3+X", +- "3+m", +- "3+Y", +- "4+Y", +- "4-m", +- "4-X" +- ], +- extraFiles: sources, +- failingTests: '1234'); +- } +- +- void buildNumberedTests() { +- buildTests('test001', ''' +-void r1(var v) { +- v.!1toString!2().!3hash!4Code +-}''', [ +- "1+toString", +- "1-=3D=3D", +- "2+toString", +- "3+hashCode", +- "3+toString", +- "4+hashCode", +- "4-toString" +- ]); +- +- buildTests('test002', ''' +-void r2(var vim) { +- v!1.toString() +-}''', ["1+vim"]); +- +- buildTests('test003', ''' +-class A { +- int a() =3D> 3; +- int b() =3D> this.!1a(); +-}''', ["1+a"]); +- +- buildTests( +- 'test004', +- ''' +-class A { +- int x; +- A() : this.!1x =3D 1; +- A.b() : this(); +- A.c() : this.!2b(); +- g() =3D> new A.!3c(); +-}''', +- ["1+x", "2+b", "3+c"], +- failingTests: '12'); +- +- buildTests( +- 'test005', +- ''' +-class A {} +-void rr(var vim) { +- var !1vq =3D v!2.toString(); +- var vf; +- v!3.toString(); +-}''', +- [ +- "1-A", +- "1-vim", +- "1+vq", +- "1-vf", +- "1-this", +- "1-void", +- "1-null", +- "1-false", +- "2-A", +- "2+vim", +- "2-vf", +- "2-vq", +- "2-this", +- "2-void", +- "2-null", +- "2-false", +- "3+vf", +- "3+vq", +- "3+vim", +- "3-A" +- ], +- failingTests: '1'); +- +- buildTests('test006', ''' +-void r2(var vim, {va: 2, b: 3}) { +- v!1.toString() +-}''', ["1+va", "1-b"]); +- +- buildTests('test007', ''' +-void r2(var vim, [va: 2, b: 3]) { +- v!1.toString() +-}''', ["1+va", "1-b"]); +- +- // keywords +- buildTests( +- 'test008', +- ''' +-!1class Aclass {} +-class Bclass !2extends!3 !4Aclass {} +-!5abstract class Eclass implements Aclass, Bclass {} +-class Fclass extends Bclass !6with !7 Eclass {}''', +- [ +- "1+class", +- "1-implements", +- "1-extends", +- "1-with", +- "2+extends", +- "3+extends", +- "4+Aclass", +- "4-Bclass", +- "5+abstract", +- "6+with", +- "7+Eclass", +- "7-Dclass", +- "7-Ctype", +- ], +- failingTests: '2346'); +- +- // keywords +- buildTests( +- 'test009', +- ''' +-typedef !1dy!2namic TestFn1(); +-typedef !3vo!4id TestFn2(); +-typ!7edef !5n!6''', +- [ +- "1+void", +- "1+TestFn2", +- "2+dynamic", +- "2-void", +- "3+dynamic", +- "4+void", +- "4-dynamic", +- "5+TestFn2", +- "6+num", +- "7+typedef" +- ], +- failingTests: '1234'); +- +- buildTests( +- 'test010', +- ''' +-class test !8!7 {} +-class tezetst !9!A {}''', +- [ +- "1-String", +- "1-List", +- "1-test", +- "2-String", +- "2-test", +- "3+extends", +- "4-tezetst", +- "4-test", +- "5-String", +- "6-List", +- "7-List", +- "8-List", +- "9-String", +- "A-String", +- "B-String", +- "C-List", +- "C-tezetst", +- "D-List", +- "D-test" +- ], +- failingTests: '23'); +- +- // name generation with conflicts +- buildTests('test011', '''r2(var object, Object object1, Object !1);''= ', +- ["1+object2"], +- failingTests: '1'); +- +- // reserved words +- buildTests( +- 'test012', +- ''' +-class X { +- f() { +- g(!1var!2 z) {!3true.!4toString();}; +- } +-}''', +- [ +- "1+var", +- "1+dynamic", +- "1-f", +- "2+var", +- "2-dynamic", +- "3+false", +- "3+true", +- "4+toString" +- ], +- failingTests: '123'); +- +- // conditions & operators +- buildTests( +- 'test013', +- ''' +-class Q { +- bool x; +- List zs; +- int k; +- var a; +- mth() { +- while (!1x !9); +- do{} while(!2x !8); +- for(z in !3zs) {} +- switch(!4k) {case 1:{!0}} +- try { +- } on !5Object catch(a){} +- if (!7x !6) {} else {}; +- } +-}''', +- [ +- "1+x", +- "2+x", +- "3+zs", +- "4+k", +- "5+Q", +- "5-a", +- "6+=3D=3D", +- "7+x", +- "8+=3D=3D", +- "9+=3D=3D", +- "0+k" +- ], +- failingTests: '689'); +- +- // keywords +- buildTests( +- 'test014', +- ''' +-class Q { +- bool x; +- List zs; +- int k; +- !Dvar a; +- !Evoid mth() { +- !1while (z) { !Gcontinue; }; +- !2do{ !Hbreak; } !3while(x); +- !4for(z !5in zs) {} +- !6for (int i; i < 3; i++); +- !7switch(k) {!8case 1:{} !9default:{}} +- !Atry { +- } !Bon Object !Ccatch(a){} +- !Fassert true; +- !Jif (x) {} !Kelse {}; +- !Lreturn; +- } +-}''', +- [ +- "1+while", +- "2+do", +- "3+while", +- "4+for", +- "5+in", +- "6+for", +- "7+switch", +- "8+case", +- "9+default", +- "A+try", +- "B+on", +- "C+catch", +- "D+var", +- "E+void", +- "F+assert", +- "G+continue", +- "H+break", +- "J+if", +- "K+else", +- "L+return" +- ], +- failingTests: '3CK'); +- +- // operators in function +- buildTests('test015', '''f(a,b,c) =3D> a + b * c !1;''', ["1+= =3D=3D"], +- failingTests: '1'); +- +- // operators in return +- buildTests( +- 'test016', +- '''class X {dynamic f(a,b,c) {return a + b * c !1;}}''', +- ["1+=3D=3D"], +- failingTests: '1'); +- +- // keywords +- buildTests( +- 'test017', +- ''' +-!1!2import 'x' !5as r; +-!3export '!8uri' !6hide Q !7show X; +-!4part 'x';''', +- [ +- "1+library", +- "2+import \'\';", +- "3+export \'\';", +- "4+part \'\';", +- "5+as", +- "6+hide", +- "7+show", +- "8-null" +- ], +- failingTests: '234567'); //TODO(jwren) 234 failing as correct sel= ection +- // offset assertions can't be passed into buildTests(..) +- +- // keywords +- buildTests('test018', '''!1part !2of foo;''', ["1+part", "2+o= f"], +- failingTests: '12'); +- +- buildTests('test019', ''' +-var truefalse =3D 0; +-var falsetrue =3D 1; +-main() { +- var foo =3D true!1 +-}''', ["1+true", "1+truefalse", "1-falsetrue"]); +- +- buildTests('test020', '''var x =3D null.!1''', ["1+toString"]= ); +- +- buildTests('test021', '''var x =3D .!1''', ["1-toString"]); +- +- buildTests('test022', '''var x =3D .!1;''', ["1-toString"]); +- +- buildTests('test023', ''' +-class Map{getKeys(){}} +-class X { +- static x1(Map m) { +- m.!1getKeys; +- } +- x2(Map m) { +- m.!2getKeys; +- } +-}''', ["1+getKeys", "2+getKeys"]); +- +-// Note lack of semicolon following completion location +- buildTests('test024', ''' +-class List{factory List.from(Iterable other) {}} +-class F { +- f() { +- new List.!1 +- } +-}''', ["1+from"]); +- +- buildTests('test025', ''' +-class R { +- static R _m; +- static R m; +- f() { +- var a =3D !1m; +- var b =3D _!2m; +- var c =3D !3g(); +- } +- static g() { +- var a =3D !4m; +- var b =3D _!5m; +- var c =3D !6g(); +- } +-} +-class T { +- f() { +- R x; +- x.!7g(); +- x.!8m; +- x._!9m; +- } +- static g() { +- var q =3D R._!Am; +- var g =3D R.!Bm; +- var h =3D R.!Cg(); +- } +- h() { +- var q =3D R._!Dm; +- var g =3D R.!Em; +- var h =3D R.!Fg(); +- } +-}''', [ +- "1+m", +- "2+_m", +- "3+g", +- "4+m", +- "5+_m", +- "6+g", +- "7-g", +- "8-m", +- "9-_m", +- "A+_m", +- "B+m", +- "C+g", +- "D+_m", +- "E+m", +- "F+g" +- ]); +- +- buildTests('test026', '''var aBcD; var x=3Dab!1''', ["1+aBcD"= ]); +- +- buildTests( +- 'test027', '''m(){try{}catch(eeee,ssss){s!1}''', ["1+ssss= "]); +- +- buildTests('test028', '''m(){var isX=3D3;if(is!1)''', ["1+isX= "]); +- +- buildTests('test029', '''m(){[1].forEach((x)=3D>!1x);}''', ["= 1+x"]); +- +- buildTests('test030', '''n(){[1].forEach((x){!1});}''', ["1+x= "]); +- +- buildTests( +- 'test031', +- '''class Caster {} m() {try {} on Cas!1ter catch (CastBlock) {!2}= }''', +- ["1+Caster", "1-CastBlock", "2+Caster", "2+CastBlock"]); +- +- buildTests('test032', ''' +-const ONE =3D 1; +-const ICHI =3D 10; +-const UKSI =3D 100; +-const EIN =3D 1000; +-m() { +- int x; +- switch (x) { +- case !3ICHI: +- case UKSI: +- case EIN!2: +- case ONE!1: return; +- default: return; +- } +-}''', [ +- "1+ONE", +- "1-UKSI", +- "2+EIN", +- "2-ICHI", +- "3+ICHI", +- "3+UKSI", +- "3+EIN", +- "3+ONE" +- ]); +- +- buildTests( +- 'test033', +- '''class A{}class B extends A{b(){}}class C implements A {c(){}}c= lass X{x(){A f;f.!1}}''', +- ["1+b", "1-c"], +- failingTests: '1'); +- +- // TODO(scheglov) decide what to do with Type for untyped field (not +- // supported by the new store) +- // test analysis of untyped fields and top-level vars +- buildTests( +- 'test034', +- ''' +-var topvar; +-class Top {top(){}} +-class Left extends Top {left(){}} +-class Right extends Top {right(){}} +-t1() { +- topvar =3D new Left(); +-} +-t2() { +- topvar =3D new Right(); +-} +-class A { +- var field; +- a() { +- field =3D new Left(); +- } +- b() { +- field =3D new Right(); +- } +- test() { +- topvar.!1top(); +- field.!2top(); +- } +-}''', +- ["1+top", "2+top"], +- failingTests: '12'); +- +- // test analysis of untyped fields and top-level vars +- buildTests('test035', '''class Y {final x=3D'hi';mth() {x.!1length;}}= ''', +- ["1+length"], +- failingTests: '1'); +- +- // TODO(scheglov) decide what to do with Type for untyped field (not +- // supported by the new store) +- // test analysis of untyped fields and top-level vars +- buildTests( +- 'test036', +- ''' +-class A1 { +- var field; +- A1() : field =3D 0; +- q() { +- A1 a =3D new A1(); +- a.field.!1 +- } +-} +-main() { +- A1 a =3D new A1(); +- a.field.!2 +-}''', +- ["1+round", "2+round"], +- failingTests: '12'); +- +- buildTests( +- 'test037', +- ''' +-class HttpServer{} +-class HttpClient{} +-main() { +- new HtS!1 +-}''', +- ["1+HttpServer", "1-HttpClient"], +- failingTests: '1'); +- +- buildTests( +- 'test038', +- ''' +-class X { +- x(){} +-} +-class Y { +- y(){} +-} +-class A { +- Y ay; +- Z az; +- A(this.ay, this.az) { +- ay.!1y; +- az.!2x; +- } +-}''', +- ["1+y", "1-x", "2+x", "2-y"], +- failingTests: '2'); +- +- // test analysis of untyped fields and top-level vars +- buildTests( +- 'test039', '''class X{}var x =3D null as !1X;''', ["1-voi= d"]); +- +- // test arg lists with named params +- buildTests('test040', '''m(){f(a, b, {x1, x2, y}) {};f(1, 2, !1)!2;}'= '', +- ["1+x1", "2-x2"], +- failingTests: '1'); +- +- // test arg lists with named params +- buildTests('test041', '''m(){f(a, b, {x1, x2, y}) {};f(1, 2, !1''', +- ["1+x1", "1+x2", "1+y"], +- failingTests: '1'); +- +- // test arg lists with named params +- buildTests('test042', '''m(){f(a, b, {x1, x2, y}) {};f(1, 2, !1;!2''', +- ["1+x1", "1+x2", "2-y"], +- failingTests: '1'); +- } +- +- void buildOtherTests() { +- buildTests('test_classMembers_inGetter', +- '''class A { var fff; get z {ff!1}}''', ["1+fff"]); +- +- buildTests( +- 'testSingle', +- '''class A {int x; !2mth() {int y =3D this.x;}}class B{}''', +- ["2+B"]); +- } +- +- /** +- * Generate a set of completion tests based on the given [originalSourc= e]. +- * +- * The source string has completion points embedded in it, which are +- * identified by '!X' where X is a single character. Each X is matched = to +- * positive or negative results in the array of [validationStrings]. +- * Validation strings contain the name of a prediction with a two chara= cter +- * prefix. The first character of the prefix corresponds to an X in the +- * [originalSource]. The second character is either a '+' or a '-' indi= cating +- * whether the string is a positive or negative result. +- * +- * The [originalSource] is the source for a completion test that contai= ns +- * completion points. The [validationStrings] are the positive and nega= tive +- * predictions. +- * +- * Optional argument [failingTests], if given, is a string, each charac= ter of +- * which corresponds to an X in the [originalSource] for which the test= is +- * expected to fail. This sould be used to mark known completion bugs = that +- * have not yet been fixed. +- */ +- void buildTests(String baseName, String originalSource, List re= sults, +- {Map extraFiles, String failingTests: ''}) { +- List completionTests =3D +- LocationSpec.from(originalSource, results); +- completionTests.sort((LocationSpec first, LocationSpec second) { +- return first.id.compareTo(second.id); +- }); +- if (completionTests.isEmpty) { +- test(baseName, () { +- fail("Expected exclamation point ('!') within the source denoting= the" +- "position at which code completion should occur"); +- }); +- } +- Set allSpecIds =3D +- completionTests.map((LocationSpec spec) =3D> spec.id).toSet(); +- for (String id in failingTests.split('')) { +- if (!allSpecIds.contains(id)) { +- test("$baseName-$id", () { +- fail( +- "Test case '$id' included in failingTests, but this id does= not exist."); +- }); +- } +- } +- for (LocationSpec spec in completionTests) { +- String testName =3D '$baseName-${spec.id}'; +- if (failingTests.contains(spec.id)) { +- ++expectedFailCount; +- test("$testName (expected failure $expectedFailCount)", () { +- CompletionTestCase test =3D new CompletionTestCase(); +- return new Future(() =3D> test.runTest(spec, extraFiles)).then(= (_) { +- fail('Test passed - expected to fail.'); +- }, onError: (_) {}); +- }); +- } else { +- ++expectedPassCount; +- test(testName, () { +- CompletionTestCase test =3D new CompletionTestCase(); +- return test.runTest(spec, extraFiles); +- }); +- } +- } +- } +-} +diff --git a/pkg/analysis_server/test/completion_test_support.dart b/pkg/a= nalysis_server/test/completion_test_support.dart +deleted file mode 100644 +index af602208b02..00000000000 +--- a/pkg/analysis_server/test/completion_test_support.dart ++++ /dev/null +@@ -1,203 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +- +-import 'domain_completion_test.dart'; +- +-/** +- * A base class for classes containing completion tests. +- */ +-class CompletionTestCase extends CompletionDomainHandlerTest { +- static const String CURSOR_MARKER =3D '!'; +- +- List get suggestedCompletions =3D> suggestions +- .map((CompletionSuggestion suggestion) =3D> suggestion.completion) +- .toList(); +- +- void assertHasCompletion(String completion) { +- int expectedOffset =3D completion.indexOf(CURSOR_MARKER); +- if (expectedOffset >=3D 0) { +- if (completion.indexOf(CURSOR_MARKER, expectedOffset + 1) >=3D 0) { +- fail( +- "Invalid completion, contains multiple cursor positions: '$co= mpletion'"); +- } +- completion =3D completion.replaceFirst(CURSOR_MARKER, ''); +- } else { +- expectedOffset =3D completion.length; +- } +- CompletionSuggestion matchingSuggestion; +- suggestions.forEach((CompletionSuggestion suggestion) { +- if (suggestion.completion =3D=3D completion) { +- if (matchingSuggestion =3D=3D null) { +- matchingSuggestion =3D suggestion; +- } else { +- fail( +- "Expected exactly one '$completion' but found multiple:\n = $suggestedCompletions"); +- } +- } +- }); +- if (matchingSuggestion =3D=3D null) { +- fail("Expected '$completion' but found none:\n $suggestedCompletio= ns"); +- } +- expect(matchingSuggestion.selectionOffset, equals(expectedOffset)); +- expect(matchingSuggestion.selectionLength, equals(0)); +- } +- +- void assertHasNoCompletion(String completion) { +- if (suggestions.any((CompletionSuggestion suggestion) =3D> +- suggestion.completion =3D=3D completion)) { +- fail( +- "Did not expect completion '$completion' but found:\n $suggest= edCompletions"); +- } +- } +- +- /** +- * Discard any results that do not start with the characters the user h= as +- * "already typed". +- */ +- void filterResults(String content) { +- String charsAlreadyTyped =3D +- content.substring(replacementOffset, completionOffset).toLowerCas= e(); +- suggestions =3D suggestions +- .where((CompletionSuggestion suggestion) =3D> +- suggestion.completion.toLowerCase().startsWith(charsAlreadyTy= ped)) +- .toList(); +- } +- +- runTest(LocationSpec spec, [Map extraFiles]) { +- super.setUp(); +- return new Future(() { +- String content =3D spec.source; +- addFile(testFile, content); +- this.testCode =3D content; +- completionOffset =3D spec.testLocation; +- if (extraFiles !=3D null) { +- extraFiles.forEach((String fileName, String content) { +- addFile(fileName, content); +- }); +- } +- }).then((_) =3D> getSuggestions()).then((_) { +- filterResults(spec.source); +- for (String result in spec.positiveResults) { +- assertHasCompletion(result); +- } +- for (String result in spec.negativeResults) { +- assertHasNoCompletion(result); +- } +- }).whenComplete(() { +- super.tearDown(); +- }); +- } +-} +- +-/** +- * A specification of the completion results expected at a given location. +- */ +-class LocationSpec { +- String id; +- int testLocation =3D -1; +- List positiveResults =3D []; +- List negativeResults =3D []; +- String source; +- +- LocationSpec(this.id); +- +- /** +- * Parse a set of tests from the given `originalSource`. Return a list = of the +- * specifications that were parsed. +- * +- * The source string has test locations embedded in it, which are ident= ified +- * by '!X' where X is a single character. Each X is matched to positive= or +- * negative results in the array of [validationStrings]. Validation str= ings +- * contain the name of a prediction with a two character prefix. The fi= rst +- * character of the prefix corresponds to an X in the [originalSource].= The +- * second character is either a '+' or a '-' indicating whether the str= ing is +- * a positive or negative result. If logical not is needed in the sourc= e it +- * can be represented by '!!'. +- * +- * The [originalSource] is the source for a test that contains test loc= ations. +- * The [validationStrings] are the positive and negative predictions. +- */ +- static List from( +- String originalSource, List validationStrings) { +- Map tests =3D new HashMap= (); +- String modifiedSource =3D originalSource; +- int modifiedPosition =3D 0; +- while (true) { +- int index =3D modifiedSource.indexOf('!', modifiedPosition); +- if (index < 0) { +- break; +- } +- int n =3D 1; // only delete one char for double-bangs +- String id =3D modifiedSource.substring(index + 1, index + 2); +- if (id !=3D '!') { +- n =3D 2; +- LocationSpec test =3D new LocationSpec(id); +- tests[id] =3D test; +- test.testLocation =3D index; +- } else { +- modifiedPosition =3D index + 1; +- } +- modifiedSource =3D modifiedSource.substring(0, index) + +- modifiedSource.substring(index + n); +- } +- if (modifiedSource =3D=3D originalSource) { +- throw new StateError("No tests in source: " + originalSource); +- } +- for (String result in validationStrings) { +- if (result.length < 3) { +- throw new StateError("Invalid location result: " + result); +- } +- String id =3D result.substring(0, 1); +- String sign =3D result.substring(1, 2); +- String value =3D result.substring(2); +- LocationSpec test =3D tests[id]; +- if (test =3D=3D null) { +- throw new StateError("Invalid location result id: $id for: $resul= t"); +- } +- test.source =3D modifiedSource; +- if (sign =3D=3D '+') { +- test.positiveResults.add(value); +- } else if (sign =3D=3D '-') { +- test.negativeResults.add(value); +- } else { +- String err =3D "Invalid location result sign: $sign for: $result"; +- throw new StateError(err); +- } +- } +- List badPoints =3D []; +- List badResults =3D []; +- for (LocationSpec test in tests.values) { +- if (test.testLocation =3D=3D -1) { +- badPoints.add(test.id); +- } +- if (test.positiveResults.isEmpty && test.negativeResults.isEmpty) { +- badResults.add(test.id); +- } +- } +- if (!(badPoints.isEmpty && badResults.isEmpty)) { +- StringBuffer err =3D new StringBuffer(); +- if (!badPoints.isEmpty) { +- err.write("No test location for tests:"); +- for (String ch in badPoints) { +- err..write(' ')..write(ch); +- } +- err.write(' '); +- } +- if (!badResults.isEmpty) { +- err.write("No results for tests:"); +- for (String ch in badResults) { +- err..write(' ')..write(ch); +- } +- } +- throw new StateError(err.toString()); +- } +- return tests.values.toList(); +- } +-} +diff --git a/pkg/analysis_server/test/context_manager_test.dart b/pkg/anal= ysis_server/test/context_manager_test.dart +deleted file mode 100644 +index f63eaf8a7b3..00000000000 +--- a/pkg/analysis_server/test/context_manager_test.dart ++++ /dev/null +@@ -1,2695 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library test.context.directory.manager; +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/context_manager.dart'; +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analysis_server/src/utilities/null_string_sink.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/source/error_processor.dart'; +-import 'package:analyzer/src/context/builder.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/file_state.dart'; +-import 'package:analyzer/src/error/codes.dart'; +-import 'package:analyzer/src/generated/engine.dart' hide AnalysisResult; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/source_io.dart'; +-import 'package:analyzer/src/services/lint.dart'; +-import 'package:analyzer/src/summary/summary_file_builder.dart'; +-import 'package:analyzer/src/util/glob.dart'; +-import 'package:front_end/byte_store.dart'; +-import 'package:front_end/src/base/performance_logger.dart'; +-import 'package:linter/src/rules.dart'; +-import 'package:linter/src/rules/avoid_as.dart'; +-import 'package:path/path.dart' as path; +-import 'package:plugin/manager.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +-import 'package:watcher/watcher.dart'; +- +-import 'mock_sdk.dart'; +-import 'mocks.dart'; +-import 'src/plugin/plugin_manager_test.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AbstractContextManagerTest); +- defineReflectiveTests(ContextManagerWithNewOptionsTest); +- defineReflectiveTests(ContextManagerWithOldOptionsTest); +- }); +-} +- +-@reflectiveTest +-class AbstractContextManagerTest extends ContextManagerTest { +- void test_contextsInAnalysisRoot_nestedContext() { +- String subProjPath =3D path.posix.join(projPath, 'subproj'); +- Folder subProjFolder =3D resourceProvider.newFolder(subProjPath); +- resourceProvider.newFile( +- path.posix.join(subProjPath, 'pubspec.yaml'), 'contents'); +- String subProjFilePath =3D path.posix.join(subProjPath, 'file.dart'); +- resourceProvider.newFile(subProjFilePath, 'contents'); +- manager.setRoots([projPath], [], {}); +- // Make sure that there really are contexts for both the main project= and +- // the subproject. +- Folder projectFolder =3D resourceProvider.getFolder(projPath); +- ContextInfo projContextInfo =3D manager.getContextInfoFor(projectFold= er); +- expect(projContextInfo, isNotNull); +- expect(projContextInfo.folder, projectFolder); +- ContextInfo subProjContextInfo =3D manager.getContextInfoFor(subProjF= older); +- expect(subProjContextInfo, isNotNull); +- expect(subProjContextInfo.folder, subProjFolder); +- expect(projContextInfo.analysisDriver, +- isNot(equals(subProjContextInfo.analysisDriver))); +- // Check that getDriversInAnalysisRoot() works. +- List drivers =3D +- manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, isNotNull); +- expect(drivers, hasLength(2)); +- expect(drivers, contains(projContextInfo.analysisDriver)); +- expect(drivers, contains(subProjContextInfo.analysisDriver)); +- } +- +- @failingTest +- test_embedder_added() async { +- // NoSuchMethodError: The getter 'apiSignature' was called on null. +- // Receiver: null +- // Tried calling: apiSignature +- // dart:core = Object.noSuchMethod +- // package:analyzer/src/dart/analysis/driver.dart 460:20 = AnalysisDriver.configure +- // package:analysis_server/src/context_manager.dart 1043:16 = ContextManagerImpl._checkForPackagespecUpdate +- // package:analysis_server/src/context_manager.dart 1553:5 = ContextManagerImpl._handleWatchEvent +- //return super.test_embedder_added(); +- fail('NoSuchMethodError'); +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'nope.dart']); +- String embedderPath =3D newFolder([projPath, 'embedder']); +- newFile([embedderPath, 'entry.dart']); +- String embedderSrcPath =3D newFolder([projPath, 'embedder', 'src']); +- newFile([embedderSrcPath, 'part.dart']); +- +- // Setup _embedder.yaml. +- newFile([libPath, '_embedder.yaml'], r''' +-embedded_libs: +- "dart:foobar": "../embedder/entry.dart" +- "dart:typed_data": "../embedder/src/part" +- '''); +- +- Folder projectFolder =3D resourceProvider.newFolder(projPath); +- +- // NOTE that this is Not in our package path yet. +- +- // Setup context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- // Confirm that one driver / context was created. +- List drivers =3D +- manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, isNotNull); +- expect(drivers, hasLength(1)); +- +- // No embedded libs yet. +- expect(sourceFactory.forUri('dart:typed_data'), isNull); +- +- // Add .packages file that introduces a dependency with embedded libs. +- newFile([projPath, '.packages'], r''' +-test_pack:lib/'''); +- +- await pumpEventQueue(); +- +- // Confirm that we still have just one driver / context. +- drivers =3D manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, isNotNull); +- expect(drivers, hasLength(1)); +- +- // Embedded lib should be defined now. +- expect(sourceFactory.forUri('dart:typed_data'), isNotNull); +- } +- +- test_embedder_packagespec() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'nope.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Setup _embedder.yaml. +- newFile([libPath, '_embedder.yaml'], r''' +-embedded_libs: +- "dart:foobar": "../sdk_ext/entry.dart" +- "dart:typed_data": "../sdk_ext/src/part" +- '''); +- // Setup .packages file +- newFile([projPath, '.packages'], r''' +-test_pack:lib/'''); +- // Setup context. +- +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- // Confirm that one context was created. +- int count =3D manager +- .numberOfContextsInAnalysisRoot(resourceProvider.newFolder(projPa= th)); +- expect(count, equals(1)); +- var source =3D sourceFactory.forUri('dart:foobar'); +- expect(source, isNotNull); +- expect(source.fullName, '/my/proj/sdk_ext/entry.dart'); +- // We can't find dart:core because we didn't list it in our +- // embedded_libs map. +- expect(sourceFactory.forUri('dart:core'), isNull); +- // We can find dart:typed_data because we listed it in our +- // embedded_libs map. +- expect(sourceFactory.forUri('dart:typed_data'), isNotNull); +- } +- +- test_ignoreFilesInPackagesFolder() { +- // create a context with a pubspec.yaml file +- String pubspecPath =3D path.posix.join(projPath, 'pubspec.yaml'); +- resourceProvider.newFile(pubspecPath, 'pubspec'); +- // create a file in the "packages" folder +- String filePath1 =3D path.posix.join(projPath, 'packages', 'file1.dar= t'); +- resourceProvider.newFile(filePath1, 'contents'); +- // "packages" files are ignored initially +- manager.setRoots([projPath], [], {}); +- expect(callbacks.currentFilePaths, isEmpty); +- // "packages" files are ignored during watch +- String filePath2 =3D path.posix.join(projPath, 'packages', 'file2.dar= t'); +- resourceProvider.newFile(filePath2, 'contents'); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentFilePaths, isEmpty); +- }); +- } +- +- void test_isInAnalysisRoot_excluded() { +- // prepare paths +- String project =3D '/project'; +- String excludedFolder =3D '$project/excluded'; +- // set roots +- resourceProvider.newFolder(project); +- resourceProvider.newFolder(excludedFolder); +- manager.setRoots( +- [project], [excludedFolder], {}); +- // verify +- expect(manager.isInAnalysisRoot('$excludedFolder/test.dart'), isFalse= ); +- } +- +- void test_isInAnalysisRoot_inNestedContext() { +- String subProjPath =3D path.posix.join(projPath, 'subproj'); +- Folder subProjFolder =3D resourceProvider.newFolder(subProjPath); +- resourceProvider.newFile( +- path.posix.join(subProjPath, 'pubspec.yaml'), 'contents'); +- String subProjFilePath =3D path.posix.join(subProjPath, 'file.dart'); +- resourceProvider.newFile(subProjFilePath, 'contents'); +- manager.setRoots([projPath], [], {}); +- // Make sure that there really is a context for the subproject. +- ContextInfo subProjContextInfo =3D manager.getContextInfoFor(subProjF= older); +- expect(subProjContextInfo, isNotNull); +- expect(subProjContextInfo.folder, subProjFolder); +- // Check that isInAnalysisRoot() works. +- expect(manager.isInAnalysisRoot(subProjFilePath), isTrue); +- } +- +- void test_isInAnalysisRoot_inRoot() { +- manager.setRoots([projPath], [], {}); +- expect(manager.isInAnalysisRoot('$projPath/test.dart'), isTrue); +- } +- +- void test_isInAnalysisRoot_notInRoot() { +- manager.setRoots([projPath], [], {}); +- expect(manager.isInAnalysisRoot('/test.dart'), isFalse); +- } +- +- test_path_filter() async { +- // Setup context. +- Folder root =3D resourceProvider.newFolder(projPath); +- manager.setRoots([projPath], [], {}); +- expect(callbacks.currentFilePaths, isEmpty); +- // Set ignore patterns for context. +- ContextInfo rootInfo =3D manager.getContextInfoFor(root); +- manager.setIgnorePatternsForContext( +- rootInfo, ['sdk_ext/**', 'lib/ignoreme.dart']); +- // Start creating files. +- newFile([projPath, ContextManagerImpl.PUBSPEC_NAME]); +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'ignoreme.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Pump event loop so new files are discovered and added to context. +- await pumpEventQueue(); +- // Verify that ignored files were ignored. +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains('/my/proj/lib/main.dart')); +- } +- +- test_refresh_folder_with_packagespec() { +- // create a context with a .packages file +- String packagespecFile =3D path.posix.join(projPath, '.packages'); +- resourceProvider.newFile(packagespecFile, ''); +- manager.setRoots([projPath], [], {}); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- callbacks.now++; +- manager.refresh(null); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])= ); +- expect(callbacks.currentContextTimestamps[projPath], callbacks.no= w); +- }); +- }); +- } +- +- // TODO(paulberry): This test only tests PackagesFileDisposition. +- // Once http://dartbug.com/23909 is fixed, add a test for sdk extensions +- // and PackageMapDisposition. +- test_refresh_folder_with_packagespec_subfolders() { +- // Create a folder with no .packages file, containing two subfolders = with +- // .packages files. +- String subdir1Path =3D path.posix.join(projPath, 'subdir1'); +- String subdir2Path =3D path.posix.join(projPath, 'subdir2'); +- String packagespec1Path =3D path.posix.join(subdir1Path, '.packages'); +- String packagespec2Path =3D path.posix.join(subdir2Path, '.packages'); +- resourceProvider.newFile(packagespec1Path, ''); +- resourceProvider.newFile(packagespec2Path, ''); +- manager.setRoots([projPath], [], {}); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, +- unorderedEquals([subdir1Path, subdir2Path, projPath])); +- callbacks.now++; +- manager.refresh(null); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, +- unorderedEquals([subdir1Path, subdir2Path, projPath])); +- expect(callbacks.currentContextTimestamps[projPath], callbacks.no= w); +- expect(callbacks.currentContextTimestamps[subdir1Path], callbacks= .now); +- expect(callbacks.currentContextTimestamps[subdir2Path], callbacks= .now); +- }); +- }); +- } +- +- test_refresh_folder_with_pubspec() { +- // create a context with a pubspec.yaml file +- String pubspecPath =3D path.posix.join(projPath, 'pubspec.yaml'); +- resourceProvider.newFile(pubspecPath, 'pubspec'); +- manager.setRoots([projPath], [], {}); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- callbacks.now++; +- manager.refresh(null); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])= ); +- expect(callbacks.currentContextTimestamps[projPath], callbacks.no= w); +- }); +- }); +- } +- +- test_refresh_folder_with_pubspec_subfolders() { +- // Create a folder with no pubspec.yaml, containing two subfolders wi= th +- // pubspec.yaml files. +- String subdir1Path =3D path.posix.join(projPath, 'subdir1'); +- String subdir2Path =3D path.posix.join(projPath, 'subdir2'); +- String pubspec1Path =3D path.posix.join(subdir1Path, 'pubspec.yaml'); +- String pubspec2Path =3D path.posix.join(subdir2Path, 'pubspec.yaml'); +- resourceProvider.newFile(pubspec1Path, 'pubspec'); +- resourceProvider.newFile(pubspec2Path, 'pubspec'); +- manager.setRoots([projPath], [], {}); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, +- unorderedEquals([subdir1Path, subdir2Path, projPath])); +- callbacks.now++; +- manager.refresh(null); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, +- unorderedEquals([subdir1Path, subdir2Path, projPath])); +- expect(callbacks.currentContextTimestamps[projPath], callbacks.no= w); +- expect(callbacks.currentContextTimestamps[subdir1Path], callbacks= .now); +- expect(callbacks.currentContextTimestamps[subdir2Path], callbacks= .now); +- }); +- }); +- } +- +- test_refresh_oneContext() { +- // create two contexts with pubspec.yaml files +- String pubspecPath =3D path.posix.join(projPath, 'pubspec.yaml'); +- resourceProvider.newFile(pubspecPath, 'pubspec1'); +- +- String proj2Path =3D '/my/proj2'; +- resourceProvider.newFolder(proj2Path); +- String pubspec2Path =3D path.posix.join(proj2Path, 'pubspec.yaml'); +- resourceProvider.newFile(pubspec2Path, 'pubspec2'); +- +- List roots =3D [projPath, proj2Path]; +- manager.setRoots(roots, [], {}); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, unorderedEquals(roots)); +- int then =3D callbacks.now; +- callbacks.now++; +- manager.refresh([resourceProvider.getResource(proj2Path)]); +- return pumpEventQueue().then((_) { +- expect(callbacks.currentContextRoots, unorderedEquals(roots)); +- expect(callbacks.currentContextTimestamps[projPath], then); +- expect(callbacks.currentContextTimestamps[proj2Path], callbacks.n= ow); +- }); +- }); +- } +- +- test_sdk_ext_packagespec() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'nope.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Setup sdk extension mapping. +- newFile([libPath, '_sdkext'], r''' +-{ +- "dart:foobar": "../sdk_ext/entry.dart" +-} +-'''); +- // Setup .packages file +- newFile([projPath, '.packages'], r''' +-test_pack:lib/'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- // Confirm that one context was created. +- int count =3D manager +- .numberOfContextsInAnalysisRoot(resourceProvider.newFolder(projPa= th)); +- expect(count, equals(1)); +- var source =3D sourceFactory.forUri('dart:foobar'); +- expect(source.fullName, equals('/my/proj/sdk_ext/entry.dart')); +- } +- +- void test_setRoots_addFolderWithDartFile() { +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- resourceProvider.newFile(filePath, 'contents'); +- manager.setRoots([projPath], [], {}); +- // verify +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- List drivers =3D +- manager.getDriversInAnalysisRoot(resourceProvider.newFolder(projP= ath)); +- expect(drivers, hasLength(1)); +- expect(drivers[0], isNotNull); +- Source result =3D sourceFactory.forUri('dart:async'); +- expect(result, isNotNull); +- } +- +- void test_setRoots_addFolderWithDartFileInSubfolder() { +- String filePath =3D path.posix.join(projPath, 'foo', 'bar.dart'); +- resourceProvider.newFile(filePath, 'contents'); +- manager.setRoots([projPath], [], {}); +- // verify +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- } +- +- void test_setRoots_addFolderWithDummyLink() { +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- resourceProvider.newDummyLink(filePath); +- manager.setRoots([projPath], [], {}); +- // verify +- expect(callbacks.currentFilePaths, isEmpty); +- } +- +- void test_setRoots_addFolderWithNestedPackageSpec() { +- String examplePath =3D newFolder([projPath, ContextManagerTest.EXAMPL= E_NAME]); +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([examplePath, ContextManagerImpl.PACKAGE_SPEC_NAME]); +- newFile([examplePath, 'example.dart']); +- +- packageMapProvider.packageMap['proj'] =3D [ +- resourceProvider.getResource(libPath) +- ]; +- +- manager.setRoots([projPath], [], {}); +- +- expect(callbacks.currentContextRoots, hasLength(2)); +- +- expect(callbacks.currentContextRoots, contains(projPath)); +- Iterable projSources =3D callbacks.currentFileSources(projPat= h); +- expect(projSources, hasLength(1)); +- expect(projSources.first.uri.toString(), 'file:///my/proj/lib/main.da= rt'); +- +- expect(callbacks.currentContextRoots, contains(examplePath)); +- Iterable exampleSources =3D callbacks.currentFileSources(exam= plePath); +- expect(exampleSources, hasLength(1)); +- expect(exampleSources.first.uri.toString(), +- 'file:///my/proj/example/example.dart'); +- } +- +- void test_setRoots_addFolderWithNestedPubspec() { +- String examplePath =3D newFolder([projPath, ContextManagerTest.EXAMPL= E_NAME]); +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- +- newFile([projPath, ContextManagerImpl.PUBSPEC_NAME]); +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], 'proj:lib/'= ); +- newFile([libPath, 'main.dart']); +- newFile([examplePath, ContextManagerImpl.PUBSPEC_NAME]); +- newFile([examplePath, 'example.dart']); +- +- manager.setRoots([projPath], [], {}); +- +- expect(callbacks.currentContextRoots, hasLength(2)); +- +- expect(callbacks.currentContextRoots, contains(projPath)); +- Iterable projSources =3D callbacks.currentFileSources(projPat= h); +- expect(projSources, hasLength(1)); +- expect(projSources.first.uri.toString(), 'package:proj/main.dart'); +- +- expect(callbacks.currentContextRoots, contains(examplePath)); +- Iterable exampleSources =3D callbacks.currentFileSources(exam= plePath); +- expect(exampleSources, hasLength(1)); +- expect(exampleSources.first.uri.toString(), +- 'file:///my/proj/example/example.dart'); +- } +- +- void test_setRoots_addFolderWithoutPubspec() { +- packageMapProvider.packageMap =3D null; +- manager.setRoots([projPath], [], {}); +- // verify +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_addFolderWithPackagespec() { +- String packagespecPath =3D path.posix.join(projPath, '.packages'); +- resourceProvider.newFile(packagespecPath, +- 'unittest:file:///home/somebody/.pub/cache/unittest-0.9.9/lib/'); +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- File mainFile =3D +- resourceProvider.newFile(path.posix.join(libPath, 'main.dart'), '= '); +- Source source =3D mainFile.createSource(); +- +- manager.setRoots([projPath], [], {}); +- +- // verify +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- expect(callbacks.currentFilePaths, hasLength(1)); +- +- // smoketest resolution +- Source resolvedSource =3D +- sourceFactory.resolveUri(source, 'package:unittest/unittest.dart'= ); +- expect(resolvedSource, isNotNull); +- expect(resolvedSource.fullName, +- equals('/home/somebody/.pub/cache/unittest-0.9.9/lib/unittest.dar= t')); +- } +- +- void test_setRoots_addFolderWithPackagespecAndPackageRoot() { +- // The package root should take priority. +- String packagespecPath =3D path.posix.join(projPath, '.packages'); +- resourceProvider.newFile(packagespecPath, +- 'unittest:file:///home/somebody/.pub/cache/unittest-0.9.9/lib/'); +- String packageRootPath =3D '/package/root/'; +- manager.setRoots([projPath], [], +- {projPath: packageRootPath}); +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- _checkPackageRoot(projPath, packageRootPath); +- } +- +- void test_setRoots_addFolderWithPubspec() { +- String pubspecPath =3D path.posix.join(projPath, 'pubspec.yaml'); +- resourceProvider.newFile(pubspecPath, 'pubspec'); +- manager.setRoots([projPath], [], {}); +- // verify +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_addFolderWithPubspec_andPackagespec() { +- String pubspecPath =3D path.posix.join(projPath, 'pubspec.yaml'); +- String packagespecPath =3D path.posix.join(projPath, '.packages'); +- resourceProvider.newFile(pubspecPath, 'pubspec'); +- resourceProvider.newFile(packagespecPath, ''); +- manager.setRoots([projPath], [], {}); +- // verify +- callbacks.assertContextPaths([projPath]); +- } +- +- void test_setRoots_addFolderWithPubspecAndLib() { +- String binPath =3D newFolder([projPath, ContextManagerTest.BIN_NAME]); +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- String srcPath =3D newFolder([libPath, ContextManagerTest.SRC_NAME]); +- String testPath =3D newFolder([projPath, ContextManagerTest.TEST_NAME= ]); +- +- newFile([projPath, ContextManagerImpl.PUBSPEC_NAME]); +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], 'proj:lib/'= ); +- String appPath =3D newFile([binPath, 'app.dart']); +- newFile([libPath, 'main.dart']); +- newFile([srcPath, 'internal.dart']); +- String testFilePath =3D newFile([testPath, 'main_test.dart']); +- +- manager.setRoots([projPath], [], {}); +- Iterable sources =3D callbacks.currentFileSources(projPath); +- +- expect(callbacks.currentContextRoots, unorderedEquals([projPath])); +- expect(sources, hasLength(4)); +- List uris =3D +- sources.map((Source source) =3D> source.uri.toString()).toList(); +- expect(uris, contains('file://$appPath')); +- expect(uris, contains('package:proj/main.dart')); +- expect(uris, contains('package:proj/src/internal.dart')); +- expect(uris, contains('file://$testFilePath')); +- } +- +- void test_setRoots_addFolderWithPubspecAndPackagespecFolders() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProjectA =3D '$root/sub/aaa'; +- String subProjectB =3D '$root/sub/sub2/bbb'; +- String subProjectA_file =3D '$subProjectA/bin/a.dart'; +- String subProjectB_file =3D '$subProjectB/bin/b.dart'; +- // create files +- resourceProvider.newFile('$subProjectA/pubspec.yaml', 'pubspec'); +- resourceProvider.newFile('$subProjectB/pubspec.yaml', 'pubspec'); +- resourceProvider.newFile('$subProjectA/.packages', ''); +- resourceProvider.newFile('$subProjectB/.packages', ''); +- +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subProjectA_file, 'library a;'); +- resourceProvider.newFile(subProjectB_file, 'library b;'); +- +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProjectA, subProjectB]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProjectA, [subProjectA_file]); +- callbacks.assertContextFiles(subProjectB, [subProjectB_file]); +- } +- +- void test_setRoots_addFolderWithPubspecFolders() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String projectA =3D '$root/sub/aaa'; +- String projectALib =3D '$root/sub/aaa/lib'; +- String subProjectA_file =3D '$projectA/bin/a.dart'; +- String projectB =3D '$root/sub/sub2/bbb'; +- String projectBLib =3D '$root/sub/sub2/bbb/lib'; +- String subProjectB_file =3D '$projectB/bin/b.dart'; +- // create files +- newFile([projectA, ContextManagerImpl.PUBSPEC_NAME]); +- newFile([projectA, ContextManagerImpl.PACKAGE_SPEC_NAME], 'foo:lib/'); +- newFile([projectB, ContextManagerImpl.PUBSPEC_NAME]); +- newFile([projectB, ContextManagerImpl.PACKAGE_SPEC_NAME], 'bar:lib/'); +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subProjectA_file, 'library a;'); +- resourceProvider.newFile(subProjectB_file, 'library b;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, projectA, projectB]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(projectA, [subProjectA_file]); +- callbacks.assertContextFiles(projectB, [subProjectB_file]); +- // verify package maps +- expect(_packageMap(root), isEmpty); +- expect( +- _packageMap(projectA), +- equals({ +- 'foo': [resourceProvider.getFolder(projectALib)] +- })); +- expect( +- _packageMap(projectB), +- equals({ +- 'bar': [resourceProvider.getFolder(projectBLib)] +- })); +- } +- +- void test_setRoots_addPackageRoot() { +- String packagePathFoo =3D '/package1/foo'; +- String packageRootPath =3D '/package2/foo'; +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], +- 'foo:file:///package1/foo'); +- Folder packageFolder =3D resourceProvider.newFolder(packagePathFoo); +- List includedPaths =3D [projPath]; +- List excludedPaths =3D []; +- manager.setRoots(includedPaths, excludedPaths, {}); +- expect( +- _currentPackageMap, +- equals({ +- 'foo': [packageFolder] +- })); +- manager.setRoots(includedPaths, excludedPaths, +- {projPath: packageRootPath}); +- _checkPackageRoot(projPath, equals(packageRootPath)); +- } +- +- void test_setRoots_changePackageRoot() { +- String packageRootPath1 =3D '/package1'; +- String packageRootPath2 =3D '/package2'; +- List includedPaths =3D [projPath]; +- List excludedPaths =3D []; +- manager.setRoots(includedPaths, excludedPaths, +- {projPath: packageRootPath1}); +- _checkPackageRoot(projPath, equals(packageRootPath1)); +- manager.setRoots(includedPaths, excludedPaths, +- {projPath: packageRootPath2}); +- _checkPackageRoot(projPath, equals(packageRootPath2)); +- } +- +- void test_setRoots_exclude_newRoot_withExcludedFile() { +- // prepare paths +- String project =3D '/project'; +- String file1 =3D '$project/file1.dart'; +- String file2 =3D '$project/file2.dart'; +- // create files +- resourceProvider.newFile(file1, '// 1'); +- resourceProvider.newFile(file2, '// 2'); +- // set roots +- manager.setRoots([project], [file1], = {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file2]); +- } +- +- void test_setRoots_exclude_newRoot_withExcludedFolder() { +- // prepare paths +- String project =3D '/project'; +- String folderA =3D '$project/aaa'; +- String folderB =3D '$project/bbb'; +- String fileA =3D '$folderA/a.dart'; +- String fileB =3D '$folderB/b.dart'; +- // create files +- resourceProvider.newFile(fileA, 'library a;'); +- resourceProvider.newFile(fileB, 'library b;'); +- // set roots +- manager.setRoots([project], [folderB], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- } +- +- void test_setRoots_exclude_sameRoot_addExcludedFile() { +- // prepare paths +- String project =3D '/project'; +- String file1 =3D '$project/file1.dart'; +- String file2 =3D '$project/file2.dart'; +- // create files +- resourceProvider.newFile(file1, '// 1'); +- resourceProvider.newFile(file2, '// 2'); +- // set roots +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file1, file2]); +- // exclude "2" +- manager.setRoots([project], [file2], = {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file1]); +- } +- +- void test_setRoots_exclude_sameRoot_addExcludedFolder() { +- // prepare paths +- String project =3D '/project'; +- String folderA =3D '$project/aaa'; +- String folderB =3D '$project/bbb'; +- String fileA =3D '$folderA/a.dart'; +- String fileB =3D '$folderB/b.dart'; +- // create files +- resourceProvider.newFile(fileA, 'library a;'); +- resourceProvider.newFile(fileB, 'library b;'); +- // initially both "aaa/a" and "bbb/b" are included +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA, fileB]); +- // exclude "bbb/" +- manager.setRoots([project], [folderB], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- } +- +- void test_setRoots_exclude_sameRoot_removeExcludedFile() { +- // prepare paths +- String project =3D '/project'; +- String file1 =3D '$project/file1.dart'; +- String file2 =3D '$project/file2.dart'; +- // create files +- resourceProvider.newFile(file1, '// 1'); +- resourceProvider.newFile(file2, '// 2'); +- // set roots +- manager.setRoots([project], [file2], = {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file1]); +- // stop excluding "2" +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file1, file2]); +- } +- +- void test_setRoots_exclude_sameRoot_removeExcludedFile_inFolder() { +- // prepare paths +- String project =3D '/project'; +- String file1 =3D '$project/bin/file1.dart'; +- String file2 =3D '$project/bin/file2.dart'; +- // create files +- resourceProvider.newFile(file1, '// 1'); +- resourceProvider.newFile(file2, '// 2'); +- // set roots +- manager.setRoots([project], [file2], = {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file1]); +- // stop excluding "2" +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [file1, file2]); +- } +- +- void test_setRoots_exclude_sameRoot_removeExcludedFolder() { +- // prepare paths +- String project =3D '/project'; +- String folderA =3D '$project/aaa'; +- String folderB =3D '$project/bbb'; +- String fileA =3D '$folderA/a.dart'; +- String fileB =3D '$folderB/b.dart'; +- // create files +- resourceProvider.newFile(fileA, 'library a;'); +- resourceProvider.newFile(fileB, 'library b;'); +- // exclude "bbb/" +- manager.setRoots([project], [folderB], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- // stop excluding "bbb/" +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA, fileB]); +- } +- +- void test_setRoots_ignoreDocFolder() { +- String project =3D '/project'; +- String fileA =3D '$project/foo.dart'; +- String fileB =3D '$project/lib/doc/bar.dart'; +- String fileC =3D '$project/doc/bar.dart'; +- resourceProvider.newFile(fileA, ''); +- resourceProvider.newFile(fileB, ''); +- resourceProvider.newFile(fileC, ''); +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA, fileB]); +- } +- +- void test_setRoots_nested_includedByOuter_innerFirst() { +- String project =3D '/project'; +- String projectPubspec =3D '$project/pubspec.yaml'; +- String example =3D '$project/example'; +- String examplePubspec =3D '$example/pubspec.yaml'; +- // create files +- resourceProvider.newFile(projectPubspec, 'name: project'); +- resourceProvider.newFile(examplePubspec, 'name: example'); +- manager +- .setRoots([example, project], [], {}); +- // verify +- { +- ContextInfo rootInfo =3D manager.rootInfo; +- expect(rootInfo.children, hasLength(1)); +- { +- ContextInfo projectInfo =3D rootInfo.children[0]; +- expect(projectInfo.folder.path, project); +- expect(projectInfo.children, hasLength(1)); +- { +- ContextInfo exampleInfo =3D projectInfo.children[0]; +- expect(exampleInfo.folder.path, example); +- expect(exampleInfo.children, isEmpty); +- } +- } +- } +- expect(callbacks.currentContextRoots, unorderedEquals([project, examp= le])); +- } +- +- void test_setRoots_nested_includedByOuter_outerPubspec() { +- String project =3D '/project'; +- String projectPubspec =3D '$project/pubspec.yaml'; +- String example =3D '$project/example'; +- // create files +- resourceProvider.newFile(projectPubspec, 'name: project'); +- resourceProvider.newFolder(example); +- manager +- .setRoots([project, example], [], {}); +- // verify +- { +- ContextInfo rootInfo =3D manager.rootInfo; +- expect(rootInfo.children, hasLength(1)); +- { +- ContextInfo projectInfo =3D rootInfo.children[0]; +- expect(projectInfo.folder.path, project); +- expect(projectInfo.children, isEmpty); +- } +- } +- expect(callbacks.currentContextRoots, unorderedEquals([project])); +- } +- +- void test_setRoots_nested_includedByOuter_twoPubspecs() { +- String project =3D '/project'; +- String projectPubspec =3D '$project/pubspec.yaml'; +- String example =3D '$project/example'; +- String examplePubspec =3D '$example/pubspec.yaml'; +- // create files +- resourceProvider.newFile(projectPubspec, 'name: project'); +- resourceProvider.newFile(examplePubspec, 'name: example'); +- manager +- .setRoots([project, example], [], {}); +- // verify +- { +- ContextInfo rootInfo =3D manager.rootInfo; +- expect(rootInfo.children, hasLength(1)); +- { +- ContextInfo projectInfo =3D rootInfo.children[0]; +- expect(projectInfo.folder.path, project); +- expect(projectInfo.children, hasLength(1)); +- { +- ContextInfo exampleInfo =3D projectInfo.children[0]; +- expect(exampleInfo.folder.path, example); +- expect(exampleInfo.children, isEmpty); +- } +- } +- } +- expect(callbacks.currentContextRoots, unorderedEquals([project, examp= le])); +- } +- +- void test_setRoots_newFolderWithPackageRoot() { +- String packageRootPath =3D '/package'; +- manager.setRoots([projPath], [], +- {projPath: packageRootPath}); +- _checkPackageRoot(projPath, equals(packageRootPath)); +- } +- +- void test_setRoots_newlyAddedFoldersGetProperPackageMap() { +- String packagePath =3D '/package/foo'; +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], +- 'foo:file:///package/foo'); +- Folder packageFolder =3D resourceProvider.newFolder(packagePath); +- manager.setRoots([projPath], [], {}); +- expect( +- _currentPackageMap, +- equals({ +- 'foo': [packageFolder] +- })); +- } +- +- void test_setRoots_noContext_excludedFolder() { +- // prepare paths +- String project =3D '/project'; +- String excludedFolder =3D '$project/excluded'; +- String excludedPubspec =3D '$excludedFolder/pubspec.yaml'; +- // create files +- resourceProvider.newFile(excludedPubspec, 'name: ignore-me'); +- // set "/project", and exclude "/project/excluded" +- manager.setRoots( +- [project], [excludedFolder], {}); +- callbacks.assertContextPaths([project]); +- } +- +- void test_setRoots_noContext_inDotFolder() { +- String pubspecPath =3D path.posix.join(projPath, '.pub', 'pubspec.yam= l'); +- resourceProvider.newFile(pubspecPath, 'name: test'); +- manager.setRoots([projPath], [], {}); +- // verify +- expect(callbacks.currentContextRoots, hasLength(1)); +- expect(callbacks.currentContextRoots, contains(projPath)); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_noContext_inPackagesFolder() { +- String pubspecPath =3D path.posix.join(projPath, 'packages', 'pubspec= .yaml'); +- resourceProvider.newFile(pubspecPath, 'name: test'); +- manager.setRoots([projPath], [], {}); +- // verify +- expect(callbacks.currentContextRoots, hasLength(1)); +- expect(callbacks.currentContextRoots, contains(projPath)); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_packageResolver() { +- String filePath =3D path.posix.join(projPath, 'lib', 'foo.dart'); +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], 'foo:lib/'); +- resourceProvider.newFile(filePath, 'contents'); +- manager.setRoots([projPath], [], {}); +- +- var drivers =3D +- manager.getDriversInAnalysisRoot(resourceProvider.newFolder(projP= ath)); +- expect(drivers, hasLength(1)); +- expect(drivers[0], isNotNull); +- Source result =3D sourceFactory.forUri('package:foo/foo.dart'); +- expect(result.fullName, filePath); +- } +- +- void test_setRoots_pathContainsDotFile() { +- // If the path to a file (relative to the context root) contains a fo= lder +- // whose name begins with '.', then the file is ignored. +- String project =3D '/project'; +- String fileA =3D '$project/foo.dart'; +- String fileB =3D '$project/.pub/bar.dart'; +- resourceProvider.newFile(fileA, ''); +- resourceProvider.newFile(fileB, ''); +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- } +- +- void test_setRoots_removeFolderWithoutPubspec() { +- packageMapProvider.packageMap =3D null; +- // add one root - there is a context +- manager.setRoots([projPath], [], {}); +- expect(callbacks.currentContextRoots, hasLength(1)); +- // set empty roots - no contexts +- manager.setRoots([], [], {}); +- expect(callbacks.currentContextRoots, hasLength(0)); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_removeFolderWithPackagespec() { +- // create a pubspec +- String pubspecPath =3D path.posix.join(projPath, '.packages'); +- resourceProvider.newFile(pubspecPath, ''); +- // add one root - there is a context +- manager.setRoots([projPath], [], {}); +- expect(manager.changeSubscriptions, hasLength(1)); +- expect(callbacks.currentContextRoots, hasLength(1)); +- // set empty roots - no contexts +- manager.setRoots([], [], {}); +- expect(manager.changeSubscriptions, hasLength(0)); +- expect(callbacks.currentContextRoots, hasLength(0)); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_removeFolderWithPackagespecFolder() { +- // prepare paths +- String projectA =3D '/projectA'; +- String projectB =3D '/projectB'; +- String subProjectA =3D '$projectA/sub'; +- String subProjectB =3D '$projectB/sub'; +- String projectA_file =3D '$projectA/a.dart'; +- String projectB_file =3D '$projectB/a.dart'; +- String subProjectA_pubspec =3D '$subProjectA/.packages'; +- String subProjectB_pubspec =3D '$subProjectB/.packages'; +- String subProjectA_file =3D '$subProjectA/bin/sub_a.dart'; +- String subProjectB_file =3D '$subProjectB/bin/sub_b.dart'; +- // create files +- resourceProvider.newFile(projectA_file, '// a'); +- resourceProvider.newFile(projectB_file, '// b'); +- resourceProvider.newFile(subProjectA_pubspec, ''); +- resourceProvider.newFile(subProjectB_pubspec, ''); +- resourceProvider.newFile(subProjectA_file, '// sub-a'); +- resourceProvider.newFile(subProjectB_file, '// sub-b'); +- // set roots +- manager +- .setRoots([projectA, projectB], [], {}); +- callbacks +- .assertContextPaths([projectA, subProjectA, projectB, subProjectB= ]); +- callbacks.assertContextFiles(projectA, [projectA_file]); +- callbacks.assertContextFiles(projectB, [projectB_file]); +- callbacks.assertContextFiles(subProjectA, [subProjectA_file]); +- callbacks.assertContextFiles(subProjectB, [subProjectB_file]); +- // remove "projectB" +- manager.setRoots([projectA], [], {}); +- callbacks.assertContextPaths([projectA, subProjectA]); +- callbacks.assertContextFiles(projectA, [projectA_file]); +- callbacks.assertContextFiles(subProjectA, [subProjectA_file]); +- } +- +- void test_setRoots_removeFolderWithPubspec() { +- // create a pubspec +- String pubspecPath =3D path.posix.join(projPath, 'pubspec.yaml'); +- resourceProvider.newFile(pubspecPath, 'pubspec'); +- // add one root - there is a context +- manager.setRoots([projPath], [], {}); +- expect(callbacks.currentContextRoots, hasLength(1)); +- // set empty roots - no contexts +- manager.setRoots([], [], {}); +- expect(callbacks.currentContextRoots, hasLength(0)); +- expect(callbacks.currentFilePaths, hasLength(0)); +- } +- +- void test_setRoots_removeFolderWithPubspecFolder() { +- // prepare paths +- String projectA =3D '/projectA'; +- String projectB =3D '/projectB'; +- String subProjectA =3D '$projectA/sub'; +- String subProjectB =3D '$projectB/sub'; +- String projectA_file =3D '$projectA/a.dart'; +- String projectB_file =3D '$projectB/a.dart'; +- String subProjectA_pubspec =3D '$subProjectA/pubspec.yaml'; +- String subProjectB_pubspec =3D '$subProjectB/pubspec.yaml'; +- String subProjectA_file =3D '$subProjectA/bin/sub_a.dart'; +- String subProjectB_file =3D '$subProjectB/bin/sub_b.dart'; +- // create files +- resourceProvider.newFile(projectA_file, '// a'); +- resourceProvider.newFile(projectB_file, '// b'); +- resourceProvider.newFile(subProjectA_pubspec, 'pubspec'); +- resourceProvider.newFile(subProjectB_pubspec, 'pubspec'); +- resourceProvider.newFile(subProjectA_file, '// sub-a'); +- resourceProvider.newFile(subProjectB_file, '// sub-b'); +- // set roots +- manager +- .setRoots([projectA, projectB], [], {}); +- callbacks +- .assertContextPaths([projectA, subProjectA, projectB, subProjectB= ]); +- callbacks.assertContextFiles(projectA, [projectA_file]); +- callbacks.assertContextFiles(projectB, [projectB_file]); +- callbacks.assertContextFiles(subProjectA, [subProjectA_file]); +- callbacks.assertContextFiles(subProjectB, [subProjectB_file]); +- // remove "projectB" +- manager.setRoots([projectA], [], {}); +- callbacks.assertContextPaths([projectA, subProjectA]); +- callbacks.assertContextFiles(projectA, [projectA_file]); +- callbacks.assertContextFiles(subProjectA, [subProjectA_file]); +- } +- +- void test_setRoots_removePackageRoot() { +- String packagePathFoo =3D '/package1/foo'; +- String packageRootPath =3D '/package2/foo'; +- Folder packageFolder =3D resourceProvider.newFolder(packagePathFoo); +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], +- 'foo:file:///package1/foo'); +- List includedPaths =3D [projPath]; +- List excludedPaths =3D []; +- manager.setRoots(includedPaths, excludedPaths, +- {projPath: packageRootPath}); +- _checkPackageRoot(projPath, equals(packageRootPath)); +- manager.setRoots(includedPaths, excludedPaths, {}); +- expect( +- _currentPackageMap, +- equals({ +- 'foo': [packageFolder] +- })); +- } +- +- void test_setRoots_rootPathContainsDotFile() { +- // If the path to the context root itself contains a folder whose name +- // begins with '.', then that is not sufficient to cause any files in= the +- // context to be ignored. +- String project =3D '/.pub/project'; +- String fileA =3D '$project/foo.dart'; +- resourceProvider.newFile(fileA, ''); +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- } +- +- test_watch_addDummyLink() { +- manager.setRoots([projPath], [], {}); +- // empty folder initially +- expect(callbacks.currentFilePaths, isEmpty); +- // add link +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- resourceProvider.newDummyLink(filePath); +- // the link was ignored +- return pumpEventQueue().then((_) { +- expect(callbacks.currentFilePaths, isEmpty); +- }); +- } +- +- test_watch_addFile() { +- manager.setRoots([projPath], [], {}); +- // empty folder initially +- expect(callbacks.currentFilePaths, hasLength(0)); +- // add file +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- resourceProvider.newFile(filePath, 'contents'); +- // the file was added +- return pumpEventQueue().then((_) { +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- }); +- } +- +- test_watch_addFile_excluded() { +- // prepare paths +- String project =3D '/project'; +- String folderA =3D '$project/aaa'; +- String folderB =3D '$project/bbb'; +- String fileA =3D '$folderA/a.dart'; +- String fileB =3D '$folderB/b.dart'; +- // create files +- resourceProvider.newFile(fileA, 'library a;'); +- // set roots +- manager.setRoots([project], [folderB], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- // add a file, ignored as excluded +- resourceProvider.newFile(fileB, 'library b;'); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- }); +- } +- +- test_watch_addFile_inDocFolder_inner() { +- // prepare paths +- String project =3D '/project'; +- String fileA =3D '$project/a.dart'; +- String fileB =3D '$project/lib/doc/b.dart'; +- // create files +- resourceProvider.newFile(fileA, ''); +- // set roots +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- // add a "lib/doc" file, it is not ignored +- resourceProvider.newFile(fileB, ''); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA, fileB]); +- }); +- } +- +- test_watch_addFile_inDocFolder_topLevel() { +- // prepare paths +- String project =3D '/project'; +- String fileA =3D '$project/a.dart'; +- String fileB =3D '$project/doc/b.dart'; +- // create files +- resourceProvider.newFile(fileA, ''); +- // set roots +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- // add a "doc" file, it is ignored +- resourceProvider.newFile(fileB, ''); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- }); +- } +- +- test_watch_addFile_pathContainsDotFile() async { +- // If a file is added and the path to it (relative to the context roo= t) +- // contains a folder whose name begins with '.', then the file is ign= ored. +- String project =3D '/project'; +- String fileA =3D '$project/foo.dart'; +- String fileB =3D '$project/.pub/bar.dart'; +- resourceProvider.newFile(fileA, ''); +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- resourceProvider.newFile(fileB, ''); +- await pumpEventQueue(); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- } +- +- test_watch_addFile_rootPathContainsDotFile() async { +- // If a file is added and the path to the context contains a folder w= hose +- // name begins with '.', then the file is not ignored. +- String project =3D '/.pub/project'; +- String fileA =3D '$project/foo.dart'; +- String fileB =3D '$project/bar/baz.dart'; +- resourceProvider.newFile(fileA, ''); +- manager.setRoots([project], [], {}); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA]); +- resourceProvider.newFile(fileB, ''); +- await pumpEventQueue(); +- callbacks.assertContextPaths([project]); +- callbacks.assertContextFiles(project, [fileA, fileB]); +- } +- +- test_watch_addFileInSubfolder() { +- manager.setRoots([projPath], [], {}); +- // empty folder initially +- expect(callbacks.currentFilePaths, hasLength(0)); +- // add file in subfolder +- String filePath =3D path.posix.join(projPath, 'foo', 'bar.dart'); +- resourceProvider.newFile(filePath, 'contents'); +- // the file was added +- return pumpEventQueue().then((_) { +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- }); +- } +- +- test_watch_addPackagespec_toRoot() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String rootPackagespec =3D '$root/.packages'; +- // create files +- resourceProvider.newFile(rootFile, 'library root;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- // add packagespec - still just one root +- resourceProvider.newFile(rootPackagespec, ''); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile]); +- // TODO(pquitslund): verify that a new source factory is created -- +- // likely this will need to happen in a corresponding ServerContext= ManagerTest. +- }); +- } +- +- test_watch_addPackagespec_toSubFolder() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub/aaa'; +- String subPubspec =3D '$subProject/.packages'; +- String subFile =3D '$subProject/bin/a.dart'; +- // create files +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subFile, 'library a;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile, subFile]); +- // add .packages +- resourceProvider.newFile(subPubspec, ''); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- }); +- } +- +- test_watch_addPackagespec_toSubFolder_ofSubFolder() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub'; +- String subPubspec =3D '$subProject/.packages'; +- String subFile =3D '$subProject/bin/sub.dart'; +- String subSubPubspec =3D '$subProject/subsub/.packages'; +- // create files +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subPubspec, ''); +- resourceProvider.newFile(subFile, 'library sub;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- // add pubspec - ignore, because is already in a packagespec-based co= ntext +- resourceProvider.newFile(subSubPubspec, ''); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- }); +- } +- +- test_watch_addPackagespec_toSubFolder_withPubspec() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub/aaa'; +- String subPackagespec =3D '$subProject/.packages'; +- String subPubspec =3D '$subProject/pubspec.yaml'; +- String subFile =3D '$subProject/bin/a.dart'; +- // create files +- resourceProvider.newFile(subPubspec, 'pubspec'); +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subFile, 'library a;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProject]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- +- // add .packages +- resourceProvider.newFile(subPackagespec, ''); +- return pumpEventQueue().then((_) { +- // Should NOT create another context. +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- }); +- } +- +- test_watch_addPubspec_toRoot() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String rootPubspec =3D '$root/pubspec.yaml'; +- // create files +- resourceProvider.newFile(rootFile, 'library root;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- // add pubspec - still just one root +- resourceProvider.newFile(rootPubspec, 'pubspec'); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile]); +- }); +- } +- +- test_watch_addPubspec_toSubFolder() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub/aaa'; +- String subPubspec =3D '$subProject/pubspec.yaml'; +- String subFile =3D '$subProject/bin/a.dart'; +- // create files +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subFile, 'library a;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile, subFile]); +- // add pubspec +- resourceProvider.newFile(subPubspec, 'pubspec'); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- }); +- } +- +- test_watch_addPubspec_toSubFolder_ofSubFolder() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub'; +- String subPubspec =3D '$subProject/pubspec.yaml'; +- String subFile =3D '$subProject/bin/sub.dart'; +- String subSubPubspec =3D '$subProject/subsub/pubspec.yaml'; +- // create files +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subPubspec, 'pubspec'); +- resourceProvider.newFile(subFile, 'library sub;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- // add pubspec - ignore, because is already in a pubspec-based context +- resourceProvider.newFile(subSubPubspec, 'pubspec'); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- }); +- } +- +- test_watch_deleteFile() { +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- // add root with a file +- File file =3D resourceProvider.newFile(filePath, 'contents'); +- Folder projFolder =3D file.parent; +- manager.setRoots([projPath], [], {}); +- // the file was added +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- expect(file.exists, isTrue); +- expect(projFolder.exists, isTrue); +- // delete the file +- resourceProvider.deleteFile(filePath); +- return pumpEventQueue().then((_) { +- expect(file.exists, isFalse); +- expect(projFolder.exists, isTrue); +- return expect(callbacks.currentFilePaths, hasLength(0)); +- }); +- } +- +- test_watch_deleteFolder() { +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- // add root with a file +- File file =3D resourceProvider.newFile(filePath, 'contents'); +- Folder projFolder =3D file.parent; +- manager.setRoots([projPath], [], {}); +- // the file was added +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- expect(file.exists, isTrue); +- expect(projFolder.exists, isTrue); +- // delete the folder +- resourceProvider.deleteFolder(projPath); +- return pumpEventQueue().then((_) { +- expect(file.exists, isFalse); +- expect(projFolder.exists, isFalse); +- return expect(callbacks.currentFilePaths, hasLength(0)); +- }); +- } +- +- test_watch_deletePackagespec_fromRoot() { +- // prepare paths +- String root =3D '/root'; +- String rootPubspec =3D '$root/.packages'; +- String rootFile =3D '$root/root.dart'; +- // create files +- resourceProvider.newFile(rootPubspec, ''); +- resourceProvider.newFile(rootFile, 'library root;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile]); +- // delete the pubspec +- resourceProvider.deleteFile(rootPubspec); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile]); +- }); +- } +- +- test_watch_deletePackagespec_fromSubFolder() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub/aaa'; +- String subPubspec =3D '$subProject/.packages'; +- String subFile =3D '$subProject/bin/a.dart'; +- // create files +- resourceProvider.newFile(subPubspec, ''); +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subFile, 'library a;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProject]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- // delete the pubspec +- resourceProvider.deleteFile(subPubspec); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile, subFile]); +- }); +- } +- +- test_watch_deletePackagespec_fromSubFolder_withPubspec() { +- // prepare paths: +- // +- // root +- // root.dart +- // sub +- // aaa +- // .packages +- // pubspec.yaml +- // bin +- // a.dart +- // +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub/aaa'; +- String subPackagespec =3D '$subProject/.packages'; +- String subPubspec =3D '$subProject/pubspec.yaml'; +- String subFile =3D '$subProject/bin/a.dart'; +- // create files +- resourceProvider.newFile(subPackagespec, ''); +- resourceProvider.newFile(subPubspec, 'pubspec'); +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subFile, 'library a;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProject]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- // delete the packagespec +- resourceProvider.deleteFile(subPackagespec); +- return pumpEventQueue().then((_) { +- // Should NOT merge +- callbacks.assertContextPaths([root, subProject]); +- callbacks.assertContextFiles(subProject, [subFile]); +- }); +- } +- +- test_watch_deletePubspec_fromRoot() { +- // prepare paths +- String root =3D '/root'; +- String rootPubspec =3D '$root/pubspec.yaml'; +- String rootFile =3D '$root/root.dart'; +- // create files +- resourceProvider.newFile(rootPubspec, 'pubspec'); +- resourceProvider.newFile(rootFile, 'library root;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile]); +- // delete the pubspec +- resourceProvider.deleteFile(rootPubspec); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile]); +- }); +- } +- +- test_watch_deletePubspec_fromSubFolder() { +- // prepare paths +- String root =3D '/root'; +- String rootFile =3D '$root/root.dart'; +- String subProject =3D '$root/sub/aaa'; +- String subPubspec =3D '$subProject/pubspec.yaml'; +- String subFile =3D '$subProject/bin/a.dart'; +- // create files +- resourceProvider.newFile(subPubspec, 'pubspec'); +- resourceProvider.newFile(rootFile, 'library root;'); +- resourceProvider.newFile(subFile, 'library a;'); +- // set roots +- manager.setRoots([root], [], {}); +- callbacks.assertContextPaths([root, subProject]); +- // verify files +- callbacks.assertContextFiles(root, [rootFile]); +- callbacks.assertContextFiles(subProject, [subFile]); +- // delete the pubspec +- resourceProvider.deleteFile(subPubspec); +- return pumpEventQueue().then((_) { +- callbacks.assertContextPaths([root]); +- callbacks.assertContextFiles(root, [rootFile, subFile]); +- }); +- } +- +- test_watch_modifyFile() { +- String filePath =3D path.posix.join(projPath, 'foo.dart'); +- // add root with a file +- resourceProvider.newFile(filePath, 'contents'); +- manager.setRoots([projPath], [], {}); +- // the file was added +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- // TODO(brianwilkerson) Test when the file was modified +- // update the file +- callbacks.now++; +- resourceProvider.modifyFile(filePath, 'new contents'); +- return pumpEventQueue().then((_) { +- // TODO(brianwilkerson) Test when the file was modified +- }); +- } +- +- test_watch_modifyPackageMapDependency_fail() async { +- // create a dependency file +- String dependencyPath =3D path.posix.join(projPath, 'dep'); +- resourceProvider.newFile(dependencyPath, 'contents'); +- packageMapProvider.dependencies.add(dependencyPath); +- // create a Dart file +- String dartFilePath =3D path.posix.join(projPath, 'main.dart'); +- resourceProvider.newFile(dartFilePath, 'contents'); +- // the created context has the expected empty package map +- manager.setRoots([projPath], [], {}); +- expect(_currentPackageMap, isEmpty); +- // Change the package map dependency so that the packageMapProvider is +- // re-run, and arrange for it to return null from computePackageMap(). +- packageMapProvider.packageMap =3D null; +- resourceProvider.modifyFile(dependencyPath, 'new contents'); +- await pumpEventQueue(); +- // The package map should have been changed to null. +- expect(_currentPackageMap, isEmpty); +- } +- +- test_watch_modifyPackagespec() { +- String packagesPath =3D '$projPath/.packages'; +- String filePath =3D '$projPath/bin/main.dart'; +- +- resourceProvider.newFile(packagesPath, ''); +- resourceProvider.newFile(filePath, 'library main;'); +- +- manager.setRoots([projPath], [], {}); +- +- Iterable filePaths =3D callbacks.currentFilePaths; +- expect(filePaths, hasLength(1)); +- expect(filePaths, contains(filePath)); +- expect(_currentPackageMap, isEmpty); +- +- // update .packages +- callbacks.now++; +- resourceProvider.modifyFile(packagesPath, 'main:./lib/'); +- return pumpEventQueue().then((_) { +- // verify new package info +- expect(_currentPackageMap.keys, unorderedEquals(['main'])); +- }); +- } +- +- /** +- * Verify that package URI's for source files in [path] will be resolved +- * using a package root matching [expectation]. +- */ +- void _checkPackageRoot(String path, expectation) { +- // TODO(brianwilkerson) Figure out how to test this. Possibly by comp= aring +- // the contents of the package map (although that approach doesn't wo= rk at +- // the moment). +-// FolderDisposition disposition =3D callbacks.currentContextDispositi= ons[path]; +-// expect(disposition.packageRoot, expectation); +- // TODO(paulberry): we should also verify that the package map itself= is +- // correct. See dartbug.com/23909. +- } +-} +- +-abstract class ContextManagerTest { +- /** +- * The name of the 'bin' directory. +- */ +- static const String BIN_NAME =3D 'bin'; +- +- /** +- * The name of the 'example' directory. +- */ +- static const String EXAMPLE_NAME =3D 'example'; +- +- /** +- * The name of the 'lib' directory. +- */ +- static const String LIB_NAME =3D 'lib'; +- +- /** +- * The name of the 'src' directory. +- */ +- static const String SRC_NAME =3D 'src'; +- +- /** +- * The name of the 'test' directory. +- */ +- static const String TEST_NAME =3D 'test'; +- +- ContextManagerImpl manager; +- +- TestContextManagerCallbacks callbacks; +- +- MemoryResourceProvider resourceProvider; +- +- MockPackageMapProvider packageMapProvider; +- +- UriResolver packageResolver =3D null; +- +- String projPath =3D '/my/proj'; +- +- AnalysisError missing_required_param =3D new AnalysisError( +- new TestSource(), 0, 1, HintCode.MISSING_REQUIRED_PARAM, [ +- ['x'] +- ]); +- +- AnalysisError missing_return =3D +- new AnalysisError(new TestSource(), 0, 1, HintCode.MISSING_RETURN, [ +- ['x'] +- ]); +- +- AnalysisError invalid_assignment_error =3D +- new AnalysisError(new TestSource(), 0, 1, HintCode.INVALID_ASSIGNME= NT, [ +- ['x'], +- ['y'] +- ]); +- +- AnalysisError unused_local_variable =3D new AnalysisError( +- new TestSource(), 0, 1, HintCode.UNUSED_LOCAL_VARIABLE, [ +- ['x'] +- ]); +- +- List get analysisFilesGlobs { +- List patterns =3D [ +- '**/*.${AnalysisEngine.SUFFIX_DART}', +- '**/*.${AnalysisEngine.SUFFIX_HTML}', +- '**/*.${AnalysisEngine.SUFFIX_HTM}', +- '**/${AnalysisEngine.ANALYSIS_OPTIONS_FILE}', +- '**/${AnalysisEngine.ANALYSIS_OPTIONS_YAML_FILE}' +- ]; +- return patterns +- .map((pattern) =3D> new Glob(path.posix.separator, pattern)) +- .toList(); +- } +- +- AnalysisOptions get analysisOptions =3D> callbacks.analysisOptions; +- +- List get errorProcessors =3D> analysisOptions.errorProc= essors; +- +- List get lints =3D> analysisOptions.lintRules; +- +- SourceFactory get sourceFactory =3D> callbacks.sourceFactory; +- +- Map> get _currentPackageMap =3D> _packageMap(projP= ath); +- +- void deleteFile(List pathComponents) { +- String filePath =3D path.posix.joinAll(pathComponents); +- resourceProvider.deleteFile(filePath); +- } +- +- /** +- * TODO(brianwilkerson) This doesn't add the strong mode processor when= using +- * the new analysis driver. +- */ +- ErrorProcessor getProcessor(AnalysisError error) =3D> errorProcessors +- .firstWhere((ErrorProcessor p) =3D> p.appliesTo(error), orElse: () = =3D> null); +- +- String newFile(List pathComponents, [String content =3D '']) { +- String filePath =3D path.posix.joinAll(pathComponents); +- resourceProvider.newFile(filePath, content); +- return filePath; +- } +- +- String newFileFromBytes(List pathComponents, List bytes) { +- String filePath =3D path.posix.joinAll(pathComponents); +- resourceProvider.newFileWithBytes(filePath, bytes); +- return filePath; +- } +- +- String newFolder(List pathComponents) { +- String folderPath =3D path.posix.joinAll(pathComponents); +- resourceProvider.newFolder(folderPath); +- return folderPath; +- } +- +- void processRequiredPlugins() { +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- +- registerLintRules(); +- } +- +- UriResolver providePackageResolver(Folder folder) =3D> packageResolver; +- +- void setUp() { +- processRequiredPlugins(); +- resourceProvider =3D new MemoryResourceProvider(); +- resourceProvider.newFolder(projPath); +- packageMapProvider =3D new MockPackageMapProvider(); +- // Create an SDK in the mock file system. +- new MockSdk(generateSummaryFiles: true, resourceProvider: resourcePro= vider); +- DartSdkManager sdkManager =3D new DartSdkManager('/', true); +- manager =3D new ContextManagerImpl( +- resourceProvider, +- sdkManager, +- providePackageResolver, +- packageMapProvider, +- analysisFilesGlobs, +- InstrumentationService.NULL_SERVICE, +- new AnalysisOptionsImpl()); +- PerformanceLog logger =3D new PerformanceLog(new NullStringSink()); +- AnalysisDriverScheduler scheduler =3D new AnalysisDriverScheduler(log= ger); +- callbacks =3D new TestContextManagerCallbacks( +- resourceProvider, sdkManager, logger, scheduler); +- manager.callbacks =3D callbacks; +- } +- +- /** +- * Verify that package URI's for source files in [path] will be resolved +- * using a package root matching [expectation]. +- */ +- void _checkPackageRoot(String path, expectation) { +- // TODO(brianwilkerson) Figure out how to test this. Possibly by comp= aring +- // the contents of the package map (although that approach doesn't wo= rk at +- // the moment). +-// FolderDisposition disposition =3D callbacks.currentContextDispositi= ons[path]; +-// expect(disposition.packageRoot, expectation); +- // TODO(paulberry): we should also verify that the package map itself= is +- // correct. See dartbug.com/23909. +- } +- +- Map> _packageMap(String contextPath) { +- Folder folder =3D resourceProvider.getFolder(contextPath); +- ContextInfo info =3D manager.getContextInfoFor(folder); +- return info.analysisDriver.sourceFactory?.packageMap; +- } +-} +- +-@reflectiveTest +-class ContextManagerWithNewOptionsTest extends ContextManagerWithOptionsT= est { +- String get optionsFileName =3D> AnalysisEngine.ANALYSIS_OPTIONS_YAML_FI= LE; +-} +- +-@reflectiveTest +-class ContextManagerWithOldOptionsTest extends ContextManagerWithOptionsT= est { +- String get optionsFileName =3D> AnalysisEngine.ANALYSIS_OPTIONS_FILE; +-} +- +-abstract class ContextManagerWithOptionsTest extends ContextManagerTest { +- String get optionsFileName; +- +- test_analysis_options_file_delete() async { +- // Setup analysis options +- newFile([projPath, optionsFileName], r''' +-embedded_libs: +- "dart:foobar": "../sdk_ext/entry.dart" +-analyzer: +- language: +- enableStrictCallChecks: true +- errors: +- unused_local_variable: false +-linter: +- rules: +- - camel_case_types +-'''); +- +- // Setup context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- +- // Verify options were set. +- expect(errorProcessors, hasLength(1)); +- expect(lints, hasLength(1)); +- expect(analysisOptions.enableStrictCallChecks, isTrue); +- +- // Remove options. +- deleteFile([projPath, optionsFileName]); +- await pumpEventQueue(); +- +- // Verify defaults restored. +- expect(errorProcessors, isEmpty); +- expect(lints, isEmpty); +- expect(analysisOptions.enableStrictCallChecks, isFalse); +- } +- +- @failingTest +- test_analysis_options_file_delete_with_embedder() async { +- // This fails because the ContextBuilder doesn't pick up the strongMo= de +- // flag from the embedder.yaml file. +- // Setup _embedder.yaml. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, '_embedder.yaml'], r''' +-analyzer: +- strong-mode: true +- errors: +- missing_return: false +-linter: +- rules: +- - avoid_as +-'''); +- +- // Setup .packages file +- newFile([projPath, '.packages'], r''' +-test_pack:lib/'''); +- +- // Setup analysis options +- newFile([projPath, optionsFileName], r''' +-analyzer: +- language: +- enableStrictCallChecks: true +- errors: +- unused_local_variable: false +-linter: +- rules: +- - camel_case_types +-'''); +- +- // Setup context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- +- // Verify options were set. +- expect(analysisOptions.enableStrictCallChecks, isTrue); +- expect(analysisOptions.strongMode, isTrue); +- expect(errorProcessors, hasLength(2)); +- expect(lints, hasLength(2)); +- +- // Remove options. +- deleteFile([projPath, optionsFileName]); +- await pumpEventQueue(); +- +- // Verify defaults restored. +- expect(analysisOptions.enableStrictCallChecks, isFalse); +- expect(lints, hasLength(1)); +- expect(lints.first, new isInstanceOf()); +- expect(errorProcessors, hasLength(1)); +- expect(getProcessor(missing_return).severity, isNull); +- } +- +- test_analysis_options_include() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Setup analysis options file which includes another options file. +- newFile([projPath, optionsFileName], r''' +-include: other_options.yaml +-'''); +- newFile([projPath, 'other_options.yaml'], r''' +-analyzer: +- language: +- enableStrictCallChecks: true +- errors: +- unused_local_variable: false +-linter: +- rules: +- - camel_case_types +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- // Verify options were set. +- expect(analysisOptions.enableStrictCallChecks, isTrue); +- expect(errorProcessors, hasLength(1)); +- expect(lints, hasLength(1)); +- expect(lints[0].name, 'camel_case_types'); +- } +- +- test_analysis_options_include_package() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Setup package +- String booLibPosixPath =3D '/my/pkg/boo/lib'; +- newFile([booLibPosixPath, 'other_options.yaml'], r''' +-analyzer: +- language: +- enableStrictCallChecks: true +- errors: +- unused_local_variable: false +-linter: +- rules: +- - camel_case_types +-'''); +- // Setup analysis options file which includes another options file. +- newFile([projPath, ContextManagerImpl.PACKAGE_SPEC_NAME], +- 'boo:$booLibPosixPath\n'); +- newFile([projPath, optionsFileName], r''' +-include: package:boo/other_options.yaml +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- // Verify options were set. +- expect(analysisOptions.enableStrictCallChecks, isTrue); +- expect(errorProcessors, hasLength(1)); +- expect(lints, hasLength(1)); +- expect(lints[0].name, 'camel_case_types'); +- } +- +- test_analysis_options_parse_failure() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Setup analysis options file with ignore list. +- String optionsFilePath =3D newFile([projPath, optionsFileName], r''' +-; +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Check that an error was produced. +- TestNotificationManager notificationManager =3D callbacks.notificatio= nManager; +- var errors =3D notificationManager.recordedErrors; +- expect(errors, hasLength(1)); +- expect(errors[errors.keys.first][optionsFilePath], hasLength(1)); +- } +- +- test_deleteRoot_hasAnalysisOptions() async { +- newFile([projPath, optionsFileName], ''); +- +- // Add the root. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- +- // Remove the root, with the analysis options file. +- // No exceptions. +- resourceProvider.deleteFolder(projPath); +- await pumpEventQueue(); +- } +- +- @failingTest +- test_embedder_options() async { +- // This fails because the ContextBuilder doesn't pick up the strongMo= de +- // flag from the embedder.yaml file. +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([projPath, 'test', 'test.dart']); +- newFile([sdkExtPath, 'entry.dart']); +- List bytes =3D new SummaryBuilder([], null, true).build(); +- newFileFromBytes([projPath, 'sdk.ds'], bytes); +- // Setup _embedder.yaml. +- newFile([libPath, '_embedder.yaml'], r''' +-embedded_libs: +- "dart:foobar": "../sdk_ext/entry.dart" +-analyzer: +- strong-mode: true +- language: +- enableSuperMixins: true +- errors: +- missing_return: false +-linter: +- rules: +- - avoid_as +-'''); +- // Setup .packages file +- newFile([projPath, '.packages'], r''' +-test_pack:lib/'''); +- +- // Setup analysis options +- newFile([projPath, optionsFileName], r''' +-analyzer: +- exclude: +- - 'test/**' +- language: +- enableStrictCallChecks: true +- errors: +- unused_local_variable: false +-linter: +- rules: +- - camel_case_types +-'''); +- +- // Setup context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- +- // Confirm that one context was created. +- int count =3D manager +- .numberOfContextsInAnalysisRoot(resourceProvider.newFolder(projPa= th)); +- expect(count, equals(1)); +- +- // Verify options. +- // * from `_embedder.yaml`: +- expect(analysisOptions.strongMode, isTrue); +- expect(analysisOptions.enableSuperMixins, isTrue); +- // * from analysis options: +- expect(analysisOptions.enableStrictCallChecks, isTrue); +- +- // * verify tests are excluded +- expect( +- callbacks.currentContextFilePaths[projPath].keys, +- unorderedEquals( +- ['/my/proj/sdk_ext/entry.dart', '/my/proj/$optionsFileName'])= ); +- +- // Verify filter setup. +- expect(errorProcessors, hasLength(2)); +- +- // * (embedder.) +- expect(getProcessor(missing_return).severity, isNull); +- +- // * (options.) +- expect(getProcessor(unused_local_variable).severity, isNull); +- +- // Verify lints. +- var lintNames =3D lints.map((lint) =3D> lint.name); +- +- expect( +- lintNames, +- unorderedEquals( +- ['avoid_as' /* embedder */, 'camel_case_types' /* options */]= )); +- +- // Sanity check embedder libs. +- var source =3D sourceFactory.forUri('dart:foobar'); +- expect(source, isNotNull); +- expect(source.fullName, '/my/proj/sdk_ext/entry.dart'); +- } +- +- test_error_filter_analysis_option() async { +- // Create files. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- errors: +- unused_local_variable: ignore +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Verify filter setup. +- expect(errorProcessors, hasLength(1)); +- expect(getProcessor(unused_local_variable).severity, isNull); +- } +- +- test_error_filter_analysis_option_multiple_filters() async { +- // Create files. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- errors: +- invalid_assignment: ignore +- unused_local_variable: error +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Verify filter setup. +- expect(errorProcessors, hasLength(2)); +- +- expect(getProcessor(invalid_assignment_error).severity, isNull); +- expect(getProcessor(unused_local_variable).severity, ErrorSeverity.ER= ROR); +- } +- +- test_error_filter_analysis_option_synonyms() async { +- // Create files. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- errors: +- unused_local_variable: ignore +- ambiguous_import: false +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Verify filter setup. +- expect(errorProcessors, isNotNull); +- expect(errorProcessors, hasLength(2)); +- } +- +- test_error_filter_analysis_option_unpsecified() async { +- // Create files. +- newFile([projPath, optionsFileName], r''' +-analyzer: +-# errors: +-# unused_local_variable: ignore +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Verify filter setup. +- expect(errorProcessors, isEmpty); +- } +- +- @failingTest +- test_optionsFile_update_strongMode() async { +- // It appears that this fails because we are not correctly updating t= he +- // analysis options in the driver when the file is modified. +- //return super.test_optionsFile_update_strongMode(); +- // After a few other changes, the test now times out on my machine, s= o I'm +- // disabling it in order to prevent it from being flaky. +- fail('Test times out'); +- var file =3D resourceProvider.newFile('$projPath/bin/test.dart', r''' +-main() { +- var paths =3D []; +- var names =3D []; +- paths.addAll(names.map((s) =3D> s.length)); +-} +-'''); +- resourceProvider.newFile('$projPath/$optionsFileName', r''' +-analyzer: +- strong-mode: false +-'''); +- // Create the context. +- manager.setRoots([projPath], [], {}); +- await pumpEventQueue(); +- +- AnalysisResult result =3D await callbacks.currentDriver.getResult(fil= e.path); +- +- // Not strong mode - both in the context and the SDK context. +- AnalysisContext sdkContext =3D sourceFactory.dartSdk.context; +- expect(analysisOptions.strongMode, isFalse); +- expect(sdkContext.analysisOptions.strongMode, isFalse); +- expect(result.errors, isEmpty); +- +- // Update the options file - turn on 'strong-mode'. +- resourceProvider.updateFile('$projPath/$optionsFileName', r''' +-analyzer: +- strong-mode: true +-'''); +- await pumpEventQueue(); +- +- // Strong mode - both in the context and the SDK context. +- result =3D await callbacks.currentDriver.getResult(file.path); +- +- // Not strong mode - both in the context and the SDK context. +- sdkContext =3D sourceFactory.dartSdk.context; +- expect(analysisOptions.strongMode, isTrue); +- expect(sdkContext.analysisOptions.strongMode, isTrue); +- // The code is strong-mode clean. +- // Verify that TypeSystem was reset. +- expect(result.errors, isEmpty); +- } +- +- @failingTest +- test_path_filter_analysis_option() async { +- // This fails because we're not analyzing the analysis options file. +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'nope.dart']); +- String sdkExtPath =3D newFolder([projPath, 'sdk_ext']); +- newFile([sdkExtPath, 'entry.dart']); +- String sdkExtSrcPath =3D newFolder([projPath, 'sdk_ext', 'src']); +- newFile([sdkExtSrcPath, 'part.dart']); +- // Setup analysis options file with ignore list. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- exclude: +- - lib/nope.dart +- - 'sdk_ext/**' +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Verify that analysis options was parsed and the ignore patterns ap= plied. +- Folder projectFolder =3D resourceProvider.newFolder(projPath); +- var drivers =3D manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, hasLength(1)); +- AnalysisDriver driver =3D drivers[0]; +- expect( +- driver.addedFiles, +- unorderedEquals( +- ['/my/proj/lib/main.dart', '/my/proj/$optionsFileName'])); +- } +- +- test_path_filter_child_contexts_option() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'pubspec.yaml'], r''' +-name: foobar +-'''); +- String otherLibPath =3D newFolder([projPath, 'other_lib']); +- newFile([otherLibPath, 'entry.dart']); +- newFile([otherLibPath, 'pubspec.yaml'], r''' +-name: other_lib +-'''); +- // Setup analysis options file with ignore list that ignores the 'oth= er_lib' +- // directory by name. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- exclude: +- - 'other_lib' +-'''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- // Verify that the context in other_lib wasn't created and that the +- // context in lib was created. +- Folder projectFolder =3D resourceProvider.newFolder(projPath); +- var drivers =3D manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, hasLength(2)); +- expect(drivers[0].name, equals('/my/proj')); +- expect(drivers[1].name, equals('/my/proj/lib')); +- } +- +- test_path_filter_recursive_wildcard_child_contexts_option() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'pubspec.yaml'], r''' +- name: foobar +- '''); +- String otherLibPath =3D newFolder([projPath, 'other_lib']); +- newFile([otherLibPath, 'entry.dart']); +- newFile([otherLibPath, 'pubspec.yaml'], r''' +- name: other_lib +- '''); +- // Setup analysis options file with ignore list that ignores 'other_l= ib' +- // and all descendants. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- exclude: +- - 'other_lib/**' +- '''); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- +- // Verify that the context in other_lib wasn't created and that the +- // context in lib was created. +- Folder projectFolder =3D resourceProvider.newFolder(projPath); +- var drivers =3D manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, hasLength(2)); +- expect(drivers[0].name, equals('/my/proj')); +- expect(drivers[1].name, equals('/my/proj/lib')); +- } +- +- test_path_filter_wildcard_child_contexts_option() async { +- // Create files. +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- newFile([libPath, 'pubspec.yaml'], r''' +-name: foobar +-'''); +- String otherLibPath =3D newFolder([projPath, 'other_lib']); +- newFile([otherLibPath, 'entry.dart']); +- newFile([otherLibPath, 'pubspec.yaml'], r''' +-name: other_lib +-'''); +- // Setup analysis options file with ignore list that ignores 'other_l= ib' +- // and all immediate children. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- exclude: +- - 'other_lib/*' +-'''); +- // Setup context / driver. +- manager.setRoots([projPath], [], {}); +- +- Folder projectFolder =3D resourceProvider.newFolder(projPath); +- var drivers =3D manager.getDriversInAnalysisRoot(projectFolder); +- expect(drivers, hasLength(2)); +- expect(drivers[0].name, equals('/my/proj')); +- expect(drivers[1].name, equals('/my/proj/lib')); +- } +- +- void test_setRoots_nested_excludedByOuter() { +- String project =3D '/project'; +- String projectPubspec =3D '$project/pubspec.yaml'; +- String example =3D '$project/example'; +- String examplePubspec =3D '$example/pubspec.yaml'; +- // create files +- resourceProvider.newFile(projectPubspec, 'name: project'); +- resourceProvider.newFile(examplePubspec, 'name: example'); +- newFile([project, optionsFileName], r''' +-analyzer: +- exclude: +- - 'example' +-'''); +- manager +- .setRoots([project, example], [], {}); +- // verify +- { +- ContextInfo rootInfo =3D manager.rootInfo; +- expect(rootInfo.children, hasLength(1)); +- { +- ContextInfo projectInfo =3D rootInfo.children[0]; +- expect(projectInfo.folder.path, project); +- expect(projectInfo.children, hasLength(1)); +- { +- ContextInfo exampleInfo =3D projectInfo.children[0]; +- expect(exampleInfo.folder.path, example); +- expect(exampleInfo.children, isEmpty); +- } +- } +- } +- expect(callbacks.currentContextRoots, hasLength(2)); +- expect(callbacks.currentContextRoots, unorderedEquals([project, examp= le])); +- } +- +- void test_setRoots_nested_excludedByOuter_deep() { +- String a =3D '/a'; +- String c =3D '$a/b/c'; +- String aPubspec =3D '$a/pubspec.yaml'; +- String cPubspec =3D '$c/pubspec.yaml'; +- // create files +- resourceProvider.newFile(aPubspec, 'name: aaa'); +- resourceProvider.newFile(cPubspec, 'name: ccc'); +- newFile([a, optionsFileName], r''' +-analyzer: +- exclude: +- - 'b**' +-'''); +- manager.setRoots([a, c], [], {}); +- // verify +- { +- ContextInfo rootInfo =3D manager.rootInfo; +- expect(rootInfo.children, hasLength(1)); +- { +- ContextInfo aInfo =3D rootInfo.children[0]; +- expect(aInfo.folder.path, a); +- expect(aInfo.children, hasLength(1)); +- { +- ContextInfo cInfo =3D aInfo.children[0]; +- expect(cInfo.folder.path, c); +- expect(cInfo.children, isEmpty); +- } +- } +- } +- expect(callbacks.currentContextRoots, hasLength(2)); +- expect(callbacks.currentContextRoots, unorderedEquals([a, c])); +- } +- +- test_strong_mode_analysis_option() async { +- // Create files. +- newFile([projPath, optionsFileName], r''' +-analyzer: +- strong-mode: true +-'''); +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- newFile([libPath, 'main.dart']); +- // Setup context. +- manager.setRoots([projPath], [], {}); +- // Verify that analysis options was parsed and strong-mode set. +- expect(analysisOptions.strongMode, true); +- } +- +- test_watchEvents() async { +- String libPath =3D newFolder([projPath, ContextManagerTest.LIB_NAME]); +- manager.setRoots([projPath], [], {}); +- newFile([libPath, 'main.dart']); +- await new Future.delayed(new Duration(milliseconds: 1)); +- expect(callbacks.watchEvents, hasLength(1)); +- } +-} +- +-class TestContextManagerCallbacks extends ContextManagerCallbacks { +- /** +- * Source of timestamps stored in [currentContextFilePaths]. +- */ +- int now =3D 0; +- +- /** +- * The analysis driver that was created. +- */ +- AnalysisDriver currentDriver; +- +- /** +- * A table mapping paths to the analysis driver associated with that pa= th. +- */ +- Map driverMap =3D {}; +- +- /** +- * Map from context to the timestamp when the context was created. +- */ +- Map currentContextTimestamps =3D {}; +- +- /** +- * Map from context to (map from file path to timestamp of last event). +- */ +- final Map> currentContextFilePaths =3D +- >{}; +- +- /** +- * A map from the paths of contexts to a set of the sources that should= be +- * explicitly analyzed in those contexts. +- */ +- final Map> currentContextSources =3D +- >{}; +- +- /** +- * Resource provider used for this test. +- */ +- final ResourceProvider resourceProvider; +- +- /** +- * The manager managing the SDKs. +- */ +- final DartSdkManager sdkManager; +- +- /** +- * The logger used by the scheduler and the driver. +- */ +- final PerformanceLog logger; +- +- /** +- * The scheduler used by the driver. +- */ +- final AnalysisDriverScheduler scheduler; +- +- /** +- * The list of `flushedFiles` in the last [removeContext] invocation. +- */ +- List lastFlushedFiles; +- +- /** +- * The watch events that have been broadcast. +- */ +- List watchEvents =3D []; +- +- @override +- NotificationManager notificationManager =3D new TestNotificationManager= (); +- +- TestContextManagerCallbacks( +- this.resourceProvider, this.sdkManager, this.logger, this.scheduler= ); +- +- /** +- * Return the current set of analysis options. +- */ +- AnalysisOptions get analysisOptions =3D> currentDriver?.analysisOptions; +- +- /** +- * Return the paths to the context roots that currently exist. +- */ +- Iterable get currentContextRoots { +- return currentContextTimestamps.keys; +- } +- +- /** +- * Return the paths to the files being analyzed in the current context = root. +- */ +- Iterable get currentFilePaths { +- if (currentDriver =3D=3D null) { +- return []; +- } +- return currentDriver.addedFiles; +- } +- +- /** +- * Return the current source factory. +- */ +- SourceFactory get sourceFactory =3D> currentDriver?.sourceFactory; +- +- @override +- AnalysisDriver addAnalysisDriver( +- Folder folder, ContextRoot contextRoot, AnalysisOptions options) { +- String path =3D folder.path; +- expect(currentContextRoots, isNot(contains(path))); +- expect(contextRoot, isNotNull); +- expect(contextRoot.root, path); +- currentContextTimestamps[path] =3D now; +- +- ContextBuilder builder =3D +- createContextBuilder(folder, options, useSummaries: true); +- AnalysisContext context =3D builder.buildContext(folder.path); +- SourceFactory sourceFactory =3D context.sourceFactory; +- AnalysisOptions analysisOptions =3D context.analysisOptions; +- context.dispose(); +- +- currentDriver =3D new AnalysisDriver( +- scheduler, +- logger, +- resourceProvider, +- new MemoryByteStore(), +- new FileContentOverlay(), +- contextRoot, +- sourceFactory, +- analysisOptions); +- driverMap[path] =3D currentDriver; +- currentDriver.exceptions.listen((ExceptionResult result) { +- AnalysisEngine.instance.logger +- .logError('Analysis failed: ${result.path}', result.exception); +- }); +- return currentDriver; +- } +- +- @override +- void afterWatchEvent(WatchEvent event) {} +- +- @override +- void applyChangesToContext(Folder contextFolder, ChangeSet changeSet) { +- AnalysisDriver driver =3D driverMap[contextFolder.path]; +- if (driver !=3D null) { +- changeSet.addedSources.forEach((source) { +- driver.addFile(source.fullName); +- }); +- changeSet.changedSources.forEach((source) { +- driver.changeFile(source.fullName); +- }); +- changeSet.removedSources.forEach((source) { +- driver.removeFile(source.fullName); +- }); +- } +- } +- +- @override +- void applyFileRemoved(AnalysisDriver driver, String file) { +- driver.removeFile(file); +- } +- +- void assertContextFiles(String contextPath, List expectedFiles)= { +- expect(getCurrentFilePaths(contextPath), unorderedEquals(expectedFile= s)); +- } +- +- void assertContextPaths(List expected) { +- expect(currentContextRoots, unorderedEquals(expected)); +- } +- +- @override +- void broadcastWatchEvent(WatchEvent event) { +- watchEvents.add(event); +- } +- +- @override +- void computingPackageMap(bool computing) { +- // Do nothing. +- } +- +- @override +- ContextBuilder createContextBuilder(Folder folder, AnalysisOptions opti= ons, +- {bool useSummaries =3D false}) { +- ContextBuilderOptions builderOptions =3D new ContextBuilderOptions(); +- builderOptions.defaultOptions =3D options; +- ContextBuilder builder =3D new ContextBuilder( +- resourceProvider, sdkManager, new ContentCache(), +- options: builderOptions); +- return builder; +- } +- +- /** +- * Return the paths to the files being analyzed in the current context = root. +- */ +- Iterable currentFileSources(String contextPath) { +- if (currentDriver =3D=3D null) { +- return []; +- } +- AnalysisDriver driver =3D driverMap[contextPath]; +- SourceFactory sourceFactory =3D driver.sourceFactory; +- return driver.addedFiles.map((String path) { +- File file =3D resourceProvider.getFile(path); +- Source source =3D file.createSource(); +- Uri uri =3D sourceFactory.restoreUri(source); +- return file.createSource(uri); +- }); +- } +- +- /** +- * Return the paths to the files being analyzed in the current context = root. +- */ +- Iterable getCurrentFilePaths(String contextPath) { +- if (currentDriver =3D=3D null) { +- return []; +- } +- return driverMap[contextPath].addedFiles; +- } +- +- @override +- void moveContext(Folder from, Folder to) { +- String path =3D from.path; +- String path2 =3D to.path; +- expect(currentContextFilePaths, contains(path)); +- expect(currentContextTimestamps, contains(path)); +- expect(currentContextSources, contains(path)); +- expect(currentContextFilePaths, isNot(contains(path2))); +- expect(currentContextTimestamps, isNot(contains(path2))); +- expect(currentContextSources, isNot(contains(path2))); +- currentContextFilePaths[path2] =3D currentContextFilePaths.remove(pat= h); +- currentContextTimestamps[path2] =3D currentContextTimestamps.remove(p= ath); +- currentContextSources[path2] =3D currentContextSources.remove(path); +- } +- +- @override +- void removeContext(Folder folder, List flushedFiles) { +- String path =3D folder.path; +- expect(currentContextRoots, contains(path)); +- currentContextTimestamps.remove(path); +- currentContextFilePaths.remove(path); +- currentContextSources.remove(path); +- lastFlushedFiles =3D flushedFiles; +- } +-} +- +-/** +- * A [Source] that knows it's [fullName]. +- */ +-class TestSource implements Source { +- TestSource(); +- +- @override +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +-} +- +-class TestUriResolver extends UriResolver { +- Map uriMap; +- +- TestUriResolver(this.uriMap); +- +- @override +- Source resolveAbsolute(Uri uri, [Uri actualUri]) { +- return uriMap[uri]; +- } +-} +diff --git a/pkg/analysis_server/test/domain_analysis_test.dart b/pkg/anal= ysis_server/test/domain_analysis_test.dart +deleted file mode 100644 +index 334e7f98191..00000000000 +--- a/pkg/analysis_server/test/domain_analysis_test.dart ++++ /dev/null +@@ -1,790 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/domain_analysis.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:plugin/manager.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'analysis_abstract.dart'; +-import 'mock_sdk.dart'; +-import 'mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisDomainTest); +- defineReflectiveTests(SetSubscriptionsTest); +- }); +- +- MockServerChannel serverChannel; +- MemoryResourceProvider resourceProvider; +- AnalysisServer server; +- AnalysisDomainHandler handler; +- +- void processRequiredPlugins() { +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- } +- +- setUp(() { +- serverChannel =3D new MockServerChannel(); +- resourceProvider =3D new MemoryResourceProvider(); +- processRequiredPlugins(); +- // Create an SDK in the mock file system. +- new MockSdk(resourceProvider: resourceProvider); +- server =3D new AnalysisServer( +- serverChannel, +- resourceProvider, +- new MockPackageMapProvider(), +- new AnalysisServerOptions(), +- new DartSdkManager('/', false), +- InstrumentationService.NULL_SERVICE); +- handler =3D new AnalysisDomainHandler(server); +- }); +- +- group('updateContent', testUpdateContent); +- +- group('AnalysisDomainHandler', () { +- // TODO(brianwilkerson) Re-enable these tests if we re-enable the +- // analysis.getReachableSources request. +-// group('getReachableSources', () { +-// test('valid sources', () async { +-// String fileA =3D '/project/a.dart'; +-// String fileB =3D '/project/b.dart'; +-// resourceProvider.newFile(fileA, 'import "b.dart";'); +-// resourceProvider.newFile(fileB, ''); +-// +-// server.setAnalysisRoots('0', ['/project/'], [], {}); +-// +-// await server.onAnalysisComplete; +-// +-// var request =3D +-// new AnalysisGetReachableSourcesParams(fileA).toRequest('0'); +-// var response =3D handler.handleRequest(request); +-// +-// Map json =3D response.toJson()[Response.RESULT]; +-// +-// // Sanity checks. +-// expect(json['sources'], hasLength(6)); +-// expect(json['sources']['file:///project/a.dart'], +-// unorderedEquals(['dart:core', 'file:///project/b.dart'])); +-// expect(json['sources']['file:///project/b.dart'], ['dart:core']= ); +-// }); +-// +-// test('invalid source', () async { +-// resourceProvider.newFile('/project/a.dart', 'import "b.dart";'); +-// server.setAnalysisRoots('0', ['/project/'], [], {}); +-// +-// await server.onAnalysisComplete; +-// +-// var request =3D +-// new AnalysisGetReachableSourcesParams('/does/not/exist.dart= ') +-// .toRequest('0'); +-// var response =3D handler.handleRequest(request); +-// expect(response.error, isNotNull); +-// expect(response.error.code, +-// RequestErrorCode.GET_REACHABLE_SOURCES_INVALID_FILE); +-// }); +-// }); +- +- group('setAnalysisRoots', () { +- Response testSetAnalysisRoots( +- List included, List excluded) { +- Request request =3D new AnalysisSetAnalysisRootsParams(included, = excluded) +- .toRequest('0'); +- return handler.handleRequest(request); +- } +- +- group('excluded', () { +- test('excluded folder', () async { +- String fileA =3D '/project/aaa/a.dart'; +- String fileB =3D '/project/bbb/b.dart'; +- resourceProvider.newFile(fileA, '// a'); +- resourceProvider.newFile(fileB, '// b'); +- var response =3D testSetAnalysisRoots(['/project'], ['/project/= bbb']); +- expect(response, isResponseSuccess('0')); +- }); +- +- test('not absolute', () async { +- var response =3D testSetAnalysisRoots([], ['foo/bar']); +- expect( +- response, +- isResponseFailure( +- '0', RequestErrorCode.INVALID_FILE_PATH_FORMAT)); +- }); +- +- test('not normalized', () async { +- var response =3D testSetAnalysisRoots([], ['/foo/../bar']); +- expect( +- response, +- isResponseFailure( +- '0', RequestErrorCode.INVALID_FILE_PATH_FORMAT)); +- }); +- }); +- +- group('included', () { +- test('new folder', () async { +- String file =3D '/project/bin/test.dart'; +- resourceProvider.newFile('/project/pubspec.yaml', 'name: projec= t'); +- resourceProvider.newFile(file, 'main() {}'); +- var response =3D testSetAnalysisRoots(['/project'], []); +- var serverRef =3D server; +- expect(response, isResponseSuccess('0')); +- // verify that unit is resolved eventually +- await server.onAnalysisComplete; +- var unit =3D await serverRef.getResolvedCompilationUnit(file); +- expect(unit, isNotNull); +- }); +- +- test('nonexistent folder', () async { +- String fileB =3D '/project_b/b.dart'; +- resourceProvider.newFile(fileB, '// b'); +- var response =3D testSetAnalysisRoots(['/project_a', '/project_= b'], []); +- var serverRef =3D server; +- expect(response, isResponseSuccess('0')); +- // Non-existence of /project_a should not prevent files in /pro= ject_b +- // from being analyzed. +- await server.onAnalysisComplete; +- var unit =3D await serverRef.getResolvedCompilationUnit(fileB); +- expect(unit, isNotNull); +- }); +- +- test('not absolute', () async { +- var response =3D testSetAnalysisRoots(['foo/bar'], []); +- expect( +- response, +- isResponseFailure( +- '0', RequestErrorCode.INVALID_FILE_PATH_FORMAT)); +- }); +- +- test('not normalized', () async { +- var response =3D testSetAnalysisRoots(['/foo/../bar'], []); +- expect( +- response, +- isResponseFailure( +- '0', RequestErrorCode.INVALID_FILE_PATH_FORMAT)); +- }); +- }); +- }); +- +- group('setPriorityFiles', () { +- test('invalid', () { +- var request =3D new AnalysisSetPriorityFilesParams(['/project/lib= .dart']) +- .toRequest('0'); +- var response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- }); +- +- test('valid', () { +- resourceProvider.newFolder('/p1'); +- resourceProvider.newFile('/p1/a.dart', 'library a;'); +- resourceProvider.newFolder('/p2'); +- resourceProvider.newFile('/p2/b.dart', 'library b;'); +- resourceProvider.newFile('/p2/c.dart', 'library c;'); +- +- var setRootsRequest =3D +- new AnalysisSetAnalysisRootsParams(['/p1', '/p2'], []) +- .toRequest('0'); +- var setRootsResponse =3D handler.handleRequest(setRootsRequest); +- expect(setRootsResponse, isResponseSuccess('0')); +- +- void setPriorityFiles(List fileList) { +- var request =3D +- new AnalysisSetPriorityFilesParams(fileList).toRequest('0'); +- var response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- // TODO(brianwilkerson) Enable the line below after getPriority= Files +- // has been implemented. +- // expect(server.getPriorityFiles(), unorderedEquals(fileList)); +- } +- +- setPriorityFiles(['/p1/a.dart', '/p2/b.dart']); +- setPriorityFiles(['/p2/b.dart', '/p2/c.dart']); +- setPriorityFiles([]); +- }); +- }); +- +- group('updateOptions', () { +- test('invalid', () { +- var request =3D new Request('0', ANALYSIS_REQUEST_UPDATE_OPTIONS,= { +- ANALYSIS_REQUEST_UPDATE_OPTIONS_OPTIONS: {'not-an-option': true} +- }); +- var response =3D handler.handleRequest(request); +- // Invalid options should be silently ignored. +- expect(response, isResponseSuccess('0')); +- }); +- +- test('null', () { +- // null is allowed as a synonym for {}. +- var request =3D new Request('0', ANALYSIS_REQUEST_UPDATE_OPTIONS, +- {ANALYSIS_REQUEST_UPDATE_OPTIONS_OPTIONS: null}); +- var response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- }); +- }); +- }); +-} +- +-testUpdateContent() { +- test('bad type', () { +- AnalysisTestHelper helper =3D new AnalysisTestHelper(); +- helper.createSingleFileProject('// empty'); +- return helper.onAnalysisComplete.then((_) { +- Request request =3D new Request('0', ANALYSIS_REQUEST_UPDATE_CONTEN= T, { +- ANALYSIS_REQUEST_UPDATE_CONTENT_FILES: { +- helper.testFile: { +- 'type': 'foo', +- } +- } +- }); +- Response response =3D helper.handler.handleRequest(request); +- expect(response, isResponseFailure('0')); +- }); +- }); +- +- test('full content', () { +- AnalysisTestHelper helper =3D new AnalysisTestHelper(); +- helper.createSingleFileProject('// empty'); +- return helper.onAnalysisComplete.then((_) { +- // no errors initially +- List errors =3D helper.getTestErrors(); +- expect(errors, isEmpty); +- // update code +- helper.sendContentChange(new AddContentOverlay('library lib')); +- // wait, there is an error +- return helper.onAnalysisComplete.then((_) { +- List errors =3D helper.getTestErrors(); +- expect(errors, hasLength(1)); +- }); +- }); +- }); +- +- test('incremental', () { +- AnalysisTestHelper helper =3D new AnalysisTestHelper(); +- String initialContent =3D 'library A;'; +- helper.createSingleFileProject(initialContent); +- return helper.onAnalysisComplete.then((_) { +- // no errors initially +- List errors =3D helper.getTestErrors(); +- expect(errors, isEmpty); +- // Add the file to the cache +- helper.sendContentChange(new AddContentOverlay(initialContent)); +- // update code +- helper.sendContentChange(new ChangeContentOverlay( +- [new SourceEdit('library '.length, 'A;'.length, 'lib')])); +- // wait, there is an error +- return helper.onAnalysisComplete.then((_) { +- List errors =3D helper.getTestErrors(); +- expect(errors, hasLength(1)); +- }); +- }); +- }); +- +- test('change on disk, normal', () { +- AnalysisTestHelper helper =3D new AnalysisTestHelper(); +- helper.createSingleFileProject('library A;'); +- return helper.onAnalysisComplete.then((_) { +- // There should be no errors +- expect(helper.getTestErrors(), hasLength(0)); +- // Change file on disk, adding a syntax error. +- helper.resourceProvider.modifyFile(helper.testFile, 'library lib'); +- // There should be errors now. +- return pumpEventQueue().then((_) { +- return helper.onAnalysisComplete.then((_) { +- expect(helper.getTestErrors(), hasLength(1)); +- }); +- }); +- }); +- }); +- +- test('change on disk, during override', () { +- AnalysisTestHelper helper =3D new AnalysisTestHelper(); +- helper.createSingleFileProject('library A;'); +- return helper.onAnalysisComplete.then((_) { +- // update code +- helper.sendContentChange(new AddContentOverlay('library B;')); +- // There should be no errors +- return helper.onAnalysisComplete.then((_) { +- expect(helper.getTestErrors(), hasLength(0)); +- // Change file on disk, adding a syntax error. +- helper.resourceProvider.modifyFile(helper.testFile, 'library lib'= ); +- // There should still be no errors (file should not have been rer= ead). +- return helper.onAnalysisComplete.then((_) { +- expect(helper.getTestErrors(), hasLength(0)); +- // Send a content change with a null content param--file should= be +- // reread from disk. +- helper.sendContentChange(new RemoveContentOverlay()); +- // There should be errors now. +- return helper.onAnalysisComplete.then((_) { +- expect(helper.getTestErrors(), hasLength(1)); +- }); +- }); +- }); +- }); +- }); +- +- group('out of range', () { +- Future outOfRangeTest(SourceEdit edit) { +- AnalysisTestHelper helper =3D new AnalysisTestHelper(); +- helper.createSingleFileProject('library A;'); +- return helper.onAnalysisComplete.then((_) { +- helper.sendContentChange(new AddContentOverlay('library B;')); +- return helper.onAnalysisComplete.then((_) { +- ChangeContentOverlay contentChange =3D new ChangeContentOverlay= ([edit]); +- Request request =3D +- new AnalysisUpdateContentParams({helper.testFile: contentCh= ange}) +- .toRequest('0'); +- Response response =3D helper.handler.handleRequest(request); +- expect(response, +- isResponseFailure('0', RequestErrorCode.INVALID_OVERLAY_CHA= NGE)); +- }); +- }); +- } +- +- test('negative length', () { +- return outOfRangeTest(new SourceEdit(3, -1, 'foo')); +- }); +- +- test('negative offset', () { +- return outOfRangeTest(new SourceEdit(-1, 3, 'foo')); +- }); +- +- test('beyond end', () { +- return outOfRangeTest(new SourceEdit(6, 6, 'foo')); +- }); +- }); +-} +- +-@reflectiveTest +-class AnalysisDomainTest extends AbstractAnalysisTest { +- Map> filesErrors =3D {}; +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ERRORS) { +- var decoded =3D new AnalysisErrorsParams.fromNotification(notificat= ion); +- filesErrors[decoded.file] =3D decoded.errors; +- } +- } +- +- test_setRoots_packages() { +- // prepare package +- String pkgFile =3D '/packages/pkgA/libA.dart'; +- resourceProvider.newFile(pkgFile, ''' +-library lib_a; +-class A {} +-'''); +- resourceProvider.newFile( +- '/project/.packages', 'pkgA:file:///packages/pkgA'); +- addTestFile(''' +-import 'package:pkgA/libA.dart'; +-main(A a) { +-} +-'''); +- // create project and wait for analysis +- createProject(); +- return waitForTasksFinished().then((_) { +- // if 'package:pkgA/libA.dart' was resolved, then there are no erro= rs +- expect(filesErrors[testFile], isEmpty); +- // errors are not reported for packages +- expect(filesErrors[pkgFile], isNull); +- }); +- } +-} +- +-/** +- * A helper to test 'analysis.*' requests. +- */ +-class AnalysisTestHelper { +- MockServerChannel serverChannel; +- MemoryResourceProvider resourceProvider; +- AnalysisServer server; +- AnalysisDomainHandler handler; +- +- Map> analysisSubscriptions =3D {}; +- +- Map> filesErrors =3D {}; +- Map> filesHighlights =3D {}; +- Map> filesNavigation =3D {}; +- +- String testFile =3D '/project/bin/test.dart'; +- String testCode; +- +- AnalysisTestHelper() { +- processRequiredPlugins(); +- serverChannel =3D new MockServerChannel(); +- resourceProvider =3D new MemoryResourceProvider(); +- // Create an SDK in the mock file system. +- new MockSdk(resourceProvider: resourceProvider); +- server =3D new AnalysisServer( +- serverChannel, +- resourceProvider, +- new MockPackageMapProvider(), +- new AnalysisServerOptions(), +- new DartSdkManager('/', false), +- InstrumentationService.NULL_SERVICE); +- handler =3D new AnalysisDomainHandler(server); +- // listen for notifications +- Stream notificationStream =3D +- serverChannel.notificationController.stream; +- notificationStream.listen((Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_ERRORS) { +- var decoded =3D new AnalysisErrorsParams.fromNotification(notific= ation); +- filesErrors[decoded.file] =3D decoded.errors; +- } +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_HIGHLIGHTS) { +- var params =3D +- new AnalysisHighlightsParams.fromNotification(notification); +- filesHighlights[params.file] =3D params.regions; +- } +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_NAVIGATION) { +- var params =3D +- new AnalysisNavigationParams.fromNotification(notification); +- filesNavigation[params.file] =3D params.regions; +- } +- }); +- } +- +- /** +- * Returns a [Future] that completes when the server's analysis is comp= lete. +- */ +- Future get onAnalysisComplete { +- return server.onAnalysisComplete; +- } +- +- void addAnalysisSubscription(AnalysisService service, String file) { +- // add file to subscription +- var files =3D analysisSubscriptions[service]; +- if (files =3D=3D null) { +- files =3D []; +- analysisSubscriptions[service] =3D files; +- } +- files.add(file); +- // set subscriptions +- Request request =3D new AnalysisSetSubscriptionsParams(analysisSubscr= iptions) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- } +- +- void addAnalysisSubscriptionHighlights(String file) { +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, file); +- } +- +- void addAnalysisSubscriptionNavigation(String file) { +- addAnalysisSubscription(AnalysisService.NAVIGATION, file); +- } +- +- /** +- * Creates an empty project `/project`. +- */ +- void createEmptyProject() { +- resourceProvider.newFolder('/project'); +- Request request =3D +- new AnalysisSetAnalysisRootsParams(['/project'], []).toRequest('0= '); +- handleSuccessfulRequest(request); +- } +- +- /** +- * Creates a project with a single Dart file `/project/bin/test.dart` w= ith +- * the given [code]. +- */ +- void createSingleFileProject(code) { +- this.testCode =3D _getCodeString(code); +- resourceProvider.newFolder('/project'); +- resourceProvider.newFile(testFile, testCode); +- Request request =3D +- new AnalysisSetAnalysisRootsParams(['/project'], []).toRequest('0= '); +- handleSuccessfulRequest(request); +- } +- +- /** +- * Returns the offset of [search] in [testCode]. +- * Fails if not found. +- */ +- int findOffset(String search) { +- int offset =3D testCode.indexOf(search); +- expect(offset, isNot(-1)); +- return offset; +- } +- +- /** +- * Returns [AnalysisError]s recorded for the given [file]. +- * May be empty, but not `null`. +- */ +- List getErrors(String file) { +- List errors =3D filesErrors[file]; +- if (errors !=3D null) { +- return errors; +- } +- return []; +- } +- +- /** +- * Returns highlights recorded for the given [file]. +- * May be empty, but not `null`. +- */ +- List getHighlights(String file) { +- List highlights =3D filesHighlights[file]; +- if (highlights !=3D null) { +- return highlights; +- } +- return []; +- } +- +- /** +- * Returns navigation regions recorded for the given [file]. +- * May be empty, but not `null`. +- */ +- List getNavigation(String file) { +- List navigation =3D filesNavigation[file]; +- if (navigation !=3D null) { +- return navigation; +- } +- return []; +- } +- +- /** +- * Returns [AnalysisError]s recorded for the [testFile]. +- * May be empty, but not `null`. +- */ +- List getTestErrors() { +- return getErrors(testFile); +- } +- +- /** +- * Returns highlights recorded for the given [testFile]. +- * May be empty, but not `null`. +- */ +- List getTestHighlights() { +- return getHighlights(testFile); +- } +- +- /** +- * Returns navigation information recorded for the given [testFile]. +- * May be empty, but not `null`. +- */ +- List getTestNavigation() { +- return getNavigation(testFile); +- } +- +- /** +- * Validates that the given [request] is handled successfully. +- */ +- void handleSuccessfulRequest(Request request) { +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- } +- +- void processRequiredPlugins() { +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- } +- +- /** +- * Send an `updateContent` request for [testFile]. +- */ +- void sendContentChange(dynamic contentChange) { +- Request request =3D new AnalysisUpdateContentParams({testFile: conten= tChange}) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- } +- +- String setFileContent(String path, String content) { +- resourceProvider.newFile(path, content); +- return path; +- } +- +- /** +- * Stops the associated server. +- */ +- void stopServer() { +- server.done(); +- } +- +- static String _getCodeString(code) { +- if (code is List) { +- code =3D code.join('\n'); +- } +- return code as String; +- } +-} +- +-@reflectiveTest +-class SetSubscriptionsTest extends AbstractAnalysisTest { +- Map> filesHighlights =3D {}; +- +- Completer _resultsAvailable =3D new Completer(); +- +- void processNotification(Notification notification) { +- if (notification.event =3D=3D ANALYSIS_NOTIFICATION_HIGHLIGHTS) { +- var params =3D new AnalysisHighlightsParams.fromNotification(notifi= cation); +- filesHighlights[params.file] =3D params.regions; +- _resultsAvailable.complete(null); +- } +- } +- +- test_afterAnalysis() async { +- addTestFile('int V =3D 42;'); +- createProject(); +- // wait for analysis, no results initially +- await waitForTasksFinished(); +- expect(filesHighlights[testFile], isNull); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, testFile); +- await _resultsAvailable.future; +- // there are results +- expect(filesHighlights[testFile], isNotEmpty); +- } +- +- test_afterAnalysis_noSuchFile() async { +- String file =3D '/no-such-file.dart'; +- addTestFile('// no matter'); +- createProject(); +- // wait for analysis, no results initially +- await waitForTasksFinished(); +- expect(filesHighlights[testFile], isNull); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, file); +- await server.onAnalysisComplete; +- // there are results +- expect(filesHighlights[file], isNull); +- } +- +- test_afterAnalysis_packageFile_external() async { +- String pkgFile =3D '/packages/pkgA/lib/libA.dart'; +- resourceProvider.newFile(pkgFile, ''' +-library lib_a; +-class A {} +-'''); +- resourceProvider.newFile( +- '/project/.packages', 'pkgA:file:///packages/pkgA/lib'); +- // +- addTestFile(''' +-import 'package:pkgA/libA.dart'; +-main() { +- new A(); +-} +-'''); +- createProject(); +- // wait for analysis, no results initially +- await waitForTasksFinished(); +- expect(filesHighlights[pkgFile], isNull); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, pkgFile); +- await _resultsAvailable.future; +- // there are results +- expect(filesHighlights[pkgFile], isNotEmpty); +- } +- +- test_afterAnalysis_packageFile_inRoot() async { +- String pkgA =3D '/pkgA'; +- String pkgB =3D '/pkgA'; +- String pkgFileA =3D '$pkgA/lib/libA.dart'; +- String pkgFileB =3D '$pkgA/lib/libB.dart'; +- resourceProvider.newFile(pkgFileA, ''' +-library lib_a; +-class A {} +-'''); +- resourceProvider.newFile(pkgFileB, ''' +-import 'package:pkgA/libA.dart'; +-main() { +- new A(); +-} +-'''); +- packageMapProvider.packageMap =3D { +- 'pkgA': [ +- resourceProvider.newFolder('$pkgA/lib'), +- resourceProvider.newFolder('$pkgB/lib') +- ] +- }; +- // add 'pkgA' and 'pkgB' as projects +- { +- resourceProvider.newFolder(projectPath); +- handleSuccessfulRequest( +- new AnalysisSetAnalysisRootsParams([pkgA, pkgB], []).toRequest(= '0')); +- } +- // wait for analysis, no results initially +- await waitForTasksFinished(); +- expect(filesHighlights[pkgFileA], isNull); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, pkgFileA); +- await _resultsAvailable.future; +- // there are results +- expect(filesHighlights[pkgFileA], isNotEmpty); +- } +- +- test_afterAnalysis_packageFile_notUsed() async { +- String pkgFile =3D '/packages/pkgA/lib/libA.dart'; +- resourceProvider.newFile(pkgFile, ''' +-library lib_a; +-class A {} +-'''); +- resourceProvider.newFile('/project/.packages', 'pkgA:/packages/pkgA/l= ib'); +- // +- addTestFile('// no "pkgA" reference'); +- createProject(); +- // wait for analysis, no results initially +- await waitForTasksFinished(); +- expect(filesHighlights[pkgFile], isNull); +- // make it a priority file, so make analyzable +- server.setPriorityFiles('0', [pkgFile]); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, pkgFile); +- await _resultsAvailable.future; +- // there are results +- expect(filesHighlights[pkgFile], isNotEmpty); +- } +- +- test_afterAnalysis_sdkFile() async { +- String file =3D '/lib/core/core.dart'; +- addTestFile('// no matter'); +- createProject(); +- // wait for analysis, no results initially +- await waitForTasksFinished(); +- expect(filesHighlights[file], isNull); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, file); +- await _resultsAvailable.future; +- // there are results +- expect(filesHighlights[file], isNotEmpty); +- } +- +- test_beforeAnalysis() async { +- addTestFile('int V =3D 42;'); +- createProject(); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, testFile); +- // wait for analysis +- await waitForTasksFinished(); +- expect(filesHighlights[testFile], isNotEmpty); +- } +- +- test_sentToPlugins() async { +- addTestFile('int V =3D 42;'); +- createProject(); +- // subscribe +- addAnalysisSubscription(AnalysisService.HIGHLIGHTS, testFile); +- // wait for analysis +- await waitForTasksFinished(); +- plugin.AnalysisSetSubscriptionsParams params =3D +- pluginManager.analysisSetSubscriptionsParams; +- expect(params, isNotNull); +- Map> subscriptions =3D +- params.subscriptions; +- expect(subscriptions, hasLength(1)); +- List files =3D subscriptions[plugin.AnalysisService.HIGHLIGHT= S]; +- expect(files, [testFile]); +- } +-} +diff --git a/pkg/analysis_server/test/domain_completion_test.dart b/pkg/an= alysis_server/test/domain_completion_test.dart +deleted file mode 100644 +index 5aad7e432c7..00000000000 +--- a/pkg/analysis_server/test/domain_completion_test.dart ++++ /dev/null +@@ -1,780 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/provisional/completion/completion_cor= e.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analysis_server/src/services/completion/dart/contribution= _sorter.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'domain_completion_util.dart'; +-import 'mocks.dart' show pumpEventQueue; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(CompletionDomainHandlerTest); +- }); +-} +- +-@reflectiveTest +-class CompletionDomainHandlerTest extends AbstractCompletionDomainTest { +- test_ArgumentList_constructor_named_fieldFormalParam() async { +- // https://github.com/dart-lang/sdk/issues/31023 +- addTestFile(''' +-main() { new A(field: ^);} +-class A { +- A({this.field: -1}) {} +-} +-'''); +- await getSuggestions(); +- } +- +- test_ArgumentList_constructor_named_param_label() async { +- addTestFile('main() { new A(^);}' +- 'class A { A({one, two}) {} }'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'one: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'two: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(2)); +- } +- +- test_ArgumentList_factory_named_param_label() async { +- addTestFile('main() { new A(^);}' +- 'class A { factory A({one, two}) =3D> null; }'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'one: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'two: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(2)); +- } +- +- test_ArgumentList_imported_function_named_param() async { +- addTestFile('main() { int.parse("16", ^);}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'radix: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'onError: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(2)); +- } +- +- test_ArgumentList_imported_function_named_param1() async { +- addTestFile('main() { foo(o^);} foo({one, two}) {}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'one: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'two: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(2)); +- } +- +- test_ArgumentList_imported_function_named_param2() async { +- addTestFile('mainx() {A a =3D new A(); a.foo(one: 7, ^);}' +- 'class A { foo({one, two}) {} }'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'two: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(1)); +- } +- +- test_ArgumentList_imported_function_named_param_label1() async { +- addTestFile('main() { int.parse("16", r^: 16);}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'radix', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'onError', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(2)); +- } +- +- test_ArgumentList_imported_function_named_param_label3() async { +- addTestFile('main() { int.parse("16", ^: 16);}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'radix: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- assertHasResult(CompletionSuggestionKind.NAMED_ARGUMENT, 'onError: ', +- relevance: DART_RELEVANCE_NAMED_PARAMETER); +- expect(suggestions, hasLength(2)); +- } +- +- test_catch() async { +- addTestFile('main() {try {} ^}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'on', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'catch', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'finally', +- relevance: DART_RELEVANCE_KEYWORD); +- expect(suggestions, hasLength(3)); +- } +- +- test_catch2() async { +- addTestFile('main() {try {} on Foo {} ^}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'on', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'catch', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'finally', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'for', +- relevance: DART_RELEVANCE_KEYWORD); +- suggestions.firstWhere( +- (CompletionSuggestion suggestion) =3D> +- suggestion.kind !=3D CompletionSuggestionKind.KEYWORD, orElse= : () { +- fail('Expected suggestions other than keyword suggestions'); +- }); +- } +- +- test_catch3() async { +- addTestFile('main() {try {} catch (e) {} finally {} ^}'); +- await getSuggestions(); +- assertNoResult('on'); +- assertNoResult('catch'); +- assertNoResult('finally'); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'for', +- relevance: DART_RELEVANCE_KEYWORD); +- suggestions.firstWhere( +- (CompletionSuggestion suggestion) =3D> +- suggestion.kind !=3D CompletionSuggestionKind.KEYWORD, orElse= : () { +- fail('Expected suggestions other than keyword suggestions'); +- }); +- } +- +- test_catch4() async { +- addTestFile('main() {try {} finally {} ^}'); +- await getSuggestions(); +- assertNoResult('on'); +- assertNoResult('catch'); +- assertNoResult('finally'); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'for', +- relevance: DART_RELEVANCE_KEYWORD); +- suggestions.firstWhere( +- (CompletionSuggestion suggestion) =3D> +- suggestion.kind !=3D CompletionSuggestionKind.KEYWORD, orElse= : () { +- fail('Expected suggestions other than keyword suggestions'); +- }); +- } +- +- test_catch5() async { +- addTestFile('main() {try {} ^ finally {}}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'on', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'catch', +- relevance: DART_RELEVANCE_KEYWORD); +- expect(suggestions, hasLength(2)); +- } +- +- test_constructor() async { +- addTestFile('class A {bool foo; A() : ^;}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'super', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_constructor2() async { +- addTestFile('class A {bool foo; A() : s^;}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'super', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_constructor3() async { +- addTestFile('class A {bool foo; A() : a=3D7,^;}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'super', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_constructor4() async { +- addTestFile('class A {bool foo; A() : a=3D7,s^;}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'super', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_constructor5() async { +- addTestFile('class A {bool foo; A() : a=3D7,s^}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'super', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_constructor6() async { +- addTestFile('class A {bool foo; A() : a=3D7,^ void bar() {}}'); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'super', +- relevance: DART_RELEVANCE_KEYWORD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_html() { +- // +- // We no longer support the analysis of non-dart files. +- // +- testFile =3D '/project/web/test.html'; +- addTestFile(''' +- ^ +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- expect(suggestions, hasLength(0)); +- }); +- } +- +- test_import_uri_with_trailing() { +- addFile('/project/bin/testA.dart', 'library libA;'); +- addTestFile(''' +- import '/project/bin/t^.dart'; +- main() {}'''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset - 14)); +- expect(replacementLength, equals(5 + 14)); +- assertHasResult( +- CompletionSuggestionKind.IMPORT, '/project/bin/testA.dart'); +- assertNoResult('test'); +- }); +- } +- +- test_imports() { +- addTestFile(''' +- import 'dart:html'; +- main() {^} +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'Object'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'HtmlElement'); +- assertNoResult('test'); +- }); +- } +- +- test_imports_aborted_new_request() async { +- addTestFile(''' +- class foo { } +- c^'''); +- +- // Make a request for suggestions +- Request request1 =3D +- new CompletionGetSuggestionsParams(testFile, completionOffset) +- .toRequest('7'); +- Future responseFuture1 =3D waitResponse(request1); +- +- // Make another request before the first request completes +- Request request2 =3D +- new CompletionGetSuggestionsParams(testFile, completionOffset) +- .toRequest('8'); +- Future responseFuture2 =3D waitResponse(request2); +- +- // Await first response +- Response response1 =3D await responseFuture1; +- var result1 =3D new CompletionGetSuggestionsResult.fromResponse(respo= nse1); +- assertValidId(result1.id); +- +- // Await second response +- Response response2 =3D await responseFuture2; +- var result2 =3D new CompletionGetSuggestionsResult.fromResponse(respo= nse2); +- assertValidId(result2.id); +- +- // Wait for all processing to be complete +- await analysisHandler.server.analysisDriverScheduler.waitForIdle(); +- await pumpEventQueue(); +- +- // Assert that first request has been aborted +- expect(allSuggestions[result1.id], hasLength(0)); +- +- // Assert valid results for the second request +- expect(allSuggestions[result2.id], same(suggestions)); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'class', +- relevance: DART_RELEVANCE_HIGH); +- } +- +- @failingTest +- test_imports_aborted_source_changed() async { +- // TODO(brianwilkerson) Figure out whether this test makes sense when +- // running the new driver. It waits for an initial empty notification= then +- // waits for a new notification. But I think that under the driver we= only +- // ever send one notification. +- addTestFile(''' +- class foo { } +- c^'''); +- +- // Make a request for suggestions +- Request request =3D +- new CompletionGetSuggestionsParams(testFile, completionOffset) +- .toRequest('0'); +- Future responseFuture =3D waitResponse(request); +- +- // Simulate user deleting text after request but before suggestions r= eturned +- server.updateContent('uc1', {testFile: new AddContentOverlay(testCode= )}); +- server.updateContent('uc2', { +- testFile: new ChangeContentOverlay( +- [new SourceEdit(completionOffset - 1, 1, '')]) +- }); +- +- // Await a response +- Response response =3D await responseFuture; +- completionId =3D response.id; +- assertValidId(completionId); +- +- // Wait for all processing to be complete +- await analysisHandler.server.analysisDriverScheduler.waitForIdle(); +- await pumpEventQueue(); +- +- // Assert that request has been aborted +- expect(suggestionsDone, isTrue); +- expect(suggestions, hasLength(0)); +- } +- +- test_imports_incremental() async { +- addTestFile('''library foo; +- e^ +- import "dart:async"; +- import "package:foo/foo.dart"; +- class foo { }'''); +- await waitForTasksFinished(); +- server.updateContent('uc1', {testFile: new AddContentOverlay(testCode= )}); +- server.updateContent('uc2', { +- testFile: +- new ChangeContentOverlay([new SourceEdit(completionOffset, 0, '= xp')]) +- }); +- completionOffset +=3D 2; +- await getSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'export \'\';', +- selectionOffset: 8, relevance: DART_RELEVANCE_HIGH); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'import \'\';', +- selectionOffset: 8, relevance: DART_RELEVANCE_HIGH); +- assertNoResult('extends'); +- assertNoResult('library'); +- } +- +- test_imports_partial() async { +- addTestFile('''^ +- import "package:foo/foo.dart"; +- import "package:bar/bar.dart"; +- class Baz { }'''); +- +- // Wait for analysis then edit the content +- await waitForTasksFinished(); +- String revisedContent =3D testCode.substring(0, completionOffset) + +- 'i' + +- testCode.substring(completionOffset); +- ++completionOffset; +- server.handleRequest(new AnalysisUpdateContentParams( +- {testFile: new AddContentOverlay(revisedContent)}).toRequest('add= 1')); +- +- // Request code completion immediately after edit +- Response response =3D await waitResponse( +- new CompletionGetSuggestionsParams(testFile, completionOffset) +- .toRequest('0')); +- completionId =3D response.id; +- assertValidId(completionId); +- await waitForTasksFinished(); +- // wait for response to arrive +- // because although the analysis is complete (waitForTasksFinished) +- // the response may not yet have been processed +- while (replacementOffset =3D=3D null) { +- await new Future.delayed(new Duration(milliseconds: 5)); +- } +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'library', +- relevance: DART_RELEVANCE_HIGH); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'import \'\';', +- selectionOffset: 8, relevance: DART_RELEVANCE_HIGH); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'export \'\';', +- selectionOffset: 8, relevance: DART_RELEVANCE_HIGH); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'part \'\';', +- selectionOffset: 6, relevance: DART_RELEVANCE_HIGH); +- assertNoResult('extends'); +- } +- +- test_imports_prefixed() { +- addTestFile(''' +- import 'dart:html' as foo; +- main() {^} +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'Object'); +- assertHasResult(CompletionSuggestionKind.IDENTIFIER, 'foo'); +- assertNoResult('HtmlElement'); +- assertNoResult('test'); +- }); +- } +- +- test_imports_prefixed2() { +- addTestFile(''' +- import 'dart:html' as foo; +- main() {foo.^} +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'HtmlElement'); +- assertNoResult('test'); +- }); +- } +- +- test_inComment_block_beforeNode() async { +- addTestFile(''' +- main(aaa, bbb) { +- /* text ^ */ +- print(42); +- } +- '''); +- await getSuggestions(); +- expect(suggestions, isEmpty); +- } +- +- test_inComment_endOfLine_beforeNode() async { +- addTestFile(''' +- main(aaa, bbb) { +- // text ^ +- print(42); +- } +- '''); +- await getSuggestions(); +- expect(suggestions, isEmpty); +- } +- +- test_inComment_endOfLine_beforeToken() async { +- addTestFile(''' +- main(aaa, bbb) { +- // text ^ +- } +- '''); +- await getSuggestions(); +- expect(suggestions, isEmpty); +- } +- +- test_inDartDoc1() async { +- addTestFile(''' +- /// ^ +- main(aaa, bbb) {} +- '''); +- await getSuggestions(); +- expect(suggestions, isEmpty); +- } +- +- test_inDartDoc2() async { +- addTestFile(''' +- /// Some text^ +- main(aaa, bbb) {} +- '''); +- await getSuggestions(); +- expect(suggestions, isEmpty); +- } +- +- test_inDartDoc_reference1() async { +- addFile('/testA.dart', ''' +- part of libA; +- foo(bar) =3D> 0;'''); +- addTestFile(''' +- library libA; +- part "/testA.dart"; +- import "dart:math"; +- /// The [^] +- main(aaa, bbb) {} +- '''); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.IDENTIFIER, 'main', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertHasResult(CompletionSuggestionKind.IDENTIFIER, 'foo', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertHasResult(CompletionSuggestionKind.IDENTIFIER, 'min'); +- } +- +- test_inDartDoc_reference2() async { +- addTestFile(''' +- /// The [m^] +- main(aaa, bbb) {} +- '''); +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.IDENTIFIER, 'main', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- } +- +- test_inherited() { +- addFile('/libA.dart', 'class A {m() {}}'); +- addTestFile(''' +-import '/libA.dart'; +-class B extends A { +- x() {^} +-} +-'''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'm'); +- }); +- } +- +- test_invocation() { +- addTestFile('class A {b() {}} main() {A a; a.^}'); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'b'); +- }); +- } +- +- test_invocation_sdk_relevancy_off() { +- var originalSorter =3D DartCompletionManager.contributionSorter; +- var mockSorter =3D new MockRelevancySorter(); +- DartCompletionManager.contributionSorter =3D mockSorter; +- addTestFile('main() {Map m; m.^}'); +- return getSuggestions().then((_) { +- // Assert that the CommonUsageComputer has been replaced +- expect(suggestions.any((s) =3D> s.relevance =3D=3D DART_RELEVANCE_C= OMMON_USAGE), +- isFalse); +- DartCompletionManager.contributionSorter =3D originalSorter; +- mockSorter.enabled =3D false; +- }); +- } +- +- test_invocation_sdk_relevancy_on() { +- addTestFile('main() {Map m; m.^}'); +- return getSuggestions().then((_) { +- // Assert that the CommonUsageComputer is working +- expect(suggestions.any((s) =3D> s.relevance =3D=3D DART_RELEVANCE_C= OMMON_USAGE), +- isTrue); +- }); +- } +- +- test_invocation_withTrailingStmt() { +- addTestFile('class A {b() {}} main() {A a; a.^ int x =3D 7;}'); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'b'); +- }); +- } +- +- test_keyword() { +- addTestFile('library A; cl^'); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset - 2)); +- expect(replacementLength, equals(2)); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'export \'\';', +- selectionOffset: 8, relevance: DART_RELEVANCE_HIGH); +- assertHasResult(CompletionSuggestionKind.KEYWORD, 'class', +- relevance: DART_RELEVANCE_HIGH); +- }); +- } +- +- test_local_named_constructor() { +- addTestFile('class A {A.c(); x() {new A.^}}'); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'c'); +- assertNoResult('A'); +- }); +- } +- +- test_local_override() { +- addFile('/libA.dart', 'class A {m() {}}'); +- addTestFile(''' +-import '/libA.dart'; +-class B extends A { +- m() {} +- x() {^} +-} +-'''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'm', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- }); +- } +- +- test_locals() { +- addTestFile('class A {var a; x() {var b;^}} class DateTime { }'); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'A'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'a', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'b', +- relevance: DART_RELEVANCE_LOCAL_VARIABLE); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'x', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'DateTime'); +- }); +- } +- +- test_offset_past_eof() async { +- addTestFile('main() { }', offset: 300); +- Request request =3D +- new CompletionGetSuggestionsParams(testFile, completionOffset) +- .toRequest('0'); +- Response response =3D await waitResponse(request); +- expect(response.id, '0'); +- expect(response.error.code, RequestErrorCode.INVALID_PARAMETER); +- } +- +- test_overrides() { +- addFile('/libA.dart', 'class A {m() {}}'); +- addTestFile(''' +-import '/libA.dart'; +-class B extends A {m() {^}} +-'''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'm', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- }); +- } +- +- test_partFile() { +- addFile('/project/bin/testA.dart', ''' +- library libA; +- part "$testFile"; +- import 'dart:html'; +- class A { } +- '''); +- addTestFile(''' +- part of libA; +- main() {^}'''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'Object'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'HtmlElement'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'A'); +- assertNoResult('test'); +- }); +- } +- +- test_partFile2() { +- addFile('/testA.dart', ''' +- part of libA; +- class A { }'''); +- addTestFile(''' +- library libA; +- part "/testA.dart"; +- import 'dart:html'; +- main() {^} +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'Object'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'HtmlElement'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'A'); +- assertNoResult('test'); +- }); +- } +- +- test_sentToPlugins() async { +- addTestFile(''' +- void main() { +- ^ +- } +- '''); +- PluginInfo info =3D new DiscoveredPluginInfo('a', 'b', 'c', null, nul= l); +- plugin.CompletionGetSuggestionsResult result =3D +- new plugin.CompletionGetSuggestionsResult( +- testFile.indexOf('^'), 0, [ +- new CompletionSuggestion(CompletionSuggestionKind.IDENTIFIER, +- DART_RELEVANCE_DEFAULT, 'plugin completion', 3, 0, false, false) +- ]); +- pluginManager.broadcastResults =3D >{ +- info: new Future.value(result.toResponse('-', 1)) +- }; +- await getSuggestions(); +- assertHasResult(CompletionSuggestionKind.IDENTIFIER, 'plugin completi= on', +- selectionOffset: 3); +- } +- +- test_simple() { +- addTestFile(''' +- void main() { +- ^ +- } +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'Object'); +- assertNoResult('HtmlElement'); +- assertNoResult('test'); +- }); +- } +- +- test_static() { +- addTestFile('class A {static b() {} c() {}} main() {A.^}'); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'b'); +- assertNoResult('c'); +- }); +- } +- +- test_topLevel() { +- addTestFile(''' +- typedef foo(); +- var test =3D ''; +- main() {tes^t} +- '''); +- return getSuggestions().then((_) { +- expect(replacementOffset, equals(completionOffset - 3)); +- expect(replacementLength, equals(4)); +- // Suggestions based upon imported elements are partially filtered +- //assertHasResult(CompletionSuggestionKind.INVOCATION, 'Object'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'test', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertNoResult('HtmlElement'); +- }); +- } +-} +- +-class MockRelevancySorter implements DartContributionSorter { +- bool enabled =3D true; +- +- @override +- Future sort( +- CompletionRequest request, Iterable suggestio= ns) { +- if (!enabled) { +- throw 'unexpected sort'; +- } +- return new Future.value(); +- } +-} +diff --git a/pkg/analysis_server/test/domain_completion_util.dart b/pkg/an= alysis_server/test/domain_completion_util.dart +deleted file mode 100644 +index 6f1da485995..00000000000 +--- a/pkg/analysis_server/test/domain_completion_util.dart ++++ /dev/null +@@ -1,123 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/constants.dart'; +-import 'package:analysis_server/src/domain_completion.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +- +-import 'analysis_abstract.dart'; +- +-class AbstractCompletionDomainTest extends AbstractAnalysisTest { +- String completionId; +- int completionOffset; +- int replacementOffset; +- int replacementLength; +- Map> receivedSuggestionsCompleters =3D {}; +- List suggestions =3D []; +- bool suggestionsDone =3D false; +- Map> allSuggestions =3D {}; +- +- String addTestFile(String content, {int offset}) { +- completionOffset =3D content.indexOf('^'); +- if (offset !=3D null) { +- expect(completionOffset, -1, reason: 'cannot supply offset and ^'); +- completionOffset =3D offset; +- return super.addTestFile(content); +- } +- expect(completionOffset, isNot(equals(-1)), reason: 'missing ^'); +- int nextOffset =3D content.indexOf('^', completionOffset + 1); +- expect(nextOffset, equals(-1), reason: 'too many ^'); +- return super.addTestFile(content.substring(0, completionOffset) + +- content.substring(completionOffset + 1)); +- } +- +- void assertHasResult(CompletionSuggestionKind kind, String completion, +- {int relevance: DART_RELEVANCE_DEFAULT, +- bool isDeprecated: false, +- bool isPotential: false, +- int selectionOffset}) { +- var cs; +- suggestions.forEach((s) { +- if (s.completion =3D=3D completion) { +- if (cs =3D=3D null) { +- cs =3D s; +- } else { +- fail('expected exactly one $completion but found > 1'); +- } +- } +- }); +- if (cs =3D=3D null) { +- var completions =3D suggestions.map((s) =3D> s.completion).toList(); +- fail('expected "$completion" but found\n $completions'); +- } +- expect(cs.kind, equals(kind)); +- expect(cs.relevance, equals(relevance)); +- expect(cs.selectionOffset, selectionOffset ?? completion.length); +- expect(cs.selectionLength, equals(0)); +- expect(cs.isDeprecated, equals(isDeprecated)); +- expect(cs.isPotential, equals(isPotential)); +- } +- +- void assertNoResult(String completion) { +- if (suggestions.any((cs) =3D> cs.completion =3D=3D completion)) { +- fail('did not expect completion: $completion'); +- } +- } +- +- void assertValidId(String id) { +- expect(id, isNotNull); +- expect(id.isNotEmpty, isTrue); +- } +- +- Future getSuggestions() async { +- await waitForTasksFinished(); +- +- Request request =3D +- new CompletionGetSuggestionsParams(testFile, completionOffset) +- .toRequest('0'); +- Response response =3D await waitResponse(request); +- var result =3D new CompletionGetSuggestionsResult.fromResponse(respon= se); +- completionId =3D result.id; +- assertValidId(completionId); +- await _getResultsCompleter(completionId).future; +- expect(suggestionsDone, isTrue); +- } +- +- processNotification(Notification notification) async { +- if (notification.event =3D=3D COMPLETION_RESULTS) { +- var params =3D new CompletionResultsParams.fromNotification(notific= ation); +- String id =3D params.id; +- assertValidId(id); +- replacementOffset =3D params.replacementOffset; +- replacementLength =3D params.replacementLength; +- suggestionsDone =3D params.isLast; +- expect(suggestionsDone, isNotNull); +- suggestions =3D params.results; +- expect(allSuggestions.containsKey(id), isFalse); +- allSuggestions[id] =3D params.results; +- _getResultsCompleter(id).complete(null); +- } else if (notification.event =3D=3D SERVER_NOTIFICATION_ERROR) { +- fail('server error: ${notification.toJson()}'); +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new CompletionDomainHandler(server); +- } +- +- Completer _getResultsCompleter(String id) { +- return receivedSuggestionsCompleters.putIfAbsent( +- id, () =3D> new Completer()); +- } +-} +diff --git a/pkg/analysis_server/test/domain_diagnostic_test.dart b/pkg/an= alysis_server/test/domain_diagnostic_test.dart +deleted file mode 100644 +index 913294f8946..00000000000 +--- a/pkg/analysis_server/test/domain_diagnostic_test.dart ++++ /dev/null +@@ -1,58 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/domain_diagnostic.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(DiagnosticDomainTest); +- }); +-} +- +-@reflectiveTest +-class DiagnosticDomainTest extends AbstractAnalysisTest { +- @override +- void setUp() { +- generateSummaryFiles =3D true; +- super.setUp(); +- handler =3D new DiagnosticDomainHandler(server); +- server.handlers =3D [handler]; +- } +- +- test_getDiagnostics() async { +- String file =3D '/project/bin/test.dart'; +- resourceProvider.newFile('/project/pubspec.yaml', 'name: project'); +- resourceProvider.newFile(file, 'main() {}'); +- +- server.setAnalysisRoots('0', ['/project/'], [], {}); +- +- await server.onAnalysisComplete; +- +- var request =3D new DiagnosticGetDiagnosticsParams().toRequest('0'); +- var response =3D handler.handleRequest(request); +- var result =3D new DiagnosticGetDiagnosticsResult.fromResponse(respon= se); +- +- expect(result.contexts, hasLength(1)); +- +- ContextData context =3D result.contexts[0]; +- expect(context.name, '/project'); +- expect(context.explicitFileCount, 1); /* test.dart */ +- +- expect(context.implicitFileCount, 4); +- +- expect(context.workItemQueueLength, isNotNull); +- } +- +- test_getDiagnostics_noRoot() async { +- var request =3D new DiagnosticGetDiagnosticsParams().toRequest('0'); +- var response =3D handler.handleRequest(request); +- var result =3D new DiagnosticGetDiagnosticsResult.fromResponse(respon= se); +- expect(result.contexts, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/domain_execution_test.dart b/pkg/ana= lysis_server/test/domain_execution_test.dart +deleted file mode 100644 +index b46daaab75a..00000000000 +--- a/pkg/analysis_server/test/domain_execution_test.dart ++++ /dev/null +@@ -1,243 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/domain_execution.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/generated/source_io.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'analysis_abstract.dart'; +-import 'mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ExecutionDomainTest); +- }); +- group('ExecutionDomainHandler', () { +- MemoryResourceProvider provider =3D new MemoryResourceProvider(); +- AnalysisServer server; +- ExecutionDomainHandler handler; +- +- setUp(() { +- server =3D new AnalysisServer( +- new MockServerChannel(), +- provider, +- new MockPackageMapProvider(), +- new AnalysisServerOptions(), +- new DartSdkManager('', false), +- InstrumentationService.NULL_SERVICE); +- handler =3D new ExecutionDomainHandler(server); +- }); +- +- group('createContext/deleteContext', () { +- test('create/delete multiple contexts', () { +- Request request =3D +- new ExecutionCreateContextParams('/a/b.dart').toRequest('0'); +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- ExecutionCreateContextResult result =3D +- new ExecutionCreateContextResult.fromResponse(response); +- String id0 =3D result.id; +- +- request =3D new ExecutionCreateContextParams('/c/d.dart').toReque= st('1'); +- response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('1')); +- result =3D new ExecutionCreateContextResult.fromResponse(response= ); +- String id1 =3D result.id; +- +- expect(id0 =3D=3D id1, isFalse); +- +- request =3D new ExecutionDeleteContextParams(id0).toRequest('2'); +- response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('2')); +- +- request =3D new ExecutionDeleteContextParams(id1).toRequest('3'); +- response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('3')); +- }); +- +- test('delete non-existent context', () { +- Request request =3D new ExecutionDeleteContextParams('13').toRequ= est('0'); +- Response response =3D handler.handleRequest(request); +- // TODO(brianwilkerson) It isn't currently specified to be an err= or if a +- // client attempts to delete a context that doesn't exist. Should= it be? +-// expect(response, isResponseFailure('0')); +- expect(response, isResponseSuccess('0')); +- }); +- }); +- +- // TODO(brianwilkerson) Re-enable these tests if we re-enable the +- // execution.mapUri request. +-// group('mapUri', () { +-// String contextId; +-// +-// void createExecutionContextIdForFile(String path) { +-// Request request =3D new ExecutionCreateContextParams(path).toRe= quest('0'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseSuccess('0')); +-// ExecutionCreateContextResult result =3D +-// new ExecutionCreateContextResult.fromResponse(response); +-// contextId =3D result.id; +-// } +-// +-// setUp(() { +-// Folder folder =3D provider.newFile('/a/b.dart', '').parent; +-// server.folderMap.putIfAbsent(folder, () { +-// SourceFactory factory =3D +-// new SourceFactory([new ResourceUriResolver(provider)]); +-// AnalysisContext context =3D +-// AnalysisEngine.instance.createAnalysisContext(); +-// context.sourceFactory =3D factory; +-// return context; +-// }); +-// createExecutionContextIdForFile('/a/b.dart'); +-// }); +-// +-// tearDown(() { +-// Request request =3D +-// new ExecutionDeleteContextParams(contextId).toRequest('1'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseSuccess('1')); +-// }); +-// +-// group('file to URI', () { +-// test('does not exist', () { +-// Request request =3D +-// new ExecutionMapUriParams(contextId, file: '/a/c.dart') +-// .toRequest('2'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseFailure('2')); +-// }); +-// +-// test('directory', () { +-// provider.newFolder('/a/d'); +-// Request request =3D +-// new ExecutionMapUriParams(contextId, file: '/a/d').toRequ= est('2'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseFailure('2')); +-// }); +-// }); +-// +-// group('URI to file', () { +-// test('invalid', () { +-// Request request =3D +-// new ExecutionMapUriParams(contextId, uri: 'foo:///a/b.dar= t') +-// .toRequest('2'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseFailure('2')); +-// }); +-// }); +-// +-// test('invalid context id', () { +-// Request request =3D +-// new ExecutionMapUriParams('xxx', uri: '').toRequest('4'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseFailure('4')); +-// }); +-// +-// test('both file and uri', () { +-// Request request =3D +-// new ExecutionMapUriParams('xxx', file: '', uri: '').toReque= st('5'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseFailure('5')); +-// }); +-// +-// test('neither file nor uri', () { +-// Request request =3D new ExecutionMapUriParams('xxx').toRequest(= '6'); +-// Response response =3D handler.handleRequest(request); +-// expect(response, isResponseFailure('6')); +-// }); +-// }); +- }); +-} +- +-@reflectiveTest +-class ExecutionDomainTest extends AbstractAnalysisTest { +- String contextId; +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new ExecutionDomainHandler(server); +- _createExecutionContext(testFile); +- } +- +- @override +- void tearDown() { +- _disposeExecutionContext(); +- super.tearDown(); +- } +- +- void test_mapUri_file() { +- String path =3D '/a/b.dart'; +- resourceProvider.newFile(path, ''); +- // map the file +- ExecutionMapUriResult result =3D _mapUri(file: path); +- expect(result.file, isNull); +- expect(result.uri, 'file:///a/b.dart'); +- } +- +- void test_mapUri_file_dartUriKind() { +- String path =3D server.findSdk().mapDartUri('dart:async').fullName; +- // hack - pretend that the SDK file exists in the project FS +- resourceProvider.newFile(path, '// hack'); +- // map file +- ExecutionMapUriResult result =3D _mapUri(file: path); +- expect(result.file, isNull); +- expect(result.uri, 'dart:async'); +- } +- +- void test_mapUri_uri() { +- String path =3D '/a/b.dart'; +- resourceProvider.newFile(path, ''); +- // map the uri +- ExecutionMapUriResult result =3D _mapUri(uri: 'file://$path'); +- expect(result.file, '/a/b.dart'); +- expect(result.uri, isNull); +- } +- +- void _createExecutionContext(String path) { +- Request request =3D new ExecutionCreateContextParams(path).toRequest(= '0'); +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- ExecutionCreateContextResult result =3D +- new ExecutionCreateContextResult.fromResponse(response); +- contextId =3D result.id; +- } +- +- void _disposeExecutionContext() { +- Request request =3D +- new ExecutionDeleteContextParams(contextId).toRequest('1'); +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('1')); +- } +- +- ExecutionMapUriResult _mapUri({String file, String uri}) { +- Request request =3D new ExecutionMapUriParams(contextId, file: file, = uri: uri) +- .toRequest('2'); +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('2')); +- return new ExecutionMapUriResult.fromResponse(response); +- } +-} +- +-/** +- * A [Source] that knows it's [fullName]. +- */ +-class TestSource implements Source { +- String fullName; +- +- TestSource(this.fullName); +- +- @override +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +-} +diff --git a/pkg/analysis_server/test/domain_server_test.dart b/pkg/analys= is_server/test/domain_server_test.dart +deleted file mode 100644 +index c4aeebd783e..00000000000 +--- a/pkg/analysis_server/test/domain_server_test.dart ++++ /dev/null +@@ -1,81 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/constants.dart'; +-import 'package:analysis_server/src/domain_server.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:test/test.dart'; +- +-import 'mocks.dart'; +- +-main() { +- AnalysisServer server; +- ServerDomainHandler handler; +- MockServerChannel serverChannel; +- +- setUp(() { +- serverChannel =3D new MockServerChannel(); +- var resourceProvider =3D new MemoryResourceProvider(); +- server =3D new AnalysisServer( +- serverChannel, +- resourceProvider, +- new MockPackageMapProvider(), +- new AnalysisServerOptions(), +- new DartSdkManager('', false), +- InstrumentationService.NULL_SERVICE); +- handler =3D new ServerDomainHandler(server); +- }); +- +- group('ServerDomainHandler', () { +- test('getVersion', () { +- var request =3D new ServerGetVersionParams().toRequest('0'); +- var response =3D handler.handleRequest(request); +- expect( +- response.toJson(), +- equals({ +- Response.ID: '0', +- Response.RESULT: {VERSION: AnalysisServer.VERSION} +- })); +- }); +- +- group('setSubscriptions', () { +- test('invalid service name', () { +- Request request =3D new Request('0', SERVER_REQUEST_SET_SUBSCRIPT= IONS, { +- SUBSCRIPTIONS: ['noSuchService'] +- }); +- var response =3D handler.handleRequest(request); +- expect(response, isResponseFailure('0')); +- }); +- +- test('success', () { +- expect(server.serverServices, isEmpty); +- // send request +- Request request =3D +- new ServerSetSubscriptionsParams([ServerService.STATUS]) +- .toRequest('0'); +- var response =3D handler.handleRequest(request); +- expect(response, isResponseSuccess('0')); +- // set of services has been changed +- expect(server.serverServices, contains(ServerService.STATUS)); +- }); +- }); +- +- test('shutdown', () async { +- expect(server.running, isTrue); +- // send request +- var request =3D new ServerShutdownParams().toRequest('0'); +- var response =3D await serverChannel.sendRequest(request); +- expect(response, isResponseSuccess('0')); +- +- // server is down +- expect(server.running, isFalse); +- }); +- }); +-} +diff --git a/pkg/analysis_server/test/edit/assists_test.dart b/pkg/analysi= s_server/test/edit/assists_test.dart +deleted file mode 100644 +index 399706d2aa9..00000000000 +--- a/pkg/analysis_server/test/edit/assists_test.dart ++++ /dev/null +@@ -1,134 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart' as p= lugin; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AssistsTest); +- }); +-} +- +-@reflectiveTest +-class AssistsTest extends AbstractAnalysisTest { +- List changes; +- +- prepareAssists(String search, [int length =3D 0]) async { +- int offset =3D findOffset(search); +- await prepareAssistsAt(offset, length); +- } +- +- prepareAssistsAt(int offset, int length) async { +- Request request =3D +- new EditGetAssistsParams(testFile, offset, length).toRequest('0'); +- Response response =3D await waitResponse(request); +- var result =3D new EditGetAssistsResult.fromResponse(response); +- changes =3D result.assists; +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- } +- +- test_fromPlugins() async { +- PluginInfo info =3D new DiscoveredPluginInfo('a', 'b', 'c', null, nul= l); +- String message =3D 'From a plugin'; +- plugin.PrioritizedSourceChange change =3D new plugin.PrioritizedSourc= eChange( +- 5, +- new SourceChange(message, edits: [ +- new SourceFileEdit('', 0, +- edits: [new SourceEdit(0, 0, 'x')]) +- ])); +- plugin.EditGetAssistsResult result =3D new plugin.EditGetAssistsResul= t( +- [change]); +- pluginManager.broadcastResults =3D >{ +- info: new Future.value(result.toResponse('-', 1)) +- }; +- +- addTestFile('main() {}'); +- await waitForTasksFinished(); +- await prepareAssists('in('); +- _assertHasChange(message, 'xmain() {}'); +- } +- +- test_removeTypeAnnotation() async { +- addTestFile(''' +-main() { +- int v =3D 1; +-} +-'''); +- await waitForTasksFinished(); +- await prepareAssists('v =3D'); +- _assertHasChange('Remove type annotation', ''' +-main() { +- var v =3D 1; +-} +-'''); +- } +- +- test_splitVariableDeclaration() async { +- addTestFile(''' +-main() { +- int v =3D 1; +-} +-'''); +- await waitForTasksFinished(); +- await prepareAssists('v =3D'); +- _assertHasChange('Split variable declaration', ''' +-main() { +- int v; +- v =3D 1; +-} +-'''); +- } +- +- test_surroundWithIf() async { +- addTestFile(''' +-main() { +- print(1); +- print(2); +-} +-'''); +- await waitForTasksFinished(); +- int offset =3D findOffset(' print(1)'); +- int length =3D findOffset('}') - offset; +- await prepareAssistsAt(offset, length); +- _assertHasChange("Surround with 'if'", ''' +-main() { +- if (condition) { +- print(1); +- print(2); +- } +-} +-'''); +- } +- +- void _assertHasChange(String message, String expectedCode) { +- for (SourceChange change in changes) { +- if (change.message =3D=3D message) { +- String resultCode =3D +- SourceEdit.applySequence(testCode, change.edits[0].edits); +- expect(resultCode, expectedCode); +- return; +- } +- } +- fail("Expected to find |$message| in\n" + changes.join('\n')); +- } +-} +diff --git a/pkg/analysis_server/test/edit/fixes_test.dart b/pkg/analysis_= server/test/edit/fixes_test.dart +deleted file mode 100644 +index 90732cdceef..00000000000 +--- a/pkg/analysis_server/test/edit/fixes_test.dart ++++ /dev/null +@@ -1,164 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart' as p= lugin; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FixesTest); +- }); +-} +- +-@reflectiveTest +-class FixesTest extends AbstractAnalysisTest { +- @override +- void setUp() { +- super.setUp(); +- handler =3D new EditDomainHandler(server); +- } +- +- test_fixUndefinedClass() async { +- createProject(); +- addTestFile(''' +-main() { +- Future x =3D null; +-} +-'''); +- await waitForTasksFinished(); +- List errorFixes =3D await _getFixesAt('Future'); +- expect(errorFixes, hasLength(1)); +- AnalysisError error =3D errorFixes[0].error; +- expect(error.severity, AnalysisErrorSeverity.WARNING); +- expect(error.type, AnalysisErrorType.STATIC_WARNING); +- List fixes =3D errorFixes[0].fixes; +- expect(fixes, hasLength(2)); +- expect(fixes[0].message, matches('Import library')); +- expect(fixes[1].message, matches('Create class')); +- } +- +- test_fromPlugins() async { +- PluginInfo info =3D new DiscoveredPluginInfo('a', 'b', 'c', null, nul= l); +- plugin.AnalysisErrorFixes fixes =3D new plugin.AnalysisErrorFixes( +- new AnalysisError(AnalysisErrorSeverity.ERROR, AnalysisErrorType.= HINT, +- new Location('', 0, 0, 0, 0), 'message', 'code')); +- plugin.EditGetFixesResult result =3D +- new plugin.EditGetFixesResult([fixes]); +- pluginManager.broadcastResults =3D >{ +- info: new Future.value(result.toResponse('-', 1)) +- }; +- +- createProject(); +- addTestFile('main() {}'); +- await waitForTasksFinished(); +- List errorFixes =3D await _getFixesAt('in('); +- expect(errorFixes, hasLength(1)); +- } +- +- test_hasFixes() async { +- createProject(); +- addTestFile(''' +-foo() { +- print(1) +-} +-bar() { +- print(10) print(20) +-} +-'''); +- await waitForTasksFinished(); +- // print(1) +- { +- List errorFixes =3D await _getFixesAt('print(1)= '); +- expect(errorFixes, hasLength(1)); +- _isSyntacticErrorWithSingleFix(errorFixes[0]); +- } +- // print(10) +- { +- List errorFixes =3D await _getFixesAt('print(10= )'); +- expect(errorFixes, hasLength(2)); +- _isSyntacticErrorWithSingleFix(errorFixes[0]); +- _isSyntacticErrorWithSingleFix(errorFixes[1]); +- } +- } +- +- test_overlayOnlyFile() async { +- createProject(); +- testCode =3D ''' +-main() { +-print(1) +-} +-'''; +- _addOverlay(testFile, testCode); +- // ask for fixes +- await waitForTasksFinished(); +- List errorFixes =3D await _getFixesAt('print(1)'); +- expect(errorFixes, hasLength(1)); +- _isSyntacticErrorWithSingleFix(errorFixes[0]); +- } +- +- test_suggestImportFromDifferentAnalysisRoot() async { +- // Set up two projects. +- resourceProvider..newFolder("/project1")..newFolder("/project2"); +- handleSuccessfulRequest( +- new AnalysisSetAnalysisRootsParams(["/project1", "/project2"], []) +- .toRequest('0'), +- handler: analysisHandler); +- +- // Set up files. +- testFile =3D "/project1/main.dart"; +- testCode =3D "main() { print(new Foo()); }"; +- _addOverlay(testFile, testCode); +- // Add another file in the same project that imports the target file. +- // This ensures it will be analyzed as an implicit Source. +- _addOverlay("/project1/another.dart", 'import "../project2/target.dar= t";'); +- _addOverlay("/project2/target.dart", "class Foo() {}"); +- +- await waitForTasksFinished(); +- +- List fixes =3D (await _getFixesAt('Foo()')) +- .single +- .fixes +- .map((f) =3D> f.message) +- .toList(); +- expect(fixes, contains("Import library '../project2/target.dart'")); +- } +- +- void _addOverlay(String name, String contents) { +- Request request =3D +- new AnalysisUpdateContentParams({name: new AddContentOverlay(cont= ents)}) +- .toRequest('0'); +- handleSuccessfulRequest(request, handler: analysisHandler); +- } +- +- Future> _getFixes(int offset) async { +- Request request =3D new EditGetFixesParams(testFile, offset).toReques= t('0'); +- Response response =3D await waitResponse(request); +- var result =3D new EditGetFixesResult.fromResponse(response); +- return result.fixes; +- } +- +- Future> _getFixesAt(String search) async { +- int offset =3D findOffset(search); +- return await _getFixes(offset); +- } +- +- void _isSyntacticErrorWithSingleFix(AnalysisErrorFixes fixes) { +- AnalysisError error =3D fixes.error; +- expect(error.severity, AnalysisErrorSeverity.ERROR); +- expect(error.type, AnalysisErrorType.SYNTACTIC_ERROR); +- expect(fixes.fixes, hasLength(1)); +- } +-} +diff --git a/pkg/analysis_server/test/edit/format_test.dart b/pkg/analysis= _server/test/edit/format_test.dart +deleted file mode 100644 +index ced5eabf4b8..00000000000 +--- a/pkg/analysis_server/test/edit/format_test.dart ++++ /dev/null +@@ -1,125 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FormatTest); +- }); +-} +- +-@reflectiveTest +-class FormatTest extends AbstractAnalysisTest { +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- } +- +- Future test_format_longLine() { +- String content =3D ''' +-fun(firstParam, secondParam, thirdParam, fourthParam) { +- if (firstParam.noNull && secondParam.noNull && thirdParam.noNull && fou= rthParam.noNull) {} +-} +-'''; +- addTestFile(content); +- return waitForTasksFinished().then((_) { +- EditFormatResult formatResult =3D _formatAt(0, 3, lineLength: 100); +- +- expect(formatResult.edits, isNotNull); +- expect(formatResult.edits, hasLength(0)); +- +- expect(formatResult.selectionOffset, equals(0)); +- expect(formatResult.selectionLength, equals(3)); +- }); +- } +- +- Future test_format_noOp() { +- // Already formatted source +- addTestFile(''' +-main() { +- int x =3D 3; +-} +-'''); +- return waitForTasksFinished().then((_) { +- EditFormatResult formatResult =3D _formatAt(0, 3); +- expect(formatResult.edits, isNotNull); +- expect(formatResult.edits, hasLength(0)); +- }); +- } +- +- Future test_format_noSelection() async { +- addTestFile(''' +-main() { int x =3D 3; } +-'''); +- await waitForTasksFinished(); +- EditFormatResult formatResult =3D _formatAt(0, 0); +- +- expect(formatResult.edits, isNotNull); +- expect(formatResult.edits, hasLength(1)); +- +- SourceEdit edit =3D formatResult.edits[0]; +- expect(edit.replacement, equals(''' +-main() { +- int x =3D 3; +-} +-''')); +- expect(formatResult.selectionOffset, equals(0)); +- expect(formatResult.selectionLength, equals(0)); +- } +- +- Future test_format_simple() { +- addTestFile(''' +-main() { int x =3D 3; } +-'''); +- return waitForTasksFinished().then((_) { +- EditFormatResult formatResult =3D _formatAt(0, 3); +- +- expect(formatResult.edits, isNotNull); +- expect(formatResult.edits, hasLength(1)); +- +- SourceEdit edit =3D formatResult.edits[0]; +- expect(edit.replacement, equals(''' +-main() { +- int x =3D 3; +-} +-''')); +- expect(formatResult.selectionOffset, equals(0)); +- expect(formatResult.selectionLength, equals(3)); +- }); +- } +- +- Future test_format_withErrors() { +- addTestFile(''' +-main() { int x =3D +-'''); +- return waitForTasksFinished().then((_) { +- Request request =3D new EditFormatParams(testFile, 0, 3).toRequest(= '0'); +- Response response =3D handler.handleRequest(request); +- expect(response, isResponseFailure('0')); +- }); +- } +- +- EditFormatResult _formatAt(int selectionOffset, int selectionLength, +- {int lineLength}) { +- Request request =3D new EditFormatParams( +- testFile, selectionOffset, selectionLength, +- lineLength: lineLength) +- .toRequest('0'); +- Response response =3D handleSuccessfulRequest(request); +- return new EditFormatResult.fromResponse(response); +- } +-} +diff --git a/pkg/analysis_server/test/edit/organize_directives_test.dart b= /pkg/analysis_server/test/edit/organize_directives_test.dart +deleted file mode 100644 +index cf320de2ca8..00000000000 +--- a/pkg/analysis_server/test/edit/organize_directives_test.dart ++++ /dev/null +@@ -1,167 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OrganizeDirectivesTest); +- }); +-} +- +-@reflectiveTest +-class OrganizeDirectivesTest extends AbstractAnalysisTest { +- SourceFileEdit fileEdit; +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- } +- +- @failingTest +- Future test_BAD_doesNotExist() async { +- // The analysis driver fails to return an error +- Request request =3D +- new EditOrganizeDirectivesParams('/no/such/file.dart').toRequest(= '0'); +- Response response =3D await waitResponse(request); +- expect( +- response, isResponseFailure('0', RequestErrorCode.FILE_NOT_ANALYZ= ED)); +- } +- +- Future test_BAD_hasParseError() async { +- addTestFile(''' +-import 'dart:async' +- +-main() {} +-'''); +- Request request =3D new EditOrganizeDirectivesParams(testFile).toRequ= est('0'); +- Response response =3D await waitResponse(request); +- expect(response, +- isResponseFailure('0', RequestErrorCode.ORGANIZE_DIRECTIVES_ERROR= )); +- } +- +- Future test_BAD_notDartFile() async { +- Request request =3D +- new EditOrganizeDirectivesParams('/not-a-Dart-file.txt').toReques= t('0'); +- Response response =3D await waitResponse(request); +- expect( +- response, isResponseFailure('0', RequestErrorCode.FILE_NOT_ANALYZ= ED)); +- } +- +- Future test_OK_remove_duplicateImports_withSamePrefix() { +- addTestFile(''' +-library lib; +- +-import 'dart:async' as async; +-import 'dart:async' as async; +- +-main() { +- async.Future f; +-} +-'''); +- return _assertOrganized(r''' +-library lib; +- +-import 'dart:async' as async; +- +-main() { +- async.Future f; +-} +-'''); +- } +- +- Future test_OK_remove_unresolvedDirectives() { +- addFile('$testFolder/existing_part1.dart', 'part of lib;'); +- addFile('$testFolder/existing_part2.dart', 'part of lib;'); +- addTestFile(''' +-library lib; +- +-export 'dart:noSuchExportSdkLibrary'; +-export 'dart:async'; +-export 'package:noSuchExportPackage/andLib.dart'; +-export 'dart:math'; +- +-import 'dart:async'; +-import 'dart:noSuchImportSdkLibrary'; +-import 'dart:math'; +-import 'package:noSuchImportPackage/andLib.dart'; +- +-part 'existing_part1.dart'; +-part 'no_such_part.dart'; +-part 'existing_part2.dart'; +- +-main(Future f) { +- print(PI); +-} +-'''); +- return _assertOrganized(r''' +-library lib; +- +-import 'dart:async'; +-import 'dart:math'; +- +-export 'dart:async'; +-export 'dart:math'; +- +-part 'existing_part1.dart'; +-part 'existing_part2.dart'; +- +-main(Future f) { +- print(PI); +-} +-'''); +- } +- +- Future test_OK_remove_unusedImports() { +- addTestFile(''' +-library lib; +- +-import 'dart:async'; +-import 'dart:math'; +-import 'dart:convert'; +-import 'dart:collection'; +- +-main() { +- print(PI); +- new HashMap(); +-} +-'''); +- return _assertOrganized(r''' +-library lib; +- +-import 'dart:collection'; +-import 'dart:math'; +- +-main() { +- print(PI); +- new HashMap(); +-} +-'''); +- } +- +- Future _assertOrganized(String expectedCode) async { +- await _requestOrganize(); +- String resultCode =3D SourceEdit.applySequence(testCode, fileEdit.edi= ts); +- expect(resultCode, expectedCode); +- } +- +- Future _requestOrganize() async { +- Request request =3D new EditOrganizeDirectivesParams(testFile).toRequ= est('0'); +- Response response =3D await waitResponse(request); +- var result =3D new EditOrganizeDirectivesResult.fromResponse(response= ); +- fileEdit =3D result.edit; +- } +-} +diff --git a/pkg/analysis_server/test/edit/postfix_completion_test.dart b/= pkg/analysis_server/test/edit/postfix_completion_test.dart +deleted file mode 100644 +index 61fb2f68d68..00000000000 +--- a/pkg/analysis_server/test/edit/postfix_completion_test.dart ++++ /dev/null +@@ -1,93 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(PostfixCompletionTest); +- }); +-} +- +-@reflectiveTest +-class PostfixCompletionTest extends AbstractAnalysisTest { +- SourceChange change; +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- } +- +- test_for() async { +- addTestFile(''' +-main() { +- [].for +-} +-'''); +- await waitForTasksFinished(); +- await _prepareCompletion('.for', atStart: true); +- _assertHasChange('Expand .for', ''' +-main() { +- for (var value in []) { +- /*caret*/ +- } +-} +-'''); +- } +- +- void _assertHasChange(String message, String expectedCode, [Function cm= p]) { +- if (change.message =3D=3D message) { +- if (!change.edits.isEmpty) { +- String resultCode =3D +- SourceEdit.applySequence(testCode, change.edits[0].edits); +- expect(resultCode, expectedCode.replaceAll('/*caret*/', '')); +- if (cmp !=3D null) { +- int offset =3D cmp(resultCode); +- expect(change.selection.offset, offset); +- } +- } else { +- if (cmp !=3D null) { +- int offset =3D cmp(testCode); +- expect(change.selection.offset, offset); +- } +- } +- return; +- } +- fail("Expected to find |$message| but got: " + change.message); +- } +- +- _prepareCompletion(String key, +- {bool atStart: false, bool atEnd: false, int delta: 0}) async { +- int offset =3D findOffset(key); +- String src =3D testCode.replaceFirst(key, '', offset); +- modifyTestFile(src); +- await _prepareCompletionAt(offset, key); +- } +- +- _prepareCompletionAt(int offset, String key) async { +- var params =3D new EditGetPostfixCompletionParams(testFile, key, offs= et); +- var request =3D +- new Request('0', "edit.isPostfixCompletionApplicable", params.toJ= son()); +- Response response =3D await waitResponse(request); +- var isApplicable =3D +- new EditIsPostfixCompletionApplicableResult.fromResponse(response= ); +- if (!isApplicable.value) { +- fail("Postfix completion not applicable at given location"); +- } +- request =3D new EditGetPostfixCompletionParams(testFile, key, offset) +- .toRequest('1'); +- response =3D await waitResponse(request); +- var result =3D new EditGetPostfixCompletionResult.fromResponse(respon= se); +- change =3D result.change; +- } +-} +diff --git a/pkg/analysis_server/test/edit/refactoring_test.dart b/pkg/ana= lysis_server/test/edit/refactoring_test.dart +deleted file mode 100644 +index fd225c6d005..00000000000 +--- a/pkg/analysis_server/test/edit/refactoring_test.dart ++++ /dev/null +@@ -1,2016 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ConvertGetterMethodToMethodTest); +- defineReflectiveTests(ConvertMethodToGetterTest); +- defineReflectiveTests(ExtractLocalVariableTest); +- defineReflectiveTests(ExtractMethodTest); +- defineReflectiveTests(GetAvailableRefactoringsTest); +- defineReflectiveTests(InlineLocalTest); +- defineReflectiveTests(InlineMethodTest); +- defineReflectiveTests(MoveFileTest); +- // TODO(brianwilkerson) Re-enable these tests. They were commented out +- // because they are non-deterministic under the new driver. I suspect= that +- // there is a future that isn't being waited for. +-// defineReflectiveTests(RenameTest); +- }); +-} +- +-@reflectiveTest +-class ConvertGetterMethodToMethodTest extends _AbstractGetRefactoring_Tes= t { +- test_function() { +- addTestFile(''' +-int get test =3D> 42; +-main() { +- var a =3D 1 + test; +- var b =3D 2 + test; +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendConvertRequest('test =3D>'); +- }, ''' +-int test() =3D> 42; +-main() { +- var a =3D 1 + test(); +- var b =3D 2 + test(); +-} +-'''); +- } +- +- test_init_fatalError_notExplicit() { +- addTestFile(''' +-int test =3D 42; +-main() { +- var v =3D test; +-} +-'''); +- return getRefactoringResult(() { +- return _sendConvertRequest('test;'); +- }).then((result) { +- assertResultProblemsFatal(result.initialProblems, +- 'Only explicit getters can be converted to methods.'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_method() { +- addTestFile(''' +-class A { +- int get test =3D> 1; +-} +-class B extends A { +- int get test =3D> 2; +-} +-class C extends B { +- int get test =3D> 3; +-} +-class D extends A { +- int get test =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test; +- var vb =3D b.test; +- var vc =3D c.test; +- var vd =3D d.test; +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendConvertRequest('test =3D> 2'); +- }, ''' +-class A { +- int test() =3D> 1; +-} +-class B extends A { +- int test() =3D> 2; +-} +-class C extends B { +- int test() =3D> 3; +-} +-class D extends A { +- int test() =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test(); +- var vb =3D b.test(); +- var vc =3D c.test(); +- var vd =3D d.test(); +-} +-'''); +- } +- +- Future _sendConvertRequest(String search) { +- Request request =3D new EditGetRefactoringParams( +- RefactoringKind.CONVERT_GETTER_TO_METHOD, +- testFile, +- findOffset(search), +- 0, +- false) +- .toRequest('0'); +- return serverChannel.sendRequest(request); +- } +-} +- +-@reflectiveTest +-class ConvertMethodToGetterTest extends _AbstractGetRefactoring_Test { +- test_function() { +- addTestFile(''' +-int test() =3D> 42; +-main() { +- var a =3D 1 + test(); +- var b =3D 2 + test(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendConvertRequest('test() =3D>'); +- }, ''' +-int get test =3D> 42; +-main() { +- var a =3D 1 + test; +- var b =3D 2 + test; +-} +-'''); +- } +- +- test_init_fatalError_hasParameters() { +- addTestFile(''' +-int test(p) =3D> p + 1; +-main() { +- var v =3D test(2); +-} +-'''); +- return getRefactoringResult(() { +- return _sendConvertRequest('test(p)'); +- }).then((result) { +- assertResultProblemsFatal(result.initialProblems, +- 'Only methods without parameters can be converted to getters.'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_init_fatalError_notExecutableElement() { +- addTestFile(''' +-main() { +- int abc =3D 1; +- print(abc); +-} +-'''); +- return getRefactoringResult(() { +- return _sendConvertRequest('abc'); +- }).then((result) { +- assertResultProblemsFatal( +- result.initialProblems, 'Unable to create a refactoring'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_method() { +- addTestFile(''' +-class A { +- int test() =3D> 1; +-} +-class B extends A { +- int test() =3D> 2; +-} +-class C extends B { +- int test() =3D> 3; +-} +-class D extends A { +- int test() =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test(); +- var vb =3D b.test(); +- var vc =3D c.test(); +- var vd =3D d.test(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendConvertRequest('test() =3D> 2'); +- }, ''' +-class A { +- int get test =3D> 1; +-} +-class B extends A { +- int get test =3D> 2; +-} +-class C extends B { +- int get test =3D> 3; +-} +-class D extends A { +- int get test =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test; +- var vb =3D b.test; +- var vc =3D c.test; +- var vd =3D d.test; +-} +-'''); +- } +- +- Future _sendConvertRequest(String search) { +- Request request =3D new EditGetRefactoringParams( +- RefactoringKind.CONVERT_METHOD_TO_GETTER, +- testFile, +- findOffset(search), +- 0, +- false) +- .toRequest('0'); +- return serverChannel.sendRequest(request); +- } +-} +- +-@reflectiveTest +-class ExtractLocalVariableTest extends _AbstractGetRefactoring_Test { +- Future sendExtractRequest( +- int offset, int length, String name, bool extractAll) { +- RefactoringKind kind =3D RefactoringKind.EXTRACT_LOCAL_VARIABLE; +- ExtractLocalVariableOptions options =3D +- name !=3D null ? new ExtractLocalVariableOptions(name, extractAll= ) : null; +- return sendRequest(kind, offset, length, options, false); +- } +- +- Future sendStringRequest( +- String search, String name, bool extractAll) { +- int offset =3D findOffset(search); +- int length =3D search.length; +- return sendExtractRequest(offset, length, name, extractAll); +- } +- +- Future sendStringSuffixRequest( +- String search, String suffix, String name, bool extractAll) { +- int offset =3D findOffset(search + suffix); +- int length =3D search.length; +- return sendExtractRequest(offset, length, name, extractAll); +- } +- +- void tearDown() { +- test_simulateRefactoringException_init =3D false; +- test_simulateRefactoringException_final =3D false; +- test_simulateRefactoringException_change =3D false; +- super.tearDown(); +- } +- +- test_analysis_onlyOneFile() async { +- shouldWaitForFullAnalysis =3D false; +- String otherFile =3D '$testFolder/other.dart'; +- addFile(otherFile, r''' +-foo(int myName) {} +-'''); +- addTestFile(''' +-import 'other.dart'; +-main() { +- foo(1 + 2); +-} +-'''); +- // Start refactoring. +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'res', true); +- }); +- // We get the refactoring feedback.... +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.names, contains('myName')); +- } +- +- test_coveringExpressions() { +- addTestFile(''' +-main() { +- var v =3D 111 + 222 + 333; +-} +-'''); +- return getRefactoringResult(() { +- return sendExtractRequest(testCode.indexOf('222 +'), 0, 'res', true= ); +- }).then((result) { +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.coveringExpressionOffsets, [ +- testCode.indexOf('222 +'), +- testCode.indexOf('111 +'), +- testCode.indexOf('111 +') +- ]); +- expect(feedback.coveringExpressionLengths, +- ['222'.length, '111 + 222'.length, '111 + 222 + 333'.length]); +- }); +- } +- +- test_extractAll() { +- addTestFile(''' +-main() { +- print(1 + 2); +- print(1 + 2); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendStringRequest('1 + 2', 'res', true); +- }, ''' +-main() { +- var res =3D 1 + 2; +- print(res); +- print(res); +-} +-'''); +- } +- +- test_extractOne() { +- addTestFile(''' +-main() { +- print(1 + 2); +- print(1 + 2); // marker +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendStringSuffixRequest('1 + 2', '); // marker', 'res', fals= e); +- }, ''' +-main() { +- print(1 + 2); +- var res =3D 1 + 2; +- print(res); // marker +-} +-'''); +- } +- +- test_names() async { +- addTestFile(''' +-class TreeItem {} +-TreeItem getSelectedItem() =3D> null; +-main() { +- var a =3D getSelectedItem(); +-} +-'''); +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendStringSuffixRequest('getSelectedItem()', ';', null, true= ); +- }); +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- expect( +- feedback.names, unorderedEquals(['treeItem', 'item', 'selectedIte= m'])); +- expect(result.change, isNull); +- } +- +- test_nameWarning() async { +- addTestFile(''' +-main() { +- print(1 + 2); +-} +-'''); +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'Name', true); +- }); +- assertResultProblemsWarning(result.optionsProblems, +- 'Variable name should start with a lowercase letter.'); +- // ...but there is still a change +- assertTestRefactoringResult(result, ''' +-main() { +- var Name =3D 1 + 2; +- print(Name); +-} +-'''); +- } +- +- test_offsetsLengths() { +- addTestFile(''' +-main() { +- print(1 + 2); +- print(1 + 2); +-} +-'''); +- return getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'res', true); +- }).then((result) { +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.offsets, [findOffset('1 + 2'), findOffset('1 + 2')= ]); +- expect(feedback.lengths, [5, 6]); +- }); +- } +- +- test_resetOnAnalysisSetChanged_overlay() async { +- addTestFile(''' +-main() { +- print(1 + 2); // 0 +-} +-'''); +- +- Future checkUpdate(doUpdate()) async { +- await getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'res', true); +- }); +- int initialResetCount =3D test_resetCount; +- doUpdate(); +- await pumpEventQueue(); +- expect(test_resetCount, initialResetCount + 1); +- } +- +- await checkUpdate(() { +- server.updateContent('u1', { +- testFile: new AddContentOverlay(''' +-main() { +- print(1 + 2); // 1 +-} +-''') +- }); +- }); +- +- await checkUpdate(() { +- server.updateContent('u2', { +- testFile: new ChangeContentOverlay([ +- new SourceEdit(0, 0, ''' +-main() { +- print(1 + 2); // 2 +-} +-''') +- ]) +- }); +- }); +- +- await checkUpdate(() { +- server.updateContent('u3', {testFile: new RemoveContentOverlay()}); +- }); +- } +- +- test_resetOnAnalysisSetChanged_watch_otherFile() async { +- String otherFile =3D '$testFolder/other.dart'; +- addFile(otherFile, '// other 1'); +- addTestFile(''' +-main() { +- foo(1 + 2); +-} +-foo(int myName) {} +-'''); +- // Send the first request. +- { +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'res', true); +- }); +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.names, contains('myName')); +- } +- int initialResetCount =3D test_resetCount; +- // Update the other.dart file. +- // The refactoring is reset, even though it's a different file. It is= up to +- // analyzer to track dependencies and provide resolved units fast when +- // possible. +- addFile(otherFile, '// other 2'); +- await pumpEventQueue(); +- expect(test_resetCount, initialResetCount + 1); +- } +- +- test_resetOnAnalysisSetChanged_watch_thisFile() async { +- addTestFile(''' +-main() { +- foo(1 + 2); +-} +-foo(int myName) {} +-'''); +- // Send the first request. +- { +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'res', true); +- }); +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.names, contains('myName')); +- } +- int initialResetCount =3D test_resetCount; +- // Update the test.dart file. +- modifyTestFile(''' +-main() { +- foo(1 + 2); +-} +-foo(int otherName) {} +-'''); +- // The refactoring was reset. +- await pumpEventQueue(); +- expect(test_resetCount, initialResetCount + 1); +- // Send the second request, with the same kind, file and offset. +- { +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendStringRequest('1 + 2', 'res', true); +- }); +- ExtractLocalVariableFeedback feedback =3D result.feedback; +- // The refactoring was reset, so we don't get stale results. +- expect(feedback.names, contains('otherName')); +- } +- } +- +- test_serverError_change() { +- test_simulateRefactoringException_change =3D true; +- addTestFile(''' +-main() { +- print(1 + 2); +-} +-'''); +- return waitForTasksFinished().then((_) { +- return sendStringRequest('1 + 2', 'res', true).then((response) { +- expect(response.error, isNotNull); +- expect(response.error.code, RequestErrorCode.SERVER_ERROR); +- }); +- }); +- } +- +- test_serverError_final() { +- test_simulateRefactoringException_final =3D true; +- addTestFile(''' +-main() { +- print(1 + 2); +-} +-'''); +- return waitForTasksFinished().then((_) { +- return sendStringRequest('1 + 2', 'res', true).then((response) { +- expect(response.error, isNotNull); +- expect(response.error.code, RequestErrorCode.SERVER_ERROR); +- }); +- }); +- } +- +- test_serverError_init() { +- test_simulateRefactoringException_init =3D true; +- addTestFile(''' +-main() { +- print(1 + 2); +-} +-'''); +- return waitForTasksFinished().then((_) { +- return sendStringRequest('1 + 2', 'res', true).then((response) { +- expect(response.error, isNotNull); +- expect(response.error.code, RequestErrorCode.SERVER_ERROR); +- }); +- }); +- } +-} +- +-@reflectiveTest +-class ExtractMethodTest extends _AbstractGetRefactoring_Test { +- int offset; +- int length; +- String name =3D 'res'; +- ExtractMethodOptions options; +- +- test_expression() { +- addTestFile(''' +-main() { +- print(1 + 2); +- print(1 + 2); +-} +-'''); +- _setOffsetLengthForString('1 + 2'); +- return assertSuccessfulRefactoring(_computeChange, ''' +-main() { +- print(res()); +- print(res()); +-} +- +-int res() =3D> 1 + 2; +-'''); +- } +- +- test_expression_hasParameters() { +- addTestFile(''' +-main() { +- int a =3D 1; +- int b =3D 2; +- print(a + b); +- print(a + b); +-} +-'''); +- _setOffsetLengthForString('a + b'); +- return assertSuccessfulRefactoring(_computeChange, ''' +-main() { +- int a =3D 1; +- int b =3D 2; +- print(res(a, b)); +- print(res(a, b)); +-} +- +-int res(int a, int b) =3D> a + b; +-'''); +- } +- +- test_expression_updateParameters() { +- addTestFile(''' +-main() { +- int a =3D 1; +- int b =3D 2; +- print(a + b); +- print(a + b); +-} +-'''); +- _setOffsetLengthForString('a + b'); +- return getRefactoringResult(_computeChange).then((result) { +- ExtractMethodFeedback feedback =3D result.feedback; +- List parameters =3D feedback.parameters; +- parameters[0].name =3D 'aaa'; +- parameters[1].name =3D 'bbb'; +- parameters[1].type =3D 'num'; +- parameters.insert(0, parameters.removeLast()); +- options.parameters =3D parameters; +- return assertSuccessfulRefactoring(_sendExtractRequest, ''' +-main() { +- int a =3D 1; +- int b =3D 2; +- print(res(b, a)); +- print(res(b, a)); +-} +- +-int res(num bbb, int aaa) =3D> aaa + bbb; +-'''); +- }); +- } +- +- test_init_fatalError_invalidStatement() { +- addTestFile(''' +-main(bool b) { +-// start +- if (b) { +- print(1); +-// end +- print(2); +- } +-} +-'''); +- _setOffsetLengthForStartEnd(); +- return waitForTasksFinished().then((_) { +- return _sendExtractRequest(); +- }).then((Response response) { +- var result =3D new EditGetRefactoringResult.fromResponse(response); +- assertResultProblemsFatal(result.initialProblems); +- // ...there is no any feedback +- expect(result.feedback, isNull); +- }); +- } +- +- test_long_expression() { +- addTestFile(''' +-main() { +- print(1 + +- 2); +-} +-'''); +- _setOffsetLengthForString('1 +\n 2'); +- return assertSuccessfulRefactoring(_computeChange, ''' +-main() { +- print(res()); +-} +- +-int res() { +- return 1 + +- 2; +-} +-'''); +- } +- +- test_names() { +- addTestFile(''' +-class TreeItem {} +-TreeItem getSelectedItem() =3D> null; +-main() { +- var a =3D getSelectedItem( ); +-} +-'''); +- _setOffsetLengthForString('getSelectedItem( )'); +- return _computeInitialFeedback().then((feedback) { +- expect(feedback.names, +- unorderedEquals(['treeItem', 'item', 'selectedItem'])); +- expect(feedback.returnType, 'TreeItem'); +- }); +- } +- +- test_offsetsLengths() { +- addTestFile(''' +-class TreeItem {} +-TreeItem getSelectedItem() =3D> null; +-main() { +- var a =3D 1 + 2; +- var b =3D 1 + 2; +-} +-'''); +- _setOffsetLengthForString('1 + 2'); +- return _computeInitialFeedback().then((feedback) { +- expect(feedback.offsets, [findOffset('1 + 2'), findOffset('1 + 2')= ]); +- expect(feedback.lengths, [5, 6]); +- }); +- } +- +- test_statements() { +- addTestFile(''' +-main() { +- int a =3D 1; +- int b =3D 2; +-// start +- print(a + b); +-// end +- print(a + b); +-} +-'''); +- _setOffsetLengthForStartEnd(); +- return assertSuccessfulRefactoring(_computeChange, ''' +-main() { +- int a =3D 1; +- int b =3D 2; +-// start +- res(a, b); +-// end +- res(a, b); +-} +- +-void res(int a, int b) { +- print(a + b); +-} +-'''); +- } +- +- Future _computeChange() async { +- await _prepareOptions(); +- // send request with the options +- return _sendExtractRequest(); +- } +- +- Future _computeInitialFeedback() async { +- await waitForTasksFinished(); +- Response response =3D await _sendExtractRequest(); +- var result =3D new EditGetRefactoringResult.fromResponse(response); +- return result.feedback; +- } +- +- Future _prepareOptions() { +- return getRefactoringResult(() { +- // get initial feedback +- return _sendExtractRequest(); +- }).then((result) { +- assertResultProblemsOK(result); +- // fill options from result +- ExtractMethodFeedback feedback =3D result.feedback; +- options =3D new ExtractMethodOptions( +- feedback.returnType, false, name, feedback.parameters, true); +- // done +- return new Future.value(); +- }); +- } +- +- Future _sendExtractRequest() { +- RefactoringKind kind =3D RefactoringKind.EXTRACT_METHOD; +- return sendRequest(kind, offset, length, options, false); +- } +- +- void _setOffsetLengthForStartEnd() { +- offset =3D findOffset('// start') + '// start\n'.length; +- length =3D findOffset('// end') - offset; +- } +- +- void _setOffsetLengthForString(String search) { +- offset =3D findOffset(search); +- length =3D search.length; +- } +-} +- +-@reflectiveTest +-class GetAvailableRefactoringsTest extends AbstractAnalysisTest { +- List kinds; +- +- /** +- * Tests that there is refactoring of the given [kind] is available at = the +- * [search] offset. +- */ +- Future assertHasKind( +- String code, String search, RefactoringKind kind, bool expected) as= ync { +- addTestFile(code); +- await waitForTasksFinished(); +- await getRefactoringsAtString(search); +- // verify +- Matcher matcher =3D contains(kind); +- if (!expected) { +- matcher =3D isNot(matcher); +- } +- expect(kinds, matcher); +- } +- +- /** +- * Tests that there is a RENAME refactoring available at the [search] o= ffset. +- */ +- Future assertHasRenameRefactoring(String code, String search) async { +- return assertHasKind(code, search, RefactoringKind.RENAME, true); +- } +- +- /** +- * Returns the list of available refactorings for the given [offset] and +- * [length]. +- */ +- Future getRefactorings(int offset, int length) async { +- Request request =3D +- new EditGetAvailableRefactoringsParams(testFile, offset, length) +- .toRequest('0'); +- serverChannel.sendRequest(request); +- var response =3D await serverChannel.waitForResponse(request); +- var result =3D new EditGetAvailableRefactoringsResult.fromResponse(re= sponse); +- kinds =3D result.kinds; +- } +- +- /** +- * Returns the list of available refactorings at the offset of [search]. +- */ +- Future getRefactoringsAtString(String search) { +- int offset =3D findOffset(search); +- return getRefactorings(offset, 0); +- } +- +- Future getRefactoringsForString(String search) { +- int offset =3D findOffset(search); +- return getRefactorings(offset, search.length); +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- server.handlers =3D [handler]; +- } +- +- Future test_convertMethodToGetter_hasElement() { +- return assertHasKind(''' +-int getValue() =3D> 42; +-''', 'getValue', RefactoringKind.CONVERT_METHOD_TO_GETTER, true); +- } +- +- Future test_extractLocal() async { +- addTestFile(''' +-main() { +- var a =3D 1 + 2; +-} +-'''); +- await waitForTasksFinished(); +- await getRefactoringsForString('1 + 2'); +- expect(kinds, contains(RefactoringKind.EXTRACT_LOCAL_VARIABLE)); +- expect(kinds, contains(RefactoringKind.EXTRACT_METHOD)); +- } +- +- Future test_rename_hasElement_class() { +- return assertHasRenameRefactoring(''' +-class Test {} +-main() { +- Test v; +-} +-''', 'Test v'); +- } +- +- Future test_rename_hasElement_constructor() { +- return assertHasRenameRefactoring(''' +-class A { +- A.test() {} +-} +-main() { +- new A.test(); +-} +-''', 'test();'); +- } +- +- Future test_rename_hasElement_function() { +- return assertHasRenameRefactoring(''' +-main() { +- test(); +-} +-test() {} +-''', 'test();'); +- } +- +- Future test_rename_hasElement_importElement_directive() { +- return assertHasRenameRefactoring(''' +-import 'dart:math' as math; +-main() { +- math.PI; +-} +-''', 'import '); +- } +- +- Future test_rename_hasElement_importElement_prefixDecl() { +- return assertHasRenameRefactoring(''' +-import 'dart:math' as math; +-main() { +- math.PI; +-} +-''', 'math;'); +- } +- +- Future test_rename_hasElement_importElement_prefixRef() { +- return assertHasRenameRefactoring(''' +-import 'dart:async' as test; +-import 'dart:math' as test; +-main() { +- test.PI; +-} +-''', 'test.PI;'); +- } +- +- Future test_rename_hasElement_instanceGetter() { +- return assertHasRenameRefactoring(''' +-class A { +- get test =3D> 0; +-} +-main(A a) { +- a.test; +-} +-''', 'test;'); +- } +- +- Future test_rename_hasElement_instanceSetter() { +- return assertHasRenameRefactoring(''' +-class A { +- set test(x) {} +-} +-main(A a) { +- a.test =3D 2; +-} +-''', 'test =3D 2;'); +- } +- +- Future test_rename_hasElement_library() { +- return assertHasRenameRefactoring(''' +-library my.lib; +-''', 'library '); +- } +- +- Future test_rename_hasElement_localVariable() { +- return assertHasRenameRefactoring(''' +-main() { +- int test =3D 0; +- print(test); +-} +-''', 'test =3D 0;'); +- } +- +- Future test_rename_hasElement_method() { +- return assertHasRenameRefactoring(''' +-class A { +- test() {} +-} +-main(A a) { +- a.test(); +-} +-''', 'test();'); +- } +- +- Future test_rename_noElement() async { +- addTestFile(''' +-main() { +- // not an element +-} +-'''); +- await waitForTasksFinished(); +- await getRefactoringsAtString('// not an element'); +- expect(kinds, isNot(contains(RefactoringKind.RENAME))); +- } +-} +- +-@reflectiveTest +-class InlineLocalTest extends _AbstractGetRefactoring_Test { +- test_analysis_onlyOneFile() async { +- shouldWaitForFullAnalysis =3D false; +- String otherFile =3D '$testFolder/other.dart'; +- addFile(otherFile, r''' +-foo(int p) {} +-'''); +- addTestFile(''' +-import 'other.dart'; +-main() { +- int res =3D 1 + 2; +- foo(res); +- foo(res); +-} +-'''); +- // Start refactoring. +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return _sendInlineRequest('res =3D'); +- }); +- // We get the refactoring feedback.... +- InlineLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.occurrences, 2); +- } +- +- test_feedback() { +- addTestFile(''' +-main() { +- int test =3D 42; +- print(test); +- print(test); +-} +-'''); +- return getRefactoringResult(() { +- return _sendInlineRequest('test =3D'); +- }).then((result) { +- InlineLocalVariableFeedback feedback =3D result.feedback; +- expect(feedback.name, 'test'); +- expect(feedback.occurrences, 2); +- }); +- } +- +- test_init_fatalError_notVariable() { +- addTestFile('main() {}'); +- return getRefactoringResult(() { +- return _sendInlineRequest('main() {}'); +- }).then((result) { +- assertResultProblemsFatal(result.initialProblems, +- 'Local variable declaration or reference must be selected to ac= tivate this refactoring.'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_OK() { +- addTestFile(''' +-main() { +- int test =3D 42; +- int a =3D test + 2; +- print(test); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendInlineRequest('test + 2'); +- }, ''' +-main() { +- int a =3D 42 + 2; +- print(42); +-} +-'''); +- } +- +- test_resetOnAnalysisSetChanged() async { +- String otherFile =3D '$testFolder/other.dart'; +- addFile(otherFile, '// other 1'); +- addTestFile(''' +-main() { +- int res =3D 1 + 2; +- print(res); +-} +-'''); +- // Send the first request. +- await getRefactoringResult(() { +- return _sendInlineRequest('res =3D '); +- }); +- int initialResetCount =3D test_resetCount; +- // Update the test.dart file. +- modifyTestFile(''' +-main() { +- print(1 + 2); +-} +-'''); +- // The refactoring was reset. +- await pumpEventQueue(); +- expect(test_resetCount, initialResetCount + 1); +- } +- +- Future _sendInlineRequest(String search) { +- Request request =3D new EditGetRefactoringParams( +- RefactoringKind.INLINE_LOCAL_VARIABLE, +- testFile, +- findOffset(search), +- 0, +- false) +- .toRequest('0'); +- return serverChannel.sendRequest(request); +- } +-} +- +-@reflectiveTest +-class InlineMethodTest extends _AbstractGetRefactoring_Test { +- InlineMethodOptions options =3D new InlineMethodOptions(true, true); +- +- test_feedback() { +- addTestFile(''' +-class A { +- int f; +- test(int p) { +- print(f + p); +- } +- main() { +- test(1); +- } +-} +-'''); +- return getRefactoringResult(() { +- return _sendInlineRequest('test(int p)'); +- }).then((result) { +- InlineMethodFeedback feedback =3D result.feedback; +- expect(feedback.className, 'A'); +- expect(feedback.methodName, 'test'); +- expect(feedback.isDeclaration, isTrue); +- }); +- } +- +- test_init_fatalError_noMethod() { +- addTestFile('// nothing to inline'); +- return getRefactoringResult(() { +- return _sendInlineRequest('// nothing'); +- }).then((result) { +- assertResultProblemsFatal(result.initialProblems, +- 'Method declaration or reference must be selected to activate t= his refactoring.'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_method() { +- addTestFile(''' +-class A { +- int f; +- test(int p) { +- print(f + p); +- } +- main() { +- test(1); +- } +-} +-main(A a) { +- a.test(2); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendInlineRequest('test(int p)'); +- }, ''' +-class A { +- int f; +- main() { +- print(f + 1); +- } +-} +-main(A a) { +- print(a.f + 2); +-} +-'''); +- } +- +- test_topLevelFunction() { +- addTestFile(''' +-test(a, b) { +- print(a + b); +-} +-main() { +- test(1, 2); +- test(10, 20); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return _sendInlineRequest('test(a'); +- }, ''' +-main() { +- print(1 + 2); +- print(10 + 20); +-} +-'''); +- } +- +- test_topLevelFunction_oneInvocation() { +- addTestFile(''' +-test(a, b) { +- print(a + b); +-} +-main() { +- test(1, 2); +- test(10, 20); +-} +-'''); +- options.deleteSource =3D false; +- options.inlineAll =3D false; +- return assertSuccessfulRefactoring(() { +- return _sendInlineRequest('test(10,'); +- }, ''' +-test(a, b) { +- print(a + b); +-} +-main() { +- test(1, 2); +- print(10 + 20); +-} +-'''); +- } +- +- Future _sendInlineRequest(String search) { +- Request request =3D new EditGetRefactoringParams( +- RefactoringKind.INLINE_METHOD, +- testFile, +- findOffset(search), +- 0, +- false, +- options: options) +- .toRequest('0'); +- return serverChannel.sendRequest(request); +- } +-} +- +-@reflectiveTest +-class MoveFileTest extends _AbstractGetRefactoring_Test { +- MoveFileOptions options; +- +- @failingTest +- test_OK() { +- fail('The move file refactoring is not supported under the new driver= '); +- resourceProvider.newFile('/project/bin/lib.dart', ''); +- addTestFile(''' +-import 'dart:math'; +-import 'lib.dart'; +-'''); +- _setOptions('/project/test.dart'); +- return assertSuccessfulRefactoring(() { +- return _sendMoveRequest(); +- }, ''' +-import 'dart:math'; +-import 'bin/lib.dart'; +-'''); +- } +- +- Future _sendMoveRequest() { +- Request request =3D new EditGetRefactoringParams( +- RefactoringKind.MOVE_FILE, testFile, 0, 0, false, +- options: options) +- .toRequest('0'); +- return serverChannel.sendRequest(request); +- } +- +- void _setOptions(String newFile) { +- options =3D new MoveFileOptions(newFile); +- } +-} +- +-@reflectiveTest +-class RenameTest extends _AbstractGetRefactoring_Test { +- Future sendRenameRequest(String search, String newName, +- {String id: '0', bool validateOnly: false}) { +- RenameOptions options =3D newName !=3D null ? new RenameOptions(newNa= me) : null; +- Request request =3D new EditGetRefactoringParams(RefactoringKind.RENA= ME, +- testFile, findOffset(search), 0, validateOnly, +- options: options) +- .toRequest(id); +- return serverChannel.sendRequest(request); +- } +- +- void tearDown() { +- test_simulateRefactoringReset_afterInitialConditions =3D false; +- test_simulateRefactoringReset_afterFinalConditions =3D false; +- test_simulateRefactoringReset_afterCreateChange =3D false; +- super.tearDown(); +- } +- +- test_cancelPendingRequest() async { +- addTestFile(''' +-main() { +- int test =3D 0; +- print(test); +-} +-'''); +- // send the "1" request, but don't wait for it +- Future futureA =3D sendRenameRequest('test =3D', 'nameA', i= d: '1'); +- // send the "2" request and wait for it +- Response responseB =3D await sendRenameRequest('test =3D', 'nameB', i= d: '2'); +- // wait for the (delayed) "1" response +- Response responseA =3D await futureA; +- // "1" was cancelled +- // "2" is successful +- expect(responseA, +- isResponseFailure('1', RequestErrorCode.REFACTORING_REQUEST_CANCE= LLED)); +- expect(responseB, isResponseSuccess('2')); +- } +- +- test_class() { +- addTestFile(''' +-class Test { +- Test() {} +- Test.named() {} +-} +-main() { +- Test v; +- new Test(); +- new Test.named(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('Test {', 'NewName'); +- }, ''' +-class NewName { +- NewName() {} +- NewName.named() {} +-} +-main() { +- NewName v; +- new NewName(); +- new NewName.named(); +-} +-'''); +- } +- +- test_class_options_fatalError() { +- addTestFile(''' +-class Test {} +-main() { +- Test v; +-} +-'''); +- return getRefactoringResult(() { +- return sendRenameRequest('Test {}', ''); +- }).then((result) { +- assertResultProblemsFatal( +- result.optionsProblems, 'Class name must not be empty.'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_class_validateOnly() { +- addTestFile(''' +-class Test {} +-main() { +- Test v; +-} +-'''); +- return getRefactoringResult(() { +- return sendRenameRequest('Test {}', 'NewName', validateOnly: true); +- }).then((result) { +- RenameFeedback feedback =3D result.feedback; +- assertResultProblemsOK(result); +- expect(feedback.elementKindName, 'class'); +- expect(feedback.oldName, 'Test'); +- expect(result.change, isNull); +- }); +- } +- +- test_class_warning() { +- addTestFile(''' +-class Test {} +-main() { +- Test v; +-} +-'''); +- return getRefactoringResult(() { +- return sendRenameRequest('Test {}', 'newName'); +- }).then((result) { +- assertResultProblemsWarning(result.optionsProblems, +- 'Class name should start with an uppercase letter.'); +- // ...but there is still a change +- assertTestRefactoringResult(result, ''' +-class newName {} +-main() { +- newName v; +-} +-'''); +- }).then((_) { +- // "NewName" is a perfectly valid name +- return getRefactoringResult(() { +- return sendRenameRequest('Test {}', 'NewName'); +- }).then((result) { +- assertResultProblemsOK(result); +- // ...and there is a new change +- assertTestRefactoringResult(result, ''' +-class NewName {} +-main() { +- NewName v; +-} +-'''); +- }); +- }); +- } +- +- test_classMember_field() { +- addTestFile(''' +-class A { +- var test =3D 0; +- A(this.test); +- main() { +- print(test); +- } +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test =3D 0', 'newName'); +- }, ''' +-class A { +- var newName =3D 0; +- A(this.newName); +- main() { +- print(newName); +- } +-} +-'''); +- } +- +- test_classMember_field_onFieldFormalParameter() { +- addTestFile(''' +-class A { +- var test =3D 0; +- A(this.test); +- main() { +- print(test); +- } +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test);', 'newName'); +- }, ''' +-class A { +- var newName =3D 0; +- A(this.newName); +- main() { +- print(newName); +- } +-} +-'''); +- } +- +- test_classMember_field_onFieldFormalParameter_named() { +- addTestFile(''' +-class A { +- final int test; +- A({this.test: 0}); +-} +-main() { +- new A(test: 42); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test: 42', 'newName'); +- }, ''' +-class A { +- final int newName; +- A({this.newName: 0}); +-} +-main() { +- new A(newName: 42); +-} +-'''); +- } +- +- test_classMember_getter() { +- addTestFile(''' +-class A { +- get test =3D> 0; +- main() { +- print(test); +- } +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test =3D>', 'newName'); +- }, ''' +-class A { +- get newName =3D> 0; +- main() { +- print(newName); +- } +-} +-'''); +- } +- +- test_classMember_method() { +- addTestFile(''' +-class A { +- test() {} +- main() { +- test(); +- } +-} +-main(A a) { +- a.test(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test() {}', 'newName'); +- }, ''' +-class A { +- newName() {} +- main() { +- newName(); +- } +-} +-main(A a) { +- a.newName(); +-} +-'''); +- } +- +- test_classMember_method_potential() { +- addTestFile(''' +-class A { +- test() {} +-} +-main(A a, a2) { +- a.test(); +- a2.test(); // a2 +-} +-'''); +- return getRefactoringResult(() { +- return sendRenameRequest('test() {}', 'newName'); +- }).then((result) { +- assertResultProblemsOK(result); +- // prepare potential edit ID +- List potentialIds =3D result.potentialEdits; +- expect(potentialIds, hasLength(1)); +- String potentialId =3D potentialIds[0]; +- // find potential edit +- SourceChange change =3D result.change; +- SourceEdit potentialEdit =3D _findEditWithId(change, potentialId); +- expect(potentialEdit, isNotNull); +- expect(potentialEdit.offset, findOffset('test(); // a2')); +- expect(potentialEdit.length, 4); +- }); +- } +- +- test_classMember_setter() { +- addTestFile(''' +-class A { +- set test(x) {} +- main() { +- test =3D 0; +- } +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test =3D 0', 'newName'); +- }, ''' +-class A { +- set newName(x) {} +- main() { +- newName =3D 0; +- } +-} +-'''); +- } +- +- test_constructor_fromFactoryRedirectingConstructor_onClassName() { +- addTestFile(''' +-class A { +- A() =3D B; +-} +-class B { +- B() {} +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('B;', 'newName'); +- }, ''' +-class A { +- A() =3D B.newName; +-} +-class B { +- B.newName() {} +-} +-'''); +- } +- +- test_constructor_fromInstanceCreation() { +- addTestFile(''' +-class A { +- A.test() {} +-} +-main() { +- new A.test(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test();', 'newName'); +- }, ''' +-class A { +- A.newName() {} +-} +-main() { +- new A.newName(); +-} +-'''); +- } +- +- test_constructor_fromInstanceCreation_default_onClassName() { +- addTestFile(''' +-class A { +- A() {} +-} +-main() { +- new A(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('A();', 'newName'); +- }, ''' +-class A { +- A.newName() {} +-} +-main() { +- new A.newName(); +-} +-'''); +- } +- +- test_constructor_fromInstanceCreation_default_onNew() { +- addTestFile(''' +-class A { +- A() {} +-} +-main() { +- new A(); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('new A();', 'newName'); +- }, ''' +-class A { +- A.newName() {} +-} +-main() { +- new A.newName(); +-} +-'''); +- } +- +- test_feedback() { +- addTestFile(''' +-class Test {} +-main() { +- Test v; +-} +-'''); +- return getRefactoringResult(() { +- return sendRenameRequest('st v;', 'NewName'); +- }).then((result) { +- RenameFeedback feedback =3D result.feedback; +- expect(feedback, isNotNull); +- expect(feedback.offset, findOffset('Test v;')); +- expect(feedback.length, 'Test'.length); +- }); +- } +- +- test_function() { +- addTestFile(''' +-test() {} +-main() { +- test(); +- print(test); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test() {}', 'newName'); +- }, ''' +-newName() {} +-main() { +- newName(); +- print(newName); +-} +-'''); +- } +- +- test_importPrefix_add() { +- addTestFile(''' +-import 'dart:math'; +-import 'dart:async'; +-main() { +- Random r; +- Future f; +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest("import 'dart:async';", 'new_name'); +- }, ''' +-import 'dart:math'; +-import 'dart:async' as new_name; +-main() { +- Random r; +- new_name.Future f; +-} +-'''); +- } +- +- test_importPrefix_remove() { +- addTestFile(''' +-import 'dart:math' as test; +-import 'dart:async' as test; +-main() { +- test.Random r; +- test.Future f; +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest("import 'dart:async' as test;", ''); +- }, ''' +-import 'dart:math' as test; +-import 'dart:async'; +-main() { +- test.Random r; +- Future f; +-} +-'''); +- } +- +- test_init_fatalError_noElement() { +- addTestFile('// nothing to rename'); +- return getRefactoringResult(() { +- return sendRenameRequest('// nothing', null); +- }).then((result) { +- assertResultProblemsFatal( +- result.initialProblems, 'Unable to create a refactoring'); +- // ...there is no any change +- expect(result.change, isNull); +- }); +- } +- +- test_library_libraryDirective() { +- addTestFile(''' +-library aaa.bbb.ccc; +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('library aaa', 'my.new_name'); +- }, ''' +-library my.new_name; +-'''); +- } +- +- test_library_libraryDirective_name() { +- addTestFile(''' +-library aaa.bbb.ccc; +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('aaa', 'my.new_name'); +- }, ''' +-library my.new_name; +-'''); +- } +- +- test_library_libraryDirective_nameDot() { +- addTestFile(''' +-library aaa.bbb.ccc; +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('.bbb', 'my.new_name'); +- }, ''' +-library my.new_name; +-'''); +- } +- +- test_library_partOfDirective() { +- addFile('$testFolder/my_lib.dart', ''' +-library aaa.bbb.ccc; +-part 'test.dart'; +-'''); +- addTestFile(''' +-part of aaa.bbb.ccc; +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('aaa.bb', 'my.new_name'); +- }, ''' +-part of my.new_name; +-'''); +- } +- +- test_localVariable() { +- addTestFile(''' +-main() { +- int test =3D 0; +- test =3D 1; +- test +=3D 2; +- print(test); +-} +-'''); +- return assertSuccessfulRefactoring(() { +- return sendRenameRequest('test =3D 1', 'newName'); +- }, ''' +-main() { +- int newName =3D 0; +- newName =3D 1; +- newName +=3D 2; +- print(newName); +-} +-'''); +- } +- +- test_localVariable_finalCheck_shadowError() { +- addTestFile(''' +-main() { +- var newName; +- int test =3D 0; +- print(test); +-} +-'''); +- return getRefactoringResult(() { +- return sendRenameRequest('test =3D 0', 'newName'); +- }).then((result) { +- List problems =3D result.finalProblems; +- expect(problems, hasLength(1)); +- assertResultProblemsError( +- problems, "Duplicate local variable 'newName'."); +- }); +- } +- +- test_reset_afterCreateChange() { +- test_simulateRefactoringReset_afterCreateChange =3D true; +- addTestFile(''' +-test() {} +-main() { +- test(); +-} +-'''); +- return waitForTasksFinished().then((_) { +- return sendRenameRequest('test() {}', 'newName').then((response) { +- _expectRefactoringRequestCancelled(response); +- }); +- }); +- } +- +- test_reset_afterFinalConditions() { +- test_simulateRefactoringReset_afterFinalConditions =3D true; +- addTestFile(''' +-test() {} +-main() { +- test(); +-} +-'''); +- return waitForTasksFinished().then((_) { +- return sendRenameRequest('test() {}', 'newName').then((response) { +- _expectRefactoringRequestCancelled(response); +- }); +- }); +- } +- +- test_reset_afterInitialConditions() { +- test_simulateRefactoringReset_afterInitialConditions =3D true; +- addTestFile(''' +-test() {} +-main() { +- test(); +-} +-'''); +- return waitForTasksFinished().then((_) { +- return sendRenameRequest('test() {}', 'newName').then((response) { +- _expectRefactoringRequestCancelled(response); +- }); +- }); +- } +- +- test_resetOnAnalysis() async { +- addTestFile(''' +-main() { +- int initialName =3D 0; +- print(initialName); +-} +-'''); +- // send the first request +- EditGetRefactoringResult result =3D await getRefactoringResult(() { +- return sendRenameRequest('initialName =3D', 'newName', validateOnly= : true); +- }); +- _validateFeedback(result, oldName: 'initialName'); +- // update the file +- modifyTestFile(''' +-main() { +- int otherName =3D 0; +- print(otherName); +-} +-'''); +- server.getAnalysisDriver(testFile).getResult(testFile); +- // send the second request, with the same kind, file and offset +- await waitForTasksFinished(); +- result =3D await getRefactoringResult(() { +- return sendRenameRequest('otherName =3D', 'newName', validateOnly: = true); +- }); +- // the refactoring was reset, so we don't get a stale result +- _validateFeedback(result, oldName: 'otherName'); +- } +- +- void _expectRefactoringRequestCancelled(Response response) { +- expect(response.error, isNotNull); +- expect(response, +- isResponseFailure('0', RequestErrorCode.REFACTORING_REQUEST_CANCE= LLED)); +- } +- +- SourceEdit _findEditWithId(SourceChange change, String id) { +- SourceEdit potentialEdit; +- change.edits.forEach((fileEdit) { +- fileEdit.edits.forEach((edit) { +- if (edit.id =3D=3D id) { +- potentialEdit =3D edit; +- } +- }); +- }); +- return potentialEdit; +- } +- +- void _validateFeedback(EditGetRefactoringResult result, {String oldName= }) { +- RenameFeedback feedback =3D result.feedback; +- expect(feedback, isNotNull); +- if (oldName !=3D null) { +- expect(feedback.oldName, oldName); +- } +- } +-} +- +-@reflectiveTest +-class _AbstractGetRefactoring_Test extends AbstractAnalysisTest { +- bool shouldWaitForFullAnalysis =3D true; +- +- /** +- * Asserts that [problems] has a single ERROR problem. +- */ +- void assertResultProblemsError(List problems, +- [String message]) { +- RefactoringProblem problem =3D problems[0]; +- expect(problem.severity, RefactoringProblemSeverity.ERROR, +- reason: problem.toString()); +- if (message !=3D null) { +- expect(problem.message, message); +- } +- } +- +- /** +- * Asserts that [result] has a single FATAL problem. +- */ +- void assertResultProblemsFatal(List problems, +- [String message]) { +- RefactoringProblem problem =3D problems[0]; +- expect(problems, hasLength(1)); +- expect(problem.severity, RefactoringProblemSeverity.FATAL, +- reason: problem.toString()); +- if (message !=3D null) { +- expect(problem.message, message); +- } +- } +- +- /** +- * Asserts that [result] has no problems at all. +- */ +- void assertResultProblemsOK(EditGetRefactoringResult result) { +- expect(result.initialProblems, isEmpty); +- expect(result.optionsProblems, isEmpty); +- expect(result.finalProblems, isEmpty); +- } +- +- /** +- * Asserts that [result] has a single WARNING problem. +- */ +- void assertResultProblemsWarning(List problems, +- [String message]) { +- RefactoringProblem problem =3D problems[0]; +- expect(problems, hasLength(1)); +- expect(problem.severity, RefactoringProblemSeverity.WARNING, +- reason: problem.toString()); +- if (message !=3D null) { +- expect(problem.message, message); +- } +- } +- +- Future assertSuccessfulRefactoring( +- Future requestSender(), String expectedCode) async { +- EditGetRefactoringResult result =3D await getRefactoringResult(reques= tSender); +- assertResultProblemsOK(result); +- assertTestRefactoringResult(result, expectedCode); +- } +- +- /** +- * Asserts that the given [EditGetRefactoringResult] has a [testFile] c= hange +- * which results in the [expectedCode]. +- */ +- void assertTestRefactoringResult( +- EditGetRefactoringResult result, String expectedCode) { +- SourceChange change =3D result.change; +- expect(change, isNotNull); +- for (SourceFileEdit fileEdit in change.edits) { +- if (fileEdit.file =3D=3D testFile) { +- String actualCode =3D SourceEdit.applySequence(testCode, fileEdit= .edits); +- expect(actualCode, expectedCode); +- return; +- } +- } +- fail('No SourceFileEdit for $testFile in $change'); +- } +- +- Future getRefactoringResult( +- Future requestSender()) async { +- if (shouldWaitForFullAnalysis) { +- await waitForTasksFinished(); +- } +- Response response =3D await requestSender(); +- return new EditGetRefactoringResult.fromResponse(response); +- } +- +- Future sendRequest( +- RefactoringKind kind, int offset, int length, RefactoringOptions op= tions, +- [bool validateOnly =3D false]) { +- Request request =3D new EditGetRefactoringParams( +- kind, testFile, offset, length, validateOnly, +- options: options) +- .toRequest('0'); +- return serverChannel.sendRequest(request); +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- server.handlers =3D [handler]; +- } +-} +diff --git a/pkg/analysis_server/test/edit/sort_members_test.dart b/pkg/an= alysis_server/test/edit/sort_members_test.dart +deleted file mode 100644 +index abce2a0fe49..00000000000 +--- a/pkg/analysis_server/test/edit/sort_members_test.dart ++++ /dev/null +@@ -1,256 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SortMembersTest); +- }); +-} +- +-@reflectiveTest +-class SortMembersTest extends AbstractAnalysisTest { +- SourceFileEdit fileEdit; +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- } +- +- @failingTest +- test_BAD_doesNotExist() async { +- // The analysis driver fails to return an error +- Request request =3D +- new EditSortMembersParams('/no/such/file.dart').toRequest('0'); +- Response response =3D await waitResponse(request); +- expect(response, +- isResponseFailure('0', RequestErrorCode.SORT_MEMBERS_INVALID_FILE= )); +- } +- +- test_BAD_hasParseError() async { +- addTestFile(''' +-main() { +- print() +-} +-'''); +- Request request =3D new EditSortMembersParams(testFile).toRequest('0'= ); +- Response response =3D await waitResponse(request); +- expect(response, +- isResponseFailure('0', RequestErrorCode.SORT_MEMBERS_PARSE_ERRORS= )); +- } +- +- test_BAD_notDartFile() async { +- Request request =3D +- new EditSortMembersParams('/not-a-Dart-file.txt').toRequest('0'); +- Response response =3D await waitResponse(request); +- expect(response, +- isResponseFailure('0', RequestErrorCode.SORT_MEMBERS_INVALID_FILE= )); +- } +- +- test_OK_afterWaitForAnalysis() async { +- addTestFile(''' +-class C {} +-class A {} +-class B {} +-'''); +- await waitForTasksFinished(); +- return _assertSorted(r''' +-class A {} +-class B {} +-class C {} +-'''); +- } +- +- test_OK_classMembers_method() async { +- addTestFile(''' +-class A { +- c() {} +- a() {} +- b() {} +-} +-'''); +- return _assertSorted(r''' +-class A { +- a() {} +- b() {} +- c() {} +-} +-'''); +- } +- +- test_OK_directives() async { +- addTestFile(''' +-library lib; +- +-export 'dart:bbb'; +-import 'dart:bbb'; +-export 'package:bbb/bbb.dart'; +-import 'bbb/bbb.dart'; +-export 'dart:aaa'; +-export 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +-export 'aaa/aaa.dart'; +-export 'bbb/bbb.dart'; +-import 'dart:aaa'; +-import 'package:aaa/aaa.dart'; +-import 'aaa/aaa.dart'; +-part 'bbb/bbb.dart'; +-part 'aaa/aaa.dart'; +- +-main() { +-} +-'''); +- return _assertSorted(r''' +-library lib; +- +-import 'dart:aaa'; +-import 'dart:bbb'; +- +-import 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +- +-import 'aaa/aaa.dart'; +-import 'bbb/bbb.dart'; +- +-export 'dart:aaa'; +-export 'dart:bbb'; +- +-export 'package:aaa/aaa.dart'; +-export 'package:bbb/bbb.dart'; +- +-export 'aaa/aaa.dart'; +-export 'bbb/bbb.dart'; +- +-part 'aaa/aaa.dart'; +-part 'bbb/bbb.dart'; +- +-main() { +-} +-'''); +- } +- +- test_OK_directives_withAnnotation() async { +- addTestFile(''' +-library lib; +- +-export 'dart:bbb'; +-@MyAnnotation(1) +-@MyAnnotation(2) +-import 'dart:bbb'; +-@MyAnnotation(3) +-export 'dart:aaa'; +-import 'dart:aaa'; +- +-class MyAnnotation { +- const MyAnnotation(_); +-} +-'''); +- return _assertSorted(r''' +-library lib; +- +-import 'dart:aaa'; +-@MyAnnotation(1) +-@MyAnnotation(2) +-import 'dart:bbb'; +- +-@MyAnnotation(3) +-export 'dart:aaa'; +-export 'dart:bbb'; +- +-class MyAnnotation { +- const MyAnnotation(_); +-} +-'''); +- } +- +- test_OK_genericFunctionType() async { +- addFile(projectPath + '/analysis_options.yaml', ''' +-analyzer: +- strong-mode: true +-'''); +- addTestFile(''' +-class C { +- void caller() { +- Super s =3D new Super(); +- takesSub(s); // <- No warning +- } +- +- void takesSub(Sub s) {} +-} +- +-class Sub extends Super {} +- +-class Super {} +- +-typedef dynamic Func(String x, String y); +- +-F allowInterop(F f) =3D> null; +- +-Func bar(Func f) { +- return allowInterop(f); +-} +-'''); +- return _assertSorted(''' +-F allowInterop(F f) =3D> null; +- +-Func bar(Func f) { +- return allowInterop(f); +-} +- +-typedef dynamic Func(String x, String y); +- +-class C { +- void caller() { +- Super s =3D new Super(); +- takesSub(s); // <- No warning +- } +- +- void takesSub(Sub s) {} +-} +- +-class Sub extends Super {} +- +-class Super {} +-'''); +- } +- +- test_OK_unitMembers_class() async { +- addTestFile(''' +-class C {} +-class A {} +-class B {} +-'''); +- return _assertSorted(r''' +-class A {} +-class B {} +-class C {} +-'''); +- } +- +- Future _assertSorted(String expectedCode) async { +- await _requestSort(); +- String resultCode =3D SourceEdit.applySequence(testCode, fileEdit.edi= ts); +- expect(resultCode, expectedCode); +- } +- +- Future _requestSort() async { +- Request request =3D new EditSortMembersParams(testFile).toRequest('0'= ); +- Response response =3D await waitResponse(request); +- var result =3D new EditSortMembersResult.fromResponse(response); +- fileEdit =3D result.edit; +- } +-} +diff --git a/pkg/analysis_server/test/edit/statement_completion_test.dart = b/pkg/analysis_server/test/edit/statement_completion_test.dart +deleted file mode 100644 +index 7df82ba87d4..00000000000 +--- a/pkg/analysis_server/test/edit/statement_completion_test.dart ++++ /dev/null +@@ -1,122 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/edit/edit_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(StatementCompletionTest); +- }); +-} +- +-@reflectiveTest +-class StatementCompletionTest extends AbstractAnalysisTest { +- SourceChange change; +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- handler =3D new EditDomainHandler(server); +- } +- +- test_plainEnterFromStart() async { +- addTestFile(''' +-main() { +- int v =3D 1; +-} +-'''); +- await waitForTasksFinished(); +- await _prepareCompletion('v =3D 1;', atStart: true); +- _assertHasChange('Insert a newline at the end of the current line', '= '' +-main() { +- int v =3D 1; +- /*caret*/ +-} +-'''); +- } +- +- test_plainOleEnter() async { +- addTestFile(''' +-main() { +- int v =3D 1; +-} +-'''); +- await waitForTasksFinished(); +- await _prepareCompletion('v =3D 1;', atEnd: true); +- _assertHasChange('Insert a newline at the end of the current line', '= '' +-main() { +- int v =3D 1; +- /*caret*/ +-} +-'''); +- } +- +- test_plainOleEnterWithError() async { +- addTestFile(''' +-main() { +- int v =3D +-} +-'''); +- await waitForTasksFinished(); +- String match =3D 'v =3D'; +- await _prepareCompletion(match, atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- int v =3D +- x +-} +-''', +- (s) =3D> s.indexOf(match) + match.length); // Ensure cursor after= '=3D'. +- } +- +- void _assertHasChange(String message, String expectedCode, [Function cm= p]) { +- if (change.message =3D=3D message) { +- if (!change.edits.isEmpty) { +- String resultCode =3D +- SourceEdit.applySequence(testCode, change.edits[0].edits); +- expect(resultCode, expectedCode.replaceAll('/*caret*/', '')); +- if (cmp !=3D null) { +- int offset =3D cmp(resultCode); +- expect(change.selection.offset, offset); +- } +- } else { +- if (cmp !=3D null) { +- int offset =3D cmp(testCode); +- expect(change.selection.offset, offset); +- } +- } +- return; +- } +- fail("Expected to find |$message| but got: " + change.message); +- } +- +- _prepareCompletion(String search, +- {bool atStart: false, bool atEnd: false, int delta: 0}) async { +- int offset =3D findOffset(search); +- if (atStart) { +- delta =3D 0; +- } else if (atEnd) { +- delta =3D search.length; +- } +- await _prepareCompletionAt(offset + delta); +- } +- +- _prepareCompletionAt(int offset) async { +- Request request =3D +- new EditGetStatementCompletionParams(testFile, offset).toRequest(= '0'); +- Response response =3D await waitResponse(request); +- var result =3D new EditGetStatementCompletionResult.fromResponse(resp= onse); +- change =3D result.change; +- } +-} +diff --git a/pkg/analysis_server/test/edit/test_all.dart b/pkg/analysis_se= rver/test/edit/test_all.dart +deleted file mode 100644 +index 1376ea6396c..00000000000 +--- a/pkg/analysis_server/test/edit/test_all.dart ++++ /dev/null +@@ -1,27 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'assists_test.dart' as assists_test; +-import 'fixes_test.dart' as fixes_test; +-import 'format_test.dart' as format_test; +-import 'organize_directives_test.dart' as organize_directives_test; +-import 'postfix_completion_test.dart' as postfix_completion_test; +-import 'refactoring_test.dart' as refactoring_test; +-import 'sort_members_test.dart' as sort_members_test; +-import 'statement_completion_test.dart' as statement_completion_test; +- +-main() { +- defineReflectiveSuite(() { +- assists_test.main(); +- fixes_test.main(); +- format_test.main(); +- organize_directives_test.main(); +- postfix_completion_test.main(); +- refactoring_test.main(); +- sort_members_test.main(); +- statement_completion_test.main(); +- }, name: 'edit'); +-} +diff --git a/pkg/analysis_server/test/integration/analysis/analysis_option= s_test.dart b/pkg/analysis_server/test/integration/analysis/analysis_option= s_test.dart +deleted file mode 100644 +index e437193487e..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/analysis_options_test.= dart ++++ /dev/null +@@ -1,81 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OptionsIntegrationTest); +- }); +-} +- +-@reflectiveTest +-class OptionsIntegrationTest extends AbstractAnalysisServerIntegrationTes= t { +- @failingTest +- test_option_warning_newOptionFile() async { +- // TimeoutException after 0:00:30.000000: Test timed out after 30 sec= onds +- // (#28868). +- +- fail('test timeout expected - #28868'); +- +- String options =3D sourcePath(AnalysisEngine.ANALYSIS_OPTIONS_YAML_FI= LE); +- writeFile(options, ''' +-linter: +- rules: +- - camel_case_typo # :) +-'''); +- +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- expect(currentAnalysisErrors[options], isList); +- List errors =3D currentAnalysisErrors[options]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.location.file, options); +- expect(error.severity, AnalysisErrorSeverity.WARNING); +- expect(error.type, AnalysisErrorType.STATIC_WARNING); +- expect(error.location.offset, 23); +- expect(error.location.length, 'camel_case_typo'.length); +- expect(error.location.startLine, 3); +- expect(error.location.startColumn, 7); +- } +- +- @failingTest +- test_option_warning_oldOptionFile() async { +- // TimeoutException after 0:00:30.000000: Test timed out after 30 sec= onds +- // (#28868). +- +- fail('test timeout expected - #28868'); +- +- String options =3D sourcePath(AnalysisEngine.ANALYSIS_OPTIONS_FILE); +- writeFile(options, ''' +-linter: +- rules: +- - camel_case_typo # :) +-'''); +- +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- expect(currentAnalysisErrors[options], isList); +- List errors =3D currentAnalysisErrors[options]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.location.file, options); +- expect(error.severity, AnalysisErrorSeverity.WARNING); +- expect(error.type, AnalysisErrorType.STATIC_WARNING); +- expect(error.location.offset, 23); +- expect(error.location.length, 'camel_case_typo'.length); +- expect(error.location.startLine, 3); +- expect(error.location.startColumn, 7); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/error_test.dart= b/pkg/analysis_server/test/integration/analysis/error_test.dart +deleted file mode 100644 +index 1c32caa732f..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/error_test.dart ++++ /dev/null +@@ -1,100 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisErrorIntegrationTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisErrorIntegrationTest +- extends AbstractAnalysisServerIntegrationTest { +- test_detect_simple_error() { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-main() { +- print(null) // parse error: missing ';' +-}'''); +- standardAnalysisSetup(); +- return analysisFinished.then((_) { +- expect(currentAnalysisErrors[pathname], isList); +- List errors =3D currentAnalysisErrors[pathname]; +- expect(errors, hasLength(1)); +- expect(errors[0].location.file, equals(pathname)); +- }); +- } +- +- test_super_mixins_disabled() async { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-class Test extends Object with C { +- void foo() {} +-} +-abstract class B { +- void foo() {} +-} +-abstract class C extends B { +- void bar() { +- super.foo(); +- } +-} +-'''); +- standardAnalysisSetup(); +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isList); +- List errors =3D currentAnalysisErrors[pathname]; +- expect(errors, hasLength(2)); +- Set allErrorMessages =3D +- errors.map((AnalysisError e) =3D> e.message).toSet(); +- expect( +- allErrorMessages, +- contains( +- "The class 'C' can't be used as a mixin because it extends a = class other than Object.")); +- expect( +- allErrorMessages, +- contains( +- "The class 'C' can't be used as a mixin because it references= 'super'.")); +- } +- +- @failingTest +- test_super_mixins_enabled() async { +- // We see errors here with the new driver (#28870). +- // Expected: empty +- // Actual: [ +- // AnalysisError:{"severity":"ERROR","type":"COMPILE_TIME_ERROR","= location":{"file":"/var/folders/00/0w95r000h01000cxqpysvccm003j4q/T/analysi= sServerfbuOQb/test.dart","offset":31,"length":1,"startLine":1,"startColumn"= :32},"message":"The class 'C' can't be used as a mixin because it extends a= class other than Object.","correction":"","code":"mixin_inherits_from_not_= object","hasFix":false}, +- // AnalysisError:{"severity":"ERROR","type":"COMPILE_TIME_ERROR","= location":{"file":"/var/folders/00/0w95r000h01000cxqpysvccm003j4q/T/analysi= sServerfbuOQb/test.dart","offset":31,"length":1,"startLine":1,"startColumn"= :32},"message":"The class 'C' can't be used as a mixin because it reference= s 'super'.","correction":"","code":"mixin_references_super","hasFix":false} +- // ] +- +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-class Test extends Object with C { +- void foo() {} +-} +-abstract class B { +- void foo() {} +-} +-abstract class C extends B { +- void bar() { +- super.foo(); +- } +-} +-'''); +- // ignore: deprecated_member_use +- await sendAnalysisUpdateOptions( +- new AnalysisOptions()..enableSuperMixins =3D true); +- standardAnalysisSetup(); +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isList); +- List errors =3D currentAnalysisErrors[pathname]; +- expect(errors, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_errors_nonS= tandard_sdk.dart b/pkg/analysis_server/test/integration/analysis/get_errors= _nonStandard_sdk.dart +deleted file mode 100644 +index 289a3321cd5..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_errors_nonStandard= _sdk.dart ++++ /dev/null +@@ -1,99 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../mock_sdk.dart'; +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisDomainGetErrorsTest); +- }); +-} +- +-/** +- * Tests that when an SDK path is specified on the command-line (via the = `--sdk` +- * argument) that the specified SDK is used. +- */ +-@reflectiveTest +-class AnalysisDomainGetErrorsTest +- extends AbstractAnalysisServerIntegrationTest { +- String createNonStandardSdk() { +- MockSdkLibrary fakeLibrary =3D +- new MockSdkLibrary('dart:fake', '/lib/fake/fake.dart', ''); +- String sdkPath =3D path.join(sourceDirectory.path, 'sdk'); +- StringBuffer librariesContent =3D new StringBuffer(); +- librariesContent.writeln( +- 'final Map LIBRARIES =3D const {'); +- MockSdk.LIBRARIES.toList() +- ..add(fakeLibrary) +- ..forEach((SdkLibrary library) { +- List components =3D path.posix.split(library.path); +- components[0] =3D sdkPath; +- String libraryPath =3D path.joinAll(components); +- new Directory(path.dirname(libraryPath)).createSync(recursive: tr= ue); +- new File(libraryPath) +- .writeAsStringSync((library as MockSdkLibrary).content); +- +- String relativePath =3D path.joinAll(components.sublist(2)); +- librariesContent.write('"'); +- librariesContent +- .write(library.shortName.substring(5)); // Remove the 'dart:'= prefix +- librariesContent.write('": const LibraryInfo("'); +- librariesContent.write(relativePath); +- librariesContent.writeln('"),'); +- }); +- librariesContent.writeln('};'); +- +- String librariesPath =3D path.joinAll([ +- sdkPath, +- 'lib', +- '_internal', +- 'sdk_library_metadata', +- 'lib', +- 'libraries.dart' +- ]); +- new Directory(path.dirname(librariesPath)).createSync(recursive: true= ); +- new File(librariesPath).writeAsStringSync(librariesContent.toString()= ); +- +- return sdkPath; +- } +- +- @override +- Future startServer( +- {bool checked: true, +- int diagnosticPort, +- int servicesPort, +- bool previewDart2: false}) { +- String sdkPath =3D createNonStandardSdk(); +- return server.start( +- checked: checked, +- diagnosticPort: diagnosticPort, +- sdkPath: sdkPath, +- servicesPort: servicesPort, +- previewDart2: previewDart2); +- } +- +- Future test_getErrors() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:core'; +-import 'dart:fake'; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- List errors =3D currentAnalysisErrors[pathname]; +- expect(errors, hasLength(1)); +- expect(errors[0].code, 'unused_import'); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_errors_test= .dart b/pkg/analysis_server/test/integration/analysis/get_errors_test.dart +deleted file mode 100644 +index 2f3954222c4..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_errors_test.dart ++++ /dev/null +@@ -1,36 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetErrorsTest); +- }); +-} +- +-@reflectiveTest +-class GetErrorsTest extends AbstractAnalysisServerIntegrationTest { +- test_getErrors() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-main() { +- var x // parse error: missing ';' +-}'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- Future finishTest() { +- return sendAnalysisGetErrors(pathname).then((result) { +- expect(result.errors, equals(currentAnalysisErrors[pathname])); +- }); +- } +- +- return analysisFinished.then((_) =3D> finishTest()); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_hover_test.= dart b/pkg/analysis_server/test/integration/analysis/get_hover_test.dart +deleted file mode 100644 +index 55be6ca2668..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_hover_test.dart ++++ /dev/null +@@ -1,189 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisGetHoverIntegrationTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisGetHoverIntegrationTest +- extends AbstractAnalysisServerIntegrationTest { +- /** +- * Pathname of the file containing Dart code. +- */ +- String pathname; +- +- /** +- * Dart code under test. +- */ +- final String text =3D r''' +-library lib.test; +- +-List topLevelVar; +- +-/** +- * Documentation for func +- */ +-void func(int param) { +- num localVar =3D topLevelVar.length; +- topLevelVar.length =3D param; +- topLevelVar.add(localVar); +-} +- +-main() { +- // comment +- func(35); +-} +-'''; +- +- /** +- * Check that a getHover request on the substring [target] produces a r= esult +- * which has length [length], has an elementDescription matching every +- * regexp in [descriptionRegexps], has a kind of [kind], and has a stat= icType +- * matching [staticTypeRegexps]. +- * +- * [isCore] means the hover info should indicate that the element is de= fined +- * in dart.core. [docRegexp], if specified, should match the documenta= tion +- * string of the element. [isLiteral] means the hover should indicate a +- * literal value. [parameterRegexps] means is a set of regexps which s= hould +- * match the hover parameters. [propagatedType], if specified, is the +- * expected propagated type of the element. +- */ +- checkHover(String target, int length, List descriptionRegexps, +- String kind, List staticTypeRegexps, +- {bool isLocal: false, +- bool isCore: false, +- String docRegexp: null, +- bool isLiteral: false, +- List parameterRegexps: null, +- propagatedType: null}) { +- int offset =3D text.indexOf(target); +- return sendAnalysisGetHover(pathname, offset).then((result) { +- expect(result.hovers, hasLength(1)); +- HoverInformation info =3D result.hovers[0]; +- expect(info.offset, equals(offset)); +- expect(info.length, equals(length)); +- if (isCore) { +- expect(path.basename(info.containingLibraryPath), equals('core.da= rt')); +- expect(info.containingLibraryName, equals('dart.core')); +- } else if (isLocal || isLiteral) { +- expect(info.containingLibraryPath, isNull); +- expect(info.containingLibraryName, isNull); +- } else { +- expect(info.containingLibraryPath, equals(pathname)); +- expect(info.containingLibraryName, equals('lib.test')); +- } +- if (docRegexp =3D=3D null) { +- expect(info.dartdoc, isNull); +- } else { +- expect(info.dartdoc, matches(docRegexp)); +- } +- if (descriptionRegexps =3D=3D null) { +- expect(info.elementDescription, isNull); +- } else { +- expect(info.elementDescription, isString); +- for (String descriptionRegexp in descriptionRegexps) { +- expect(info.elementDescription, matches(descriptionRegexp)); +- } +- } +- expect(info.elementKind, equals(kind)); +- if (parameterRegexps =3D=3D null) { +- expect(info.parameter, isNull); +- } else { +- expect(info.parameter, isString); +- for (String parameterRegexp in parameterRegexps) { +- expect(info.parameter, matches(parameterRegexp)); +- } +- } +- expect(info.propagatedType, equals(propagatedType)); +- if (staticTypeRegexps =3D=3D null) { +- expect(info.staticType, isNull); +- } else { +- expect(info.staticType, isString); +- for (String staticTypeRegexp in staticTypeRegexps) { +- expect(info.staticType, matches(staticTypeRegexp)); +- } +- } +- }); +- } +- +- /** +- * Check that a getHover request on the substring [target] produces no +- * results. +- */ +- Future checkNoHover(String target) { +- int offset =3D text.indexOf(target); +- return sendAnalysisGetHover(pathname, offset).then((result) { +- expect(result.hovers, hasLength(0)); +- }); +- } +- +- setUp() { +- return super.setUp().then((_) { +- pathname =3D sourcePath('test.dart'); +- }); +- } +- +- test_getHover() { +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- // Note: analysis.getHover doesn't wait for analysis to complete--it = simply +- // returns the latest results that are available at the time that the +- // request is made. So wait for analysis to finish before testing an= ything. +- return analysisFinished.then((_) { +- List tests =3D []; +- tests.add(checkHover('topLevelVar;', 11, ['List', 'topLevelVar'], +- 'top level variable', ['List'])); +- tests.add(checkHover( +- 'func(', 4, ['func', 'int', 'param'], 'function', null, +- docRegexp: 'Documentation for func')); +- tests.add(checkHover('int param', 3, ['int'], 'class', null, +- isCore: true, docRegexp: '.*')); +- tests.add(checkHover('param)', 5, ['int', 'param'], 'parameter', ['= int'], +- isLocal: true, docRegexp: 'Documentation for func')); +- tests.add(checkHover('num localVar', 3, ['num'], 'class', null, +- isCore: true, docRegexp: '.*')); +- tests.add(checkHover( +- 'localVar =3D', 8, ['num', 'localVar'], 'local variable', ['num= '], +- isLocal: true, propagatedType: 'int')); +- tests.add(checkHover('topLevelVar.length;', 11, ['List', 'topLevelV= ar'], +- 'top level variable', ['List'])); +- tests.add(checkHover( +- 'length;', 6, ['get', 'length', 'int'], 'getter', null, +- isCore: true, docRegexp: '.*')); +- tests.add(checkHover( +- 'length =3D', 6, ['set', 'length', 'int'], 'setter', null, +- isCore: true, docRegexp: '.*')); +- tests.add(checkHover('param;', 5, ['int', 'param'], 'parameter', ['= int'], +- isLocal: true, +- docRegexp: 'Documentation for func', +- parameterRegexps: ['.*'])); +- tests.add(checkHover( +- 'add(', 3, ['List', 'add'], 'method', ['dynamic', 'void'], +- isCore: true, docRegexp: '.*')); +- tests.add(checkHover( +- 'localVar)', 8, ['num', 'localVar'], 'local variable', ['num'], +- isLocal: true, parameterRegexps: ['.*'], propagatedType: 'int')= ); +- tests.add(checkHover( +- 'func(35', 4, ['func', 'int', 'param'], 'function', ['int', 'vo= id'], +- docRegexp: 'Documentation for func')); +- tests.add(checkHover('35', 2, null, null, ['int'], +- isLiteral: true, parameterRegexps: ['int', 'param'])); +- tests.add(checkNoHover('comment')); +- return Future.wait(tests); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_imported_el= ements_test.dart b/pkg/analysis_server/test/integration/analysis/get_import= ed_elements_test.dart +deleted file mode 100644 +index f5a98cd9909..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_imported_elements_= test.dart ++++ /dev/null +@@ -1,135 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisGetImportedElementsIntegrationTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisGetImportedElementsIntegrationTest +- extends AbstractAnalysisServerIntegrationTest { +- /** +- * Pathname of the file containing Dart code. +- */ +- String pathname; +- +- /** +- * Dart code under test. +- */ +- String text; +- +- /** +- * Check that an analysis.getImportedElements request on the region sta= rting +- * with the first character that matches [target] and having the given +- * [length] matches the given list of [expected] imported elements. +- */ +- checkElements(String target, List expected) async { +- bool equals( +- ImportedElements actualElements, ImportedElements expectedElement= s) { +- if (actualElements.path.endsWith(expectedElements.path) && +- actualElements.prefix =3D=3D expectedElements.prefix) { +- List actual =3D actualElements.elements; +- List expected =3D expectedElements.elements; +- if (actual.length =3D=3D expected.length) { +- for (int i =3D 0; i < actual.length; i++) { +- if (!expected.contains(actual[i])) { +- return false; +- } +- } +- return true; +- } +- } +- return false; +- } +- +- int find(List actual, ImportedElements expectedElem= ents) { +- for (int i =3D 0; i < actual.length; i++) { +- ImportedElements actualElements =3D actual[i]; +- if (equals(actualElements, expectedElements)) { +- return i; +- } +- } +- return -1; +- } +- +- int offset =3D text.indexOf(target); +- AnalysisGetImportedElementsResult result =3D +- await sendAnalysisGetImportedElements(pathname, offset, target.le= ngth); +- +- List actual =3D result.elements; +- expect(actual, hasLength(expected.length)); +- for (ImportedElements elements in expected) { +- int index =3D find(actual, elements); +- if (index < 0) { +- fail('Expected $elements; not found'); +- } +- actual.removeAt(index); +- } +- } +- +- /** +- * Check that an analysis.getImportedElements request on the region mat= ching +- * [target] produces an empty list of elements. +- */ +- Future checkNoElements(String target) async { +- int offset =3D text.indexOf(target); +- AnalysisGetImportedElementsResult result =3D +- await sendAnalysisGetImportedElements(pathname, offset, target.le= ngth); +- +- expect(result.elements, hasLength(0)); +- } +- +- setUp() { +- return super.setUp().then((_) { +- pathname =3D sourcePath('test.dart'); +- }); +- } +- +- test_getImportedElements_none() async { +- text =3D r''' +-main() {} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- await checkNoElements('main() {}'); +- } +- +- test_getImportedElements_some() async { +- String selection =3D r''' +-main() { +- Random r =3D new Random(); +- String s =3D r.nextBool().toString(); +- print(s); +-} +-'''; +- text =3D ''' +-import 'dart:math'; +- +-$selection +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- await checkElements(selection, [ +- new ImportedElements( +- path.join('lib', 'core', 'core.dart'), '', ['String', 'print']), +- new ImportedElements( +- path.join('lib', 'math', 'math.dart'), '', ['Random']) +- ]); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_library_dep= endencies_test.dart b/pkg/analysis_server/test/integration/analysis/get_lib= rary_dependencies_test.dart +deleted file mode 100644 +index 51a76599663..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_library_dependenci= es_test.dart ++++ /dev/null +@@ -1,47 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetLibraryDependenciesTest); +- }); +-} +- +-@reflectiveTest +-class GetLibraryDependenciesTest extends AbstractAnalysisServerIntegratio= nTest { +- @failingTest +- test_libraryDeps() async { +- // This fails with the new analysis driver ('Bad state: Should not be= used +- // with the new analysis driver') - #29310. +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-class Foo {} +- +-class Bar { +- Foo foo; +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- AnalysisGetLibraryDependenciesResult result =3D +- await sendAnalysisGetLibraryDependencies(); +- List libraries =3D result.libraries; +- Map>> packageMaps =3D result.package= Map; +- +- expect(libraries, contains(pathname)); +- expect(libraries.any((String lib) =3D> lib.endsWith('core/core.dart')= ), true); +- +- expect(packageMaps.keys, hasLength(1)); +- Map> map =3D packageMaps[packageMaps.keys.first]; +- expect(map.keys, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_navigation_= test.dart b/pkg/analysis_server/test/integration/analysis/get_navigation_te= st.dart +deleted file mode 100644 +index 9725e588998..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_navigation_test.da= rt ++++ /dev/null +@@ -1,67 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetNavigationTest); +- }); +-} +- +-@reflectiveTest +-class GetNavigationTest extends AbstractAnalysisServerIntegrationTest { +- test_navigation() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-class Foo {} +- +-class Bar { +- Foo foo; +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- AnalysisGetNavigationResult result =3D +- await sendAnalysisGetNavigation(pathname, text.indexOf('Foo foo')= , 0); +- expect(result.targets, hasLength(1)); +- NavigationTarget target =3D result.targets.first; +- expect(target.kind, ElementKind.CLASS); +- expect(target.offset, text.indexOf('Foo {}')); +- expect(target.length, 3); +- expect(target.startLine, 1); +- expect(target.startColumn, 7); +- } +- +- @failingTest +- test_navigation_no_result() async { +- // This fails - it returns navigation results for a whitespace area (= #28799). +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-// +- +-class Foo {} +- +-class Bar { +- Foo foo; +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- AnalysisGetNavigationResult result =3D +- await sendAnalysisGetNavigation(pathname, 0, 0); +- expect(result.targets, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/get_reachable_s= ources_test.dart b/pkg/analysis_server/test/integration/analysis/get_reacha= ble_sources_test.dart +deleted file mode 100644 +index 150c67ff3f2..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/get_reachable_sources_= test.dart ++++ /dev/null +@@ -1,49 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetReachableSourcesTest); +- }); +-} +- +-@reflectiveTest +-class GetReachableSourcesTest extends AbstractAnalysisServerIntegrationTe= st { +- @failingTest +- test_reachable() async { +- // This fails with the new analysis driver ('Bad state: Should not be= used +- // with the new analysis driver') - #29311. +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-class Foo {} +- +-class Bar { +- Foo foo; +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- AnalysisGetReachableSourcesResult result =3D +- await sendAnalysisGetReachableSources(pathname); +- Map> sources =3D result.sources; +- List keys =3D sources.keys.toList(); +- String url =3D new File(pathname).uri.toString(); +- +- expect(keys, contains('dart:core')); +- expect(keys, contains('dart:collection')); +- expect(keys, contains('dart:math')); +- expect(keys, contains(url)); +- expect(sources[url], contains('dart:core')); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/highlights_test= .dart b/pkg/analysis_server/test/integration/analysis/highlights_test.dart +deleted file mode 100644 +index 64d331372ab..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/highlights_test.dart ++++ /dev/null +@@ -1,146 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisHighlightsTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisHighlightsTest extends AbstractAnalysisServerIntegrationTes= t { +- test_highlights() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:async' as async; +- +-/** +- * Doc comment +- */ +-class Class { +- Class() { +- field =3D {1.0: [].toList()}; +- } +- +- Class.constructor() { +- dynamic local =3D true; +- field =3D {2: local}; +- } +- +- Map field; +- static int staticField; +- +- method() { +- // End of line comment +- /* Block comment */ +- } +- +- static staticMethod() { +- } +- +- get getter { +- } +- +- set setter(int parameter) { +- } +-} +- +-class Class2 extends Class { +- @override +- method() { +- } +-} +- +-typedef functionType(); +- +-function(dynamicType) { +- print('string'); +- unresolvedIdentifier =3D 42; +- return async.Future.wait([]); +-} +- +-int topLevelVariable; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- sendAnalysisSetSubscriptions({ +- AnalysisService.HIGHLIGHTS: [pathname] +- }); +- // Map from highlight type to highlighted text +- Map> highlights; +- onAnalysisHighlights.listen((AnalysisHighlightsParams params) { +- expect(params.file, equals(pathname)); +- highlights =3D >{}; +- for (HighlightRegion region in params.regions) { +- int startIndex =3D region.offset; +- int endIndex =3D startIndex + region.length; +- String highlightedText =3D text.substring(startIndex, endIndex); +- HighlightRegionType type =3D region.type; +- if (!highlights.containsKey(type)) { +- highlights[type] =3D new Set(); +- } +- highlights[type].add(highlightedText); +- } +- }); +- return analysisFinished.then((_) { +- // There should be 1 error due to the fact that unresolvedIdentifie= r is +- // unresolved. +- expect(currentAnalysisErrors[pathname], hasLength(1)); +- void check(HighlightRegionType type, List expected) { +- expect(highlights[type], equals(expected.toSet())); +- highlights.remove(type); +- } +- +- check(HighlightRegionType.ANNOTATION, ['@override']); +- check(HighlightRegionType.BUILT_IN, +- ['as', 'get', 'import', 'set', 'static', 'typedef']); +- check(HighlightRegionType.CLASS, +- ['Class', 'Class2', 'Future', 'Map', 'int']); +- check(HighlightRegionType.COMMENT_BLOCK, ['/* Block comment */']); +- check(HighlightRegionType.COMMENT_DOCUMENTATION, +- ['/**\n * Doc comment\n */']); +- check( +- HighlightRegionType.COMMENT_END_OF_LINE, ['// End of line comme= nt']); +- check(HighlightRegionType.CONSTRUCTOR, ['constructor']); +- check(HighlightRegionType.DIRECTIVE, ["import 'dart:async' as async= ;"]); +- check(HighlightRegionType.DYNAMIC_TYPE, ['dynamicType']); +- check(HighlightRegionType.FIELD, ['field']); +- check(HighlightRegionType.FIELD_STATIC, ['staticField']); +- check(HighlightRegionType.FUNCTION, ['print']); +- check(HighlightRegionType.FUNCTION_DECLARATION, ['function']); +- check(HighlightRegionType.FUNCTION_TYPE_ALIAS, ['functionType']); +- check(HighlightRegionType.GETTER_DECLARATION, ['getter']); +- check(HighlightRegionType.IDENTIFIER_DEFAULT, ['unresolvedIdentifie= r']); +- check(HighlightRegionType.IMPORT_PREFIX, ['async']); +- check(HighlightRegionType.KEYWORD, ['class', 'true', 'return']); +- check(HighlightRegionType.LITERAL_BOOLEAN, ['true']); +- check(HighlightRegionType.LITERAL_DOUBLE, ['1.0']); +- check(HighlightRegionType.LITERAL_INTEGER, ['2', '42']); +- check(HighlightRegionType.LITERAL_LIST, ['[]']); +- check(HighlightRegionType.LITERAL_MAP, +- ['{1.0: [].toList()}', '{2: local}']); +- check(HighlightRegionType.LITERAL_STRING, ["'dart:async'", "'string= '"]); +- check(HighlightRegionType.LOCAL_VARIABLE, ['local']); +- check(HighlightRegionType.LOCAL_VARIABLE_DECLARATION, ['local']); +- check(HighlightRegionType.METHOD, ['toList']); +- check(HighlightRegionType.METHOD_DECLARATION, ['method']); +- check(HighlightRegionType.METHOD_DECLARATION_STATIC, ['staticMethod= ']); +- check(HighlightRegionType.METHOD_STATIC, ['wait']); +- check(HighlightRegionType.PARAMETER, ['parameter']); +- check(HighlightRegionType.SETTER_DECLARATION, ['setter']); +- check(HighlightRegionType.TOP_LEVEL_VARIABLE, +- ['override', 'topLevelVariable']); +- check(HighlightRegionType.TYPE_NAME_DYNAMIC, ['dynamic']); +- check(HighlightRegionType.TYPE_PARAMETER, ['TypeParameter']); +- expect(highlights, isEmpty); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/highlights_test= 2.dart b/pkg/analysis_server/test/integration/analysis/highlights_test2.dart +deleted file mode 100644 +index 2e672288905..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/highlights_test2.dart ++++ /dev/null +@@ -1,166 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisHighlightsTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisHighlightsTest extends AbstractAnalysisServerIntegrationTes= t { +- Future startServer({ +- bool checked: true, +- int diagnosticPort, +- int servicesPort, +- bool previewDart2: false, +- }) { +- return server.start( +- checked: checked, +- diagnosticPort: diagnosticPort, +- servicesPort: servicesPort, +- useAnalysisHighlight2: true, +- previewDart2: previewDart2); +- } +- +- test_highlights() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:async' as async; +- +-/** +- * Doc comment +- */ +-class Class { +- Class() { +- field =3D {1.0: [].toList()}; +- } +- +- Class.constructor() { +- dynamic local =3D true; +- field =3D {2: local}; +- } +- +- Map field; +- static int staticField; +- +- method() { +- // End of line comment +- /* Block comment */ +- } +- +- static staticMethod() { +- } +- +- get getter { +- } +- +- set setter(int parameter) { +- print(parameter); +- } +-} +- +-class Class2 extends Class { +- @override +- method() { +- } +-} +- +-typedef functionType(); +- +-function(dynamicType) { +- print('string'); +- unresolvedIdentifier =3D 42; +- return async.Future.wait([]); +-} +- +-int topLevelVariable; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- sendAnalysisSetSubscriptions({ +- AnalysisService.HIGHLIGHTS: [pathname] +- }); +- // Map from highlight type to highlighted text +- Map> highlights; +- onAnalysisHighlights.listen((AnalysisHighlightsParams params) { +- expect(params.file, equals(pathname)); +- highlights =3D >{}; +- for (HighlightRegion region in params.regions) { +- int startIndex =3D region.offset; +- int endIndex =3D startIndex + region.length; +- String highlightedText =3D text.substring(startIndex, endIndex); +- HighlightRegionType type =3D region.type; +- if (!highlights.containsKey(type)) { +- highlights[type] =3D new Set(); +- } +- highlights[type].add(highlightedText); +- } +- }); +- return analysisFinished.then((_) { +- // There should be 1 error due to the fact that unresolvedIdentifie= r is +- // unresolved. +- expect(currentAnalysisErrors[pathname], hasLength(1)); +- void check(HighlightRegionType type, List expected) { +- expect(highlights[type], equals(expected.toSet())); +- highlights.remove(type); +- } +- +- check(HighlightRegionType.ANNOTATION, ['@override']); +- check(HighlightRegionType.BUILT_IN, +- ['as', 'get', 'import', 'set', 'static', 'typedef']); +- check(HighlightRegionType.CLASS, +- ['Class', 'Class2', 'Future', 'Map', 'int']); +- check(HighlightRegionType.COMMENT_BLOCK, ['/* Block comment */']); +- check(HighlightRegionType.COMMENT_DOCUMENTATION, +- ['/**\n * Doc comment\n */']); +- check( +- HighlightRegionType.COMMENT_END_OF_LINE, ['// End of line comme= nt']); +- check(HighlightRegionType.CONSTRUCTOR, ['constructor']); +- check(HighlightRegionType.DIRECTIVE, ["import 'dart:async' as async= ;"]); +- check(HighlightRegionType.DYNAMIC_PARAMETER_DECLARATION, ['dynamicT= ype']); +- check(HighlightRegionType.INSTANCE_FIELD_DECLARATION, ['field']); +- check(HighlightRegionType.INSTANCE_SETTER_REFERENCE, ['field']); +- check(HighlightRegionType.STATIC_FIELD_DECLARATION, ['staticField']= ); +- check(HighlightRegionType.TOP_LEVEL_FUNCTION_REFERENCE, ['print']); +- check(HighlightRegionType.TOP_LEVEL_FUNCTION_DECLARATION, ['functio= n']); +- check(HighlightRegionType.FUNCTION_TYPE_ALIAS, ['functionType']); +- check(HighlightRegionType.INSTANCE_GETTER_DECLARATION, ['getter']); +- check(HighlightRegionType.IDENTIFIER_DEFAULT, ['unresolvedIdentifie= r']); +- check(HighlightRegionType.IMPORT_PREFIX, ['async']); +- check(HighlightRegionType.KEYWORD, ['class', 'true', 'return']); +- check(HighlightRegionType.LITERAL_BOOLEAN, ['true']); +- check(HighlightRegionType.LITERAL_DOUBLE, ['1.0']); +- check(HighlightRegionType.LITERAL_INTEGER, ['2', '42']); +- check(HighlightRegionType.LITERAL_LIST, ['[]']); +- check(HighlightRegionType.LITERAL_MAP, +- ['{1.0: [].toList()}', '{2: local}']); +- check(HighlightRegionType.LITERAL_STRING, ["'dart:async'", "'string= '"]); +- check(HighlightRegionType.LOCAL_VARIABLE_DECLARATION, ['local']); +- check(HighlightRegionType.LOCAL_VARIABLE_REFERENCE, ['local']); +- check(HighlightRegionType.INSTANCE_METHOD_REFERENCE, ['toList']); +- check(HighlightRegionType.INSTANCE_METHOD_DECLARATION, ['method']); +- check(HighlightRegionType.STATIC_METHOD_DECLARATION, ['staticMethod= ']); +- check(HighlightRegionType.STATIC_METHOD_REFERENCE, ['wait']); +- check(HighlightRegionType.PARAMETER_DECLARATION, ['parameter']); +- check(HighlightRegionType.PARAMETER_REFERENCE, ['parameter']); +- check(HighlightRegionType.INSTANCE_SETTER_DECLARATION, ['setter']); +- check(HighlightRegionType.TOP_LEVEL_GETTER_REFERENCE, ['override']); +- check(HighlightRegionType.TOP_LEVEL_VARIABLE_DECLARATION, +- ['topLevelVariable']); +- check(HighlightRegionType.TYPE_NAME_DYNAMIC, ['dynamic']); +- check(HighlightRegionType.TYPE_PARAMETER, ['TypeParameter']); +- expect(highlights, isEmpty); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/lint_test.dart = b/pkg/analysis_server/test/integration/analysis/lint_test.dart +deleted file mode 100644 +index 699b43bad43..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/lint_test.dart ++++ /dev/null +@@ -1,83 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LintIntegrationTest); +- }); +-} +- +-@reflectiveTest +-class LintIntegrationTest extends AbstractAnalysisServerIntegrationTest { +- test_no_lints_when_not_specified() async { +- String source =3D sourcePath('test.dart'); +- writeFile(source, ''' +-class abc { // lint: not CamelCase (should get ignored though) +-}'''); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[source], isList); +- // Should be empty without an analysis options file. +- List errors =3D currentAnalysisErrors[source]; +- expect(errors, hasLength(0)); +- } +- +- test_simple_lint_newOptionsFile() async { +- writeFile(sourcePath(AnalysisEngine.ANALYSIS_OPTIONS_YAML_FILE), ''' +-linter: +- rules: +- - camel_case_types +-'''); +- +- String source =3D sourcePath('test.dart'); +- writeFile(source, ''' +-class a { // lint: not CamelCase +-}'''); +- +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- expect(currentAnalysisErrors[source], isList); +- List errors =3D currentAnalysisErrors[source]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.location.file, source); +- expect(error.severity, AnalysisErrorSeverity.INFO); +- expect(error.type, AnalysisErrorType.LINT); +- } +- +- test_simple_lint_oldOptionsFile() async { +- writeFile(sourcePath(AnalysisEngine.ANALYSIS_OPTIONS_FILE), ''' +-linter: +- rules: +- - camel_case_types +-'''); +- +- String source =3D sourcePath('test.dart'); +- writeFile(source, ''' +-class a { // lint: not CamelCase +-}'''); +- +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- expect(currentAnalysisErrors[source], isList); +- List errors =3D currentAnalysisErrors[source]; +- expect(errors, hasLength(1)); +- AnalysisError error =3D errors[0]; +- expect(error.location.file, source); +- expect(error.severity, AnalysisErrorSeverity.INFO); +- expect(error.type, AnalysisErrorType.LINT); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/navigation_test= .dart b/pkg/analysis_server/test/integration/analysis/navigation_test.dart +deleted file mode 100644 +index a5143236515..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/navigation_test.dart ++++ /dev/null +@@ -1,136 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisNavigationTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisNavigationTest extends AbstractAnalysisServerIntegrationTes= t { +- test_navigation() async { +- String pathname1 =3D sourcePath('test1.dart'); +- String text1 =3D r''' +-library foo; +- +-import 'dart:async'; +-part 'test2.dart'; +- +-class Class { +- Class.constructor(); /* constructor declaration */ +- +- TypeParameter field; +- +- method() {} +-} +- +-typedef FunctionTypeAlias(); +- +-function(FunctionTypeAlias parameter) { +- print(parameter()); +-} +- +-int topLevelVariable; +- +-main() { +- Class localVariable =3D new Class.constructor(); // usage +- function(() =3D> localVariable.field); +- localVariable.method(); +- localVariable.field =3D 1; +-} +-'''; +- writeFile(pathname1, text1); +- String pathname2 =3D sourcePath('test2.dart'); +- String text2 =3D r''' +-part of foo; +-'''; +- writeFile(pathname2, text2); +- standardAnalysisSetup(); +- sendAnalysisSetSubscriptions({ +- AnalysisService.NAVIGATION: [pathname1] +- }); +- List regions; +- List targets; +- List targetFiles; +- onAnalysisNavigation.listen((AnalysisNavigationParams params) { +- expect(params.file, equals(pathname1)); +- regions =3D params.regions; +- targets =3D params.targets; +- targetFiles =3D params.files; +- }); +- +- await analysisFinished; +- +- // There should be a single error, due to the fact that 'dart:async' = is not +- // used. +- expect(currentAnalysisErrors[pathname1], hasLength(1)); +- expect(currentAnalysisErrors[pathname2], isEmpty); +- NavigationTarget findTargetElement(int index) { +- for (NavigationRegion region in regions) { +- if (region.offset <=3D index && index < region.offset + region.le= ngth) { +- expect(region.targets, hasLength(1)); +- int targetIndex =3D region.targets[0]; +- return targets[targetIndex]; +- } +- } +- fail('No element found for index $index'); +- return null; +- } +- +- void checkLocal( +- String source, String expectedTarget, ElementKind expectedKind) { +- int sourceIndex =3D text1.indexOf(source); +- int targetIndex =3D text1.indexOf(expectedTarget); +- NavigationTarget element =3D findTargetElement(sourceIndex); +- expect(targetFiles[element.fileIndex], equals(pathname1)); +- expect(element.offset, equals(targetIndex)); +- expect(element.kind, equals(expectedKind)); +- } +- +- void checkRemote( +- String source, String expectedTargetRegexp, ElementKind expectedK= ind) { +- int sourceIndex =3D text1.indexOf(source); +- NavigationTarget element =3D findTargetElement(sourceIndex); +- expect(targetFiles[element.fileIndex], matches(expectedTargetRegexp= )); +- expect(element.kind, equals(expectedKind)); +- } +- +- // TODO(paulberry): will the element type 'CLASS_TYPE_ALIAS' ever app= ear as +- // a navigation target? +- checkLocal('Class', 'Class', ElementKind.CLASS); +- checkRemote("'test2.dart';", r'test2.dart$', ElementKind.COMPILATION_= UNIT); +- checkLocal( +- 'Class.constructor', +- 'constructor(); /* constructor declaration */', +- ElementKind.CONSTRUCTOR); +- checkLocal( +- 'constructor(); // usage', +- 'constructor(); /* constructor declaration */', +- ElementKind.CONSTRUCTOR); +- checkLocal('field;', 'field;', ElementKind.FIELD); +- checkLocal('function(() =3D> localVariable.field)', +- 'function(FunctionTypeAlias parameter)', ElementKind.FUNCTION); +- checkLocal('FunctionTypeAlias parameter', 'FunctionTypeAlias();', +- ElementKind.FUNCTION_TYPE_ALIAS); +- checkLocal('field)', 'field;', ElementKind.GETTER); +- checkRemote("'dart:async'", r'async\.dart$', ElementKind.LIBRARY); +- checkLocal( +- 'localVariable.field', 'localVariable =3D', ElementKind.LOCAL_VAR= IABLE); +- checkLocal('method();', 'method() {', ElementKind.METHOD); +- checkLocal('parameter());', 'parameter) {', ElementKind.PARAMETER); +- checkLocal('field =3D 1', 'field;', ElementKind.SETTER); +- checkLocal('topLevelVariable;', 'topLevelVariable;', +- ElementKind.TOP_LEVEL_VARIABLE); +- checkLocal( +- 'TypeParameter field;', 'TypeParameter>', ElementKind.TYPE_PARAME= TER); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/occurrences_tes= t.dart b/pkg/analysis_server/test/integration/analysis/occurrences_test.dart +deleted file mode 100644 +index 94c942ceba8..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/occurrences_test.dart ++++ /dev/null +@@ -1,68 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OccurrencesTest); +- }); +-} +- +-@reflectiveTest +-class OccurrencesTest extends AbstractAnalysisServerIntegrationTest { +- test_occurrences() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-main() { +- int sum =3D 0; +- for (int i =3D 0; i < 10; i++) { +- for (int j =3D 0; j < i; j++) { +- sum +=3D j; +- } +- } +- print(sum); +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- sendAnalysisSetSubscriptions({ +- AnalysisService.OCCURRENCES: [pathname] +- }); +- List occurrences; +- onAnalysisOccurrences.listen((AnalysisOccurrencesParams params) { +- expect(params.file, equals(pathname)); +- occurrences =3D params.occurrences; +- }); +- return analysisFinished.then((_) { +- expect(currentAnalysisErrors[pathname], isEmpty); +- Set findOffsets(String elementName) { +- for (Occurrences occurrence in occurrences) { +- if (occurrence.element.name =3D=3D elementName) { +- return occurrence.offsets.toSet(); +- } +- } +- fail('No element found matching $elementName'); +- return null; +- } +- +- void check(String elementName, Iterable expectedOccurrences= ) { +- Set expectedOffsets =3D expectedOccurrences +- .map((String substring) =3D> text.indexOf(substring)) +- .toSet(); +- Set foundOffsets =3D findOffsets(elementName); +- expect(foundOffsets, equals(expectedOffsets)); +- } +- +- check('i', ['i =3D 0', 'i < 10', 'i++', 'i;']); +- check('j', ['j =3D 0', 'j < i', 'j++', 'j;']); +- check('sum', ['sum =3D 0', 'sum +=3D', 'sum)']); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/outline_test.da= rt b/pkg/analysis_server/test/integration/analysis/outline_test.dart +deleted file mode 100644 +index bef8bd257f1..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/outline_test.dart ++++ /dev/null +@@ -1,84 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OutlineTest); +- }); +-} +- +-@reflectiveTest +-class OutlineTest extends AbstractAnalysisServerIntegrationTest { +- /** +- * Verify that the range of source text covered by the given outline ob= jects +- * is connected (the end of each object in the list corresponds to the = start +- * of the next). +- */ +- void checkConnected(List outlineObjects) { +- for (int i =3D 0; i < outlineObjects.length - 1; i++) { +- expect(outlineObjects[i + 1].offset, +- equals(outlineObjects[i].offset + outlineObjects[i].length)); +- } +- } +- +- test_outline() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-class Class1 { +- int field; +- +- void method() { +- } +- +- static staticMethod() { +- } +- +- get getter { +- return null; +- } +- +- set setter(value) { +- } +-} +- +-class Class2 { +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- sendAnalysisSetSubscriptions({ +- AnalysisService.OUTLINE: [pathname] +- }); +- Outline outline; +- onAnalysisOutline.listen((AnalysisOutlineParams params) { +- expect(params.file, equals(pathname)); +- outline =3D params.outline; +- }); +- return analysisFinished.then((_) { +- expect(outline.element.kind, equals(ElementKind.COMPILATION_UNIT)); +- expect(outline.offset, equals(0)); +- expect(outline.length, equals(text.length)); +- List classes =3D outline.children; +- expect(classes, hasLength(2)); +- expect(classes[0].element.name, equals('Class1')); +- expect(classes[1].element.name, equals('Class2')); +- checkConnected(classes); +- List members =3D classes[0].children; +- expect(members, hasLength(5)); +- expect(members[0].element.name, equals('field')); +- expect(members[1].element.name, equals('method')); +- expect(members[2].element.name, equals('staticMethod')); +- expect(members[3].element.name, equals('getter')); +- expect(members[4].element.name, equals('setter')); +- checkConnected(members); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/overrides_test.= dart b/pkg/analysis_server/test/integration/analysis/overrides_test.dart +deleted file mode 100644 +index 32c238ca122..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/overrides_test.dart ++++ /dev/null +@@ -1,122 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OverridesTest); +- }); +-} +- +-@reflectiveTest +-class OverridesTest extends AbstractAnalysisServerIntegrationTest { +- test_overrides() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-abstract class Interface1 { +- method0(); +- method1(); +- method2(); +- method3(); +-} +- +-abstract class Interface2 { +- method0(); +- method1(); +- method4(); +- method5(); +-} +- +-abstract class Base { +- method0(); +- method2(); +- method4(); +- method6(); +-} +- +-class Target extends Base implements Interface1, Interface2 { +- method0() {} +- method1() {} +- method2() {} +- method3() {} +- method4() {} +- method5() {} +- method6() {} +- method7() {} +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- sendAnalysisSetSubscriptions({ +- AnalysisService.OVERRIDES: [pathname] +- }); +- List overrides; +- onAnalysisOverrides.listen((AnalysisOverridesParams params) { +- expect(params.file, equals(pathname)); +- overrides =3D params.overrides; +- }); +- return analysisFinished.then((_) { +- int targetOffset =3D text.indexOf('Target'); +- Override findOverride(String methodName) { +- int methodOffset =3D text.indexOf(methodName, targetOffset); +- for (Override override in overrides) { +- if (override.offset =3D=3D methodOffset) { +- return override; +- } +- } +- return null; +- } +- +- void checkOverrides(String methodName, bool expectedOverridesBase, +- List expectedOverridesInterfaces) { +- Override override =3D findOverride(methodName); +- if (!expectedOverridesBase && expectedOverridesInterfaces.isEmpty= ) { +- // This method overrides nothing, so it should not appear in the +- // overrides list. +- expect(override, isNull); +- return; +- } else { +- expect(override, isNotNull); +- } +- expect(override.length, equals(methodName.length)); +- OverriddenMember superclassMember =3D override.superclassMember; +- if (expectedOverridesBase) { +- expect(superclassMember.element.name, equals(methodName)); +- expect(superclassMember.className, equals('Base')); +- } else { +- expect(superclassMember, isNull); +- } +- List interfaceMembers =3D override.interfaceMem= bers; +- if (expectedOverridesInterfaces.isNotEmpty) { +- expect(interfaceMembers, isNotNull); +- Set actualOverridesInterfaces =3D new Set(); +- for (OverriddenMember overriddenMember in interfaceMembers) { +- expect(overriddenMember.element.name, equals(methodName)); +- String className =3D overriddenMember.className; +- bool wasAdded =3D actualOverridesInterfaces.add(className); +- expect(wasAdded, isTrue); +- } +- expect(actualOverridesInterfaces, +- equals(expectedOverridesInterfaces.toSet())); +- } else { +- expect(interfaceMembers, isNull); +- } +- } +- +- checkOverrides('method0', true, ['Interface1', 'Interface2']); +- checkOverrides('method1', false, ['Interface1', 'Interface2']); +- checkOverrides('method2', true, ['Interface1']); +- checkOverrides('method3', false, ['Interface1']); +- checkOverrides('method4', true, ['Interface2']); +- checkOverrides('method5', false, ['Interface2']); +- checkOverrides('method6', true, []); +- checkOverrides('method7', false, []); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/package_root_te= st.dart b/pkg/analysis_server/test/integration/analysis/package_root_test.d= art +deleted file mode 100644 +index d2e1c2c1b98..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/package_root_test.dart ++++ /dev/null +@@ -1,79 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetAnalysisRootsTest); +- }); +-} +- +-@reflectiveTest +-class SetAnalysisRootsTest extends AbstractAnalysisServerIntegrationTest { +- test_package_root() { +- String projPath =3D sourcePath('project'); +- String mainPath =3D path.join(projPath, 'main.dart'); +- String packagesPath =3D sourcePath('packages'); +- String fooBarPath =3D path.join(packagesPath, 'foo', 'bar.dart'); +- String mainText =3D """ +-library main; +- +-import 'package:foo/bar.dart' +- +-main() { +- f(); +-} +-"""; +- String fooBarText =3D """ +-library foo.bar; +- +-f() {} +-"""; +- writeFile(mainPath, mainText); +- String normalizedFooBarPath =3D writeFile(fooBarPath, fooBarText); +- sendServerSetSubscriptions([ServerService.STATUS]); +- sendAnalysisSetSubscriptions({ +- AnalysisService.NAVIGATION: [mainPath] +- }); +- List navigationRegions; +- List navigationTargets; +- List navigationTargetFiles; +- onAnalysisNavigation.listen((AnalysisNavigationParams params) { +- expect(params.file, equals(mainPath)); +- navigationRegions =3D params.regions; +- navigationTargets =3D params.targets; +- navigationTargetFiles =3D params.files; +- }); +- sendAnalysisSetAnalysisRoots([projPath], [], +- packageRoots: {projPath: packagesPath}); +- sendAnalysisSetPriorityFiles([mainPath]); +- return analysisFinished.then((_) { +- // Verify that fooBarPath was properly resolved by checking that f() +- // refers to it. +- bool found =3D false; +- for (NavigationRegion region in navigationRegions) { +- String navigationSource =3D +- mainText.substring(region.offset, region.offset + region.leng= th); +- if (navigationSource =3D=3D 'f') { +- found =3D true; +- expect(region.targets, hasLength(1)); +- int navigationTargetIndex =3D region.targets[0]; +- NavigationTarget navigationTarget =3D +- navigationTargets[navigationTargetIndex]; +- String navigationFile =3D +- navigationTargetFiles[navigationTarget.fileIndex]; +- expect(navigationFile, equals(normalizedFooBarPath)); +- } +- } +- expect(found, isTrue); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/reanalyze_concu= rrent_test.dart b/pkg/analysis_server/test/integration/analysis/reanalyze_c= oncurrent_test.dart +deleted file mode 100644 +index 11b7ceb615c..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/reanalyze_concurrent_t= est.dart ++++ /dev/null +@@ -1,49 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * This test verifies that if reanalysis is performed while reanalysis is= in +- * progress, no problems occur. +- * +- * See dartbug.com/21448. +- */ +-import 'dart:async'; +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ReanalyzeTest); +- }); +-} +- +-@reflectiveTest +-class ReanalyzeTest extends AbstractAnalysisServerIntegrationTest { +- test_reanalyze_concurrent() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D ''' +-// Do a bunch of imports so that analysis has some work to do. +-import 'dart:io'; +-import 'dart:convert'; +-import 'dart:async'; +- +-main() {}'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- return analysisFinished.then((_) { +- sendAnalysisReanalyze(); +- // Wait for reanalysis to start. +- return onServerStatus.first.then((_) { +- sendAnalysisReanalyze(); +- return analysisFinished.then((_) { +- // Now that reanalysis has finished, give the server an extra s= econd +- // to make sure it doesn't crash. +- return new Future.delayed(new Duration(seconds: 1)); +- }); +- }); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/reanalyze_test.= dart b/pkg/analysis_server/test/integration/analysis/reanalyze_test.dart +deleted file mode 100644 +index 8740ef03f28..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/reanalyze_test.dart ++++ /dev/null +@@ -1,40 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ReanalyzeTest); +- }); +-} +- +-@reflectiveTest +-class ReanalyzeTest extends AbstractAnalysisServerIntegrationTest { +- test_reanalyze() { +- String pathname =3D sourcePath('test.dart'); +- String text =3D 'main() {}'; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- return analysisFinished.then((_) { +- // Make sure that reanalyze causes analysis to restart. +- bool analysisRestarted =3D false; +- onServerStatus.listen((ServerStatusParams data) { +- if (data.analysis !=3D null) { +- if (data.analysis.isAnalyzing) { +- analysisRestarted =3D true; +- } +- } +- }); +- sendAnalysisReanalyze(); +- return analysisFinished.then((_) { +- expect(analysisRestarted, isTrue); +- }); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/set_analysis_ro= ots_test.dart b/pkg/analysis_server/test/integration/analysis/set_analysis_= roots_test.dart +deleted file mode 100644 +index f6c1d6125bd..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/set_analysis_roots_tes= t.dart ++++ /dev/null +@@ -1,32 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetAnalysisRootsTest); +- }); +-} +- +-@reflectiveTest +-class SetAnalysisRootsTest extends AbstractAnalysisServerIntegrationTest { +- test_options() async { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-class Foo { +- void bar() {} +-} +-'''); +- +- // Calling this will call analysis.setAnalysisRoots. +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/set_general_sub= scriptions_test.dart b/pkg/analysis_server/test/integration/analysis/set_ge= neral_subscriptions_test.dart +deleted file mode 100644 +index 9d491570730..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/set_general_subscripti= ons_test.dart ++++ /dev/null +@@ -1,40 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetGeneralSubscriptionsTest); +- }); +-} +- +-@reflectiveTest +-class SetGeneralSubscriptionsTest +- extends AbstractAnalysisServerIntegrationTest { +- test_options() async { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-class Foo { +- void bar() {} +-} +-'''); +- +- standardAnalysisSetup(); +- +- await sendAnalysisSetGeneralSubscriptions( +- [GeneralAnalysisService.ANALYZED_FILES]); +- await analysisFinished; +- +- expect(lastAnalyzedFiles, isNotEmpty); +- expect(lastAnalyzedFiles, contains(pathname)); +- expect( +- lastAnalyzedFiles.any((String file) =3D> file.endsWith('core/core= .dart')), +- true); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/set_priority_fi= les_test.dart b/pkg/analysis_server/test/integration/analysis/set_priority_= files_test.dart +deleted file mode 100644 +index 10cb1a07fbd..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/set_priority_files_tes= t.dart ++++ /dev/null +@@ -1,30 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetPriorityFilesTest); +- }); +-} +- +-@reflectiveTest +-class SetPriorityFilesTest extends AbstractAnalysisServerIntegrationTest { +- test_options() async { +- String pathname =3D sourcePath('foo.dart'); +- writeFile(pathname, 'class Foo { void baz() {} }'); +- writeFile(sourcePath('bar.dart'), 'class Bar { void baz() {} }'); +- +- standardAnalysisSetup(); +- await sendAnalysisSetPriorityFiles([pathname]); +- +- ServerStatusParams status =3D await analysisFinished; +- expect(status.analysis.isAnalyzing, false); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/set_subscriptio= ns_test.dart b/pkg/analysis_server/test/integration/analysis/set_subscripti= ons_test.dart +deleted file mode 100644 +index 9524b4dd443..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/set_subscriptions_test= .dart ++++ /dev/null +@@ -1,32 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetSubscriptionsTest); +- }); +-} +- +-@reflectiveTest +-class SetSubscriptionsTest extends AbstractAnalysisServerIntegrationTest { +- test_subscriptions() async { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-class Foo { +- void bar() {} +-} +-'''); +- +- // Calling this will subscribe to ServerService.STATUS. +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/test_all.dart b= /pkg/analysis_server/test/integration/analysis/test_all.dart +deleted file mode 100644 +index e7a825d80c6..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/test_all.dart ++++ /dev/null +@@ -1,66 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'analysis_options_test.dart' as analysis_options_test; +-import 'error_test.dart' as error_test; +-import 'get_errors_nonStandard_sdk.dart' as get_errors_nonStandard_sdk; +-import 'get_errors_test.dart' as get_errors_test; +-import 'get_hover_test.dart' as get_hover_test; +-import 'get_imported_elements_test.dart' as get_imported_elements_test; +-import 'get_library_dependencies_test.dart' as get_library_dependencies_t= est; +-import 'get_navigation_test.dart' as get_navigation_test; +-import 'get_reachable_sources_test.dart' as get_reachable_sources_test; +-import 'highlights_test.dart' as highlights_test; +-import 'highlights_test2.dart' as highlights_test2; +-import 'lint_test.dart' as lint_test; +-import 'navigation_test.dart' as navigation_test; +-import 'occurrences_test.dart' as occurrences_test; +-import 'outline_test.dart' as outline_test; +-import 'overrides_test.dart' as overrides_test; +-import 'package_root_test.dart' as package_root_test; +-import 'reanalyze_concurrent_test.dart' as reanalyze_concurrent_test; +-import 'reanalyze_test.dart' as reanalyze_test; +-import 'set_analysis_roots_test.dart' as set_analysis_roots_test; +-import 'set_general_subscriptions_test.dart' as set_general_subscriptions= _test; +-import 'set_priority_files_test.dart' as set_priority_files_test; +-import 'set_subscriptions_test.dart' as set_subscriptions_test; +-import 'update_content_list_test.dart' as update_content_list_test; +-import 'update_content_test.dart' as update_content_test; +-import 'update_options_test.dart' as update_options_test; +- +-/** +- * Utility for manually running all integration tests. +- */ +-main() { +- defineReflectiveSuite(() { +- analysis_options_test.main(); +- error_test.main(); +- get_errors_test.main(); +- get_errors_nonStandard_sdk.main(); +- get_library_dependencies_test.main(); +- get_hover_test.main(); +- get_imported_elements_test.main(); +- get_navigation_test.main(); +- get_reachable_sources_test.main(); +- highlights_test.main(); +- highlights_test2.main(); +- lint_test.main(); +- navigation_test.main(); +- occurrences_test.main(); +- outline_test.main(); +- overrides_test.main(); +- package_root_test.main(); +- reanalyze_concurrent_test.main(); +- reanalyze_test.main(); +- set_analysis_roots_test.main(); +- set_general_subscriptions_test.main(); +- set_priority_files_test.main(); +- set_subscriptions_test.main(); +- update_content_test.main(); +- update_content_list_test.main(); +- update_options_test.main(); +- }, name: 'analysis'); +-} +diff --git a/pkg/analysis_server/test/integration/analysis/update_content_= list_test.dart b/pkg/analysis_server/test/integration/analysis/update_conte= nt_list_test.dart +deleted file mode 100644 +index d44cce76f90..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/update_content_list_te= st.dart ++++ /dev/null +@@ -1,52 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(UpdateContentTest); +- }); +-} +- +-@reflectiveTest +-class UpdateContentTest extends AbstractAnalysisServerIntegrationTest { +- test_updateContent_list() { +- String pathname =3D sourcePath('test.dart'); +- String goodText =3D r''' +-main() { +- print("Hello"); +- print("World!"); +-}'''; +- String badText =3D goodText.replaceAll('"', ''); +- // Create a dummy file +- writeFile(pathname, '// dummy text'); +- standardAnalysisSetup(); +- // Override file contents with badText. +- sendAnalysisUpdateContent({pathname: new AddContentOverlay(badText)}); +- return analysisFinished.then((_) { +- // The overridden contents (badText) are missing quotation marks. +- expect(currentAnalysisErrors[pathname], isNotEmpty); +- }).then((_) { +- // Prepare a set of edits which add the missing quotation marks, in= the +- // order in which they appear in the file. If these edits are appl= ied in +- // the wrong order, some of the quotation marks will be in the wrong +- // places, and there will still be errors. +- List edits =3D '"' +- .allMatches(goodText) +- .map((Match match) =3D> new SourceEdit(match.start, 0, '"')) +- .toList(); +- sendAnalysisUpdateContent({pathname: new ChangeContentOverlay(edits= )}); +- return analysisFinished; +- }).then((_) { +- // There should be no errors now, assuming that quotation marks hav= e been +- // inserted in all the correct places. +- expect(currentAnalysisErrors[pathname], isEmpty); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/update_content_= test.dart b/pkg/analysis_server/test/integration/analysis/update_content_te= st.dart +deleted file mode 100644 +index 0e307b3aedc..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/update_content_test.da= rt ++++ /dev/null +@@ -1,107 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(UpdateContentTest); +- }); +-} +- +-@reflectiveTest +-class UpdateContentTest extends AbstractAnalysisServerIntegrationTest { +- test_updateContent() async { +- String path =3D sourcePath('test.dart'); +- String goodText =3D r''' +-main() { +- print("Hello, world!"); +-}'''; +- +- String badText =3D goodText.replaceAll(';', ''); +- writeFile(path, badText); +- standardAnalysisSetup(); +- +- // The contents on disk (badText) are missing a semicolon. +- await analysisFinished; +- expect(currentAnalysisErrors[path], isNotEmpty); +- +- // There should be no errors now because the contents on disk have be= en +- // overridden with goodText. +- sendAnalysisUpdateContent({path: new AddContentOverlay(goodText)}); +- await analysisFinished; +- expect(currentAnalysisErrors[path], isEmpty); +- +- // There should be errors now because we've removed the semicolon. +- sendAnalysisUpdateContent({ +- path: new ChangeContentOverlay( +- [new SourceEdit(goodText.indexOf(';'), 1, '')]) +- }); +- await analysisFinished; +- expect(currentAnalysisErrors[path], isNotEmpty); +- +- // There should be no errors now because we've added the semicolon ba= ck. +- sendAnalysisUpdateContent({ +- path: new ChangeContentOverlay( +- [new SourceEdit(goodText.indexOf(';'), 0, ';')]) +- }); +- await analysisFinished; +- expect(currentAnalysisErrors[path], isEmpty); +- +- // Now there should be errors again, because the contents on disk are= no +- // longer overridden. +- sendAnalysisUpdateContent({path: new RemoveContentOverlay()}); +- await analysisFinished; +- expect(currentAnalysisErrors[path], isNotEmpty); +- } +- +- @failingTest +- test_updateContent_multipleAdds() async { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, r''' +-class Person { +- String _name; +- Person(this._name); +- String get name =3D> this._name; +- String toString() =3D> "Name: ${name}"; +-} +-void main() { +- var p =3D new Person("Skeletor"); +- p.xname =3D "Faker"; +- print(p); +-} +-'''); +- standardAnalysisSetup(); +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isList); +- List errors1 =3D currentAnalysisErrors[pathname]; +- expect(errors1, hasLength(1)); +- expect(errors1[0].location.file, equals(pathname)); +- +- await sendAnalysisUpdateContent({ +- pathname: new AddContentOverlay(r''' +-class Person { +- String _name; +- Person(this._name); +- String get name =3D> this._name; +- String toString() =3D> "Name: ${name}"; +-} +-void main() { +- var p =3D new Person("Skeletor"); +- p.name =3D "Faker"; +- print(p); +-} +-''') +- }); +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isList); +- List errors2 =3D currentAnalysisErrors[pathname]; +- expect(errors2, hasLength(1)); +- expect(errors2[0].location.file, equals(pathname)); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analysis/update_options_= test.dart b/pkg/analysis_server/test/integration/analysis/update_options_te= st.dart +deleted file mode 100644 +index 1172d78e8ea..00000000000 +--- a/pkg/analysis_server/test/integration/analysis/update_options_test.da= rt ++++ /dev/null +@@ -1,47 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(UpdateOptionsTest); +- }); +-} +- +-@reflectiveTest +-class UpdateOptionsTest extends AbstractAnalysisServerIntegrationTest { +- @failingTest +- test_options() async { +- // We fail after the first analysis.updateOptions - we should not see= a hint +- // for the unused import (#28800). +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-import 'dart:async'; // unused +- +-class Foo { +- void bar() {} +-} +-'''); +- standardAnalysisSetup(); +- +- // ignore: deprecated_member_use +- await sendAnalysisUpdateOptions( +- new AnalysisOptions()..generateHints =3D false); +- await sendAnalysisReanalyze(); +- await analysisFinished; +- expect(getErrors(pathname), isEmpty); +- +- // ignore: deprecated_member_use +- await sendAnalysisUpdateOptions( +- new AnalysisOptions()..generateHints =3D true); +- await sendAnalysisReanalyze(); +- await analysisFinished; +- expect(getErrors(pathname), hasLength(1)); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analytics/enable_test.da= rt b/pkg/analysis_server/test/integration/analytics/enable_test.dart +deleted file mode 100644 +index a32971f9458..00000000000 +--- a/pkg/analysis_server/test/integration/analytics/enable_test.dart ++++ /dev/null +@@ -1,33 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(EnableTest); +- }); +-} +- +-@reflectiveTest +-class EnableTest extends AbstractAnalysisServerIntegrationTest { +- test_call_enable() async { +- standardAnalysisSetup(); +- +- // Toggle the value twice, and verify the changes. +- AnalyticsIsEnabledResult result1 =3D await sendAnalyticsIsEnabled(); +- await sendAnalyticsEnable(!result1.enabled); +- +- AnalyticsIsEnabledResult result2 =3D await sendAnalyticsIsEnabled(); +- expect(result2.enabled, !result1.enabled); +- +- await sendAnalyticsEnable(result1.enabled); +- result2 =3D await sendAnalyticsIsEnabled(); +- expect(result2.enabled, result1.enabled); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analytics/is_enabled_tes= t.dart b/pkg/analysis_server/test/integration/analytics/is_enabled_test.dart +deleted file mode 100644 +index 8e2ffd5aae1..00000000000 +--- a/pkg/analysis_server/test/integration/analytics/is_enabled_test.dart ++++ /dev/null +@@ -1,26 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(IsEnabledTest); +- }); +-} +- +-@reflectiveTest +-class IsEnabledTest extends AbstractAnalysisServerIntegrationTest { +- test_isEnabled() async { +- standardAnalysisSetup(); +- +- AnalyticsIsEnabledResult result =3D await sendAnalyticsIsEnabled(); +- // Very lightweight validation of the returned data. +- expect(result, isNotNull); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analytics/send_event_tes= t.dart b/pkg/analysis_server/test/integration/analytics/send_event_test.dart +deleted file mode 100644 +index fbeb48adf19..00000000000 +--- a/pkg/analysis_server/test/integration/analytics/send_event_test.dart ++++ /dev/null +@@ -1,31 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SendEventTest); +- }); +-} +- +-@reflectiveTest +-class SendEventTest extends AbstractAnalysisServerIntegrationTest { +- test_send_event() async { +- standardAnalysisSetup(); +- +- // Disable analytics. +- AnalyticsIsEnabledResult result1 =3D await sendAnalyticsIsEnabled(); +- await sendAnalyticsEnable(false); +- +- // Send an event. +- await sendAnalyticsSendEvent('test-action'); +- +- // Restore the original value. +- await sendAnalyticsEnable(result1.enabled); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analytics/send_timing_te= st.dart b/pkg/analysis_server/test/integration/analytics/send_timing_test.d= art +deleted file mode 100644 +index fb65d8a478c..00000000000 +--- a/pkg/analysis_server/test/integration/analytics/send_timing_test.dart ++++ /dev/null +@@ -1,31 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SendTimingTest); +- }); +-} +- +-@reflectiveTest +-class SendTimingTest extends AbstractAnalysisServerIntegrationTest { +- test_send_timing() async { +- standardAnalysisSetup(); +- +- // Disable analytics. +- AnalyticsIsEnabledResult result1 =3D await sendAnalyticsIsEnabled(); +- await sendAnalyticsEnable(false); +- +- // Send an event. +- await sendAnalyticsSendTiming('test-action', 100); +- +- // Restore the original value. +- await sendAnalyticsEnable(result1.enabled); +- } +-} +diff --git a/pkg/analysis_server/test/integration/analytics/test_all.dart = b/pkg/analysis_server/test/integration/analytics/test_all.dart +deleted file mode 100644 +index d4352b7a485..00000000000 +--- a/pkg/analysis_server/test/integration/analytics/test_all.dart ++++ /dev/null +@@ -1,19 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'enable_test.dart' as enable_test; +-import 'is_enabled_test.dart' as is_enabled_test; +-import 'send_event_test.dart' as send_event_test; +-import 'send_timing_test.dart' as send_timing_test; +- +-main() { +- defineReflectiveSuite(() { +- enable_test.main(); +- is_enabled_test.main(); +- send_event_test.main(); +- send_timing_test.main(); +- }, name: 'analytics'); +-} +diff --git a/pkg/analysis_server/test/integration/completion/get_suggestio= ns_test.dart b/pkg/analysis_server/test/integration/completion/get_suggesti= ons_test.dart +deleted file mode 100644 +index 1efd154b081..00000000000 +--- a/pkg/analysis_server/test/integration/completion/get_suggestions_test= .dart ++++ /dev/null +@@ -1,118 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetSuggestionsTest); +- }); +-} +- +-@reflectiveTest +-class GetSuggestionsTest extends AbstractAnalysisServerIntegrationTest { +- String path; +- String content; +- int completionOffset; +- +- void setTestSource(String relPath, String content) { +- path =3D sourcePath(relPath); +- expect(completionOffset, isNull, reason: 'Call addTestUnit exactly on= ce'); +- completionOffset =3D content.indexOf('^'); +- expect(completionOffset, isNot(equals(-1)), reason: 'missing ^'); +- int nextOffset =3D content.indexOf('^', completionOffset + 1); +- expect(nextOffset, equals(-1), reason: 'too many ^'); +- this.content =3D content.substring(0, completionOffset) + +- content.substring(completionOffset + 1); +- } +- +- test_getSuggestions() async { +- setTestSource('test.dart', r''' +-String test =3D ''; +-main() { +- test.^ +-} +-'''); +- writeFile(path, content); +- await standardAnalysisSetup(); +- await analysisFinished; +- CompletionGetSuggestionsResult result =3D +- await sendCompletionGetSuggestions(path, completionOffset); +- String completionId =3D result.id; +- CompletionResultsParams param =3D await onCompletionResults.firstWher= e( +- (CompletionResultsParams param) =3D> +- param.id =3D=3D completionId && param.isLast); +- expect(param.replacementOffset, completionOffset); +- expect(param.replacementLength, 0); +- param.results.firstWhere( +- (CompletionSuggestion suggestion) =3D> suggestion.completion =3D= =3D 'length'); +- } +- +- test_getSuggestions_onlyOverlay() async { +- setTestSource('test.dart', r''' +-String test =3D ''; +-main() { +- test.^ +-} +-'''); +- // Create an overlay but do not write the file to "disk" +- // writeFile(pathname, text); +- await standardAnalysisSetup(); +- await sendAnalysisUpdateContent({path: new AddContentOverlay(content)= }); +- await analysisFinished; +- CompletionGetSuggestionsResult result =3D +- await sendCompletionGetSuggestions(path, completionOffset); +- String completionId =3D result.id; +- CompletionResultsParams param =3D await onCompletionResults.firstWher= e( +- (CompletionResultsParams param) =3D> +- param.id =3D=3D completionId && param.isLast); +- expect(param.replacementOffset, completionOffset); +- expect(param.replacementLength, 0); +- param.results.firstWhere( +- (CompletionSuggestion suggestion) =3D> suggestion.completion =3D= =3D 'length'); +- } +- +- test_getSuggestions_onlyOverlay_noWait() async { +- setTestSource('test.dart', r''' +-String test =3D ''; +-main() { +- test.^ +-} +-'''); +- // Create an overlay but do not write the file to "disk" +- // writeFile(pathname, text); +- // Don't wait for any results except the completion notifications +- standardAnalysisSetup(subscribeStatus: false); +- sendAnalysisUpdateContent({path: new AddContentOverlay(content)}); +- sendCompletionGetSuggestions(path, completionOffset); +- CompletionResultsParams param =3D await onCompletionResults +- .firstWhere((CompletionResultsParams param) =3D> param.isLast); +- expect(param.replacementOffset, completionOffset); +- expect(param.replacementLength, 0); +- param.results.firstWhere( +- (CompletionSuggestion suggestion) =3D> suggestion.completion =3D= =3D 'length'); +- } +- +- test_getSuggestions_sourceMissing_noWait() { +- path =3D sourcePath('does_not_exist.dart'); +- // Do not write the file to "disk" +- // writeFile(pathname, text); +- // Don't wait for any results except the completion notifications +- standardAnalysisSetup(subscribeStatus: false); +- // Missing file and no overlay +- //sendAnalysisUpdateContent({path: new AddContentOverlay(content)}); +- var errorToken =3D 'exception from server'; +- return sendCompletionGetSuggestions(path, 0).catchError((e) { +- // Exception expected +- return errorToken; +- }).then((result) { +- expect(result, new isInstanceOf()); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/completion/test_all.dart= b/pkg/analysis_server/test/integration/completion/test_all.dart +deleted file mode 100644 +index f07053b91ad..00000000000 +--- a/pkg/analysis_server/test/integration/completion/test_all.dart ++++ /dev/null +@@ -1,16 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'get_suggestions_test.dart' as get_suggestions_test; +- +-/** +- * Utility for manually running all integration tests. +- */ +-main() { +- defineReflectiveSuite(() { +- get_suggestions_test.main(); +- }, name: 'completion'); +-} +diff --git a/pkg/analysis_server/test/integration/coverage.md b/pkg/analys= is_server/test/integration/coverage.md +deleted file mode 100644 +index 9d0ac620842..00000000000 +--- a/pkg/analysis_server/test/integration/coverage.md ++++ /dev/null +@@ -1,83 +0,0 @@ +-Checklist to ensure that we have integration test coverage of all analysis +-server calls. This file is validated by `coverage_test.dart`. +- +-## analysis domain +-- [x] analysis.getErrors +-- [x] analysis.getHover +-- [x] analysis.getImportedElements +-- [x] analysis.getLibraryDependencies (failing - see #29310) +-- [x] analysis.getNavigation (failing - see #28799) +-- [x] analysis.getReachableSources (failing - see #29311) +-- [x] analysis.reanalyze +-- [x] analysis.setAnalysisRoots +-- [x] analysis.setGeneralSubscriptions +-- [x] analysis.setPriorityFiles +-- [x] analysis.setSubscriptions +-- [x] analysis.updateContent +-- [x] analysis.updateOptions (failing - see #28800) (deprecated) +-- [ ] analysis.analyzedFiles +-- [ ] analysis.closingLabels +-- [ ] analysis.errors +-- [ ] analysis.flushResults +-- [ ] analysis.folding +-- [x] analysis.highlights +-- [ ] analysis.implemented +-- [ ] analysis.invalidate +-- [x] analysis.navigation +-- [x] analysis.occurrences +-- [x] analysis.outline +-- [x] analysis.overrides +- +-## completion domain +-- [x] completion.getSuggestions +-- [ ] completion.results +- +-## diagnostic domain +-- [x] diagnostic.getDiagnostics +-- [x] diagnostic.getServerPort +- +-## edit domain +-- [x] edit.format +-- [x] edit.getAssists +-- [x] edit.getAvailableRefactorings +-- [x] edit.getFixes +-- [x] edit.getPostfixCompletion +-- [x] edit.getRefactoring +-- [x] edit.getStatementCompletion +-- [x] edit.importElements +-- [x] edit.isPostfixCompletionApplicable +-- [x] edit.listPostfixCompletionTemplates +-- [x] edit.sortMembers +-- [x] edit.organizeDirectives +- +-## execution domain +-- [x] execution.createContext +-- [x] execution.deleteContext +-- [x] execution.mapUri +-- [x] execution.setSubscriptions +-- [ ] execution.launchData +- +-## search domain +-- [x] search.findElementReferences +-- [x] search.findMemberDeclarations +-- [x] search.findMemberReferences +-- [x] search.findTopLevelDeclarations +-- [x] search.getTypeHierarchy +-- [ ] search.results +- +-## server domain +-- [x] server.getVersion +-- [x] server.shutdown +-- [x] server.setSubscriptions +-- [ ] server.connected +-- [ ] server.error +-- [x] server.status +- +-## analytics domain +-- [x] analytics.isEnabled +-- [x] analytics.enable +-- [x] analytics.sendEvent +-- [x] analytics.sendTiming +- +-## kythe domain +-- [x] kythe.getKytheEntries +diff --git a/pkg/analysis_server/test/integration/coverage_test.dart b/pkg= /analysis_server/test/integration/coverage_test.dart +deleted file mode 100644 +index b8b3c14e237..00000000000 +--- a/pkg/analysis_server/test/integration/coverage_test.dart ++++ /dev/null +@@ -1,129 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +- +-import '../../tool/spec/api.dart'; +-import '../../tool/spec/from_html.dart'; +- +-/// Define tests to fail if there's no mention in the coverage file. +-main() { +- Api api; +- File coverageFile; +- String pathPrefix; +- +- // parse the API file +- if (FileSystemEntity +- .isFileSync(path.join('tool', 'spec', 'spec_input.html'))) { +- api =3D readApi('.'); +- pathPrefix =3D '.'; +- } else { +- api =3D readApi(path.join('pkg', 'analysis_server')); +- pathPrefix =3D path.join('pkg', 'analysis_server'); +- } +- +- coverageFile =3D +- new File(path.join(pathPrefix, 'test', 'integration', 'coverage.md'= )); +- List lines =3D coverageFile.readAsLinesSync(); +- +- // ## server domain +- Set coveredDomains =3D lines +- .where((line) =3D> line.startsWith('## ') && line.endsWith(' domain= ')) +- .map((line) =3D> +- line.substring('##'.length, line.length - 'domain'.length).trim= ()) +- .toSet(); +- +- // Remove any ' (test failed)' suffixes. +- lines =3D lines.map((String line) { +- int index =3D line.indexOf('('); +- return index !=3D -1 ? line.substring(0, index).trim() : line; +- }).toList(); +- +- // - [ ] server.getVersion +- Set allMembers =3D lines +- .where((line) =3D> line.startsWith('- ')) +- .map((line) =3D> line.substring('- [ ]'.length).trim()) +- .toSet(); +- Set coveredMembers =3D lines +- .where((line) =3D> line.startsWith('- [x]')) +- .map((line) =3D> line.substring('- [x]'.length).trim()) +- .toSet(); +- +- // generate domain tests +- for (Domain domain in api.domains) { +- group('integration coverage of ${domain.name}', () { +- // domain +- test('domain', () { +- if (!coveredDomains.contains(domain.name)) { +- fail('${domain.name} domain not found in ${coverageFile.path}'); +- } +- }); +- +- // requests +- group('request', () { +- for (Request request in domain.requests) { +- String fullName =3D '${domain.name}.${request.method}'; +- test(fullName, () { +- if (!allMembers.contains(fullName)) { +- fail('$fullName not found in ${coverageFile.path}'); +- } +- +- final String fileName =3D getCamelWords(request.method) +- .map((s) =3D> s.toLowerCase()) +- .join('_'); +- final String testName =3D +- path.join(domain.name, '${fileName}_test.dart'); +- final String testPath =3D +- path.join(pathPrefix, 'test', 'integration', testName); +- +- // Test that if checked, a test file exists; if not checked, = no such +- // file exists. +- expect(FileSystemEntity.isFileSync(testPath), +- coveredMembers.contains(fullName), +- reason: '$testName state incorrect'); +- }); +- } +- }); +- +- // notifications +- group('notification', () { +- for (Notification notification in domain.notifications) { +- String fullName =3D '${domain.name}.${notification.event}'; +- test(fullName, () { +- if (!allMembers.contains(fullName)) { +- fail('$fullName not found in ${coverageFile.path}'); +- } +- +- final String fileName =3D getCamelWords(notification.event) +- .map((s) =3D> s.toLowerCase()) +- .join('_'); +- final String testName =3D +- path.join(domain.name, '${fileName}_test.dart'); +- final String testPath =3D +- path.join(pathPrefix, 'test', 'integration', testName); +- +- // Test that if checked, a test file exists; if not checked, = no such +- // file exists. +- expect(FileSystemEntity.isFileSync(testPath), +- coveredMembers.contains(fullName), +- reason: '$testName state incorrect'); +- }); +- } +- }); +- }); +- } +- +- // validate no unexpected domains +- group('integration coverage', () { +- test('no unexpected domains', () { +- for (String domain in coveredDomains) { +- expect(api.domains.map((d) =3D> d.name), contains(domain)); +- } +- }); +- }); +-} +diff --git a/pkg/analysis_server/test/integration/diagnostic/get_diagnosti= cs_test.dart b/pkg/analysis_server/test/integration/diagnostic/get_diagnost= ics_test.dart +deleted file mode 100644 +index e8bf76e8a8c..00000000000 +--- a/pkg/analysis_server/test/integration/diagnostic/get_diagnostics_test= .dart ++++ /dev/null +@@ -1,30 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetDiagnosticsTest); +- }); +-} +- +-@reflectiveTest +-class GetDiagnosticsTest extends AbstractAnalysisServerIntegrationTest { +- test_getDiagnostics() async { +- standardAnalysisSetup(); +- +- DiagnosticGetDiagnosticsResult result =3D +- await sendDiagnosticGetDiagnostics(); +- +- // Do some lightweight validation of the returned data. +- expect(result.contexts, hasLength(1)); +- ContextData context =3D result.contexts.first; +- expect(context.name, isNotEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/diagnostic/get_server_po= rt_test.dart b/pkg/analysis_server/test/integration/diagnostic/get_server_p= ort_test.dart +deleted file mode 100644 +index b04384f11da..00000000000 +--- a/pkg/analysis_server/test/integration/diagnostic/get_server_port_test= .dart ++++ /dev/null +@@ -1,37 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetServerPortTest); +- }); +-} +- +-@reflectiveTest +-class GetServerPortTest extends AbstractAnalysisServerIntegrationTest { +- test_connect() async { +- standardAnalysisSetup(); +- +- DiagnosticGetServerPortResult result =3D await sendDiagnosticGetServe= rPort(); +- expect(result.port, isNotNull); +- expect(result.port, isNonZero); +- +- // Connect to the server and verify that it's serving the status page. +- HttpClient client =3D new HttpClient(); +- HttpClientRequest request =3D await client +- .getUrl(Uri.parse('http://localhost:${result.port}/status')); +- HttpClientResponse response =3D await request.close(); +- String responseBody =3D await UTF8.decodeStream(response); +- expect(responseBody, contains('Analysis Server')); +- } +-} +diff --git a/pkg/analysis_server/test/integration/diagnostic/test_all.dart= b/pkg/analysis_server/test/integration/diagnostic/test_all.dart +deleted file mode 100644 +index 4e45dea57d5..00000000000 +--- a/pkg/analysis_server/test/integration/diagnostic/test_all.dart ++++ /dev/null +@@ -1,15 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'get_diagnostics_test.dart' as get_diagnostics_test; +-import 'get_server_port_test.dart' as get_server_port_test; +- +-main() { +- defineReflectiveSuite(() { +- get_diagnostics_test.main(); +- get_server_port_test.main(); +- }, name: 'diagnostics'); +-} +diff --git a/pkg/analysis_server/test/integration/edit/format_test.dart b/= pkg/analysis_server/test/integration/edit/format_test.dart +deleted file mode 100644 +index 89061094201..00000000000 +--- a/pkg/analysis_server/test/integration/edit/format_test.dart ++++ /dev/null +@@ -1,80 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FormatTest); +- }); +-} +- +-@reflectiveTest +-class FormatTest extends AbstractAnalysisServerIntegrationTest { +- String formatTestSetup({bool withErrors: false}) { +- String pathname =3D sourcePath('test.dart'); +- +- if (withErrors) { +- String text =3D r''' +-class Class1 { +- int field +- void foo() { +- } +-} +-'''; +- writeFile(pathname, text); +- } else { +- String text =3D r''' +-class Class1 { +- int field; +- +- void foo() { +- } +- +- void bar() { +- } +-} +-'''; +- writeFile(pathname, text); +- } +- standardAnalysisSetup(); +- return pathname; +- } +- +- test_format() async { +- String pathname =3D formatTestSetup(); +- +- EditFormatResult result =3D await sendEditFormat(pathname, 0, 0); +- expect(result.edits, isNotEmpty); +- expect(result.selectionOffset, 0); +- expect(result.selectionLength, 0); +- } +- +- test_format_preserve_selection() async { +- String pathname =3D formatTestSetup(); +- +- // format with 'bar' selected +- int initialPosition =3D readFile(pathname).indexOf('bar()'); +- EditFormatResult result =3D +- await sendEditFormat(pathname, initialPosition, 'bar'.length); +- expect(result.edits, isNotEmpty); +- expect(result.selectionOffset, initialPosition - 3); +- expect(result.selectionLength, 'bar'.length); +- } +- +- test_format_with_errors() async { +- String pathname =3D formatTestSetup(withErrors: true); +- +- try { +- await sendEditFormat(pathname, 0, 0); +- fail('expected FORMAT_WITH_ERRORS'); +- } on ServerErrorMessage catch (message) { +- expect(message.error['code'], 'FORMAT_WITH_ERRORS'); +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/get_assists_test.da= rt b/pkg/analysis_server/test/integration/edit/get_assists_test.dart +deleted file mode 100644 +index 69e10f093ea..00000000000 +--- a/pkg/analysis_server/test/integration/edit/get_assists_test.dart ++++ /dev/null +@@ -1,50 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetAssistsTest); +- }); +-} +- +-@reflectiveTest +-class GetAssistsTest extends AbstractAnalysisServerIntegrationTest { +- test_has_assists() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:async'; +- +-Future f; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- +- // expect at least one assist (add show combinator to the dart:async = import) +- EditGetAssistsResult result =3D +- await sendEditGetAssists(pathname, text.indexOf('dart:async'), 0); +- expect(result.assists, isNotEmpty); +- +- // apply it and make sure that the code analyzing cleanly +- SourceChange change =3D result.assists.singleWhere((SourceChange chan= ge) =3D> +- change.message =3D=3D "Add explicit 'show' combinator"); +- expect(change.edits, hasLength(1)); +- expect(change.edits.first.edits, hasLength(1)); +- SourceEdit edit =3D change.edits.first.edits.first; +- text =3D text.replaceRange(edit.offset, edit.end, edit.replacement); +- writeFile(pathname, text); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/get_available_refac= torings_test.dart b/pkg/analysis_server/test/integration/edit/get_available= _refactorings_test.dart +deleted file mode 100644 +index 820b5862acd..00000000000 +--- a/pkg/analysis_server/test/integration/edit/get_available_refactorings= _test.dart ++++ /dev/null +@@ -1,37 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetAvailableRefactoringsTest); +- }); +-} +- +-@reflectiveTest +-class GetAvailableRefactoringsTest +- extends AbstractAnalysisServerIntegrationTest { +- test_has_refactorings() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-void foo() { } +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- +- // expect at least one refactoring +- EditGetAvailableRefactoringsResult result =3D +- await sendEditGetAvailableRefactorings( +- pathname, text.indexOf('foo('), 0); +- expect(result.kinds, isNotEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/get_fixes_test.dart= b/pkg/analysis_server/test/integration/edit/get_fixes_test.dart +deleted file mode 100644 +index a76680d76ed..00000000000 +--- a/pkg/analysis_server/test/integration/edit/get_fixes_test.dart ++++ /dev/null +@@ -1,60 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetFixesTest); +- }); +-} +- +-@reflectiveTest +-class GetFixesTest extends AbstractAnalysisServerIntegrationTest { +- test_has_fixes() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-Future f; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isNotEmpty); +- +- EditGetFixesResult result =3D +- await sendEditGetFixes(pathname, text.indexOf('Future f')); +- expect(result.fixes, hasLength(1)); +- +- // expect a suggestion to add the dart:async import +- AnalysisErrorFixes fix =3D result.fixes.first; +- expect(fix.error.code, 'undefined_class'); +- expect(fix.fixes, isNotEmpty); +- +- SourceChange change =3D fix.fixes.singleWhere( +- (SourceChange change) =3D> change.message.startsWith('Import ')); +- expect(change.edits, hasLength(1)); +- expect(change.edits.first.edits, hasLength(1)); +- } +- +- test_no_fixes() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:async'; +- +-Future f; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- EditGetFixesResult result =3D +- await sendEditGetFixes(pathname, text.indexOf('Future f')); +- expect(result.fixes, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/get_postfix_complet= ion_test.dart b/pkg/analysis_server/test/integration/edit/get_postfix_compl= etion_test.dart +deleted file mode 100644 +index b4b3cd481c9..00000000000 +--- a/pkg/analysis_server/test/integration/edit/get_postfix_completion_tes= t.dart ++++ /dev/null +@@ -1,52 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetPostfixCompletionTest); +- }); +-} +- +-@reflectiveTest +-class GetPostfixCompletionTest extends AbstractAnalysisServerIntegrationT= est { +- test_postfix_completion() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-void bar() { +- foo();.tryon +-} +-void foo() { } +-'''; +- int loc =3D text.indexOf('.tryon'); +- text =3D text.replaceAll('.tryon', ''); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- +- // expect a postfix completion result +- EditGetPostfixCompletionResult result =3D +- await sendEditGetPostfixCompletion(pathname, '.tryon', loc); +- expect(result.change.edits, isNotEmpty); +- +- // apply the edit, expect that the new code has no errors +- SourceChange change =3D result.change; +- expect(change.edits.first.edits, isNotEmpty); +- for (SourceEdit edit in change.edits.first.edits) { +- text =3D text.replaceRange(edit.offset, edit.end, edit.replacement); +- } +- await sendAnalysisUpdateContent({pathname: new AddContentOverlay(text= )}); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/get_refactoring_tes= t.dart b/pkg/analysis_server/test/integration/edit/get_refactoring_test.dart +deleted file mode 100644 +index c3e5553acf8..00000000000 +--- a/pkg/analysis_server/test/integration/edit/get_refactoring_test.dart ++++ /dev/null +@@ -1,66 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetRefactoringTest); +- }); +-} +- +-@reflectiveTest +-class GetRefactoringTest extends AbstractAnalysisServerIntegrationTest { +- test_rename() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-void foo() { } +- +-void bar() { +- foo(); +- foo(); +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- +- // expect no edits if no rename options specified +- EditGetRefactoringResult result =3D await sendEditGetRefactoring( +- RefactoringKind.RENAME, pathname, text.indexOf('foo('), 0, false); +- expect(result.initialProblems, isEmpty); +- expect(result.optionsProblems, isEmpty); +- expect(result.finalProblems, isEmpty); +- expect(result.potentialEdits, isNull); +- expect(result.change, isNull); +- +- // expect a valid rename refactoring +- result =3D await sendEditGetRefactoring( +- RefactoringKind.RENAME, pathname, text.indexOf('foo('), 0, false, +- options: new RenameOptions('baz')); +- expect(result.initialProblems, isEmpty); +- expect(result.optionsProblems, isEmpty); +- expect(result.finalProblems, isEmpty); +- expect(result.potentialEdits, isNull); +- expect(result.change.edits, isNotEmpty); +- +- // apply the refactoring, expect that the new code has no errors +- SourceChange change =3D result.change; +- expect(change.edits.first.edits, isNotEmpty); +- for (SourceEdit edit in change.edits.first.edits) { +- text =3D text.replaceRange(edit.offset, edit.end, edit.replacement); +- } +- await sendAnalysisUpdateContent({pathname: new AddContentOverlay(text= )}); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/get_statement_compl= etion_test.dart b/pkg/analysis_server/test/integration/edit/get_statement_c= ompletion_test.dart +deleted file mode 100644 +index 1adece605ac..00000000000 +--- a/pkg/analysis_server/test/integration/edit/get_statement_completion_t= est.dart ++++ /dev/null +@@ -1,47 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetStatementCompletionTest); +- }); +-} +- +-@reflectiveTest +-class GetStatementCompletionTest extends AbstractAnalysisServerIntegratio= nTest { +- test_statement_completion() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-void bar() { foo() } // missing semi-colon +-void foo() { }'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isNotEmpty); +- +- // expect a statement completion result +- EditGetStatementCompletionResult result =3D +- await sendEditGetStatementCompletion(pathname, text.indexOf('foo(= ')); +- expect(result.change.edits, isNotEmpty); +- +- // apply the edit, expect that the new code has no errors +- SourceChange change =3D result.change; +- expect(change.edits.first.edits, isNotEmpty); +- for (SourceEdit edit in change.edits.first.edits) { +- text =3D text.replaceRange(edit.offset, edit.end, edit.replacement); +- } +- await sendAnalysisUpdateContent({pathname: new AddContentOverlay(text= )}); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/import_elements_tes= t.dart b/pkg/analysis_server/test/integration/edit/import_elements_test.dart +deleted file mode 100644 +index b22fa39e121..00000000000 +--- a/pkg/analysis_server/test/integration/edit/import_elements_test.dart ++++ /dev/null +@@ -1,139 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer/src/dart/sdk/sdk.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisGetImportElementsIntegrationTest); +- }); +-} +- +-@reflectiveTest +-class AnalysisGetImportElementsIntegrationTest +- extends AbstractAnalysisServerIntegrationTest { +- /** +- * Pathname of the file containing Dart code. +- */ +- String pathname; +- +- /** +- * Check that an edit.importElements request with the given list of [el= ements] +- * produces the [expected] list of edits. +- */ +- checkEdits(List elements, List expected, +- {String expectedFile}) async { +- bool equals(SourceEdit actualEdit, SourceEdit expectedEdit) { +- return actualEdit.offset =3D=3D expectedEdit.offset && +- actualEdit.length =3D=3D expectedEdit.length && +- actualEdit.replacement =3D=3D expectedEdit.replacement; +- } +- +- int find(List actual, SourceEdit expectedEdit) { +- for (int i =3D 0; i < actual.length; i++) { +- SourceEdit actualEdit =3D actual[i]; +- if (equals(actualEdit, expectedEdit)) { +- return i; +- } +- } +- return -1; +- } +- +- EditImportElementsResult result =3D +- await sendEditImportElements(pathname, elements); +- +- SourceFileEdit edit =3D result.edit; +- expect(edit, isNotNull); +- if (expectedFile =3D=3D null) { +- expect(edit.file, pathname); +- } else { +- expect(edit.file, expectedFile); +- } +- List actual =3D edit.edits; +- expect(actual, hasLength(expected.length)); +- for (SourceEdit expectedEdit in expected) { +- int index =3D find(actual, expectedEdit); +- if (index < 0) { +- fail('Expected $expectedEdit; not found'); +- } +- actual.removeAt(index); +- } +- } +- +- /** +- * Check that an edit.importElements request with the given list of [el= ements] +- * produces no edits. +- */ +- Future checkNoEdits(List elements) async { +- EditImportElementsResult result =3D +- await sendEditImportElements(pathname, []); +- +- SourceFileEdit edit =3D result.edit; +- expect(edit, isNotNull); +- expect(edit.edits, hasLength(0)); +- } +- +- Future setUp() async { +- await super.setUp(); +- pathname =3D sourcePath('test.dart'); +- } +- +- test_importElements_definingUnit() async { +- writeFile(pathname, 'main() {}'); +- standardAnalysisSetup(); +- await analysisFinished; +- PhysicalResourceProvider provider =3D PhysicalResourceProvider.INSTAN= CE; +- String sdkPath =3D FolderBasedDartSdk.defaultSdkDirectory(provider).p= ath; +- String mathPath =3D +- provider.pathContext.join(sdkPath, 'lib', 'math', 'math.dart'); +- +- await checkEdits([ +- new ImportedElements(mathPath, '', ['Random']) +- ], [ +- new SourceEdit(0, 0, "import 'dart:math';\n\n") +- ]); +- } +- +- test_importElements_noEdits() async { +- writeFile(pathname, ''); +- standardAnalysisSetup(); +- await analysisFinished; +- +- await checkNoEdits([]); +- } +- +- test_importElements_part() async { +- String libName =3D sourcePath('lib.dart'); +- writeFile(libName, ''' +-part 'test.dart'; +-main() {} +-'''); +- writeFile(pathname, ''' +-part of 'lib.dart'; +- +-class C {} +-'''); +- standardAnalysisSetup(); +- await analysisFinished; +- PhysicalResourceProvider provider =3D PhysicalResourceProvider.INSTAN= CE; +- String sdkPath =3D FolderBasedDartSdk.defaultSdkDirectory(provider).p= ath; +- String mathPath =3D +- provider.pathContext.join(sdkPath, 'lib', 'math', 'math.dart'); +- +- await checkEdits([ +- new ImportedElements(mathPath, '', ['Random']) +- ], [ +- new SourceEdit(0, 0, "import 'dart:math';\n\n") +- ], expectedFile: libName); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/is_postfix_completi= on_applicable_test.dart b/pkg/analysis_server/test/integration/edit/is_post= fix_completion_applicable_test.dart +deleted file mode 100644 +index be1ff11aa3f..00000000000 +--- a/pkg/analysis_server/test/integration/edit/is_postfix_completion_appl= icable_test.dart ++++ /dev/null +@@ -1,41 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(IsPostfixCompletionApplicableTest); +- }); +-} +- +-@reflectiveTest +-class IsPostfixCompletionApplicableTest +- extends AbstractAnalysisServerIntegrationTest { +- test_is_postfix_completion_applicable() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-void bar() { +- foo();.tryon +-} +-void foo() { } +-'''; +- int loc =3D text.indexOf('.tryon'); +- text =3D text.replaceAll('.tryon', ''); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- expect(currentAnalysisErrors[pathname], isEmpty); +- +- // expect a postfix completion applicable result +- EditIsPostfixCompletionApplicableResult result =3D +- await sendEditIsPostfixCompletionApplicable(pathname, '.tryon', l= oc); +- expect(result.value, isTrue); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/list_postfix_comple= tion_templates_test.dart b/pkg/analysis_server/test/integration/edit/list_p= ostfix_completion_templates_test.dart +deleted file mode 100644 +index f248e06aef0..00000000000 +--- a/pkg/analysis_server/test/integration/edit/list_postfix_completion_te= mplates_test.dart ++++ /dev/null +@@ -1,41 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ListPostfixCompletionTemplatesTest); +- }); +-} +- +-@reflectiveTest +-class ListPostfixCompletionTemplatesTest +- extends AbstractAnalysisServerIntegrationTest { +- test_list_postfix_completion_templates() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-void bar() { +- foo();.tryon +-} +-void foo() { } +-'''; +- text =3D text.replaceAll('.tryon', ''); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- // expect a postfix template list result +- EditListPostfixCompletionTemplatesResult result =3D +- await sendEditListPostfixCompletionTemplates(); +- expect(result.templates, isNotNull); +- expect(result.templates.length, greaterThan(15)); +- expect(result.templates[0].runtimeType, PostfixTemplateDescriptor); +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/organize_directives= _test.dart b/pkg/analysis_server/test/integration/edit/organize_directives_= test.dart +deleted file mode 100644 +index 0e372f43f72..00000000000 +--- a/pkg/analysis_server/test/integration/edit/organize_directives_test.d= art ++++ /dev/null +@@ -1,76 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OrganizeDirectivesTest); +- }); +-} +- +-@reflectiveTest +-class OrganizeDirectivesTest extends AbstractAnalysisServerIntegrationTes= t { +- test_organize_directives() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:math'; +-import 'dart:async'; +- +-Future foo; +-int minified(int x, int y) =3D> min(x, y); +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- EditOrganizeDirectivesResult result =3D +- await sendEditOrganizeDirectives(pathname); +- SourceFileEdit edit =3D result.edit; +- expect(edit.edits, hasLength(1)); +- expect(edit.edits.first.replacement, +- "import 'dart:async';\nimport 'dart:math"); +- } +- +- test_organize_directives_no_changes() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:async'; +-import 'dart:math'; +- +-Future foo; +-int minified(int x, int y) =3D> min(x, y); +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- EditOrganizeDirectivesResult result =3D +- await sendEditOrganizeDirectives(pathname); +- SourceFileEdit edit =3D result.edit; +- expect(edit.edits, isEmpty); +- } +- +- test_organize_directives_with_errors() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-import 'dart:async' +-import 'dart:math'; +- +-Future foo; +-int minified(int x, int y) =3D> min(x, y); +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- try { +- await sendEditOrganizeDirectives(pathname); +- } on ServerErrorMessage catch (message) { +- expect(message.error['code'], 'ORGANIZE_DIRECTIVES_ERROR'); +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/sort_members_test.d= art b/pkg/analysis_server/test/integration/edit/sort_members_test.dart +deleted file mode 100644 +index 3ff78a758be..00000000000 +--- a/pkg/analysis_server/test/integration/edit/sort_members_test.dart ++++ /dev/null +@@ -1,64 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SortMembersTest); +- }); +-} +- +-@reflectiveTest +-class SortMembersTest extends AbstractAnalysisServerIntegrationTest { +- test_sort() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-int foo; +-int bar; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- EditSortMembersResult result =3D await sendEditSortMembers(pathname); +- SourceFileEdit edit =3D result.edit; +- expect(edit.edits, hasLength(1)); +- expect(edit.edits.first.replacement, "bar;\nint foo"); +- } +- +- test_sort_no_changes() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-int bar; +-int foo; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- EditSortMembersResult result =3D await sendEditSortMembers(pathname); +- SourceFileEdit edit =3D result.edit; +- expect(edit.edits, isEmpty); +- } +- +- test_sort_with_errors() async { +- String pathname =3D sourcePath('test.dart'); +- String text =3D r''' +-int foo +-int bar; +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- try { +- await sendEditSortMembers(pathname); +- } on ServerErrorMessage catch (message) { +- expect(message.error['code'], 'SORT_MEMBERS_PARSE_ERRORS'); +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/edit/test_all.dart b/pkg= /analysis_server/test/integration/edit/test_all.dart +deleted file mode 100644 +index 81aa1219c35..00000000000 +--- a/pkg/analysis_server/test/integration/edit/test_all.dart ++++ /dev/null +@@ -1,38 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'format_test.dart' as format_test; +-import 'get_assists_test.dart' as get_assists_test; +-import 'get_available_refactorings_test.dart' +- as get_available_refactorings_test; +-import 'get_fixes_test.dart' as get_fixes_test; +-import 'get_postfix_completion_test.dart' as get_postfix_completion_test; +-import 'get_refactoring_test.dart' as get_refactoring_test; +-import 'get_statement_completion_test.dart' as get_statement_completion_t= est; +-import 'import_elements_test.dart' as import_elements_test; +-import 'is_postfix_completion_applicable_test.dart' +- as is_postfix_completion_applicable_test; +-import 'list_postfix_completion_templates_test.dart' +- as list_postfix_completion_templates_test; +-import 'organize_directives_test.dart' as organize_directives_test; +-import 'sort_members_test.dart' as sort_members_test; +- +-main() { +- defineReflectiveSuite(() { +- format_test.main(); +- get_assists_test.main(); +- get_available_refactorings_test.main(); +- get_fixes_test.main(); +- get_refactoring_test.main(); +- get_postfix_completion_test.main(); +- get_statement_completion_test.main(); +- import_elements_test.main(); +- is_postfix_completion_applicable_test.main(); +- list_postfix_completion_templates_test.main(); +- organize_directives_test.main(); +- sort_members_test.main(); +- }, name: 'edit'); +-} +diff --git a/pkg/analysis_server/test/integration/execution/create_context= _test.dart b/pkg/analysis_server/test/integration/execution/create_context_= test.dart +deleted file mode 100644 +index 6564810a95c..00000000000 +--- a/pkg/analysis_server/test/integration/execution/create_context_test.d= art ++++ /dev/null +@@ -1,24 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(CreateContextTest); +- }); +-} +- +-@reflectiveTest +-class CreateContextTest extends AbstractAnalysisServerIntegrationTest { +- test_create() async { +- standardAnalysisSetup(); +- String contextId =3D +- (await sendExecutionCreateContext(sourceDirectory.path)).id; +- expect(contextId, isNotNull); +- } +-} +diff --git a/pkg/analysis_server/test/integration/execution/delete_context= _test.dart b/pkg/analysis_server/test/integration/execution/delete_context_= test.dart +deleted file mode 100644 +index c807fa5b4e0..00000000000 +--- a/pkg/analysis_server/test/integration/execution/delete_context_test.d= art ++++ /dev/null +@@ -1,43 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(DeleteContextTest); +- }); +-} +- +-@reflectiveTest +-class DeleteContextTest extends AbstractAnalysisServerIntegrationTest { +- test_delete() async { +- String pathname =3D sourcePath('lib/main.dart'); +- writeFile(pathname, '// dummy'); +- writeFile(sourcePath('.packages'), 'foo:lib/'); +- standardAnalysisSetup(); +- +- String contextId =3D +- (await sendExecutionCreateContext(sourceDirectory.path)).id; +- +- ExecutionMapUriResult result =3D +- await sendExecutionMapUri(contextId, uri: 'package:foo/main.dart'= ); +- expect(result.file, pathname); +- +- expect(await sendExecutionDeleteContext(contextId), isNull); +- +- // After the delete, expect this to fail. +- try { +- result =3D +- await sendExecutionMapUri(contextId, uri: 'package:foo/main.dar= t'); +- fail('expected exception after context delete'); +- } on ServerErrorMessage catch (message) { +- expect(message.error['code'], 'INVALID_PARAMETER'); +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/execution/map_uri_test.d= art b/pkg/analysis_server/test/integration/execution/map_uri_test.dart +deleted file mode 100644 +index f5abbc0106c..00000000000 +--- a/pkg/analysis_server/test/integration/execution/map_uri_test.dart ++++ /dev/null +@@ -1,40 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(MapUriTest); +- }); +-} +- +-@reflectiveTest +-class MapUriTest extends AbstractAnalysisServerIntegrationTest { +- test_mapUri() async { +- String pathname =3D sourcePath('lib/main.dart'); +- writeFile(pathname, '// dummy'); +- writeFile(sourcePath('.packages'), 'foo:lib/'); +- standardAnalysisSetup(); +- +- String contextId =3D +- (await sendExecutionCreateContext(sourceDirectory.path))?.id; +- +- { +- ExecutionMapUriResult result =3D +- await sendExecutionMapUri(contextId, uri: 'package:foo/main.dar= t'); +- expect(result.file, pathname); +- } +- +- { +- ExecutionMapUriResult result =3D +- await sendExecutionMapUri(contextId, file: pathname); +- expect(result.uri, 'package:foo/main.dart'); +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/execution/set_subscripti= ons_test.dart b/pkg/analysis_server/test/integration/execution/set_subscrip= tions_test.dart +deleted file mode 100644 +index 441093b35f3..00000000000 +--- a/pkg/analysis_server/test/integration/execution/set_subscriptions_tes= t.dart ++++ /dev/null +@@ -1,23 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetSubscriptionsTest); +- }); +-} +- +-@reflectiveTest +-class SetSubscriptionsTest extends AbstractAnalysisServerIntegrationTest { +- test_subscribe() async { +- standardAnalysisSetup(); +- // ignore: deprecated_member_use +- await sendExecutionSetSubscriptions([ExecutionService.LAUNCH_DATA]); +- } +-} +diff --git a/pkg/analysis_server/test/integration/execution/test_all.dart = b/pkg/analysis_server/test/integration/execution/test_all.dart +deleted file mode 100644 +index 6da630db1a0..00000000000 +--- a/pkg/analysis_server/test/integration/execution/test_all.dart ++++ /dev/null +@@ -1,19 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'create_context_test.dart' as create_context_test; +-import 'delete_context_test.dart' as delete_context_test; +-import 'map_uri_test.dart' as map_uri_test; +-import 'set_subscriptions_test.dart' as set_subscription_test; +- +-main() { +- defineReflectiveSuite(() { +- create_context_test.main(); +- delete_context_test.main(); +- map_uri_test.main(); +- set_subscription_test.main(); +- }, name: 'execution'); +-} +diff --git a/pkg/analysis_server/test/integration/kythe/get_kythe_entries_= test.dart b/pkg/analysis_server/test/integration/kythe/get_kythe_entries_te= st.dart +deleted file mode 100644 +index ccd3c49572c..00000000000 +--- a/pkg/analysis_server/test/integration/kythe/get_kythe_entries_test.da= rt ++++ /dev/null +@@ -1,39 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetKytheEntriesTest); +- }); +-} +- +-@reflectiveTest +-class GetKytheEntriesTest extends AbstractAnalysisServerIntegrationTest { +- test_getKytheEntries() async { +- writeFile(sourcePath('WORKSPACE'), ''); +- String pathname =3D sourcePath('pkg/test.dart'); +- String text =3D r''' +-class Foo {} +- +-class Bar { +- Foo foo; +-} +-'''; +- writeFile(pathname, text); +- standardAnalysisSetup(); +- +- await analysisFinished; +- +- KytheGetKytheEntriesResult result =3D +- await sendKytheGetKytheEntries(pathname); +- expect(result.entries, isNotEmpty); +- expect(result.files, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/integration/kythe/test_all.dart b/pk= g/analysis_server/test/integration/kythe/test_all.dart +deleted file mode 100644 +index d65cff4a1df..00000000000 +--- a/pkg/analysis_server/test/integration/kythe/test_all.dart ++++ /dev/null +@@ -1,13 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'get_kythe_entries_test.dart' as get_kythe_entries_test; +- +-main() { +- defineReflectiveSuite(() { +- get_kythe_entries_test.main(); +- }, name: 'kythe'); +-} +diff --git a/pkg/analysis_server/test/integration/search/find_element_refe= rences_test.dart b/pkg/analysis_server/test/integration/search/find_element= _references_test.dart +deleted file mode 100644 +index 10bfbfa6af1..00000000000 +--- a/pkg/analysis_server/test/integration/search/find_element_references_= test.dart ++++ /dev/null +@@ -1,72 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FindElementReferencesTest); +- }); +-} +- +-@reflectiveTest +-class FindElementReferencesTest extends AbstractAnalysisServerIntegration= Test { +- String pathname; +- +- test_badTarget() async { +- String text =3D r''' +-main() { +- if /* target */ (true) { +- print('Hello'); +- } +-} +-'''; +- +- pathname =3D sourcePath('foo.dart'); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- List results =3D await _findElementReferences(text); +- expect(results, isNull); +- } +- +- test_findReferences() async { +- String text =3D r''' +-main() { +- print /* target */ ('Hello'); +-} +-'''; +- +- pathname =3D sourcePath('foo.dart'); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- List results =3D await _findElementReferences(text); +- expect(results, hasLength(1)); +- SearchResult result =3D results.first; +- expect(result.location.file, pathname); +- expect(result.isPotential, isFalse); +- expect(result.kind.name, SearchResultKind.INVOCATION.name); +- expect(result.path.first.name, 'main'); +- } +- +- Future> _findElementReferences(String text) async { +- int offset =3D text.indexOf(' /* target */') - 1; +- SearchFindElementReferencesResult result =3D +- await sendSearchFindElementReferences(pathname, offset, false); +- if (result.id =3D=3D null) return null; +- SearchResultsParams searchParams =3D await onSearchResults.first; +- expect(searchParams.id, result.id); +- expect(searchParams.isLast, isTrue); +- return searchParams.results; +- } +-} +diff --git a/pkg/analysis_server/test/integration/search/find_member_decla= rations_test.dart b/pkg/analysis_server/test/integration/search/find_member= _declarations_test.dart +deleted file mode 100644 +index 81148c09ccc..00000000000 +--- a/pkg/analysis_server/test/integration/search/find_member_declarations= _test.dart ++++ /dev/null +@@ -1,51 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FindMemberDeclarationsTest); +- }); +-} +- +-@reflectiveTest +-class FindMemberDeclarationsTest extends AbstractAnalysisServerIntegratio= nTest { +- String pathname; +- +- test_findMemberDeclarations() async { +- String text =3D r''' +-String qux() =3D> 'qux'; +- +-class Foo { +- void bar() { }; +- int baz() =3D> 0; +-} +-'''; +- +- pathname =3D sourcePath('foo.dart'); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- SearchFindMemberDeclarationsResult declarationsResult =3D +- await sendSearchFindMemberDeclarations('bar'); +- expect(declarationsResult.id, isNotNull); +- +- SearchResultsParams searchParams =3D await onSearchResults.first; +- expect(searchParams.id, declarationsResult.id); +- expect(searchParams.isLast, isTrue); +- expect(searchParams.results, isNotEmpty); +- +- SearchResult result =3D searchParams.results.first; +- expect(result.location.file, pathname); +- expect(result.isPotential, isFalse); +- expect(result.kind.name, SearchResultKind.DECLARATION.name); +- expect(result.path.first.name, 'bar'); +- } +-} +diff --git a/pkg/analysis_server/test/integration/search/find_member_refer= ences_test.dart b/pkg/analysis_server/test/integration/search/find_member_r= eferences_test.dart +deleted file mode 100644 +index 36fccbc35e4..00000000000 +--- a/pkg/analysis_server/test/integration/search/find_member_references_t= est.dart ++++ /dev/null +@@ -1,52 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FindMemberReferencesTest); +- }); +-} +- +-@reflectiveTest +-class FindMemberReferencesTest extends AbstractAnalysisServerIntegrationT= est { +- String pathname; +- +- test_findMemberReferences() async { +- String text =3D r''' +-String qux() =3D> 'qux'; +- +-class Foo { +- //int bar() =3D> 1; +- baz() =3D> bar() * bar(); +-} +-'''; +- +- pathname =3D sourcePath('foo.dart'); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- SearchFindMemberReferencesResult referencesResult =3D +- await sendSearchFindMemberReferences('bar'); +- expect(referencesResult.id, isNotNull); +- +- SearchResultsParams searchParams =3D await onSearchResults.first; +- expect(searchParams.id, referencesResult.id); +- expect(searchParams.isLast, isTrue); +- expect(searchParams.results, isNotEmpty); +- expect(searchParams.results, hasLength(2)); +- +- SearchResult result =3D searchParams.results.first; +- expect(result.location.file, pathname); +- expect(result.isPotential, isTrue); +- expect(result.kind.name, SearchResultKind.INVOCATION.name); +- expect(result.path.first.name, 'baz'); +- } +-} +diff --git a/pkg/analysis_server/test/integration/search/find_top_level_de= clarations_test.dart b/pkg/analysis_server/test/integration/search/find_top= _level_declarations_test.dart +deleted file mode 100644 +index 66352f892d2..00000000000 +--- a/pkg/analysis_server/test/integration/search/find_top_level_declarati= ons_test.dart ++++ /dev/null +@@ -1,56 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FindTopLevelDeclarationsTest); +- }); +-} +- +-@reflectiveTest +-class FindTopLevelDeclarationsTest +- extends AbstractAnalysisServerIntegrationTest { +- String pathname; +- +- test_findTopLevelDeclarations() async { +- String text =3D r''' +-String qux() =3D> 'qux'; +- +-class Foo { +- void bar() { }; +- int baz() =3D> 0; +-} +-'''; +- +- pathname =3D sourcePath('foo.dart'); +- writeFile(pathname, text); +- standardAnalysisSetup(); +- await analysisFinished; +- +- SearchFindTopLevelDeclarationsResult declarationsResult =3D +- await sendSearchFindTopLevelDeclarations(r'qu.*'); +- expect(declarationsResult.id, isNotNull); +- +- SearchResultsParams searchParams =3D await onSearchResults.first; +- expect(searchParams.id, declarationsResult.id); +- expect(searchParams.isLast, isTrue); +- expect(searchParams.results, isNotEmpty); +- +- for (SearchResult result in searchParams.results) { +- if (result.location.file =3D=3D pathname) { +- expect(result.isPotential, isFalse); +- expect(result.kind.name, SearchResultKind.DECLARATION.name); +- expect(result.path.first.name, 'qux'); +- return; +- } +- } +- fail('No result for $pathname'); +- } +-} +diff --git a/pkg/analysis_server/test/integration/search/get_type_hierarch= y_test.dart b/pkg/analysis_server/test/integration/search/get_type_hierarch= y_test.dart +deleted file mode 100644 +index 0919aa22957..00000000000 +--- a/pkg/analysis_server/test/integration/search/get_type_hierarchy_test.= dart ++++ /dev/null +@@ -1,275 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetTypeHierarchyTest); +- }); +-} +- +-@reflectiveTest +-class GetTypeHierarchyTest extends AbstractAnalysisServerIntegrationTest { +- /** +- * Pathname of the main file to run tests in. +- */ +- String pathname; +- +- Future getTypeHierarchy_badTarget() { +- String text =3D r''' +-main() { +- if /* target */ (true) { +- print('Hello'); +- } +-} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results, isNull); +- }); +- } +- +- Future getTypeHierarchy_classElement() { +- String text =3D r''' +-class Base {} +-class Pivot /* target */ extends Base {} +-class Derived extends Pivot {} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(4)); +- expect(results.nameToIndex['Pivot'], equals(0)); +- void checkElement(String name) { +- // We don't check the full element data structure; just enough to= make +- // sure that we're pointing to the correct element. +- Element element =3D results.items[results.nameToIndex[name]].clas= sElement; +- expect(element.kind, equals(ElementKind.CLASS)); +- expect(element.name, equals(name)); +- if (name !=3D 'Object') { +- expect(element.location.offset, +- equals(text.indexOf('class $name') + 'class '.length)); +- } +- } +- +- checkElement('Object'); +- checkElement('Base'); +- checkElement('Pivot'); +- checkElement('Derived'); +- }); +- } +- +- Future getTypeHierarchy_displayName() { +- String text =3D r''' +-class Base {} +-class Pivot /* target */ extends Base {} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(3)); +- expect(results.getItem('Object').displayName, isNull); +- expect(results.getItem('Base').displayName, equals('Base')); +- expect(results.getItem('Pivot').displayName, isNull); +- }); +- } +- +- Future getTypeHierarchy_functionTarget() { +- String text =3D r''' +-main /* target */ () { +-} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results, isNull); +- }); +- } +- +- Future getTypeHierarchy_interfaces() { +- String text =3D r''' +-class Interface1 {} +-class Interface2 {} +-class Pivot /* target */ implements Interface1, Interface2 {} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(4)); +- expect(results.pivot.interfaces, hasLength(2)); +- expect(results.pivot.interfaces, +- contains(results.nameToIndex['Interface1'])); +- expect(results.pivot.interfaces, +- contains(results.nameToIndex['Interface2'])); +- expect(results.getItem('Object').interfaces, isEmpty); +- expect(results.getItem('Interface1').interfaces, isEmpty); +- expect(results.getItem('Interface2').interfaces, isEmpty); +- }); +- } +- +- Future getTypeHierarchy_memberElement() { +- String text =3D r''' +-class Base1 { +- void foo /* base1 */ (); +-} +-class Base2 extends Base1 {} +-class Pivot extends Base2 { +- void foo /* target */ (); +-} +-class Derived1 extends Pivot {} +-class Derived2 extends Derived1 { +- void foo /* derived2 */ (); +-}'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(6)); +- expect(results.getItem('Object').memberElement, isNull); +- expect(results.getItem('Base1').memberElement.location.offset, +- equals(text.indexOf('foo /* base1 */'))); +- expect(results.getItem('Base2').memberElement, isNull); +- expect(results.getItem('Pivot').memberElement.location.offset, +- equals(text.indexOf('foo /* target */'))); +- expect(results.getItem('Derived1').memberElement, isNull); +- expect(results.getItem('Derived2').memberElement.location.offset, +- equals(text.indexOf('foo /* derived2 */'))); +- }); +- } +- +- Future getTypeHierarchy_mixins() { +- String text =3D r''' +-class Base {} +-class Mixin1 {} +-class Mixin2 {} +-class Pivot /* target */ extends Base with Mixin1, Mixin2 {} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(5)); +- expect(results.pivot.mixins, hasLength(2)); +- expect(results.pivot.mixins, contains(results.nameToIndex['Mixin1']= )); +- expect(results.pivot.mixins, contains(results.nameToIndex['Mixin2']= )); +- expect(results.getItem('Object').mixins, isEmpty); +- expect(results.getItem('Base').mixins, isEmpty); +- expect(results.getItem('Mixin1').mixins, isEmpty); +- expect(results.getItem('Mixin2').mixins, isEmpty); +- }); +- } +- +- Future getTypeHierarchy_subclasses() { +- String text =3D r''' +-class Base {} +-class Pivot /* target */ extends Base {} +-class Sub1 extends Pivot {} +-class Sub2 extends Pivot {} +-class Sub2a extends Sub2 {} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(6)); +- expect(results.pivot.subclasses, hasLength(2)); +- expect(results.pivot.subclasses, contains(results.nameToIndex['Sub1= '])); +- expect(results.pivot.subclasses, contains(results.nameToIndex['Sub2= '])); +- expect(results.getItem('Object').subclasses, isEmpty); +- expect(results.getItem('Base').subclasses, isEmpty); +- expect(results.getItem('Sub1').subclasses, isEmpty); +- expect(results.getItem('Sub2').subclasses, +- equals([results.nameToIndex['Sub2a']])); +- expect(results.getItem('Sub2a').subclasses, isEmpty); +- }); +- } +- +- Future getTypeHierarchy_superclass() { +- String text =3D r''' +-class Base1 {} +-class Base2 extends Base1 {} +-class Pivot /* target */ extends Base2 {} +-'''; +- return typeHierarchyTest(text).then((HierarchyResults results) { +- expect(results.items, hasLength(4)); +- expect(results.getItem('Object').superclass, isNull); +- expect(results.getItem('Base1').superclass, +- equals(results.nameToIndex['Object'])); +- expect(results.getItem('Base2').superclass, +- equals(results.nameToIndex['Base1'])); +- expect(results.getItem('Pivot').superclass, +- equals(results.nameToIndex['Base2'])); +- }); +- } +- +- test_getTypeHierarchy() { +- pathname =3D sourcePath('test.dart'); +- // Write a dummy file which will be overridden by tests using +- // [sendAnalysisUpdateContent]. +- writeFile(pathname, '// dummy'); +- standardAnalysisSetup(); +- +- // Run all the getTypeHierarchy tests at once so that the server can = take +- // advantage of incremental analysis and the test doesn't time out. +- List tests =3D [ +- getTypeHierarchy_classElement, +- getTypeHierarchy_displayName, +- getTypeHierarchy_memberElement, +- getTypeHierarchy_superclass, +- getTypeHierarchy_interfaces, +- getTypeHierarchy_mixins, +- getTypeHierarchy_subclasses, +- getTypeHierarchy_badTarget, +- getTypeHierarchy_functionTarget +- ]; +- return Future.forEach(tests, (test) =3D> test()); +- } +- +- Future typeHierarchyTest(String text) async { +- int offset =3D text.indexOf(' /* target */') - 1; +- sendAnalysisUpdateContent({pathname: new AddContentOverlay(text)}); +- await analysisFinished; +- var result =3D await sendSearchGetTypeHierarchy(pathname, offset); +- if (result.hierarchyItems =3D=3D null) { +- return null; +- } else { +- return new HierarchyResults(result.hierarchyItems); +- } +- } +-} +- +-/** +- * Results of a getTypeHierarchy request, processed for easier testing. +- */ +-class HierarchyResults { +- /** +- * The list of hierarchy items from the result. +- */ +- List items; +- +- /** +- * The first hierarchy item from the result, which represents the pivot +- * class. +- */ +- TypeHierarchyItem pivot; +- +- /** +- * A map from element name to item index. +- */ +- Map nameToIndex; +- +- /** +- * Create a [HierarchyResults] object based on the result from a +- * getTypeHierarchy request. +- */ +- HierarchyResults(this.items) { +- pivot =3D items[0]; +- nameToIndex =3D {}; +- for (int i =3D 0; i < items.length; i++) { +- nameToIndex[items[i].classElement.name] =3D i; +- } +- } +- +- /** +- * Get an item by class name. +- */ +- TypeHierarchyItem getItem(String name) { +- if (nameToIndex.containsKey(name)) { +- return items[nameToIndex[name]]; +- } else { +- fail('Class $name not found in hierarchy results'); +- return null; +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/search/test_all.dart b/p= kg/analysis_server/test/integration/search/test_all.dart +deleted file mode 100644 +index bf7e7a4a296..00000000000 +--- a/pkg/analysis_server/test/integration/search/test_all.dart ++++ /dev/null +@@ -1,25 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'find_element_references_test.dart' as find_element_references_tes= t; +-import 'find_member_declarations_test.dart' as find_member_declarations_t= est; +-import 'find_member_references_test.dart' as find_member_references_test; +-import 'find_top_level_declarations_test.dart' +- as find_top_level_declarations_test; +-import 'get_type_hierarchy_test.dart' as get_type_hierarchy_test; +- +-/** +- * Utility for manually running all integration tests. +- */ +-main() { +- defineReflectiveSuite(() { +- find_element_references_test.main(); +- find_member_declarations_test.main(); +- find_member_references_test.main(); +- find_top_level_declarations_test.main(); +- get_type_hierarchy_test.main(); +- }, name: 'search'); +-} +diff --git a/pkg/analysis_server/test/integration/server/get_version_test.= dart b/pkg/analysis_server/test/integration/server/get_version_test.dart +deleted file mode 100644 +index c3dc407c553..00000000000 +--- a/pkg/analysis_server/test/integration/server/get_version_test.dart ++++ /dev/null +@@ -1,20 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetVersionTest); +- }); +-} +- +-@reflectiveTest +-class GetVersionTest extends AbstractAnalysisServerIntegrationTest { +- test_getVersion() { +- return sendServerGetVersion(); +- } +-} +diff --git a/pkg/analysis_server/test/integration/server/set_subscriptions= _invalid_service_test.dart b/pkg/analysis_server/test/integration/server/se= t_subscriptions_invalid_service_test.dart +deleted file mode 100644 +index c95e046a81a..00000000000 +--- a/pkg/analysis_server/test/integration/server/set_subscriptions_invali= d_service_test.dart ++++ /dev/null +@@ -1,30 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetSubscriptionsInvalidTest); +- }); +-} +- +-@reflectiveTest +-class SetSubscriptionsInvalidTest +- extends AbstractAnalysisServerIntegrationTest { +- test_setSubscriptions_invalidService() { +- // TODO(paulberry): verify that if an invalid service is specified, t= he +- // current subscriptions are unchanged. +- return server.send("server.setSubscriptions", { +- 'subscriptions': ['bogus'] +- }).then((_) { +- fail('setSubscriptions should have produced an error'); +- }, onError: (error) { +- // The expected error occurred. +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/server/set_subscriptions= _test.dart b/pkg/analysis_server/test/integration/server/set_subscriptions_= test.dart +deleted file mode 100644 +index 9cfd81caa40..00000000000 +--- a/pkg/analysis_server/test/integration/server/set_subscriptions_test.d= art ++++ /dev/null +@@ -1,64 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SetSubscriptionsTest); +- }); +-} +- +-@reflectiveTest +-class SetSubscriptionsTest extends AbstractAnalysisServerIntegrationTest { +- @failingTest +- test_setSubscriptions() { +- // This test times out on the bots and has been disabled to keep them= green. +- // We need to discover the cause and re-enable it. +- +- fail( +- 'This test times out on the bots and has been disabled to keep th= em green.' +- 'We need to discover the cause and re-enable it.'); +- +- bool statusReceived =3D false; +- Completer analysisBegun =3D new Completer(); +- onServerStatus.listen((_) { +- statusReceived =3D true; +- }); +- onAnalysisErrors.listen((_) { +- if (!analysisBegun.isCompleted) { +- analysisBegun.complete(); +- } +- }); +- return sendServerSetSubscriptions([]).then((_) { +- String pathname =3D sourcePath('test.dart'); +- writeFile(pathname, ''' +-main() { +- var x; +-}'''); +- standardAnalysisSetup(subscribeStatus: false); +- // Analysis should begin, but no server.status notification should = be +- // received. +- return analysisBegun.future.then((_) { +- expect(statusReceived, isFalse); +- return sendServerSetSubscriptions([ServerService.STATUS]).then((_= ) { +- // Tickle test.dart just in case analysis has already completed. +- writeFile(pathname, ''' +-main() { +- var y; +-}'''); +- // Analysis should eventually complete, and we should be notifi= ed +- // about it. +- return analysisFinished; +- }); +- }); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/server/shutdown_test.dar= t b/pkg/analysis_server/test/integration/server/shutdown_test.dart +deleted file mode 100644 +index 8478d48020b..00000000000 +--- a/pkg/analysis_server/test/integration/server/shutdown_test.dart ++++ /dev/null +@@ -1,31 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ShutdownTest); +- }); +-} +- +-@reflectiveTest +-class ShutdownTest extends AbstractAnalysisServerIntegrationTest { +- test_shutdown() { +- return sendServerShutdown().then((_) { +- return new Future.delayed(new Duration(seconds: 1)).then((_) { +- sendServerGetVersion().then((_) { +- fail('Server still alive after server.shutdown'); +- }); +- // Give the server time to respond before terminating the test. +- return new Future.delayed(new Duration(seconds: 1)); +- }); +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/server/status_test.dart = b/pkg/analysis_server/test/integration/server/status_test.dart +deleted file mode 100644 +index 72163c354ab..00000000000 +--- a/pkg/analysis_server/test/integration/server/status_test.dart ++++ /dev/null +@@ -1,50 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../support/integration_tests.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(StatusTest); +- }); +-} +- +-@reflectiveTest +-class StatusTest extends AbstractAnalysisServerIntegrationTest { +- test_status() { +- // After we kick off analysis, we should get one server.status messag= e with +- // analyzing=3Dtrue, and another server.status message after that with +- // analyzing=3Dfalse. +- Completer analysisBegun =3D new Completer(); +- Completer analysisFinished =3D new Completer(); +- onServerStatus.listen((ServerStatusParams params) { +- if (params.analysis !=3D null) { +- if (params.analysis.isAnalyzing) { +- expect(analysisBegun.isCompleted, isFalse); +- analysisBegun.complete(); +- } else { +- expect(analysisFinished.isCompleted, isFalse); +- analysisFinished.complete(); +- } +- } +- }); +- writeFile(sourcePath('test.dart'), ''' +-main() { +- var x; +-}'''); +- standardAnalysisSetup(); +- expect(analysisBegun.isCompleted, isFalse); +- expect(analysisFinished.isCompleted, isFalse); +- return analysisBegun.future.then((_) { +- expect(analysisFinished.isCompleted, isFalse); +- return analysisFinished.future; +- }); +- } +-} +diff --git a/pkg/analysis_server/test/integration/server/test_all.dart b/p= kg/analysis_server/test/integration/server/test_all.dart +deleted file mode 100644 +index 6ab8ac95174..00000000000 +--- a/pkg/analysis_server/test/integration/server/test_all.dart ++++ /dev/null +@@ -1,25 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'get_version_test.dart' as get_version_test; +-import 'set_subscriptions_invalid_service_test.dart' +- as set_subscriptions_invalid_service_test; +-import 'set_subscriptions_test.dart' as set_subscriptions_test; +-import 'shutdown_test.dart' as shutdown_test; +-import 'status_test.dart' as status_test; +- +-/** +- * Utility for manually running all integration tests. +- */ +-main() { +- defineReflectiveSuite(() { +- get_version_test.main(); +- set_subscriptions_test.main(); +- set_subscriptions_invalid_service_test.main(); +- shutdown_test.main(); +- status_test.main(); +- }, name: 'server'); +-} +diff --git a/pkg/analysis_server/test/integration/support/integration_test= _methods.dart b/pkg/analysis_server/test/integration/support/integration_te= st_methods.dart +deleted file mode 100644 +index 2580f2cfc85..00000000000 +--- a/pkg/analysis_server/test/integration/support/integration_test_method= s.dart ++++ /dev/null +@@ -1,2240 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +-// +-// This file has been automatically generated. Please do not edit it man= ually. +-// To regenerate the file, use the script +-// "pkg/analysis_server/tool/spec/generate_files". +- +-/** +- * Convenience methods for running integration tests +- */ +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart'; +-import 'package:test/test.dart'; +- +-import 'integration_tests.dart'; +-import 'protocol_matchers.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * Convenience methods for running integration tests +- */ +-abstract class IntegrationTestMixin { +- Server get server; +- +- /** +- * Return the version number of the analysis server. +- * +- * Returns +- * +- * version: String +- * +- * The version number of the analysis server. +- */ +- Future sendServerGetVersion() async { +- var result =3D await server.send("server.getVersion", null); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new ServerGetVersionResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Cleanly shutdown the analysis server. Requests that are received aft= er +- * this request will not be processed. Requests that were received befo= re +- * this request, but for which a response has not yet been sent, will n= ot be +- * responded to. No further responses or notifications will be sent aft= er the +- * response to this request has been sent. +- */ +- Future sendServerShutdown() async { +- var result =3D await server.send("server.shutdown", null); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Subscribe for services. All previous subscriptions are replaced by t= he +- * given set of services. +- * +- * It is an error if any of the elements in the list are not valid serv= ices. +- * If there is an error, then the current subscriptions will remain +- * unchanged. +- * +- * Parameters +- * +- * subscriptions: List +- * +- * A list of the services being subscribed to. +- */ +- Future sendServerSetSubscriptions(List subscriptions) as= ync { +- var params =3D new ServerSetSubscriptionsParams(subscriptions).toJson= (); +- var result =3D await server.send("server.setSubscriptions", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Reports that the server is running. This notification is issued once= after +- * the server has started running but before any requests are processed= to +- * let the client know that it started correctly. +- * +- * It is not possible to subscribe to or unsubscribe from this notifica= tion. +- * +- * Parameters +- * +- * version: String +- * +- * The version number of the analysis server. +- * +- * pid: int +- * +- * The process id of the analysis server process. +- * +- * sessionId: String (optional) +- * +- * The session id for this session. +- */ +- Stream onServerConnected; +- +- /** +- * Stream controller for [onServerConnected]. +- */ +- StreamController _onServerConnected; +- +- /** +- * Reports that an unexpected error has occurred while executing the se= rver. +- * This notification is not used for problems with specific requests (w= hich +- * are returned as part of the response) but is used for exceptions that +- * occur while performing other tasks, such as analysis or preparing +- * notifications. +- * +- * It is not possible to subscribe to or unsubscribe from this notifica= tion. +- * +- * Parameters +- * +- * isFatal: bool +- * +- * True if the error is a fatal error, meaning that the server will +- * shutdown automatically after sending this notification. +- * +- * message: String +- * +- * The error message indicating what kind of error was encountered. +- * +- * stackTrace: String +- * +- * The stack trace associated with the generation of the error, used = for +- * debugging the server. +- */ +- Stream onServerError; +- +- /** +- * Stream controller for [onServerError]. +- */ +- StreamController _onServerError; +- +- /** +- * Reports the current status of the server. Parameters are omitted if = there +- * has been no change in the status represented by that parameter. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "STATUS" in the list of services passed in a +- * server.setSubscriptions request. +- * +- * Parameters +- * +- * analysis: AnalysisStatus (optional) +- * +- * The current status of analysis, including whether analysis is being +- * performed and if so what is being analyzed. +- * +- * pub: PubStatus (optional) +- * +- * The current status of pub execution, indicating whether we are cur= rently +- * running pub. +- */ +- Stream onServerStatus; +- +- /** +- * Stream controller for [onServerStatus]. +- */ +- StreamController _onServerStatus; +- +- /** +- * Return the errors associated with the given file. If the errors for = the +- * given file have not yet been computed, or the most recently computed +- * errors for the given file are out of date, then the response for this +- * request will be delayed until they have been computed. If some or al= l of +- * the errors for the file cannot be computed, then the subset of the e= rrors +- * that can be computed will be returned and the response will contain = an +- * error to indicate why the errors could not be computed. If the conte= nt of +- * the file changes after this request was received but before a respon= se +- * could be sent, then an error of type CONTENT_MODIFIED will be genera= ted. +- * +- * This request is intended to be used by clients that cannot asynchron= ously +- * apply updated error information. Clients that can apply error inform= ation +- * as it becomes available should use the information provided by the +- * 'analysis.errors' notification. +- * +- * If a request is made for a file which does not exist, or which is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified to analysis.setAnalysisRoots), an error of t= ype +- * GET_ERRORS_INVALID_FILE will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file for which errors are being requested. +- * +- * Returns +- * +- * errors: List +- * +- * The errors associated with the file. +- */ +- Future sendAnalysisGetErrors(String file) asyn= c { +- var params =3D new AnalysisGetErrorsParams(file).toJson(); +- var result =3D await server.send("analysis.getErrors", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetErrorsResult.fromJson(decoder, 'result', result= ); +- } +- +- /** +- * Return the hover information associate with the given location. If s= ome or +- * all of the hover information is not available at the time this reque= st is +- * processed the information will be omitted from the response. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which hover information is being requested. +- * +- * offset: int +- * +- * The offset for which hover information is being requested. +- * +- * Returns +- * +- * hovers: List +- * +- * The hover information associated with the location. The list will = be +- * empty if no information could be determined for the location. The = list +- * can contain multiple items if the file is being analyzed in multip= le +- * contexts in conflicting ways (such as a part that is included in +- * multiple libraries). +- */ +- Future sendAnalysisGetHover( +- String file, int offset) async { +- var params =3D new AnalysisGetHoverParams(file, offset).toJson(); +- var result =3D await server.send("analysis.getHover", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetHoverResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Return a description of all of the elements referenced in a given re= gion +- * of a given file that come from imported libraries. +- * +- * If a request is made for a file that does not exist, or that is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified via analysis.setAnalysisRoots), an error of = type +- * GET_IMPORTED_ELEMENTS_INVALID_FILE will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which import information is being requested. +- * +- * offset: int +- * +- * The offset of the region for which import information is being +- * requested. +- * +- * length: int +- * +- * The length of the region for which import information is being +- * requested. +- * +- * Returns +- * +- * elements: List +- * +- * The information about the elements that are referenced in the spec= ified +- * region of the specified file that come from imported libraries. +- */ +- Future sendAnalysisGetImportedElemen= ts( +- String file, int offset, int length) async { +- var params =3D +- new AnalysisGetImportedElementsParams(file, offset, length).toJso= n(); +- var result =3D await server.send("analysis.getImportedElements", para= ms); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetImportedElementsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return library dependency information for use in client-side indexin= g and +- * package URI resolution. +- * +- * Clients that are only using the libraries field should consider usin= g the +- * analyzedFiles notification instead. +- * +- * Returns +- * +- * libraries: List +- * +- * A list of the paths of library elements referenced by files in exi= sting +- * analysis roots. +- * +- * packageMap: Map>> +- * +- * A mapping from context source roots to package maps which map pack= age +- * names to source directories for use in client-side package URI +- * resolution. +- */ +- Future +- sendAnalysisGetLibraryDependencies() async { +- var result =3D await server.send("analysis.getLibraryDependencies", n= ull); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetLibraryDependenciesResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return the navigation information associated with the given region o= f the +- * given file. If the navigation information for the given file has not= yet +- * been computed, or the most recently computed navigation information = for +- * the given file is out of date, then the response for this request wi= ll be +- * delayed until it has been computed. If the content of the file chang= es +- * after this request was received but before a response could be sent,= then +- * an error of type CONTENT_MODIFIED will be generated. +- * +- * If a navigation region overlaps (but extends either before or after)= the +- * given region of the file it will be included in the result. This mea= ns +- * that it is theoretically possible to get the same navigation region = in +- * response to multiple requests. Clients can avoid this by always choo= sing a +- * region that starts at the beginning of a line and ends at the end of= a +- * (possibly different) line in the file. +- * +- * If a request is made for a file which does not exist, or which is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified to analysis.setAnalysisRoots), an error of t= ype +- * GET_NAVIGATION_INVALID_FILE will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which navigation information is being requested. +- * +- * offset: int +- * +- * The offset of the region for which navigation information is being +- * requested. +- * +- * length: int +- * +- * The length of the region for which navigation information is being +- * requested. +- * +- * Returns +- * +- * files: List +- * +- * A list of the paths of files that are referenced by the navigation +- * targets. +- * +- * targets: List +- * +- * A list of the navigation targets that are referenced by the naviga= tion +- * regions. +- * +- * regions: List +- * +- * A list of the navigation regions within the requested region of the +- * file. +- */ +- Future sendAnalysisGetNavigation( +- String file, int offset, int length) async { +- var params =3D new AnalysisGetNavigationParams(file, offset, length).= toJson(); +- var result =3D await server.send("analysis.getNavigation", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetNavigationResult.fromJson(decoder, 'result', re= sult); +- } +- +- /** +- * Return the transitive closure of reachable sources for a given file. +- * +- * If a request is made for a file which does not exist, or which is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified to analysis.setAnalysisRoots), an error of t= ype +- * GET_REACHABLE_SOURCES_INVALID_FILE will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file for which reachable source information is being requested. +- * +- * Returns +- * +- * sources: Map> +- * +- * A mapping from source URIs to directly reachable source URIs. For +- * example, a file "foo.dart" that imports "bar.dart" would have the +- * corresponding mapping { "file:///foo.dart" : ["file:///bar.dart"] = }. If +- * "bar.dart" has further imports (or exports) there will be a mappin= g from +- * the URI "file:///bar.dart" to them. To check if a specific URI is +- * reachable from a given file, clients can check for its presence in= the +- * resulting key set. +- */ +- Future sendAnalysisGetReachableSourc= es( +- String file) async { +- var params =3D new AnalysisGetReachableSourcesParams(file).toJson(); +- var result =3D await server.send("analysis.getReachableSources", para= ms); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetReachableSourcesResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Force the re-analysis of everything contained in the specified analy= sis +- * roots. This will cause all previously computed analysis results to be +- * discarded and recomputed, and will cause all subscribed notification= s to +- * be re-sent. +- * +- * If no analysis roots are provided, then all current analysis roots w= ill be +- * re-analyzed. If an empty list of analysis roots is provided, then no= thing +- * will be re-analyzed. If the list contains one or more paths that are= not +- * currently analysis roots, then an error of type INVALID_ANALYSIS_ROO= T will +- * be generated. +- * +- * Parameters +- * +- * roots: List (optional) +- * +- * A list of the analysis roots that are to be re-analyzed. +- */ +- Future sendAnalysisReanalyze({List roots}) async { +- var params =3D new AnalysisReanalyzeParams(roots: roots).toJson(); +- var result =3D await server.send("analysis.reanalyze", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Sets the root paths used to determine which files to analyze. The se= t of +- * files to be analyzed are all of the files in one of the root paths t= hat +- * are not either explicitly or implicitly excluded. A file is explicit= ly +- * excluded if it is in one of the excluded paths. A file is implicitly +- * excluded if it is in a subdirectory of one of the root paths where t= he +- * name of the subdirectory starts with a period (that is, a hidden +- * directory). +- * +- * Note that this request determines the set of requested analysis root= s. The +- * actual set of analysis roots at any given time is the intersection o= f this +- * set with the set of files and directories actually present on the +- * filesystem. When the filesystem changes, the actual set of analysis = roots +- * is automatically updated, but the set of requested analysis roots is +- * unchanged. This means that if the client sets an analysis root befor= e the +- * root becomes visible to server in the filesystem, there is no error;= once +- * the server sees the root in the filesystem it will start analyzing i= t. +- * Similarly, server will stop analyzing files that are removed from th= e file +- * system but they will remain in the set of requested roots. +- * +- * If an included path represents a file, then server will look in the +- * directory containing the file for a pubspec.yaml file. If none is fo= und, +- * then the parents of the directory will be searched until such a file= is +- * found or the root of the file system is reached. If such a file is f= ound, +- * it will be used to resolve package: URI=E2=80=99s within the file. +- * +- * Parameters +- * +- * included: List +- * +- * A list of the files and directories that should be analyzed. +- * +- * excluded: List +- * +- * A list of the files and directories within the included directorie= s that +- * should not be analyzed. +- * +- * packageRoots: Map (optional) +- * +- * A mapping from source directories to package roots that should ove= rride +- * the normal package: URI resolution mechanism. +- * +- * If a package root is a directory, then the analyzer will behave as +- * though the associated source directory in the map contains a speci= al +- * pubspec.yaml file which resolves any package: URI to the correspon= ding +- * path within that package root directory. The effect is the same as +- * specifying the package root directory as a "--package_root" parame= ter to +- * the Dart VM when executing any Dart file inside the source directo= ry. +- * +- * If a package root is a file, then the analyzer will behave as thou= gh +- * that file is a ".packages" file in the source directory. The effec= t is +- * the same as specifying the file as a "--packages" parameter to the= Dart +- * VM when executing any Dart file inside the source directory. +- * +- * Files in any directories that are not overridden by this mapping h= ave +- * their package: URI's resolved using the normal pubspec.yaml mechan= ism. +- * If this field is absent, or the empty map is specified, that indic= ates +- * that the normal pubspec.yaml mechanism should always be used. +- */ +- Future sendAnalysisSetAnalysisRoots( +- List included, List excluded, +- {Map packageRoots}) async { +- var params =3D new AnalysisSetAnalysisRootsParams(included, excluded, +- packageRoots: packageRoots) +- .toJson(); +- var result =3D await server.send("analysis.setAnalysisRoots", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Subscribe for general services (that is, services that are not speci= fic to +- * individual files). All previous subscriptions are replaced by the gi= ven +- * set of services. +- * +- * It is an error if any of the elements in the list are not valid serv= ices. +- * If there is an error, then the current subscriptions will remain +- * unchanged. +- * +- * Parameters +- * +- * subscriptions: List +- * +- * A list of the services being subscribed to. +- */ +- Future sendAnalysisSetGeneralSubscriptions( +- List subscriptions) async { +- var params =3D +- new AnalysisSetGeneralSubscriptionsParams(subscriptions).toJson(); +- var result =3D await server.send("analysis.setGeneralSubscriptions", = params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Set the priority files to the files in the given list. A priority fi= le is +- * a file that is given priority when scheduling which analysis work to= do +- * first. The list typically contains those files that are visible to t= he +- * user and those for which analysis results will have the biggest impa= ct on +- * the user experience. The order of the files within the list is +- * significant: the first file will be given higher priority than the s= econd, +- * the second higher priority than the third, and so on. +- * +- * Note that this request determines the set of requested priority file= s. The +- * actual set of priority files is the intersection of the requested se= t of +- * priority files with the set of files currently subject to analysis. = (See +- * analysis.setSubscriptions for a description of files that are subjec= t to +- * analysis.) +- * +- * If a requested priority file is a directory it is ignored, but remai= ns in +- * the set of requested priority files so that if it later becomes a fi= le it +- * can be included in the set of actual priority files. +- * +- * Parameters +- * +- * files: List +- * +- * The files that are to be a priority for analysis. +- */ +- Future sendAnalysisSetPriorityFiles(List files) async { +- var params =3D new AnalysisSetPriorityFilesParams(files).toJson(); +- var result =3D await server.send("analysis.setPriorityFiles", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Subscribe for services that are specific to individual files. All pr= evious +- * subscriptions are replaced by the current set of subscriptions. If a= given +- * service is not included as a key in the map then no files will be +- * subscribed to the service, exactly as if the service had been includ= ed in +- * the map with an explicit empty list of files. +- * +- * Note that this request determines the set of requested subscriptions= . The +- * actual set of subscriptions at any given time is the intersection of= this +- * set with the set of files currently subject to analysis. The files +- * currently subject to analysis are the set of files contained within = an +- * actual analysis root but not excluded, plus all of the files transit= ively +- * reachable from those files via import, export and part directives. (= See +- * analysis.setAnalysisRoots for an explanation of how the actual analy= sis +- * roots are determined.) When the actual analysis roots change, the ac= tual +- * set of subscriptions is automatically updated, but the set of reques= ted +- * subscriptions is unchanged. +- * +- * If a requested subscription is a directory it is ignored, but remain= s in +- * the set of requested subscriptions so that if it later becomes a fil= e it +- * can be included in the set of actual subscriptions. +- * +- * It is an error if any of the keys in the map are not valid services.= If +- * there is an error, then the existing subscriptions will remain uncha= nged. +- * +- * Parameters +- * +- * subscriptions: Map> +- * +- * A table mapping services to a list of the files being subscribed t= o the +- * service. +- */ +- Future sendAnalysisSetSubscriptions( +- Map> subscriptions) async { +- var params =3D new AnalysisSetSubscriptionsParams(subscriptions).toJs= on(); +- var result =3D await server.send("analysis.setSubscriptions", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Update the content of one or more files. Files that were previously +- * updated but not included in this update remain unchanged. This effec= tively +- * represents an overlay of the filesystem. The files whose content is +- * overridden are therefore seen by server as being files with the given +- * content, even if the files do not exist on the filesystem or if the = file +- * path represents the path to a directory on the filesystem. +- * +- * Parameters +- * +- * files: Map +- * +- * A table mapping the files whose content has changed to a descripti= on of +- * the content change. +- * +- * Returns +- */ +- Future sendAnalysisUpdateContent( +- Map files) async { +- var params =3D new AnalysisUpdateContentParams(files).toJson(); +- var result =3D await server.send("analysis.updateContent", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisUpdateContentResult.fromJson(decoder, 'result', re= sult); +- } +- +- /** +- * Deprecated: all of the options can be set by users in an analysis op= tions +- * file. +- * +- * Update the options controlling analysis based on the given set of op= tions. +- * Any options that are not included in the analysis options will not be +- * changed. If there are options in the analysis options that are not v= alid, +- * they will be silently ignored. +- * +- * Parameters +- * +- * options: AnalysisOptions +- * +- * The options that are to be used to control analysis. +- */ +- @deprecated +- Future sendAnalysisUpdateOptions(AnalysisOptions options) async { +- var params =3D new AnalysisUpdateOptionsParams(options).toJson(); +- var result =3D await server.send("analysis.updateOptions", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Reports the paths of the files that are being analyzed. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "ANALYZED_FILES" in the list of services pass= ed in +- * an analysis.setGeneralSubscriptions request. +- * +- * Parameters +- * +- * directories: List +- * +- * A list of the paths of the files that are being analyzed. +- */ +- Stream onAnalysisAnalyzedFiles; +- +- /** +- * Stream controller for [onAnalysisAnalyzedFiles]. +- */ +- StreamController _onAnalysisAnalyzedFiles; +- +- /** +- * Reports closing labels relevant to a given file. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "CLOSING_LABELS" in the list of services pass= ed in +- * an analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file the closing labels relate to. +- * +- * labels: List +- * +- * Closing labels relevant to the file. Each item represents a useful= label +- * associated with some range with may be useful to display to the us= er +- * within the editor at the end of the range to indicate what constru= ct is +- * closed at that location. Closing labels include constructor/method= calls +- * and List arguments that span multiple lines. Note that the ranges = that +- * are returned can overlap each other because they may be associated= with +- * constructs that can be nested. +- */ +- Stream onAnalysisClosingLabels; +- +- /** +- * Stream controller for [onAnalysisClosingLabels]. +- */ +- StreamController _onAnalysisClosingLabels; +- +- /** +- * Reports the errors associated with a given file. The set of errors +- * included in the notification is always a complete list that supersed= es any +- * previously reported errors. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the errors. +- * +- * errors: List +- * +- * The errors contained in the file. +- */ +- Stream onAnalysisErrors; +- +- /** +- * Stream controller for [onAnalysisErrors]. +- */ +- StreamController _onAnalysisErrors; +- +- /** +- * Reports that any analysis results that were previously associated wi= th the +- * given files should be considered to be invalid because those files a= re no +- * longer being analyzed, either because the analysis root that contain= ed it +- * is no longer being analyzed or because the file no longer exists. +- * +- * If a file is included in this notification and at some later time a +- * notification with results for the file is received, clients should a= ssume +- * that the file is once again being analyzed and the information shoul= d be +- * processed. +- * +- * It is not possible to subscribe to or unsubscribe from this notifica= tion. +- * +- * Parameters +- * +- * files: List +- * +- * The files that are no longer being analyzed. +- */ +- Stream onAnalysisFlushResults; +- +- /** +- * Stream controller for [onAnalysisFlushResults]. +- */ +- StreamController _onAnalysisFlushResults; +- +- /** +- * Reports the folding regions associated with a given file. Folding re= gions +- * can be nested, but will not be overlapping. Nesting occurs when a fo= ldable +- * element, such as a method, is nested inside another foldable element= such +- * as a class. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "FOLDING" in the list of services passed in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the folding regions. +- * +- * regions: List +- * +- * The folding regions contained in the file. +- */ +- Stream onAnalysisFolding; +- +- /** +- * Stream controller for [onAnalysisFolding]. +- */ +- StreamController _onAnalysisFolding; +- +- /** +- * Reports the highlight regions associated with a given file. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "HIGHLIGHTS" in the list of services passed i= n an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the highlight regions. +- * +- * regions: List +- * +- * The highlight regions contained in the file. Each highlight region +- * represents a particular syntactic or semantic meaning associated w= ith +- * some range. Note that the highlight regions that are returned can +- * overlap other highlight regions if there is more than one meaning +- * associated with a particular region. +- */ +- Stream onAnalysisHighlights; +- +- /** +- * Stream controller for [onAnalysisHighlights]. +- */ +- StreamController _onAnalysisHighlights; +- +- /** +- * Reports the classes that are implemented or extended and class membe= rs +- * that are implemented or overridden in a file. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "IMPLEMENTED" in the list of services passed = in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file with which the implementations are associated. +- * +- * classes: List +- * +- * The classes defined in the file that are implemented or extended. +- * +- * members: List +- * +- * The member defined in the file that are implemented or overridden. +- */ +- Stream onAnalysisImplemented; +- +- /** +- * Stream controller for [onAnalysisImplemented]. +- */ +- StreamController _onAnalysisImplemented; +- +- /** +- * Reports that the navigation information associated with a region of a +- * single file has become invalid and should be re-requested. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "INVALIDATE" in the list of services passed i= n an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file whose information has been invalidated. +- * +- * offset: int +- * +- * The offset of the invalidated region. +- * +- * length: int +- * +- * The length of the invalidated region. +- * +- * delta: int +- * +- * The delta to be applied to the offsets in information that follows= the +- * invalidated region in order to update it so that it doesn't need t= o be +- * re-requested. +- */ +- Stream onAnalysisInvalidate; +- +- /** +- * Stream controller for [onAnalysisInvalidate]. +- */ +- StreamController _onAnalysisInvalidate; +- +- /** +- * Reports the navigation targets associated with a given file. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "NAVIGATION" in the list of services passed i= n an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the navigation regions. +- * +- * regions: List +- * +- * The navigation regions contained in the file. The regions are sort= ed by +- * their offsets. Each navigation region represents a list of targets +- * associated with some range. The lists will usually contain a single +- * target, but can contain more in the case of a part that is include= d in +- * multiple libraries or in Dart code that is compiled against multip= le +- * versions of a package. Note that the navigation regions that are +- * returned do not overlap other navigation regions. +- * +- * targets: List +- * +- * The navigation targets referenced in the file. They are referenced= by +- * NavigationRegions by their index in this array. +- * +- * files: List +- * +- * The files containing navigation targets referenced in the file. Th= ey are +- * referenced by NavigationTargets by their index in this array. +- */ +- Stream onAnalysisNavigation; +- +- /** +- * Stream controller for [onAnalysisNavigation]. +- */ +- StreamController _onAnalysisNavigation; +- +- /** +- * Reports the occurrences of references to elements within a single fi= le. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "OCCURRENCES" in the list of services passed = in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which the references occur. +- * +- * occurrences: List +- * +- * The occurrences of references to elements within the file. +- */ +- Stream onAnalysisOccurrences; +- +- /** +- * Stream controller for [onAnalysisOccurrences]. +- */ +- StreamController _onAnalysisOccurrences; +- +- /** +- * Reports the outline associated with a single file. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "OUTLINE" in the list of services passed in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file with which the outline is associated. +- * +- * kind: FileKind +- * +- * The kind of the file. +- * +- * libraryName: String (optional) +- * +- * The name of the library defined by the file using a "library" dire= ctive, +- * or referenced by a "part of" directive. If both "library" and "par= t of" +- * directives are present, then the "library" directive takes precede= nce. +- * This field will be omitted if the file has neither "library" nor "= part +- * of" directives. +- * +- * outline: Outline +- * +- * The outline associated with the file. +- */ +- Stream onAnalysisOutline; +- +- /** +- * Stream controller for [onAnalysisOutline]. +- */ +- StreamController _onAnalysisOutline; +- +- /** +- * Reports the overriding members in a file. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "OVERRIDES" in the list of services passed in= an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file with which the overrides are associated. +- * +- * overrides: List +- * +- * The overrides associated with the file. +- */ +- Stream onAnalysisOverrides; +- +- /** +- * Stream controller for [onAnalysisOverrides]. +- */ +- StreamController _onAnalysisOverrides; +- +- /** +- * Request that completion suggestions for the given offset in the give= n file +- * be returned. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the point at which suggestions are to be made. +- * +- * offset: int +- * +- * The offset within the file at which suggestions are to be made. +- * +- * Returns +- * +- * id: CompletionId +- * +- * The identifier used to associate results with this completion requ= est. +- */ +- Future sendCompletionGetSuggestions( +- String file, int offset) async { +- var params =3D new CompletionGetSuggestionsParams(file, offset).toJso= n(); +- var result =3D await server.send("completion.getSuggestions", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new CompletionGetSuggestionsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Reports the completion suggestions that should be presented to the u= ser. +- * The set of suggestions included in the notification is always a comp= lete +- * list that supersedes any previously reported suggestions. +- * +- * Parameters +- * +- * id: CompletionId +- * +- * The id associated with the completion. +- * +- * replacementOffset: int +- * +- * The offset of the start of the text to be replaced. This will be +- * different than the offset used to request the completion suggestio= ns if +- * there was a portion of an identifier before the original offset. In +- * particular, the replacementOffset will be the offset of the beginn= ing of +- * said identifier. +- * +- * replacementLength: int +- * +- * The length of the text to be replaced if the remainder of the iden= tifier +- * containing the cursor is to be replaced when the suggestion is app= lied +- * (that is, the number of characters in the existing identifier). +- * +- * results: List +- * +- * The completion suggestions being reported. The notification contai= ns all +- * possible completions at the requested cursor position, even those = that +- * do not match the characters the user has already typed. This allow= s the +- * client to respond to further keystrokes from the user without havi= ng to +- * make additional requests. +- * +- * isLast: bool +- * +- * True if this is that last set of results that will be returned for= the +- * indicated completion. +- */ +- Stream onCompletionResults; +- +- /** +- * Stream controller for [onCompletionResults]. +- */ +- StreamController _onCompletionResults; +- +- /** +- * Perform a search for references to the element defined or referenced= at +- * the given offset in the given file. +- * +- * An identifier is returned immediately, and individual results will be +- * returned via the search.results notification as they become availabl= e. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the declaration of or reference to the element= used +- * to define the search. +- * +- * offset: int +- * +- * The offset within the file of the declaration of or reference to t= he +- * element. +- * +- * includePotential: bool +- * +- * True if potential matches are to be included in the results. +- * +- * Returns +- * +- * id: SearchId (optional) +- * +- * The identifier used to associate results with this search request. +- * +- * If no element was found at the given location, this field will be +- * absent, and no results will be reported via the search.results +- * notification. +- * +- * element: Element (optional) +- * +- * The element referenced or defined at the given offset and whose +- * references will be returned in the search results. +- * +- * If no element was found at the given location, this field will be +- * absent. +- */ +- Future sendSearchFindElementReferenc= es( +- String file, int offset, bool includePotential) async { +- var params =3D +- new SearchFindElementReferencesParams(file, offset, includePotent= ial) +- .toJson(); +- var result =3D await server.send("search.findElementReferences", para= ms); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new SearchFindElementReferencesResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Perform a search for declarations of members whose name is equal to = the +- * given name. +- * +- * An identifier is returned immediately, and individual results will be +- * returned via the search.results notification as they become availabl= e. +- * +- * Parameters +- * +- * name: String +- * +- * The name of the declarations to be found. +- * +- * Returns +- * +- * id: SearchId +- * +- * The identifier used to associate results with this search request. +- */ +- Future sendSearchFindMemberDeclarat= ions( +- String name) async { +- var params =3D new SearchFindMemberDeclarationsParams(name).toJson(); +- var result =3D await server.send("search.findMemberDeclarations", par= ams); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new SearchFindMemberDeclarationsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Perform a search for references to members whose name is equal to the +- * given name. This search does not check to see that there is a member +- * defined with the given name, so it is able to find references to und= efined +- * members as well. +- * +- * An identifier is returned immediately, and individual results will be +- * returned via the search.results notification as they become availabl= e. +- * +- * Parameters +- * +- * name: String +- * +- * The name of the references to be found. +- * +- * Returns +- * +- * id: SearchId +- * +- * The identifier used to associate results with this search request. +- */ +- Future sendSearchFindMemberReferences( +- String name) async { +- var params =3D new SearchFindMemberReferencesParams(name).toJson(); +- var result =3D await server.send("search.findMemberReferences", param= s); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new SearchFindMemberReferencesResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Perform a search for declarations of top-level elements (classes, +- * typedefs, getters, setters, functions and fields) whose name matches= the +- * given pattern. +- * +- * An identifier is returned immediately, and individual results will be +- * returned via the search.results notification as they become availabl= e. +- * +- * Parameters +- * +- * pattern: String +- * +- * The regular expression used to match the names of the declarations= to be +- * found. +- * +- * Returns +- * +- * id: SearchId +- * +- * The identifier used to associate results with this search request. +- */ +- Future +- sendSearchFindTopLevelDeclarations(String pattern) async { +- var params =3D new SearchFindTopLevelDeclarationsParams(pattern).toJs= on(); +- var result =3D await server.send("search.findTopLevelDeclarations", p= arams); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new SearchFindTopLevelDeclarationsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return the type hierarchy of the class declared or referenced at the= given +- * location. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the declaration or reference to the type for w= hich a +- * hierarchy is being requested. +- * +- * offset: int +- * +- * The offset of the name of the type within the file. +- * +- * superOnly: bool (optional) +- * +- * True if the client is only requesting superclasses and interfaces +- * hierarchy. +- * +- * Returns +- * +- * hierarchyItems: List (optional) +- * +- * A list of the types in the requested hierarchy. The first element = of the +- * list is the item representing the type for which the hierarchy was +- * requested. The index of other elements of the list is unspecified,= but +- * correspond to the integers used to reference supertype and subtype= items +- * within the items. +- * +- * This field will be absent if the code at the given file and offset= does +- * not represent a type, or if the file has not been sufficiently ana= lyzed +- * to allow a type hierarchy to be produced. +- */ +- Future sendSearchGetTypeHierarchy( +- String file, int offset, +- {bool superOnly}) async { +- var params =3D +- new SearchGetTypeHierarchyParams(file, offset, superOnly: superOn= ly) +- .toJson(); +- var result =3D await server.send("search.getTypeHierarchy", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new SearchGetTypeHierarchyResult.fromJson(decoder, 'result', r= esult); +- } +- +- /** +- * Reports some or all of the results of performing a requested search. +- * Unlike other notifications, this notification contains search result= s that +- * should be added to any previously received search results associated= with +- * the same search id. +- * +- * Parameters +- * +- * id: SearchId +- * +- * The id associated with the search. +- * +- * results: List +- * +- * The search results being reported. +- * +- * isLast: bool +- * +- * True if this is that last set of results that will be returned for= the +- * indicated search. +- */ +- Stream onSearchResults; +- +- /** +- * Stream controller for [onSearchResults]. +- */ +- StreamController _onSearchResults; +- +- /** +- * Format the contents of a single file. The currently selected region = of +- * text is passed in so that the selection can be preserved across the +- * formatting operation. The updated selection will be as close to matc= hing +- * the original as possible, but whitespace at the beginning or end of = the +- * selected region will be ignored. If preserving selection information= is +- * not required, zero (0) can be specified for both the selection offse= t and +- * selection length. +- * +- * If a request is made for a file which does not exist, or which is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified to analysis.setAnalysisRoots), an error of t= ype +- * FORMAT_INVALID_FILE will be generated. If the source contains syntax +- * errors, an error of type FORMAT_WITH_ERRORS will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code to be formatted. +- * +- * selectionOffset: int +- * +- * The offset of the current selection in the file. +- * +- * selectionLength: int +- * +- * The length of the current selection in the file. +- * +- * lineLength: int (optional) +- * +- * The line length to be used by the formatter. +- * +- * Returns +- * +- * edits: List +- * +- * The edit(s) to be applied in order to format the code. The list wi= ll be +- * empty if the code was already formatted (there are no changes). +- * +- * selectionOffset: int +- * +- * The offset of the selection after formatting the code. +- * +- * selectionLength: int +- * +- * The length of the selection after formatting the code. +- */ +- Future sendEditFormat( +- String file, int selectionOffset, int selectionLength, +- {int lineLength}) async { +- var params =3D new EditFormatParams(file, selectionOffset, selectionL= ength, +- lineLength: lineLength) +- .toJson(); +- var result =3D await server.send("edit.format", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditFormatResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Return the set of assists that are available at the given location. = An +- * assist is distinguished from a refactoring primarily by the fact tha= t it +- * affects a single file and does not require user input in order to be +- * performed. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code for which assists are being requested. +- * +- * offset: int +- * +- * The offset of the code for which assists are being requested. +- * +- * length: int +- * +- * The length of the code for which assists are being requested. +- * +- * Returns +- * +- * assists: List +- * +- * The assists that are available at the given location. +- */ +- Future sendEditGetAssists( +- String file, int offset, int length) async { +- var params =3D new EditGetAssistsParams(file, offset, length).toJson(= ); +- var result =3D await server.send("edit.getAssists", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetAssistsResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Get a list of the kinds of refactorings that are valid for the given +- * selection in the given file. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code on which the refactoring would be bas= ed. +- * +- * offset: int +- * +- * The offset of the code on which the refactoring would be based. +- * +- * length: int +- * +- * The length of the code on which the refactoring would be based. +- * +- * Returns +- * +- * kinds: List +- * +- * The kinds of refactorings that are valid for the given selection. +- */ +- Future sendEditGetAvailableRefactor= ings( +- String file, int offset, int length) async { +- var params =3D +- new EditGetAvailableRefactoringsParams(file, offset, length).toJs= on(); +- var result =3D await server.send("edit.getAvailableRefactorings", par= ams); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetAvailableRefactoringsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return the set of fixes that are available for the errors at a given +- * offset in a given file. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the errors for which fixes are being requested. +- * +- * offset: int +- * +- * The offset used to select the errors for which fixes will be retur= ned. +- * +- * Returns +- * +- * fixes: List +- * +- * The fixes that are available for the errors at the given offset. +- */ +- Future sendEditGetFixes(String file, int offset) as= ync { +- var params =3D new EditGetFixesParams(file, offset).toJson(); +- var result =3D await server.send("edit.getFixes", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetFixesResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Get the changes required to convert the postfix template at the given +- * location into the template's expanded form. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the postfix template to be expanded. +- * +- * key: String +- * +- * The unique name that identifies the template in use. +- * +- * offset: int +- * +- * The offset used to identify the code to which the template will be +- * applied. +- * +- * Returns +- * +- * change: SourceChange +- * +- * The change to be applied in order to complete the statement. +- */ +- Future sendEditGetPostfixCompletion( +- String file, String key, int offset) async { +- var params =3D new EditGetPostfixCompletionParams(file, key, offset).= toJson(); +- var result =3D await server.send("edit.getPostfixCompletion", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetPostfixCompletionResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Get the changes required to perform a refactoring. +- * +- * If another refactoring request is received during the processing of = this +- * one, an error of type REFACTORING_REQUEST_CANCELLED will be generate= d. +- * +- * Parameters +- * +- * kind: RefactoringKind +- * +- * The kind of refactoring to be performed. +- * +- * file: FilePath +- * +- * The file containing the code involved in the refactoring. +- * +- * offset: int +- * +- * The offset of the region involved in the refactoring. +- * +- * length: int +- * +- * The length of the region involved in the refactoring. +- * +- * validateOnly: bool +- * +- * True if the client is only requesting that the values of the optio= ns be +- * validated and no change be generated. +- * +- * options: RefactoringOptions (optional) +- * +- * Data used to provide values provided by the user. The structure of= the +- * data is dependent on the kind of refactoring being performed. The = data +- * that is expected is documented in the section titled Refactorings, +- * labeled as "Options". This field can be omitted if the refactoring= does +- * not require any options or if the values of those options are not = known. +- * +- * Returns +- * +- * initialProblems: List +- * +- * The initial status of the refactoring, i.e. problems related to the +- * context in which the refactoring is requested. The array will be e= mpty +- * if there are no known problems. +- * +- * optionsProblems: List +- * +- * The options validation status, i.e. problems in the given options,= such +- * as light-weight validation of a new name, flags compatibility, etc= . The +- * array will be empty if there are no known problems. +- * +- * finalProblems: List +- * +- * The final status of the refactoring, i.e. problems identified in t= he +- * result of a full, potentially expensive validation and / or change +- * creation. The array will be empty if there are no known problems. +- * +- * feedback: RefactoringFeedback (optional) +- * +- * Data used to provide feedback to the user. The structure of the da= ta is +- * dependent on the kind of refactoring being created. The data that = is +- * returned is documented in the section titled Refactorings, labeled= as +- * "Feedback". +- * +- * change: SourceChange (optional) +- * +- * The changes that are to be applied to affect the refactoring. This= field +- * will be omitted if there are problems that prevent a set of change= s from +- * being computed, such as having no options specified for a refactor= ing +- * that requires them, or if only validation was requested. +- * +- * potentialEdits: List (optional) +- * +- * The ids of source edits that are not known to be valid. An edit is= not +- * known to be valid if there was insufficient type information for t= he +- * server to be able to determine whether or not the code needs to be +- * modified, such as when a member is being renamed and there is a +- * reference to a member from an unknown type. This field will be omi= tted +- * if the change field is omitted or if there are no potential edits = for +- * the refactoring. +- */ +- Future sendEditGetRefactoring(RefactoringKind= kind, +- String file, int offset, int length, bool validateOnly, +- {RefactoringOptions options}) async { +- var params =3D new EditGetRefactoringParams( +- kind, file, offset, length, validateOnly, +- options: options) +- .toJson(); +- var result =3D await server.send("edit.getRefactoring", params); +- ResponseDecoder decoder =3D new ResponseDecoder(kind); +- return new EditGetRefactoringResult.fromJson(decoder, 'result', resul= t); +- } +- +- /** +- * Get the changes required to convert the partial statement at the giv= en +- * location into a syntactically valid statement. If the current statem= ent is +- * already valid the change will insert a newline plus appropriate +- * indentation at the end of the line containing the offset. If a chang= e that +- * makes the statement valid cannot be determined (perhaps because it h= as not +- * yet been implemented) the statement will be considered already valid= and +- * the appropriate change returned. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the statement to be completed. +- * +- * offset: int +- * +- * The offset used to identify the statement to be completed. +- * +- * Returns +- * +- * change: SourceChange +- * +- * The change to be applied in order to complete the statement. +- * +- * whitespaceOnly: bool +- * +- * Will be true if the change contains nothing but whitespace charact= ers, +- * or is empty. +- */ +- Future sendEditGetStatementCompletion( +- String file, int offset) async { +- var params =3D new EditGetStatementCompletionParams(file, offset).toJ= son(); +- var result =3D await server.send("edit.getStatementCompletion", param= s); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetStatementCompletionResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Determine if the request postfix completion template is applicable a= t the +- * given location in the given file. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the postfix template to be expanded. +- * +- * key: String +- * +- * The unique name that identifies the template in use. +- * +- * offset: int +- * +- * The offset used to identify the code to which the template will be +- * applied. +- * +- * Returns +- * +- * value: bool +- * +- * True if the template can be expanded at the given location. +- */ +- Future +- sendEditIsPostfixCompletionApplicable( +- String file, String key, int offset) async { +- var params =3D +- new EditIsPostfixCompletionApplicableParams(file, key, offset).to= Json(); +- var result =3D +- await server.send("edit.isPostfixCompletionApplicable", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditIsPostfixCompletionApplicableResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return a list of all postfix templates currently available. +- * +- * Returns +- * +- * templates: List +- * +- * The list of available templates. +- */ +- Future +- sendEditListPostfixCompletionTemplates() async { +- var result =3D await server.send("edit.listPostfixCompletionTemplates= ", null); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditListPostfixCompletionTemplatesResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return a list of edits that would need to be applied in order to ens= ure +- * that all of the elements in the specified list of imported elements = are +- * accessible within the library. +- * +- * If a request is made for a file that does not exist, or that is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified via analysis.setAnalysisRoots), an error of = type +- * IMPORT_ELEMENTS_INVALID_FILE will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which the specified elements are to be made accessible. +- * +- * elements: List +- * +- * The elements to be made accessible in the specified file. +- * +- * Returns +- * +- * edit: SourceFileEdit +- * +- * The edits to be applied in order to make the specified elements +- * accessible. The file to be edited will be the defining compilation= unit +- * of the library containing the file specified in the request, which= can +- * be different than the file specified in the request if the specifi= ed +- * file is a part file. +- */ +- Future sendEditImportElements( +- String file, List elements) async { +- var params =3D new EditImportElementsParams(file, elements).toJson(); +- var result =3D await server.send("edit.importElements", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditImportElementsResult.fromJson(decoder, 'result', resul= t); +- } +- +- /** +- * Sort all of the directives, unit and class members of the given Dart= file. +- * +- * If a request is made for a file that does not exist, does not belong= to an +- * analysis root or is not a Dart file, SORT_MEMBERS_INVALID_FILE will = be +- * generated. +- * +- * If the Dart file has scan or parse errors, SORT_MEMBERS_PARSE_ERRORS= will +- * be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The Dart file to sort. +- * +- * Returns +- * +- * edit: SourceFileEdit +- * +- * The file edit that is to be applied to the given file to effect the +- * sorting. +- */ +- Future sendEditSortMembers(String file) async { +- var params =3D new EditSortMembersParams(file).toJson(); +- var result =3D await server.send("edit.sortMembers", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditSortMembersResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Organizes all of the directives - removes unused imports and sorts +- * directives of the given Dart file according to the Dart Style Guide. +- * +- * If a request is made for a file that does not exist, does not belong= to an +- * analysis root or is not a Dart file, FILE_NOT_ANALYZED will be gener= ated. +- * +- * If directives of the Dart file cannot be organized, for example beca= use it +- * has scan or parse errors, or by other reasons, ORGANIZE_DIRECTIVES_E= RROR +- * will be generated. The message will provide details about the reason. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The Dart file to organize directives in. +- * +- * Returns +- * +- * edit: SourceFileEdit +- * +- * The file edit that is to be applied to the given file to effect the +- * organizing. +- */ +- Future sendEditOrganizeDirectives( +- String file) async { +- var params =3D new EditOrganizeDirectivesParams(file).toJson(); +- var result =3D await server.send("edit.organizeDirectives", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditOrganizeDirectivesResult.fromJson(decoder, 'result', r= esult); +- } +- +- /** +- * Create an execution context for the executable file with the given p= ath. +- * The context that is created will persist until execution.deleteConte= xt is +- * used to delete it. Clients, therefore, are responsible for managing = the +- * lifetime of execution contexts. +- * +- * Parameters +- * +- * contextRoot: FilePath +- * +- * The path of the Dart or HTML file that will be launched, or the pa= th of +- * the directory containing the file. +- * +- * Returns +- * +- * id: ExecutionContextId +- * +- * The identifier used to refer to the execution context that was cre= ated. +- */ +- Future sendExecutionCreateContext( +- String contextRoot) async { +- var params =3D new ExecutionCreateContextParams(contextRoot).toJson(); +- var result =3D await server.send("execution.createContext", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new ExecutionCreateContextResult.fromJson(decoder, 'result', r= esult); +- } +- +- /** +- * Delete the execution context with the given identifier. The context = id is +- * no longer valid after this command. The server is allowed to re-use = ids +- * when they are no longer valid. +- * +- * Parameters +- * +- * id: ExecutionContextId +- * +- * The identifier of the execution context that is to be deleted. +- */ +- Future sendExecutionDeleteContext(String id) async { +- var params =3D new ExecutionDeleteContextParams(id).toJson(); +- var result =3D await server.send("execution.deleteContext", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Map a URI from the execution context to the file that it corresponds= to, +- * or map a file to the URI that it corresponds to in the execution con= text. +- * +- * Exactly one of the file and uri fields must be provided. If both fie= lds +- * are provided, then an error of type INVALID_PARAMETER will be genera= ted. +- * Similarly, if neither field is provided, then an error of type +- * INVALID_PARAMETER will be generated. +- * +- * If the file field is provided and the value is not the path of a file +- * (either the file does not exist or the path references something oth= er +- * than a file), then an error of type INVALID_PARAMETER will be genera= ted. +- * +- * If the uri field is provided and the value is not a valid URI or if = the +- * URI references something that is not a file (either a file that does= not +- * exist or something other than a file), then an error of type +- * INVALID_PARAMETER will be generated. +- * +- * If the contextRoot used to create the execution context does not exi= st, +- * then an error of type INVALID_EXECUTION_CONTEXT will be generated. +- * +- * Parameters +- * +- * id: ExecutionContextId +- * +- * The identifier of the execution context in which the URI is to be +- * mapped. +- * +- * file: FilePath (optional) +- * +- * The path of the file to be mapped into a URI. +- * +- * uri: String (optional) +- * +- * The URI to be mapped into a file path. +- * +- * Returns +- * +- * file: FilePath (optional) +- * +- * The file to which the URI was mapped. This field is omitted if the= uri +- * field was not given in the request. +- * +- * uri: String (optional) +- * +- * The URI to which the file path was mapped. This field is omitted i= f the +- * file field was not given in the request. +- */ +- Future sendExecutionMapUri(String id, +- {String file, String uri}) async { +- var params =3D new ExecutionMapUriParams(id, file: file, uri: uri).to= Json(); +- var result =3D await server.send("execution.mapUri", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new ExecutionMapUriResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Deprecated: the analysis server no longer fires LAUNCH_DATA events. +- * +- * Subscribe for services. All previous subscriptions are replaced by t= he +- * given set of services. +- * +- * It is an error if any of the elements in the list are not valid serv= ices. +- * If there is an error, then the current subscriptions will remain +- * unchanged. +- * +- * Parameters +- * +- * subscriptions: List +- * +- * A list of the services being subscribed to. +- */ +- @deprecated +- Future sendExecutionSetSubscriptions( +- List subscriptions) async { +- var params =3D new ExecutionSetSubscriptionsParams(subscriptions).toJ= son(); +- var result =3D await server.send("execution.setSubscriptions", params= ); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Reports information needed to allow a single file to be launched. +- * +- * This notification is not subscribed to by default. Clients can subsc= ribe +- * by including the value "LAUNCH_DATA" in the list of services passed = in an +- * execution.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file for which launch data is being provided. This will either= be a +- * Dart library or an HTML file. +- * +- * kind: ExecutableKind (optional) +- * +- * The kind of the executable file. This field is omitted if the file= is +- * not a Dart file. +- * +- * referencedFiles: List (optional) +- * +- * A list of the Dart files that are referenced by the file. This fie= ld is +- * omitted if the file is not an HTML file. +- */ +- Stream onExecutionLaunchData; +- +- /** +- * Stream controller for [onExecutionLaunchData]. +- */ +- StreamController _onExecutionLaunchData; +- +- /** +- * Return server diagnostics. +- * +- * Returns +- * +- * contexts: List +- * +- * The list of analysis contexts. +- */ +- Future sendDiagnosticGetDiagnostics() a= sync { +- var result =3D await server.send("diagnostic.getDiagnostics", null); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new DiagnosticGetDiagnosticsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Return the port of the diagnostic web server. If the server is not r= unning +- * this call will start the server. If unable to start the diagnostic w= eb +- * server, this call will return an error of DEBUG_PORT_COULD_NOT_BE_OP= ENED. +- * +- * Returns +- * +- * port: int +- * +- * The diagnostic server port. +- */ +- Future sendDiagnosticGetServerPort() asy= nc { +- var result =3D await server.send("diagnostic.getServerPort", null); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new DiagnosticGetServerPortResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Query whether analytics is enabled. +- * +- * This flag controls whether the analysis server sends any analytics d= ata to +- * the cloud. If disabled, the analysis server does not send any analyt= ics +- * data, and any data sent to it by clients (from sendEvent and sendTim= ing) +- * will be ignored. +- * +- * The value of this flag can be changed by other tools outside of the +- * analysis server's process. When you query the flag, you get the valu= e of +- * the flag at a given moment. Clients should not use the value returne= d to +- * decide whether or not to send the sendEvent and sendTiming requests.= Those +- * requests should be used unconditionally and server will determine wh= ether +- * or not it is appropriate to forward the information to the cloud at = the +- * time each request is received. +- * +- * Returns +- * +- * enabled: bool +- * +- * Whether sending analytics is enabled or not. +- */ +- Future sendAnalyticsIsEnabled() async { +- var result =3D await server.send("analytics.isEnabled", null); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalyticsIsEnabledResult.fromJson(decoder, 'result', resul= t); +- } +- +- /** +- * Enable or disable the sending of analytics data. Note that there are= other +- * ways for users to change this setting, so clients cannot assume that= they +- * have complete control over this setting. In particular, there is no +- * guarantee that the result returned by the isEnabled request will mat= ch the +- * last value set via this request. +- * +- * Parameters +- * +- * value: bool +- * +- * Enable or disable analytics. +- */ +- Future sendAnalyticsEnable(bool value) async { +- var params =3D new AnalyticsEnableParams(value).toJson(); +- var result =3D await server.send("analytics.enable", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Send information about client events. +- * +- * Ask the analysis server to include the fact that an action was perfo= rmed +- * in the client as part of the analytics data being sent. The data wil= l only +- * be included if the sending of analytics data is enabled at the time = the +- * request is processed. The action that was performed is indicated by = the +- * value of the action field. +- * +- * The value of the action field should not include the identity of the +- * client. The analytics data sent by server will include the client id +- * passed in using the --client-id command-line argument. The request w= ill be +- * ignored if the client id was not provided when server was started. +- * +- * Parameters +- * +- * action: String +- * +- * The value used to indicate which action was performed. +- */ +- Future sendAnalyticsSendEvent(String action) async { +- var params =3D new AnalyticsSendEventParams(action).toJson(); +- var result =3D await server.send("analytics.sendEvent", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Send timing information for client events (e.g. code completions). +- * +- * Ask the analysis server to include the fact that a timed event occur= red as +- * part of the analytics data being sent. The data will only be include= d if +- * the sending of analytics data is enabled at the time the request is +- * processed. +- * +- * The value of the event field should not include the identity of the +- * client. The analytics data sent by server will include the client id +- * passed in using the --client-id command-line argument. The request w= ill be +- * ignored if the client id was not provided when server was started. +- * +- * Parameters +- * +- * event: String +- * +- * The name of the event. +- * +- * millis: int +- * +- * The duration of the event in milliseconds. +- */ +- Future sendAnalyticsSendTiming(String event, int millis) async { +- var params =3D new AnalyticsSendTimingParams(event, millis).toJson(); +- var result =3D await server.send("analytics.sendTiming", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Return the list of KytheEntry objects for some file, given the curre= nt +- * state of the file system populated by "analysis.updateContent". +- * +- * If a request is made for a file that does not exist, or that is not +- * currently subject to analysis (e.g. because it is not associated wit= h any +- * analysis root specified to analysis.setAnalysisRoots), an error of t= ype +- * GET_KYTHE_ENTRIES_INVALID_FILE will be generated. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code for which the Kythe Entry objects are= being +- * requested. +- * +- * Returns +- * +- * entries: List +- * +- * The list of KytheEntry objects for the queried file. +- * +- * files: List +- * +- * The set of files paths that were required, but not in the file sys= tem, +- * to give a complete and accurate Kythe graph for the file. This cou= ld be +- * due to a referenced file that does not exist or generated files not +- * being generated or passed before the call to "getKytheEntries". +- */ +- Future sendKytheGetKytheEntries( +- String file) async { +- var params =3D new KytheGetKytheEntriesParams(file).toJson(); +- var result =3D await server.send("kythe.getKytheEntries", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new KytheGetKytheEntriesResult.fromJson(decoder, 'result', res= ult); +- } +- +- /** +- * Initialize the fields in InttestMixin, and ensure that notifications= will +- * be handled. +- */ +- void initializeInttestMixin() { +- _onServerConnected =3D +- new StreamController(sync: true); +- onServerConnected =3D _onServerConnected.stream.asBroadcastStream(); +- _onServerError =3D new StreamController(sync: true= ); +- onServerError =3D _onServerError.stream.asBroadcastStream(); +- _onServerStatus =3D new StreamController(sync: tr= ue); +- onServerStatus =3D _onServerStatus.stream.asBroadcastStream(); +- _onAnalysisAnalyzedFiles =3D +- new StreamController(sync: true); +- onAnalysisAnalyzedFiles =3D +- _onAnalysisAnalyzedFiles.stream.asBroadcastStream(); +- _onAnalysisClosingLabels =3D +- new StreamController(sync: true); +- onAnalysisClosingLabels =3D +- _onAnalysisClosingLabels.stream.asBroadcastStream(); +- _onAnalysisErrors =3D new StreamController(sync= : true); +- onAnalysisErrors =3D _onAnalysisErrors.stream.asBroadcastStream(); +- _onAnalysisFlushResults =3D +- new StreamController(sync: true); +- onAnalysisFlushResults =3D _onAnalysisFlushResults.stream.asBroadcast= Stream(); +- _onAnalysisFolding =3D +- new StreamController(sync: true); +- onAnalysisFolding =3D _onAnalysisFolding.stream.asBroadcastStream(); +- _onAnalysisHighlights =3D +- new StreamController(sync: true); +- onAnalysisHighlights =3D _onAnalysisHighlights.stream.asBroadcastStre= am(); +- _onAnalysisImplemented =3D +- new StreamController(sync: true); +- onAnalysisImplemented =3D _onAnalysisImplemented.stream.asBroadcastSt= ream(); +- _onAnalysisInvalidate =3D +- new StreamController(sync: true); +- onAnalysisInvalidate =3D _onAnalysisInvalidate.stream.asBroadcastStre= am(); +- _onAnalysisNavigation =3D +- new StreamController(sync: true); +- onAnalysisNavigation =3D _onAnalysisNavigation.stream.asBroadcastStre= am(); +- _onAnalysisOccurrences =3D +- new StreamController(sync: true); +- onAnalysisOccurrences =3D _onAnalysisOccurrences.stream.asBroadcastSt= ream(); +- _onAnalysisOutline =3D +- new StreamController(sync: true); +- onAnalysisOutline =3D _onAnalysisOutline.stream.asBroadcastStream(); +- _onAnalysisOverrides =3D +- new StreamController(sync: true); +- onAnalysisOverrides =3D _onAnalysisOverrides.stream.asBroadcastStream= (); +- _onCompletionResults =3D +- new StreamController(sync: true); +- onCompletionResults =3D _onCompletionResults.stream.asBroadcastStream= (); +- _onSearchResults =3D new StreamController(sync: = true); +- onSearchResults =3D _onSearchResults.stream.asBroadcastStream(); +- _onExecutionLaunchData =3D +- new StreamController(sync: true); +- onExecutionLaunchData =3D _onExecutionLaunchData.stream.asBroadcastSt= ream(); +- } +- +- /** +- * Dispatch the notification named [event], and containing parameters +- * [params], to the appropriate stream. +- */ +- void dispatchNotification(String event, params) { +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- switch (event) { +- case "server.connected": +- outOfTestExpect(params, isServerConnectedParams); +- _onServerConnected +- .add(new ServerConnectedParams.fromJson(decoder, 'params', pa= rams)); +- break; +- case "server.error": +- outOfTestExpect(params, isServerErrorParams); +- _onServerError +- .add(new ServerErrorParams.fromJson(decoder, 'params', params= )); +- break; +- case "server.status": +- outOfTestExpect(params, isServerStatusParams); +- _onServerStatus +- .add(new ServerStatusParams.fromJson(decoder, 'params', param= s)); +- break; +- case "analysis.analyzedFiles": +- outOfTestExpect(params, isAnalysisAnalyzedFilesParams); +- _onAnalysisAnalyzedFiles.add(new AnalysisAnalyzedFilesParams.from= Json( +- decoder, 'params', params)); +- break; +- case "analysis.closingLabels": +- outOfTestExpect(params, isAnalysisClosingLabelsParams); +- _onAnalysisClosingLabels.add(new AnalysisClosingLabelsParams.from= Json( +- decoder, 'params', params)); +- break; +- case "analysis.errors": +- outOfTestExpect(params, isAnalysisErrorsParams); +- _onAnalysisErrors +- .add(new AnalysisErrorsParams.fromJson(decoder, 'params', par= ams)); +- break; +- case "analysis.flushResults": +- outOfTestExpect(params, isAnalysisFlushResultsParams); +- _onAnalysisFlushResults.add( +- new AnalysisFlushResultsParams.fromJson(decoder, 'params', pa= rams)); +- break; +- case "analysis.folding": +- outOfTestExpect(params, isAnalysisFoldingParams); +- _onAnalysisFolding +- .add(new AnalysisFoldingParams.fromJson(decoder, 'params', pa= rams)); +- break; +- case "analysis.highlights": +- outOfTestExpect(params, isAnalysisHighlightsParams); +- _onAnalysisHighlights.add( +- new AnalysisHighlightsParams.fromJson(decoder, 'params', para= ms)); +- break; +- case "analysis.implemented": +- outOfTestExpect(params, isAnalysisImplementedParams); +- _onAnalysisImplemented.add( +- new AnalysisImplementedParams.fromJson(decoder, 'params', par= ams)); +- break; +- case "analysis.invalidate": +- outOfTestExpect(params, isAnalysisInvalidateParams); +- _onAnalysisInvalidate.add( +- new AnalysisInvalidateParams.fromJson(decoder, 'params', para= ms)); +- break; +- case "analysis.navigation": +- outOfTestExpect(params, isAnalysisNavigationParams); +- _onAnalysisNavigation.add( +- new AnalysisNavigationParams.fromJson(decoder, 'params', para= ms)); +- break; +- case "analysis.occurrences": +- outOfTestExpect(params, isAnalysisOccurrencesParams); +- _onAnalysisOccurrences.add( +- new AnalysisOccurrencesParams.fromJson(decoder, 'params', par= ams)); +- break; +- case "analysis.outline": +- outOfTestExpect(params, isAnalysisOutlineParams); +- _onAnalysisOutline +- .add(new AnalysisOutlineParams.fromJson(decoder, 'params', pa= rams)); +- break; +- case "analysis.overrides": +- outOfTestExpect(params, isAnalysisOverridesParams); +- _onAnalysisOverrides.add( +- new AnalysisOverridesParams.fromJson(decoder, 'params', param= s)); +- break; +- case "completion.results": +- outOfTestExpect(params, isCompletionResultsParams); +- _onCompletionResults.add( +- new CompletionResultsParams.fromJson(decoder, 'params', param= s)); +- break; +- case "search.results": +- outOfTestExpect(params, isSearchResultsParams); +- _onSearchResults +- .add(new SearchResultsParams.fromJson(decoder, 'params', para= ms)); +- break; +- case "execution.launchData": +- outOfTestExpect(params, isExecutionLaunchDataParams); +- _onExecutionLaunchData.add( +- new ExecutionLaunchDataParams.fromJson(decoder, 'params', par= ams)); +- break; +- default: +- fail('Unexpected notification: $event'); +- break; +- } +- } +-} +diff --git a/pkg/analysis_server/test/integration/support/integration_test= s.dart b/pkg/analysis_server/test/integration/support/integration_tests.dart +deleted file mode 100644 +index e025849a09b..00000000000 +--- a/pkg/analysis_server/test/integration/support/integration_tests.dart ++++ /dev/null +@@ -1,1003 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:path/path.dart'; +-import 'package:test/test.dart'; +- +-import 'integration_test_methods.dart'; +-import 'protocol_matchers.dart'; +- +-const Matcher isBool =3D const isInstanceOf(); +- +-const Matcher isInt =3D const isInstanceOf(); +- +-const Matcher isNotification =3D const MatchesJsonObject( +- 'notification', const {'event': isString}, +- optionalFields: const {'params': isMap}); +- +-const Matcher isObject =3D isMap; +- +-const Matcher isString =3D const isInstanceOf(); +- +-final Matcher isResponse =3D new MatchesJsonObject('response', {'id': isS= tring}, +- optionalFields: {'result': anything, 'error': isRequestError}); +- +-Matcher isListOf(Matcher elementMatcher) =3D> new _ListOf(elementMatcher); +- +-Matcher isMapOf(Matcher keyMatcher, Matcher valueMatcher) =3D> +- new _MapOf(keyMatcher, valueMatcher); +- +-Matcher isOneOf(List choiceMatchers) =3D> new _OneOf(choiceMatch= ers); +- +-/** +- * Assert that [actual] matches [matcher]. +- */ +-void outOfTestExpect(actual, matcher, +- {String reason, skip, bool verbose: false}) { +- var matchState =3D {}; +- try { +- if (matcher.matches(actual, matchState)) return; +- } catch (e, trace) { +- if (reason =3D=3D null) { +- reason =3D '${(e is String) ? e : e.toString()} at $trace'; +- } +- } +- fail(_defaultFailFormatter(actual, matcher, reason, matchState, verbose= )); +-} +- +-String _defaultFailFormatter( +- actual, Matcher matcher, String reason, Map matchState, bool verbose)= { +- var description =3D new StringDescription(); +- description.add('Expected: ').addDescriptionOf(matcher).add('\n'); +- description.add(' Actual: ').addDescriptionOf(actual).add('\n'); +- +- var mismatchDescription =3D new StringDescription(); +- matcher.describeMismatch(actual, mismatchDescription, matchState, verbo= se); +- +- if (mismatchDescription.length > 0) { +- description.add(' Which: $mismatchDescription\n'); +- } +- if (reason !=3D null) description.add(reason).add('\n'); +- return description.toString(); +-} +- +-/** +- * Type of closures used by LazyMatcher. +- */ +-typedef Matcher MatcherCreator(); +- +-/** +- * Type of closures used by MatchesJsonObject to record field mismatches. +- */ +-typedef Description MismatchDescriber(Description mismatchDescription); +- +-/** +- * Type of callbacks used to process notifications. +- */ +-typedef void NotificationProcessor(String event, params); +- +-/** +- * Base class for analysis server integration tests. +- */ +-abstract class AbstractAnalysisServerIntegrationTest +- extends IntegrationTestMixin { +- /** +- * Amount of time to give the server to respond to a shutdown request b= efore +- * forcibly terminating it. +- */ +- static const Duration SHUTDOWN_TIMEOUT =3D const Duration(seconds: 5); +- +- /** +- * Connection to the analysis server. +- */ +- final Server server =3D new Server(); +- +- /** +- * Temporary directory in which source files can be stored. +- */ +- Directory sourceDirectory; +- +- /** +- * Map from file path to the list of analysis errors which have most re= cently +- * been received for the file. +- */ +- HashMap> currentAnalysisErrors =3D +- new HashMap>(); +- +- /** +- * The last list of analyzed files received. +- */ +- List lastAnalyzedFiles; +- +- /** +- * True if the teardown process should skip sending a "server.shutdown" +- * request (e.g. because the server is known to have already shutdown). +- */ +- bool skipShutdown =3D false; +- +- /** +- * True if we are currently subscribed to [SERVER_NOTIFICATION_STATUS] = updates. +- */ +- bool _subscribedToServerStatus =3D false; +- +- AbstractAnalysisServerIntegrationTest() { +- initializeInttestMixin(); +- } +- +- /** +- * Return a future which will complete when a 'server.status' notificat= ion is +- * received from the server with 'analyzing' set to false. +- * +- * The future will only be completed by 'server.status' notifications t= hat are +- * received after this function call. So it is safe to use this getter +- * multiple times in one test; each time it is used it will wait afresh= for +- * analysis to finish. +- */ +- Future get analysisFinished { +- Completer completer =3D new Completer(); +- StreamSubscription subscription; +- // This will only work if the caller has already subscribed to +- // SERVER_STATUS (e.g. using sendServerSetSubscriptions(['STATUS'])) +- outOfTestExpect(_subscribedToServerStatus, isTrue); +- subscription =3D onServerStatus.listen((ServerStatusParams params) { +- if (params.analysis !=3D null && !params.analysis.isAnalyzing) { +- completer.complete(params); +- subscription.cancel(); +- } +- }); +- return completer.future; +- } +- +- /** +- * Print out any messages exchanged with the server. If some messages = have +- * already been exchanged with the server, they are printed out immedia= tely. +- */ +- void debugStdio() { +- server.debugStdio(); +- } +- +- List getErrors(String pathname) =3D> +- currentAnalysisErrors[pathname]; +- +- /** +- * Read a source file with the given absolute [pathname]. +- */ +- String readFile(String pathname) =3D> new File(pathname).readAsStringSy= nc(); +- +- @override +- Future sendServerSetSubscriptions(List subscriptions) { +- _subscribedToServerStatus =3D subscriptions.contains(ServerService.ST= ATUS); +- return super.sendServerSetSubscriptions(subscriptions); +- } +- +- /** +- * The server is automatically started before every test, and a tempora= ry +- * [sourceDirectory] is created. +- */ +- Future setUp() async { +- sourceDirectory =3D new Directory(Directory.systemTemp +- .createTempSync('analysisServer') +- .resolveSymbolicLinksSync()); +- +- onAnalysisErrors.listen((AnalysisErrorsParams params) { +- currentAnalysisErrors[params.file] =3D params.errors; +- }); +- onAnalysisAnalyzedFiles.listen((AnalysisAnalyzedFilesParams params) { +- lastAnalyzedFiles =3D params.directories; +- }); +- Completer serverConnected =3D new Completer(); +- onServerConnected.listen((_) { +- outOfTestExpect(serverConnected.isCompleted, isFalse); +- serverConnected.complete(); +- }); +- onServerError.listen((ServerErrorParams params) { +- // A server error should never happen during an integration test. +- fail('${params.message}\n${params.stackTrace}'); +- }); +- await startServer(); +- server.listenToOutput(dispatchNotification); +- server.exitCode.then((_) { +- skipShutdown =3D true; +- }); +- return serverConnected.future; +- } +- +- /** +- * If [skipShutdown] is not set, shut down the server. +- */ +- Future shutdownIfNeeded() { +- if (skipShutdown) { +- return new Future.value(); +- } +- // Give the server a short time to comply with the shutdown request; = if it +- // doesn't exit, then forcibly terminate it. +- sendServerShutdown(); +- return server.exitCode.timeout(SHUTDOWN_TIMEOUT, onTimeout: () { +- // The integer value of the exit code isn't used, but we have to re= turn +- // an integer to keep the typing correct. +- return server.kill('server failed to exit').then((_) =3D> -1); +- }); +- } +- +- /** +- * Convert the given [relativePath] to an absolute path, by interpretin= g it +- * relative to [sourceDirectory]. On Windows any forward slashes in +- * [relativePath] are converted to backslashes. +- */ +- String sourcePath(String relativePath) { +- return join(sourceDirectory.path, relativePath.replaceAll('/', separa= tor)); +- } +- +- /** +- * Send the server an 'analysis.setAnalysisRoots' command directing it = to +- * analyze [sourceDirectory]. If [subscribeStatus] is true (the defaul= t), +- * then also enable [SERVER_NOTIFICATION_STATUS] notifications so that +- * [analysisFinished] can be used. +- */ +- Future standardAnalysisSetup({bool subscribeStatus: true}) { +- List futures =3D []; +- if (subscribeStatus) { +- futures.add(sendServerSetSubscriptions([ServerService.STATUS])); +- } +- futures.add(sendAnalysisSetAnalysisRoots([sourceDirectory.path], [])); +- return Future.wait(futures); +- } +- +- /** +- * Start [server]. +- */ +- Future startServer({ +- bool checked: true, +- int diagnosticPort, +- int servicesPort, +- bool previewDart2: false, +- }) { +- return server.start( +- checked: checked, +- diagnosticPort: diagnosticPort, +- servicesPort: servicesPort, +- previewDart2: previewDart2); +- } +- +- /** +- * After every test, the server is stopped and [sourceDirectory] is del= eted. +- */ +- Future tearDown() { +- return shutdownIfNeeded().then((_) { +- sourceDirectory.deleteSync(recursive: true); +- }); +- } +- +- /** +- * Write a source file with the given absolute [pathname] and [contents= ]. +- * +- * If the file didn't previously exist, it is created. If it did, it is +- * overwritten. +- * +- * Parent directories are created as necessary. +- * +- * Return a normalized path to the file (with symbolic links resolved). +- */ +- String writeFile(String pathname, String contents) { +- new Directory(dirname(pathname)).createSync(recursive: true); +- File file =3D new File(pathname); +- file.writeAsStringSync(contents); +- return file.resolveSymbolicLinksSync(); +- } +-} +- +-/** +- * Wrapper class for Matcher which doesn't create the underlying Matcher = object +- * until it is needed. This is necessary in order to create matchers tha= t can +- * refer to themselves (so that recursive data structures can be represen= ted). +- */ +-class LazyMatcher implements Matcher { +- /** +- * Callback that will be used to create the matcher the first time it is +- * needed. +- */ +- final MatcherCreator _creator; +- +- /** +- * The matcher returned by [_creator], if it has already been called. +- * Otherwise null. +- */ +- Matcher _wrappedMatcher; +- +- LazyMatcher(this._creator); +- +- @override +- Description describe(Description description) { +- _createMatcher(); +- return _wrappedMatcher.describe(description); +- } +- +- @override +- Description describeMismatch( +- item, Description mismatchDescription, Map matchState, bool verbose= ) { +- _createMatcher(); +- return _wrappedMatcher.describeMismatch( +- item, mismatchDescription, matchState, verbose); +- } +- +- @override +- bool matches(item, Map matchState) { +- _createMatcher(); +- return _wrappedMatcher.matches(item, matchState); +- } +- +- /** +- * Create the wrapped matcher object, if it hasn't been created already. +- */ +- void _createMatcher() { +- if (_wrappedMatcher =3D=3D null) { +- _wrappedMatcher =3D _creator(); +- } +- } +-} +- +-/** +- * Matcher that matches a String drawn from a limited set. +- */ +-class MatchesEnum extends Matcher { +- /** +- * Short description of the expected type. +- */ +- final String description; +- +- /** +- * The set of enum values that are allowed. +- */ +- final List allowedValues; +- +- const MatchesEnum(this.description, this.allowedValues); +- +- @override +- Description describe(Description description) =3D> +- description.add(this.description); +- +- @override +- bool matches(item, Map matchState) { +- return allowedValues.contains(item); +- } +-} +- +-/** +- * Matcher that matches a JSON object, with a given set of required and +- * optional fields, and their associated types (expressed as [Matcher]s). +- */ +-class MatchesJsonObject extends _RecursiveMatcher { +- /** +- * Short description of the expected type. +- */ +- final String description; +- +- /** +- * Fields that are required to be in the JSON object, and [Matcher]s de= scribing +- * their expected types. +- */ +- final Map requiredFields; +- +- /** +- * Fields that are optional in the JSON object, and [Matcher]s describi= ng +- * their expected types. +- */ +- final Map optionalFields; +- +- const MatchesJsonObject(this.description, this.requiredFields, +- {this.optionalFields}); +- +- @override +- Description describe(Description description) =3D> +- description.add(this.description); +- +- @override +- void populateMismatches(item, List mismatches) { +- if (item is! Map) { +- mismatches.add(simpleDescription('is not a map')); +- return; +- } +- if (requiredFields !=3D null) { +- requiredFields.forEach((String key, Matcher valueMatcher) { +- if (!item.containsKey(key)) { +- mismatches.add((Description mismatchDescription) =3D> +- mismatchDescription +- .add('is missing field ') +- .addDescriptionOf(key) +- .add(' (') +- .addDescriptionOf(valueMatcher) +- .add(')')); +- } else { +- _checkField(key, item[key], valueMatcher, mismatches); +- } +- }); +- } +- item.forEach((key, value) { +- if (requiredFields !=3D null && requiredFields.containsKey(key)) { +- // Already checked this field +- } else if (optionalFields !=3D null && optionalFields.containsKey(k= ey)) { +- _checkField(key, value, optionalFields[key], mismatches); +- } else { +- mismatches.add((Description mismatchDescription) =3D> mismatchDes= cription +- .add('has unexpected field ') +- .addDescriptionOf(key)); +- } +- }); +- } +- +- /** +- * Check the type of a field called [key], having value [value], using +- * [valueMatcher]. If it doesn't match, record a closure in [mismatche= s] +- * which can describe the mismatch. +- */ +- void _checkField(String key, value, Matcher valueMatcher, +- List mismatches) { +- checkSubstructure( +- value, +- valueMatcher, +- mismatches, +- (Description description) =3D> +- description.add('field ').addDescriptionOf(key)); +- } +-} +- +-/** +- * Instances of the class [Server] manage a connection to a server proces= s, and +- * facilitate communication to and from the server. +- */ +-class Server { +- /** +- * Server process object, or null if server hasn't been started yet. +- */ +- Process _process; +- +- /** +- * Commands that have been sent to the server but not yet acknowledged,= and +- * the [Completer] objects which should be completed when acknowledgeme= nt is +- * received. +- */ +- final Map>> _pendingCommands =3D +- >>{}; +- +- /** +- * Number which should be used to compute the 'id' to send in the next = command +- * sent to the server. +- */ +- int _nextId =3D 0; +- +- /** +- * Messages which have been exchanged with the server; we buffer these +- * up until the test finishes, so that they can be examined in the debu= gger +- * or printed out in response to a call to [debugStdio]. +- */ +- final List _recordedStdio =3D []; +- +- /** +- * True if we are currently printing out messages exchanged with the se= rver. +- */ +- bool _debuggingStdio =3D false; +- +- /** +- * True if we've received bad data from the server, and we are aborting= the +- * test. +- */ +- bool _receivedBadDataFromServer =3D false; +- +- /** +- * Stopwatch that we use to generate timing information for debug outpu= t. +- */ +- Stopwatch _time =3D new Stopwatch(); +- +- /** +- * The [currentElapseTime] at which the last communication was received= from the server +- * or `null` if no communication has been received. +- */ +- double lastCommunicationTime; +- +- /** +- * The current elapse time (seconds) since the server was started. +- */ +- double get currentElapseTime =3D> _time.elapsedTicks / _time.frequency; +- +- /** +- * Future that completes when the server process exits. +- */ +- Future get exitCode =3D> _process.exitCode; +- +- /** +- * Print out any messages exchanged with the server. If some messages = have +- * already been exchanged with the server, they are printed out immedia= tely. +- */ +- void debugStdio() { +- if (_debuggingStdio) { +- return; +- } +- _debuggingStdio =3D true; +- for (String line in _recordedStdio) { +- print(line); +- } +- } +- +- /** +- * Find the root directory of the analysis_server package by proceeding +- * upward to the 'test' dir, and then going up one more directory. +- */ +- String findRoot(String pathname) { +- while (!['benchmark', 'test'].contains(basename(pathname))) { +- String parent =3D dirname(pathname); +- if (parent.length >=3D pathname.length) { +- throw new Exception("Can't find root directory"); +- } +- pathname =3D parent; +- } +- return dirname(pathname); +- } +- +- /** +- * Return a future that will complete when all commands that have been = sent +- * to the server so far have been flushed to the OS buffer. +- */ +- Future flushCommands() { +- return _process.stdin.flush(); +- } +- +- /** +- * Stop the server. +- */ +- Future kill(String reason) { +- debugStdio(); +- _recordStdio('FORCIBLY TERMINATING PROCESS: $reason'); +- _process.kill(); +- return _process.exitCode; +- } +- +- /** +- * Start listening to output from the server, and deliver notifications= to +- * [notificationProcessor]. +- */ +- void listenToOutput(NotificationProcessor notificationProcessor) { +- _process.stdout +- .transform((new Utf8Codec()).decoder) +- .transform(new LineSplitter()) +- .listen((String line) { +- lastCommunicationTime =3D currentElapseTime; +- String trimmedLine =3D line.trim(); +- if (trimmedLine.startsWith('Observatory listening on ')) { +- return; +- } +- _recordStdio('RECV: $trimmedLine'); +- var message; +- try { +- message =3D JSON.decoder.convert(trimmedLine); +- } catch (exception) { +- _badDataFromServer('JSON decode failure: $exception'); +- return; +- } +- outOfTestExpect(message, isMap); +- Map messageAsMap =3D message; +- if (messageAsMap.containsKey('id')) { +- outOfTestExpect(messageAsMap['id'], isString); +- String id =3D message['id']; +- Completer> completer =3D _pendingCommands[id= ]; +- if (completer =3D=3D null) { +- fail('Unexpected response from server: id=3D$id'); +- } else { +- _pendingCommands.remove(id); +- } +- if (messageAsMap.containsKey('error')) { +- completer.completeError(new ServerErrorMessage(messageAsMap)); +- } else { +- completer.complete(messageAsMap['result']); +- } +- // Check that the message is well-formed. We do this after calli= ng +- // completer.complete() or completer.completeError() so that we d= on't +- // stall the test in the event of an error. +- outOfTestExpect(message, isResponse); +- } else { +- // Message is a notification. It should have an event and possib= ly +- // params. +- outOfTestExpect(messageAsMap, contains('event')); +- outOfTestExpect(messageAsMap['event'], isString); +- notificationProcessor(messageAsMap['event'], messageAsMap['params= ']); +- // Check that the message is well-formed. We do this after calli= ng +- // notificationController.add() so that we don't stall the test i= n the +- // event of an error. +- outOfTestExpect(message, isNotification); +- } +- }); +- _process.stderr +- .transform((new Utf8Codec()).decoder) +- .transform(new LineSplitter()) +- .listen((String line) { +- String trimmedLine =3D line.trim(); +- _recordStdio('ERR: $trimmedLine'); +- _badDataFromServer('Message received on stderr', silent: true); +- }); +- } +- +- /** +- * Send a command to the server. An 'id' will be automatically assigne= d. +- * The returned [Future] will be completed when the server acknowledges= the +- * command with a response. If the server acknowledges the command wit= h a +- * normal (non-error) response, the future will be completed with the '= result' +- * field from the response. If the server acknowledges the command wit= h an +- * error response, the future will be completed with an error. +- */ +- Future> send( +- String method, Map params) { +- String id =3D '${_nextId++}'; +- Map command =3D { +- 'id': id, +- 'method': method +- }; +- if (params !=3D null) { +- command['params'] =3D params; +- } +- Completer> completer =3D +- new Completer>(); +- _pendingCommands[id] =3D completer; +- String line =3D JSON.encode(command); +- _recordStdio('SEND: $line'); +- _process.stdin.add(UTF8.encoder.convert("$line\n")); +- return completer.future; +- } +- +- /** +- * Start the server. If [profileServer] is `true`, the server will be s= tarted +- * with "--observe" and "--pause-isolates-on-exit", allowing the observ= atory +- * to be used. +- */ +- Future start({ +- bool checked: true, +- int diagnosticPort, +- String instrumentationLogFile, +- bool profileServer: false, +- String sdkPath, +- int servicesPort, +- bool previewDart2: false, +- bool useAnalysisHighlight2: false, +- }) async { +- if (_process !=3D null) { +- throw new Exception('Process already started'); +- } +- _time.start(); +- String dartBinary =3D Platform.executable; +- String rootDir =3D +- findRoot(Platform.script.toFilePath(windows: Platform.isWindows)); +- String serverPath =3D normalize(join(rootDir, 'bin', 'server.dart')); +- List arguments =3D []; +- // +- // Add VM arguments. +- // +- if (profileServer) { +- if (servicesPort =3D=3D null) { +- arguments.add('--observe'); +- } else { +- arguments.add('--observe=3D$servicesPort'); +- } +- arguments.add('--pause-isolates-on-exit'); +- } else if (servicesPort !=3D null) { +- arguments.add('--enable-vm-service=3D$servicesPort'); +- } +- if (Platform.packageRoot !=3D null) { +- arguments.add('--package-root=3D${Platform.packageRoot}'); +- } +- if (Platform.packageConfig !=3D null) { +- arguments.add('--packages=3D${Platform.packageConfig}'); +- } +- if (checked) { +- arguments.add('--checked'); +- } +- // +- // Add the server executable. +- // +- arguments.add(serverPath); +- // +- // Add server arguments. +- // +- arguments.add('--suppress-analytics'); +- if (diagnosticPort !=3D null) { +- arguments.add('--port'); +- arguments.add(diagnosticPort.toString()); +- } +- if (instrumentationLogFile !=3D null) { +- arguments.add('--instrumentation-log-file=3D$instrumentationLogFile= '); +- } +- if (sdkPath !=3D null) { +- arguments.add('--sdk=3D$sdkPath'); +- } +- if (useAnalysisHighlight2) { +- arguments.add('--useAnalysisHighlight2'); +- } +- if (previewDart2) { +- arguments.add('--preview-dart-2'); +- } +- // TODO(devoncarew): We could experiment with instead launching the a= nalysis +- // server in a separate isolate. This would make it easier to debug t= he +- // integration tests, and would likely speed up the tests as well. +- _process =3D await Process.start(dartBinary, arguments); +- _process.exitCode.then((int code) { +- if (code !=3D 0) { +- _badDataFromServer('server terminated with exit code $code'); +- } +- }); +- } +- +- /** +- * Deal with bad data received from the server. +- */ +- void _badDataFromServer(String details, {bool silent: false}) { +- if (!silent) { +- _recordStdio('BAD DATA FROM SERVER: $details'); +- } +- if (_receivedBadDataFromServer) { +- // We're already dealing with it. +- return; +- } +- _receivedBadDataFromServer =3D true; +- debugStdio(); +- // Give the server 1 second to continue outputting bad data before we= kill +- // the test. This is helpful if the server has had an unhandled exce= ption +- // and is outputting a stacktrace, because it ensures that we see the +- // entire stacktrace. Use expectAsync() to prevent the test from +- // ending during this 1 second. +- new Future.delayed(new Duration(seconds: 1), expectAsync0(() { +- fail('Bad data received from server: $details'); +- })); +- } +- +- /** +- * Record a message that was exchanged with the server, and print it ou= t if +- * [debugStdio] has been called. +- */ +- void _recordStdio(String line) { +- double elapsedTime =3D currentElapseTime; +- line =3D "$elapsedTime: $line"; +- if (_debuggingStdio) { +- print(line); +- } +- _recordedStdio.add(line); +- } +-} +- +-/** +- * An error result from a server request. +- */ +-class ServerErrorMessage { +- final Map message; +- +- ServerErrorMessage(this.message); +- +- dynamic get error =3D> message['error']; +- +- String toString() =3D> message.toString(); +-} +- +-/** +- * Matcher that matches a list of objects, each of which satisfies the gi= ven +- * matcher. +- */ +-class _ListOf extends Matcher { +- /** +- * Matcher which every element of the list must satisfy. +- */ +- final Matcher elementMatcher; +- +- /** +- * Iterable matcher which we use to test the contents of the list. +- */ +- final Matcher iterableMatcher; +- +- _ListOf(elementMatcher) +- : elementMatcher =3D elementMatcher, +- iterableMatcher =3D everyElement(elementMatcher); +- +- @override +- Description describe(Description description) =3D> +- description.add('List of ').addDescriptionOf(elementMatcher); +- +- @override +- Description describeMismatch( +- item, Description mismatchDescription, Map matchState, bool verbose= ) { +- if (item is! List) { +- return super +- .describeMismatch(item, mismatchDescription, matchState, verbos= e); +- } else { +- return iterableMatcher.describeMismatch( +- item, mismatchDescription, matchState, verbose); +- } +- } +- +- @override +- bool matches(item, Map matchState) { +- if (item is! List) { +- return false; +- } +- return iterableMatcher.matches(item, matchState); +- } +-} +- +-/** +- * Matcher that matches a map of objects, where each key/value pair in the +- * map satisies the given key and value matchers. +- */ +-class _MapOf extends _RecursiveMatcher { +- /** +- * Matcher which every key in the map must satisfy. +- */ +- final Matcher keyMatcher; +- +- /** +- * Matcher which every value in the map must satisfy. +- */ +- final Matcher valueMatcher; +- +- _MapOf(this.keyMatcher, this.valueMatcher); +- +- @override +- Description describe(Description description) =3D> description +- .add('Map from ') +- .addDescriptionOf(keyMatcher) +- .add(' to ') +- .addDescriptionOf(valueMatcher); +- +- @override +- void populateMismatches(item, List mismatches) { +- if (item is! Map) { +- mismatches.add(simpleDescription('is not a map')); +- return; +- } +- item.forEach((key, value) { +- checkSubstructure( +- key, +- keyMatcher, +- mismatches, +- (Description description) =3D> +- description.add('key ').addDescriptionOf(key)); +- checkSubstructure( +- value, +- valueMatcher, +- mismatches, +- (Description description) =3D> +- description.add('field ').addDescriptionOf(key)); +- }); +- } +-} +- +-/** +- * Matcher that matches a union of different types, each of which is desc= ribed +- * by a matcher. +- */ +-class _OneOf extends Matcher { +- /** +- * Matchers for the individual choices. +- */ +- final List choiceMatchers; +- +- _OneOf(this.choiceMatchers); +- +- @override +- Description describe(Description description) { +- for (int i =3D 0; i < choiceMatchers.length; i++) { +- if (i !=3D 0) { +- if (choiceMatchers.length =3D=3D 2) { +- description =3D description.add(' or '); +- } else { +- description =3D description.add(', '); +- if (i =3D=3D choiceMatchers.length - 1) { +- description =3D description.add('or '); +- } +- } +- } +- description =3D description.addDescriptionOf(choiceMatchers[i]); +- } +- return description; +- } +- +- @override +- bool matches(item, Map matchState) { +- for (Matcher choiceMatcher in choiceMatchers) { +- Map subState =3D {}; +- if (choiceMatcher.matches(item, subState)) { +- return true; +- } +- } +- return false; +- } +-} +- +-/** +- * Base class for matchers that operate by recursing through the contents= of +- * an object. +- */ +-abstract class _RecursiveMatcher extends Matcher { +- const _RecursiveMatcher(); +- +- /** +- * Check the type of a substructure whose value is [item], using [match= er]. +- * If it doesn't match, record a closure in [mismatches] which can desc= ribe +- * the mismatch. [describeSubstructure] is used to describe which +- * substructure did not match. +- */ +- checkSubstructure(item, Matcher matcher, List mismat= ches, +- Description describeSubstructure(Description description)) { +- Map subState =3D {}; +- if (!matcher.matches(item, subState)) { +- mismatches.add((Description mismatchDescription) { +- mismatchDescription =3D mismatchDescription.add('contains malform= ed '); +- mismatchDescription =3D describeSubstructure(mismatchDescription); +- mismatchDescription =3D +- mismatchDescription.add(' (should be ').addDescriptionOf(matc= her); +- String subDescription =3D matcher +- .describeMismatch(item, new StringDescription(), subState, fa= lse) +- .toString(); +- if (subDescription.isNotEmpty) { +- mismatchDescription =3D +- mismatchDescription.add('; ').add(subDescription); +- } +- return mismatchDescription.add(')'); +- }); +- } +- } +- +- @override +- Description describeMismatch( +- item, Description mismatchDescription, Map matchState, bool verbose= ) { +- List mismatches =3D +- matchState['mismatches'] as List; +- if (mismatches !=3D null) { +- for (int i =3D 0; i < mismatches.length; i++) { +- MismatchDescriber mismatch =3D mismatches[i]; +- if (i > 0) { +- if (mismatches.length =3D=3D 2) { +- mismatchDescription =3D mismatchDescription.add(' and '); +- } else if (i =3D=3D mismatches.length - 1) { +- mismatchDescription =3D mismatchDescription.add(', and '); +- } else { +- mismatchDescription =3D mismatchDescription.add(', '); +- } +- } +- mismatchDescription =3D mismatch(mismatchDescription); +- } +- return mismatchDescription; +- } else { +- return super +- .describeMismatch(item, mismatchDescription, matchState, verbos= e); +- } +- } +- +- @override +- bool matches(item, Map matchState) { +- List mismatches =3D []; +- populateMismatches(item, mismatches); +- if (mismatches.isEmpty) { +- return true; +- } else { +- addStateInfo(matchState, {'mismatches': mismatches}); +- return false; +- } +- } +- +- /** +- * Populate [mismatches] with descriptions of all the ways in which [it= em] +- * does not match. +- */ +- void populateMismatches(item, List mismatches); +- +- /** +- * Create a [MismatchDescriber] describing a mismatch with a simple str= ing. +- */ +- MismatchDescriber simpleDescription(String description) =3D> +- (Description mismatchDescription) { +- mismatchDescription.add(description); +- }; +-} +diff --git a/pkg/analysis_server/test/integration/support/protocol_matcher= s.dart b/pkg/analysis_server/test/integration/support/protocol_matchers.dart +deleted file mode 100644 +index 53e4f7c0ae6..00000000000 +--- a/pkg/analysis_server/test/integration/support/protocol_matchers.dart ++++ /dev/null +@@ -1,2644 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +-// +-// This file has been automatically generated. Please do not edit it man= ually. +-// To regenerate the file, use the script +-// "pkg/analysis_server/tool/spec/generate_files". +- +-/** +- * Matchers for data types defined in the analysis server API +- */ +-import 'package:test/test.dart'; +- +-import 'integration_tests.dart'; +- +-/** +- * AddContentOverlay +- * +- * { +- * "type": "add" +- * "content": String +- * } +- */ +-final Matcher isAddContentOverlay =3D new LazyMatcher(() =3D> new Matches= JsonObject( +- "AddContentOverlay", {"type": equals("add"), "content": isString})); +- +-/** +- * AnalysisError +- * +- * { +- * "severity": AnalysisErrorSeverity +- * "type": AnalysisErrorType +- * "location": Location +- * "message": String +- * "correction": optional String +- * "code": String +- * "hasFix": optional bool +- * } +- */ +-final Matcher isAnalysisError =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("AnalysisError", { +- "severity": isAnalysisErrorSeverity, +- "type": isAnalysisErrorType, +- "location": isLocation, +- "message": isString, +- "code": isString +- }, optionalFields: { +- "correction": isString, +- "hasFix": isBool +- })); +- +-/** +- * AnalysisErrorFixes +- * +- * { +- * "error": AnalysisError +- * "fixes": List +- * } +- */ +-final Matcher isAnalysisErrorFixes =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("AnalysisErrorFixes", +- {"error": isAnalysisError, "fixes": isListOf(isSourceChange)})); +- +-/** +- * AnalysisErrorSeverity +- * +- * enum { +- * INFO +- * WARNING +- * ERROR +- * } +- */ +-final Matcher isAnalysisErrorSeverity =3D +- new MatchesEnum("AnalysisErrorSeverity", ["INFO", "WARNING", "ERROR"]= ); +- +-/** +- * AnalysisErrorType +- * +- * enum { +- * CHECKED_MODE_COMPILE_TIME_ERROR +- * COMPILE_TIME_ERROR +- * HINT +- * LINT +- * STATIC_TYPE_WARNING +- * STATIC_WARNING +- * SYNTACTIC_ERROR +- * TODO +- * } +- */ +-final Matcher isAnalysisErrorType =3D new MatchesEnum("AnalysisErrorType"= , [ +- "CHECKED_MODE_COMPILE_TIME_ERROR", +- "COMPILE_TIME_ERROR", +- "HINT", +- "LINT", +- "STATIC_TYPE_WARNING", +- "STATIC_WARNING", +- "SYNTACTIC_ERROR", +- "TODO" +-]); +- +-/** +- * AnalysisOptions +- * +- * { +- * "enableAsync": optional bool +- * "enableDeferredLoading": optional bool +- * "enableEnums": optional bool +- * "enableNullAwareOperators": optional bool +- * "enableSuperMixins": optional bool +- * "generateDart2jsHints": optional bool +- * "generateHints": optional bool +- * "generateLints": optional bool +- * } +- */ +-final Matcher isAnalysisOptions =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("AnalysisOptions", null, optionalFields= : { +- "enableAsync": isBool, +- "enableDeferredLoading": isBool, +- "enableEnums": isBool, +- "enableNullAwareOperators": isBool, +- "enableSuperMixins": isBool, +- "generateDart2jsHints": isBool, +- "generateHints": isBool, +- "generateLints": isBool +- })); +- +-/** +- * AnalysisService +- * +- * enum { +- * CLOSING_LABELS +- * FOLDING +- * HIGHLIGHTS +- * IMPLEMENTED +- * INVALIDATE +- * NAVIGATION +- * OCCURRENCES +- * OUTLINE +- * OVERRIDES +- * } +- */ +-final Matcher isAnalysisService =3D new MatchesEnum("AnalysisService", [ +- "CLOSING_LABELS", +- "FOLDING", +- "HIGHLIGHTS", +- "IMPLEMENTED", +- "INVALIDATE", +- "NAVIGATION", +- "OCCURRENCES", +- "OUTLINE", +- "OVERRIDES" +-]); +- +-/** +- * AnalysisStatus +- * +- * { +- * "isAnalyzing": bool +- * "analysisTarget": optional String +- * } +- */ +-final Matcher isAnalysisStatus =3D new LazyMatcher(() =3D> new MatchesJso= nObject( +- "AnalysisStatus", {"isAnalyzing": isBool}, +- optionalFields: {"analysisTarget": isString})); +- +-/** +- * ChangeContentOverlay +- * +- * { +- * "type": "change" +- * "edits": List +- * } +- */ +-final Matcher isChangeContentOverlay =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("ChangeContentOverlay", +- {"type": equals("change"), "edits": isListOf(isSourceEdit)})); +- +-/** +- * ClosingLabel +- * +- * { +- * "offset": int +- * "length": int +- * "label": String +- * } +- */ +-final Matcher isClosingLabel =3D new LazyMatcher(() =3D> new MatchesJsonO= bject( +- "ClosingLabel", {"offset": isInt, "length": isInt, "label": isString}= )); +- +-/** +- * CompletionId +- * +- * String +- */ +-final Matcher isCompletionId =3D isString; +- +-/** +- * CompletionSuggestion +- * +- * { +- * "kind": CompletionSuggestionKind +- * "relevance": int +- * "completion": String +- * "selectionOffset": int +- * "selectionLength": int +- * "isDeprecated": bool +- * "isPotential": bool +- * "docSummary": optional String +- * "docComplete": optional String +- * "declaringType": optional String +- * "defaultArgumentListString": optional String +- * "defaultArgumentListTextRanges": optional List +- * "element": optional Element +- * "returnType": optional String +- * "parameterNames": optional List +- * "parameterTypes": optional List +- * "requiredParameterCount": optional int +- * "hasNamedParameters": optional bool +- * "parameterName": optional String +- * "parameterType": optional String +- * "importUri": optional String +- * } +- */ +-final Matcher isCompletionSuggestion =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("CompletionSuggestion",= { +- "kind": isCompletionSuggestionKind, +- "relevance": isInt, +- "completion": isString, +- "selectionOffset": isInt, +- "selectionLength": isInt, +- "isDeprecated": isBool, +- "isPotential": isBool +- }, optionalFields: { +- "docSummary": isString, +- "docComplete": isString, +- "declaringType": isString, +- "defaultArgumentListString": isString, +- "defaultArgumentListTextRanges": isListOf(isInt), +- "element": isElement, +- "returnType": isString, +- "parameterNames": isListOf(isString), +- "parameterTypes": isListOf(isString), +- "requiredParameterCount": isInt, +- "hasNamedParameters": isBool, +- "parameterName": isString, +- "parameterType": isString, +- "importUri": isString +- })); +- +-/** +- * CompletionSuggestionKind +- * +- * enum { +- * ARGUMENT_LIST +- * IMPORT +- * IDENTIFIER +- * INVOCATION +- * KEYWORD +- * NAMED_ARGUMENT +- * OPTIONAL_ARGUMENT +- * PARAMETER +- * } +- */ +-final Matcher isCompletionSuggestionKind =3D +- new MatchesEnum("CompletionSuggestionKind", [ +- "ARGUMENT_LIST", +- "IMPORT", +- "IDENTIFIER", +- "INVOCATION", +- "KEYWORD", +- "NAMED_ARGUMENT", +- "OPTIONAL_ARGUMENT", +- "PARAMETER" +-]); +- +-/** +- * ContextData +- * +- * { +- * "name": String +- * "explicitFileCount": int +- * "implicitFileCount": int +- * "workItemQueueLength": int +- * "cacheEntryExceptions": List +- * } +- */ +-final Matcher isContextData =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("ContextData", { +- "name": isString, +- "explicitFileCount": isInt, +- "implicitFileCount": isInt, +- "workItemQueueLength": isInt, +- "cacheEntryExceptions": isListOf(isString) +- })); +- +-/** +- * Element +- * +- * { +- * "kind": ElementKind +- * "name": String +- * "location": optional Location +- * "flags": int +- * "parameters": optional String +- * "returnType": optional String +- * "typeParameters": optional String +- * } +- */ +-final Matcher isElement =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("Element", { +- "kind": isElementKind, +- "name": isString, +- "flags": isInt +- }, optionalFields: { +- "location": isLocation, +- "parameters": isString, +- "returnType": isString, +- "typeParameters": isString +- })); +- +-/** +- * ElementKind +- * +- * enum { +- * CLASS +- * CLASS_TYPE_ALIAS +- * COMPILATION_UNIT +- * CONSTRUCTOR +- * CONSTRUCTOR_INVOCATION +- * ENUM +- * ENUM_CONSTANT +- * FIELD +- * FILE +- * FUNCTION +- * FUNCTION_INVOCATION +- * FUNCTION_TYPE_ALIAS +- * GETTER +- * LABEL +- * LIBRARY +- * LOCAL_VARIABLE +- * METHOD +- * PARAMETER +- * PREFIX +- * SETTER +- * TOP_LEVEL_VARIABLE +- * TYPE_PARAMETER +- * UNIT_TEST_GROUP +- * UNIT_TEST_TEST +- * UNKNOWN +- * } +- */ +-final Matcher isElementKind =3D new MatchesEnum("ElementKind", [ +- "CLASS", +- "CLASS_TYPE_ALIAS", +- "COMPILATION_UNIT", +- "CONSTRUCTOR", +- "CONSTRUCTOR_INVOCATION", +- "ENUM", +- "ENUM_CONSTANT", +- "FIELD", +- "FILE", +- "FUNCTION", +- "FUNCTION_INVOCATION", +- "FUNCTION_TYPE_ALIAS", +- "GETTER", +- "LABEL", +- "LIBRARY", +- "LOCAL_VARIABLE", +- "METHOD", +- "PARAMETER", +- "PREFIX", +- "SETTER", +- "TOP_LEVEL_VARIABLE", +- "TYPE_PARAMETER", +- "UNIT_TEST_GROUP", +- "UNIT_TEST_TEST", +- "UNKNOWN" +-]); +- +-/** +- * ExecutableFile +- * +- * { +- * "file": FilePath +- * "kind": ExecutableKind +- * } +- */ +-final Matcher isExecutableFile =3D new LazyMatcher(() =3D> new MatchesJso= nObject( +- "ExecutableFile", {"file": isFilePath, "kind": isExecutableKind})); +- +-/** +- * ExecutableKind +- * +- * enum { +- * CLIENT +- * EITHER +- * NOT_EXECUTABLE +- * SERVER +- * } +- */ +-final Matcher isExecutableKind =3D new MatchesEnum( +- "ExecutableKind", ["CLIENT", "EITHER", "NOT_EXECUTABLE", "SERVER"]); +- +-/** +- * ExecutionContextId +- * +- * String +- */ +-final Matcher isExecutionContextId =3D isString; +- +-/** +- * ExecutionService +- * +- * enum { +- * LAUNCH_DATA +- * } +- */ +-final Matcher isExecutionService =3D +- new MatchesEnum("ExecutionService", ["LAUNCH_DATA"]); +- +-/** +- * FileKind +- * +- * enum { +- * LIBRARY +- * PART +- * } +- */ +-final Matcher isFileKind =3D new MatchesEnum("FileKind", ["LIBRARY", "PAR= T"]); +- +-/** +- * FilePath +- * +- * String +- */ +-final Matcher isFilePath =3D isString; +- +-/** +- * FoldingKind +- * +- * enum { +- * COMMENT +- * CLASS_MEMBER +- * DIRECTIVES +- * DOCUMENTATION_COMMENT +- * TOP_LEVEL_DECLARATION +- * } +- */ +-final Matcher isFoldingKind =3D new MatchesEnum("FoldingKind", [ +- "COMMENT", +- "CLASS_MEMBER", +- "DIRECTIVES", +- "DOCUMENTATION_COMMENT", +- "TOP_LEVEL_DECLARATION" +-]); +- +-/** +- * FoldingRegion +- * +- * { +- * "kind": FoldingKind +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isFoldingRegion =3D new LazyMatcher(() =3D> new MatchesJson= Object( +- "FoldingRegion", +- {"kind": isFoldingKind, "offset": isInt, "length": isInt})); +- +-/** +- * GeneralAnalysisService +- * +- * enum { +- * ANALYZED_FILES +- * } +- */ +-final Matcher isGeneralAnalysisService =3D +- new MatchesEnum("GeneralAnalysisService", ["ANALYZED_FILES"]); +- +-/** +- * HighlightRegion +- * +- * { +- * "type": HighlightRegionType +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isHighlightRegion =3D new LazyMatcher(() =3D> new MatchesJs= onObject( +- "HighlightRegion", +- {"type": isHighlightRegionType, "offset": isInt, "length": isInt})); +- +-/** +- * HighlightRegionType +- * +- * enum { +- * ANNOTATION +- * BUILT_IN +- * CLASS +- * COMMENT_BLOCK +- * COMMENT_DOCUMENTATION +- * COMMENT_END_OF_LINE +- * CONSTRUCTOR +- * DIRECTIVE +- * DYNAMIC_TYPE +- * DYNAMIC_LOCAL_VARIABLE_DECLARATION +- * DYNAMIC_LOCAL_VARIABLE_REFERENCE +- * DYNAMIC_PARAMETER_DECLARATION +- * DYNAMIC_PARAMETER_REFERENCE +- * ENUM +- * ENUM_CONSTANT +- * FIELD +- * FIELD_STATIC +- * FUNCTION +- * FUNCTION_DECLARATION +- * FUNCTION_TYPE_ALIAS +- * GETTER_DECLARATION +- * IDENTIFIER_DEFAULT +- * IMPORT_PREFIX +- * INSTANCE_FIELD_DECLARATION +- * INSTANCE_FIELD_REFERENCE +- * INSTANCE_GETTER_DECLARATION +- * INSTANCE_GETTER_REFERENCE +- * INSTANCE_METHOD_DECLARATION +- * INSTANCE_METHOD_REFERENCE +- * INSTANCE_SETTER_DECLARATION +- * INSTANCE_SETTER_REFERENCE +- * INVALID_STRING_ESCAPE +- * KEYWORD +- * LABEL +- * LIBRARY_NAME +- * LITERAL_BOOLEAN +- * LITERAL_DOUBLE +- * LITERAL_INTEGER +- * LITERAL_LIST +- * LITERAL_MAP +- * LITERAL_STRING +- * LOCAL_FUNCTION_DECLARATION +- * LOCAL_FUNCTION_REFERENCE +- * LOCAL_VARIABLE +- * LOCAL_VARIABLE_DECLARATION +- * LOCAL_VARIABLE_REFERENCE +- * METHOD +- * METHOD_DECLARATION +- * METHOD_DECLARATION_STATIC +- * METHOD_STATIC +- * PARAMETER +- * SETTER_DECLARATION +- * TOP_LEVEL_VARIABLE +- * PARAMETER_DECLARATION +- * PARAMETER_REFERENCE +- * STATIC_FIELD_DECLARATION +- * STATIC_GETTER_DECLARATION +- * STATIC_GETTER_REFERENCE +- * STATIC_METHOD_DECLARATION +- * STATIC_METHOD_REFERENCE +- * STATIC_SETTER_DECLARATION +- * STATIC_SETTER_REFERENCE +- * TOP_LEVEL_FUNCTION_DECLARATION +- * TOP_LEVEL_FUNCTION_REFERENCE +- * TOP_LEVEL_GETTER_DECLARATION +- * TOP_LEVEL_GETTER_REFERENCE +- * TOP_LEVEL_SETTER_DECLARATION +- * TOP_LEVEL_SETTER_REFERENCE +- * TOP_LEVEL_VARIABLE_DECLARATION +- * TYPE_NAME_DYNAMIC +- * TYPE_PARAMETER +- * UNRESOLVED_INSTANCE_MEMBER_REFERENCE +- * VALID_STRING_ESCAPE +- * } +- */ +-final Matcher isHighlightRegionType =3D new MatchesEnum("HighlightRegionT= ype", [ +- "ANNOTATION", +- "BUILT_IN", +- "CLASS", +- "COMMENT_BLOCK", +- "COMMENT_DOCUMENTATION", +- "COMMENT_END_OF_LINE", +- "CONSTRUCTOR", +- "DIRECTIVE", +- "DYNAMIC_TYPE", +- "DYNAMIC_LOCAL_VARIABLE_DECLARATION", +- "DYNAMIC_LOCAL_VARIABLE_REFERENCE", +- "DYNAMIC_PARAMETER_DECLARATION", +- "DYNAMIC_PARAMETER_REFERENCE", +- "ENUM", +- "ENUM_CONSTANT", +- "FIELD", +- "FIELD_STATIC", +- "FUNCTION", +- "FUNCTION_DECLARATION", +- "FUNCTION_TYPE_ALIAS", +- "GETTER_DECLARATION", +- "IDENTIFIER_DEFAULT", +- "IMPORT_PREFIX", +- "INSTANCE_FIELD_DECLARATION", +- "INSTANCE_FIELD_REFERENCE", +- "INSTANCE_GETTER_DECLARATION", +- "INSTANCE_GETTER_REFERENCE", +- "INSTANCE_METHOD_DECLARATION", +- "INSTANCE_METHOD_REFERENCE", +- "INSTANCE_SETTER_DECLARATION", +- "INSTANCE_SETTER_REFERENCE", +- "INVALID_STRING_ESCAPE", +- "KEYWORD", +- "LABEL", +- "LIBRARY_NAME", +- "LITERAL_BOOLEAN", +- "LITERAL_DOUBLE", +- "LITERAL_INTEGER", +- "LITERAL_LIST", +- "LITERAL_MAP", +- "LITERAL_STRING", +- "LOCAL_FUNCTION_DECLARATION", +- "LOCAL_FUNCTION_REFERENCE", +- "LOCAL_VARIABLE", +- "LOCAL_VARIABLE_DECLARATION", +- "LOCAL_VARIABLE_REFERENCE", +- "METHOD", +- "METHOD_DECLARATION", +- "METHOD_DECLARATION_STATIC", +- "METHOD_STATIC", +- "PARAMETER", +- "SETTER_DECLARATION", +- "TOP_LEVEL_VARIABLE", +- "PARAMETER_DECLARATION", +- "PARAMETER_REFERENCE", +- "STATIC_FIELD_DECLARATION", +- "STATIC_GETTER_DECLARATION", +- "STATIC_GETTER_REFERENCE", +- "STATIC_METHOD_DECLARATION", +- "STATIC_METHOD_REFERENCE", +- "STATIC_SETTER_DECLARATION", +- "STATIC_SETTER_REFERENCE", +- "TOP_LEVEL_FUNCTION_DECLARATION", +- "TOP_LEVEL_FUNCTION_REFERENCE", +- "TOP_LEVEL_GETTER_DECLARATION", +- "TOP_LEVEL_GETTER_REFERENCE", +- "TOP_LEVEL_SETTER_DECLARATION", +- "TOP_LEVEL_SETTER_REFERENCE", +- "TOP_LEVEL_VARIABLE_DECLARATION", +- "TYPE_NAME_DYNAMIC", +- "TYPE_PARAMETER", +- "UNRESOLVED_INSTANCE_MEMBER_REFERENCE", +- "VALID_STRING_ESCAPE" +-]); +- +-/** +- * HoverInformation +- * +- * { +- * "offset": int +- * "length": int +- * "containingLibraryPath": optional String +- * "containingLibraryName": optional String +- * "containingClassDescription": optional String +- * "dartdoc": optional String +- * "elementDescription": optional String +- * "elementKind": optional String +- * "isDeprecated": optional bool +- * "parameter": optional String +- * "propagatedType": optional String +- * "staticType": optional String +- * } +- */ +-final Matcher isHoverInformation =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("HoverInformation", { +- "offset": isInt, +- "length": isInt +- }, optionalFields: { +- "containingLibraryPath": isString, +- "containingLibraryName": isString, +- "containingClassDescription": isString, +- "dartdoc": isString, +- "elementDescription": isString, +- "elementKind": isString, +- "isDeprecated": isBool, +- "parameter": isString, +- "propagatedType": isString, +- "staticType": isString +- })); +- +-/** +- * ImplementedClass +- * +- * { +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isImplementedClass =3D new LazyMatcher(() =3D> new MatchesJ= sonObject( +- "ImplementedClass", {"offset": isInt, "length": isInt})); +- +-/** +- * ImplementedMember +- * +- * { +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isImplementedMember =3D new LazyMatcher(() =3D> new Matches= JsonObject( +- "ImplementedMember", {"offset": isInt, "length": isInt})); +- +-/** +- * ImportedElements +- * +- * { +- * "path": FilePath +- * "prefix": String +- * "elements": List +- * } +- */ +-final Matcher isImportedElements =3D new LazyMatcher(() =3D> new MatchesJ= sonObject( +- "ImportedElements", +- {"path": isFilePath, "prefix": isString, "elements": isListOf(isStrin= g)})); +- +-/** +- * KytheEntry +- * +- * { +- * "source": KytheVName +- * "kind": optional String +- * "target": optional KytheVName +- * "fact": String +- * "value": optional List +- * } +- */ +-final Matcher isKytheEntry =3D new LazyMatcher(() =3D> new MatchesJsonObj= ect( +- "KytheEntry", { +- "source": isKytheVName, +- "fact": isString +- }, optionalFields: { +- "kind": isString, +- "target": isKytheVName, +- "value": isListOf(isInt) +- })); +- +-/** +- * KytheVName +- * +- * { +- * "signature": String +- * "corpus": String +- * "root": String +- * "path": String +- * "language": String +- * } +- */ +-final Matcher isKytheVName =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("KytheVName", { +- "signature": isString, +- "corpus": isString, +- "root": isString, +- "path": isString, +- "language": isString +- })); +- +-/** +- * LinkedEditGroup +- * +- * { +- * "positions": List +- * "length": int +- * "suggestions": List +- * } +- */ +-final Matcher isLinkedEditGroup =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("LinkedEditGroup", { +- "positions": isListOf(isPosition), +- "length": isInt, +- "suggestions": isListOf(isLinkedEditSuggestion) +- })); +- +-/** +- * LinkedEditSuggestion +- * +- * { +- * "value": String +- * "kind": LinkedEditSuggestionKind +- * } +- */ +-final Matcher isLinkedEditSuggestion =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("LinkedEditSuggestion", +- {"value": isString, "kind": isLinkedEditSuggestionKind})); +- +-/** +- * LinkedEditSuggestionKind +- * +- * enum { +- * METHOD +- * PARAMETER +- * TYPE +- * VARIABLE +- * } +- */ +-final Matcher isLinkedEditSuggestionKind =3D new MatchesEnum( +- "LinkedEditSuggestionKind", ["METHOD", "PARAMETER", "TYPE", "VARIABLE= "]); +- +-/** +- * Location +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * "startLine": int +- * "startColumn": int +- * } +- */ +-final Matcher isLocation =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("Location", { +- "file": isFilePath, +- "offset": isInt, +- "length": isInt, +- "startLine": isInt, +- "startColumn": isInt +- })); +- +-/** +- * NavigationRegion +- * +- * { +- * "offset": int +- * "length": int +- * "targets": List +- * } +- */ +-final Matcher isNavigationRegion =3D new LazyMatcher(() =3D> new MatchesJ= sonObject( +- "NavigationRegion", +- {"offset": isInt, "length": isInt, "targets": isListOf(isInt)})); +- +-/** +- * NavigationTarget +- * +- * { +- * "kind": ElementKind +- * "fileIndex": int +- * "offset": int +- * "length": int +- * "startLine": int +- * "startColumn": int +- * } +- */ +-final Matcher isNavigationTarget =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("NavigationTarget", { +- "kind": isElementKind, +- "fileIndex": isInt, +- "offset": isInt, +- "length": isInt, +- "startLine": isInt, +- "startColumn": isInt +- })); +- +-/** +- * Occurrences +- * +- * { +- * "element": Element +- * "offsets": List +- * "length": int +- * } +- */ +-final Matcher isOccurrences =3D new LazyMatcher(() =3D> new MatchesJsonOb= ject( +- "Occurrences", +- {"element": isElement, "offsets": isListOf(isInt), "length": isInt})); +- +-/** +- * Outline +- * +- * { +- * "element": Element +- * "offset": int +- * "length": int +- * "children": optional List +- * } +- */ +-final Matcher isOutline =3D new LazyMatcher(() =3D> new MatchesJsonObject( +- "Outline", {"element": isElement, "offset": isInt, "length": isInt}, +- optionalFields: {"children": isListOf(isOutline)})); +- +-/** +- * OverriddenMember +- * +- * { +- * "element": Element +- * "className": String +- * } +- */ +-final Matcher isOverriddenMember =3D new LazyMatcher(() =3D> new MatchesJ= sonObject( +- "OverriddenMember", {"element": isElement, "className": isString})); +- +-/** +- * Override +- * +- * { +- * "offset": int +- * "length": int +- * "superclassMember": optional OverriddenMember +- * "interfaceMembers": optional List +- * } +- */ +-final Matcher isOverride =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("Override", { +- "offset": isInt, +- "length": isInt +- }, optionalFields: { +- "superclassMember": isOverriddenMember, +- "interfaceMembers": isListOf(isOverriddenMember) +- })); +- +-/** +- * Position +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- */ +-final Matcher isPosition =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("Position", {"file": isFilePath, "offset": isIn= t})); +- +-/** +- * PostfixTemplateDescriptor +- * +- * { +- * "name": String +- * "key": String +- * "example": String +- * } +- */ +-final Matcher isPostfixTemplateDescriptor =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("PostfixTemplateDescriptor", +- {"name": isString, "key": isString, "example": isString})); +- +-/** +- * PubStatus +- * +- * { +- * "isListingPackageDirs": bool +- * } +- */ +-final Matcher isPubStatus =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("PubStatus", {"isListingPackageDirs": i= sBool})); +- +-/** +- * RefactoringFeedback +- * +- * { +- * } +- */ +-final Matcher isRefactoringFeedback =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("RefactoringFeedback", = null)); +- +-/** +- * RefactoringKind +- * +- * enum { +- * CONVERT_GETTER_TO_METHOD +- * CONVERT_METHOD_TO_GETTER +- * EXTRACT_LOCAL_VARIABLE +- * EXTRACT_METHOD +- * INLINE_LOCAL_VARIABLE +- * INLINE_METHOD +- * MOVE_FILE +- * RENAME +- * SORT_MEMBERS +- * } +- */ +-final Matcher isRefactoringKind =3D new MatchesEnum("RefactoringKind", [ +- "CONVERT_GETTER_TO_METHOD", +- "CONVERT_METHOD_TO_GETTER", +- "EXTRACT_LOCAL_VARIABLE", +- "EXTRACT_METHOD", +- "INLINE_LOCAL_VARIABLE", +- "INLINE_METHOD", +- "MOVE_FILE", +- "RENAME", +- "SORT_MEMBERS" +-]); +- +-/** +- * RefactoringMethodParameter +- * +- * { +- * "id": optional String +- * "kind": RefactoringMethodParameterKind +- * "type": String +- * "name": String +- * "parameters": optional String +- * } +- */ +-final Matcher isRefactoringMethodParameter =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("RefactoringMethodParameter", { +- "kind": isRefactoringMethodParameterKind, +- "type": isString, +- "name": isString +- }, optionalFields: { +- "id": isString, +- "parameters": isString +- })); +- +-/** +- * RefactoringMethodParameterKind +- * +- * enum { +- * REQUIRED +- * POSITIONAL +- * NAMED +- * } +- */ +-final Matcher isRefactoringMethodParameterKind =3D new MatchesEnum( +- "RefactoringMethodParameterKind", ["REQUIRED", "POSITIONAL", "NAMED"]= ); +- +-/** +- * RefactoringOptions +- * +- * { +- * } +- */ +-final Matcher isRefactoringOptions =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("RefactoringOptions", n= ull)); +- +-/** +- * RefactoringProblem +- * +- * { +- * "severity": RefactoringProblemSeverity +- * "message": String +- * "location": optional Location +- * } +- */ +-final Matcher isRefactoringProblem =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("RefactoringProblem", +- {"severity": isRefactoringProblemSeverity, "message": isString}, +- optionalFields: {"location": isLocation})); +- +-/** +- * RefactoringProblemSeverity +- * +- * enum { +- * INFO +- * WARNING +- * ERROR +- * FATAL +- * } +- */ +-final Matcher isRefactoringProblemSeverity =3D new MatchesEnum( +- "RefactoringProblemSeverity", ["INFO", "WARNING", "ERROR", "FATAL"]); +- +-/** +- * RemoveContentOverlay +- * +- * { +- * "type": "remove" +- * } +- */ +-final Matcher isRemoveContentOverlay =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("RemoveContentOverlay", {"type": equals("remove= ")})); +- +-/** +- * RequestError +- * +- * { +- * "code": RequestErrorCode +- * "message": String +- * "stackTrace": optional String +- * } +- */ +-final Matcher isRequestError =3D new LazyMatcher(() =3D> new MatchesJsonO= bject( +- "RequestError", {"code": isRequestErrorCode, "message": isString}, +- optionalFields: {"stackTrace": isString})); +- +-/** +- * RequestErrorCode +- * +- * enum { +- * CONTENT_MODIFIED +- * DEBUG_PORT_COULD_NOT_BE_OPENED +- * FILE_NOT_ANALYZED +- * FORMAT_INVALID_FILE +- * FORMAT_WITH_ERRORS +- * GET_ERRORS_INVALID_FILE +- * GET_IMPORTED_ELEMENTS_INVALID_FILE +- * GET_KYTHE_ENTRIES_INVALID_FILE +- * GET_NAVIGATION_INVALID_FILE +- * GET_REACHABLE_SOURCES_INVALID_FILE +- * IMPORT_ELEMENTS_INVALID_FILE +- * INVALID_ANALYSIS_ROOT +- * INVALID_EXECUTION_CONTEXT +- * INVALID_FILE_PATH_FORMAT +- * INVALID_OVERLAY_CHANGE +- * INVALID_PARAMETER +- * INVALID_REQUEST +- * ORGANIZE_DIRECTIVES_ERROR +- * REFACTORING_REQUEST_CANCELLED +- * SERVER_ALREADY_STARTED +- * SERVER_ERROR +- * SORT_MEMBERS_INVALID_FILE +- * SORT_MEMBERS_PARSE_ERRORS +- * UNANALYZED_PRIORITY_FILES +- * UNKNOWN_REQUEST +- * UNKNOWN_SOURCE +- * UNSUPPORTED_FEATURE +- * } +- */ +-final Matcher isRequestErrorCode =3D new MatchesEnum("RequestErrorCode", [ +- "CONTENT_MODIFIED", +- "DEBUG_PORT_COULD_NOT_BE_OPENED", +- "FILE_NOT_ANALYZED", +- "FORMAT_INVALID_FILE", +- "FORMAT_WITH_ERRORS", +- "GET_ERRORS_INVALID_FILE", +- "GET_IMPORTED_ELEMENTS_INVALID_FILE", +- "GET_KYTHE_ENTRIES_INVALID_FILE", +- "GET_NAVIGATION_INVALID_FILE", +- "GET_REACHABLE_SOURCES_INVALID_FILE", +- "IMPORT_ELEMENTS_INVALID_FILE", +- "INVALID_ANALYSIS_ROOT", +- "INVALID_EXECUTION_CONTEXT", +- "INVALID_FILE_PATH_FORMAT", +- "INVALID_OVERLAY_CHANGE", +- "INVALID_PARAMETER", +- "INVALID_REQUEST", +- "ORGANIZE_DIRECTIVES_ERROR", +- "REFACTORING_REQUEST_CANCELLED", +- "SERVER_ALREADY_STARTED", +- "SERVER_ERROR", +- "SORT_MEMBERS_INVALID_FILE", +- "SORT_MEMBERS_PARSE_ERRORS", +- "UNANALYZED_PRIORITY_FILES", +- "UNKNOWN_REQUEST", +- "UNKNOWN_SOURCE", +- "UNSUPPORTED_FEATURE" +-]); +- +-/** +- * SearchId +- * +- * String +- */ +-final Matcher isSearchId =3D isString; +- +-/** +- * SearchResult +- * +- * { +- * "location": Location +- * "kind": SearchResultKind +- * "isPotential": bool +- * "path": List +- * } +- */ +-final Matcher isSearchResult =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("SearchResult", { +- "location": isLocation, +- "kind": isSearchResultKind, +- "isPotential": isBool, +- "path": isListOf(isElement) +- })); +- +-/** +- * SearchResultKind +- * +- * enum { +- * DECLARATION +- * INVOCATION +- * READ +- * READ_WRITE +- * REFERENCE +- * UNKNOWN +- * WRITE +- * } +- */ +-final Matcher isSearchResultKind =3D new MatchesEnum("SearchResultKind", [ +- "DECLARATION", +- "INVOCATION", +- "READ", +- "READ_WRITE", +- "REFERENCE", +- "UNKNOWN", +- "WRITE" +-]); +- +-/** +- * ServerService +- * +- * enum { +- * STATUS +- * } +- */ +-final Matcher isServerService =3D new MatchesEnum("ServerService", ["STAT= US"]); +- +-/** +- * SourceChange +- * +- * { +- * "message": String +- * "edits": List +- * "linkedEditGroups": List +- * "selection": optional Position +- * } +- */ +-final Matcher isSourceChange =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("SourceChange", { +- "message": isString, +- "edits": isListOf(isSourceFileEdit), +- "linkedEditGroups": isListOf(isLinkedEditGroup) +- }, optionalFields: { +- "selection": isPosition +- })); +- +-/** +- * SourceEdit +- * +- * { +- * "offset": int +- * "length": int +- * "replacement": String +- * "id": optional String +- * } +- */ +-final Matcher isSourceEdit =3D new LazyMatcher(() =3D> new MatchesJsonObj= ect( +- "SourceEdit", {"offset": isInt, "length": isInt, "replacement": isStr= ing}, +- optionalFields: {"id": isString})); +- +-/** +- * SourceFileEdit +- * +- * { +- * "file": FilePath +- * "fileStamp": long +- * "edits": List +- * } +- */ +-final Matcher isSourceFileEdit =3D new LazyMatcher(() =3D> new MatchesJso= nObject( +- "SourceFileEdit", +- {"file": isFilePath, "fileStamp": isInt, "edits": isListOf(isSourceEd= it)})); +- +-/** +- * TypeHierarchyItem +- * +- * { +- * "classElement": Element +- * "displayName": optional String +- * "memberElement": optional Element +- * "superclass": optional int +- * "interfaces": List +- * "mixins": List +- * "subclasses": List +- * } +- */ +-final Matcher isTypeHierarchyItem =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("TypeHierarchyItem", { +- "classElement": isElement, +- "interfaces": isListOf(isInt), +- "mixins": isListOf(isInt), +- "subclasses": isListOf(isInt) +- }, optionalFields: { +- "displayName": isString, +- "memberElement": isElement, +- "superclass": isInt +- })); +- +-/** +- * analysis.analyzedFiles params +- * +- * { +- * "directories": List +- * } +- */ +-final Matcher isAnalysisAnalyzedFilesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.analyzedFiles params", +- {"directories": isListOf(isFilePath)})); +- +-/** +- * analysis.closingLabels params +- * +- * { +- * "file": FilePath +- * "labels": List +- * } +- */ +-final Matcher isAnalysisClosingLabelsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.closingLabels params", +- {"file": isFilePath, "labels": isListOf(isClosingLabel)})); +- +-/** +- * analysis.errors params +- * +- * { +- * "file": FilePath +- * "errors": List +- * } +- */ +-final Matcher isAnalysisErrorsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.errors params", +- {"file": isFilePath, "errors": isListOf(isAnalysisError)})); +- +-/** +- * analysis.flushResults params +- * +- * { +- * "files": List +- * } +- */ +-final Matcher isAnalysisFlushResultsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analysis.flushResults params", {"files": isListOf(isFilePath)})); +- +-/** +- * analysis.folding params +- * +- * { +- * "file": FilePath +- * "regions": List +- * } +- */ +-final Matcher isAnalysisFoldingParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.folding params", +- {"file": isFilePath, "regions": isListOf(isFoldingRegion)})); +- +-/** +- * analysis.getErrors params +- * +- * { +- * "file": FilePath +- * } +- */ +-final Matcher isAnalysisGetErrorsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.getErrors params", {"file": isFilePat= h})); +- +-/** +- * analysis.getErrors result +- * +- * { +- * "errors": List +- * } +- */ +-final Matcher isAnalysisGetErrorsResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analysis.getErrors result", {"errors": isListOf(isAnalysisError)= })); +- +-/** +- * analysis.getHover params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- */ +-final Matcher isAnalysisGetHoverParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analysis.getHover params", {"file": isFilePath, "offset": isInt}= )); +- +-/** +- * analysis.getHover result +- * +- * { +- * "hovers": List +- * } +- */ +-final Matcher isAnalysisGetHoverResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analysis.getHover result", {"hovers": isListOf(isHoverInformatio= n)})); +- +-/** +- * analysis.getImportedElements params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isAnalysisGetImportedElementsParams =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("analysis.getImportedElements params", +- {"file": isFilePath, "offset": isInt, "length": isInt})); +- +-/** +- * analysis.getImportedElements result +- * +- * { +- * "elements": List +- * } +- */ +-final Matcher isAnalysisGetImportedElementsResult =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("analysis.getImportedElements result", +- {"elements": isListOf(isImportedElements)})); +- +-/** +- * analysis.getLibraryDependencies params +- */ +-final Matcher isAnalysisGetLibraryDependenciesParams =3D isNull; +- +-/** +- * analysis.getLibraryDependencies result +- * +- * { +- * "libraries": List +- * "packageMap": Map>> +- * } +- */ +-final Matcher isAnalysisGetLibraryDependenciesResult =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("analysis.getLibraryDependencies result= ", { +- "libraries": isListOf(isFilePath), +- "packageMap": +- isMapOf(isString, isMapOf(isString, isListOf(isFilePath))) +- })); +- +-/** +- * analysis.getNavigation params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isAnalysisGetNavigationParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.getNavigation params", +- {"file": isFilePath, "offset": isInt, "length": isInt})); +- +-/** +- * analysis.getNavigation result +- * +- * { +- * "files": List +- * "targets": List +- * "regions": List +- * } +- */ +-final Matcher isAnalysisGetNavigationResult =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("analysis.getNavigation result", { +- "files": isListOf(isFilePath), +- "targets": isListOf(isNavigationTarget), +- "regions": isListOf(isNavigationRegion) +- })); +- +-/** +- * analysis.getReachableSources params +- * +- * { +- * "file": FilePath +- * } +- */ +-final Matcher isAnalysisGetReachableSourcesParams =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject( +- "analysis.getReachableSources params", {"file": isFilePath})); +- +-/** +- * analysis.getReachableSources result +- * +- * { +- * "sources": Map> +- * } +- */ +-final Matcher isAnalysisGetReachableSourcesResult =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("analysis.getReachableSources result", +- {"sources": isMapOf(isString, isListOf(isString))})); +- +-/** +- * analysis.highlights params +- * +- * { +- * "file": FilePath +- * "regions": List +- * } +- */ +-final Matcher isAnalysisHighlightsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.highlights params", +- {"file": isFilePath, "regions": isListOf(isHighlightRegion)})); +- +-/** +- * analysis.implemented params +- * +- * { +- * "file": FilePath +- * "classes": List +- * "members": List +- * } +- */ +-final Matcher isAnalysisImplementedParams =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("analysis.implemented p= arams", { +- "file": isFilePath, +- "classes": isListOf(isImplementedClass), +- "members": isListOf(isImplementedMember) +- })); +- +-/** +- * analysis.invalidate params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * "delta": int +- * } +- */ +-final Matcher isAnalysisInvalidateParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.invalidate params", { +- "file": isFilePath, +- "offset": isInt, +- "length": isInt, +- "delta": isInt +- })); +- +-/** +- * analysis.navigation params +- * +- * { +- * "file": FilePath +- * "regions": List +- * "targets": List +- * "files": List +- * } +- */ +-final Matcher isAnalysisNavigationParams =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("analysis.navigation pa= rams", { +- "file": isFilePath, +- "regions": isListOf(isNavigationRegion), +- "targets": isListOf(isNavigationTarget), +- "files": isListOf(isFilePath) +- })); +- +-/** +- * analysis.occurrences params +- * +- * { +- * "file": FilePath +- * "occurrences": List +- * } +- */ +-final Matcher isAnalysisOccurrencesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.occurrences params", +- {"file": isFilePath, "occurrences": isListOf(isOccurrences)})); +- +-/** +- * analysis.outline params +- * +- * { +- * "file": FilePath +- * "kind": FileKind +- * "libraryName": optional String +- * "outline": Outline +- * } +- */ +-final Matcher isAnalysisOutlineParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.outline params", +- {"file": isFilePath, "kind": isFileKind, "outline": isOutline}, +- optionalFields: {"libraryName": isString})); +- +-/** +- * analysis.overrides params +- * +- * { +- * "file": FilePath +- * "overrides": List +- * } +- */ +-final Matcher isAnalysisOverridesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.overrides params", +- {"file": isFilePath, "overrides": isListOf(isOverride)})); +- +-/** +- * analysis.reanalyze params +- * +- * { +- * "roots": optional List +- * } +- */ +-final Matcher isAnalysisReanalyzeParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.reanalyze params", null, +- optionalFields: {"roots": isListOf(isFilePath)})); +- +-/** +- * analysis.reanalyze result +- */ +-final Matcher isAnalysisReanalyzeResult =3D isNull; +- +-/** +- * analysis.setAnalysisRoots params +- * +- * { +- * "included": List +- * "excluded": List +- * "packageRoots": optional Map +- * } +- */ +-final Matcher isAnalysisSetAnalysisRootsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.setAnalysisRoots params", +- {"included": isListOf(isFilePath), "excluded": isListOf(isFilePat= h)}, +- optionalFields: {"packageRoots": isMapOf(isFilePath, isFilePath)}= )); +- +-/** +- * analysis.setAnalysisRoots result +- */ +-final Matcher isAnalysisSetAnalysisRootsResult =3D isNull; +- +-/** +- * analysis.setGeneralSubscriptions params +- * +- * { +- * "subscriptions": List +- * } +- */ +-final Matcher isAnalysisSetGeneralSubscriptionsParams =3D new LazyMatcher= (() =3D> +- new MatchesJsonObject("analysis.setGeneralSubscriptions params", +- {"subscriptions": isListOf(isGeneralAnalysisService)})); +- +-/** +- * analysis.setGeneralSubscriptions result +- */ +-final Matcher isAnalysisSetGeneralSubscriptionsResult =3D isNull; +- +-/** +- * analysis.setPriorityFiles params +- * +- * { +- * "files": List +- * } +- */ +-final Matcher isAnalysisSetPriorityFilesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analysis.setPriorityFiles params", {"files": isListOf(isFilePath= )})); +- +-/** +- * analysis.setPriorityFiles result +- */ +-final Matcher isAnalysisSetPriorityFilesResult =3D isNull; +- +-/** +- * analysis.setSubscriptions params +- * +- * { +- * "subscriptions": Map> +- * } +- */ +-final Matcher isAnalysisSetSubscriptionsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analysis.setSubscriptions params", +- {"subscriptions": isMapOf(isAnalysisService, isListOf(isFilePath)= )})); +- +-/** +- * analysis.setSubscriptions result +- */ +-final Matcher isAnalysisSetSubscriptionsResult =3D isNull; +- +-/** +- * analysis.updateContent params +- * +- * { +- * "files": Map +- * } +- */ +-final Matcher isAnalysisUpdateContentParams =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("analysis.updateContent params", { +- "files": isMapOf( +- isFilePath, +- isOneOf([ +- isAddContentOverlay, +- isChangeContentOverlay, +- isRemoveContentOverlay +- ])) +- })); +- +-/** +- * analysis.updateContent result +- * +- * { +- * } +- */ +-final Matcher isAnalysisUpdateContentResult =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("analysis.updateContent result", null)); +- +-/** +- * analysis.updateOptions params +- * +- * { +- * "options": AnalysisOptions +- * } +- */ +-final Matcher isAnalysisUpdateOptionsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analysis.updateOptions params", {"options": isAnalysisOptions})); +- +-/** +- * analysis.updateOptions result +- */ +-final Matcher isAnalysisUpdateOptionsResult =3D isNull; +- +-/** +- * analytics.enable params +- * +- * { +- * "value": bool +- * } +- */ +-final Matcher isAnalyticsEnableParams =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("analytics.enable params", {"value": is= Bool})); +- +-/** +- * analytics.enable result +- */ +-final Matcher isAnalyticsEnableResult =3D isNull; +- +-/** +- * analytics.isEnabled params +- */ +-final Matcher isAnalyticsIsEnabledParams =3D isNull; +- +-/** +- * analytics.isEnabled result +- * +- * { +- * "enabled": bool +- * } +- */ +-final Matcher isAnalyticsIsEnabledResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analytics.isEnabled result", {"enabled": isBoo= l})); +- +-/** +- * analytics.sendEvent params +- * +- * { +- * "action": String +- * } +- */ +-final Matcher isAnalyticsSendEventParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("analytics.sendEvent params", {"action": isStri= ng})); +- +-/** +- * analytics.sendEvent result +- */ +-final Matcher isAnalyticsSendEventResult =3D isNull; +- +-/** +- * analytics.sendTiming params +- * +- * { +- * "event": String +- * "millis": int +- * } +- */ +-final Matcher isAnalyticsSendTimingParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "analytics.sendTiming params", {"event": isString, "millis": isIn= t})); +- +-/** +- * analytics.sendTiming result +- */ +-final Matcher isAnalyticsSendTimingResult =3D isNull; +- +-/** +- * completion.getSuggestions params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- */ +-final Matcher isCompletionGetSuggestionsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("completion.getSuggestions params", +- {"file": isFilePath, "offset": isInt})); +- +-/** +- * completion.getSuggestions result +- * +- * { +- * "id": CompletionId +- * } +- */ +-final Matcher isCompletionGetSuggestionsResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "completion.getSuggestions result", {"id": isCompletionId})); +- +-/** +- * completion.results params +- * +- * { +- * "id": CompletionId +- * "replacementOffset": int +- * "replacementLength": int +- * "results": List +- * "isLast": bool +- * } +- */ +-final Matcher isCompletionResultsParams =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("completion.results par= ams", { +- "id": isCompletionId, +- "replacementOffset": isInt, +- "replacementLength": isInt, +- "results": isListOf(isCompletionSuggestion), +- "isLast": isBool +- })); +- +-/** +- * convertGetterToMethod feedback +- */ +-final Matcher isConvertGetterToMethodFeedback =3D isNull; +- +-/** +- * convertGetterToMethod options +- */ +-final Matcher isConvertGetterToMethodOptions =3D isNull; +- +-/** +- * convertMethodToGetter feedback +- */ +-final Matcher isConvertMethodToGetterFeedback =3D isNull; +- +-/** +- * convertMethodToGetter options +- */ +-final Matcher isConvertMethodToGetterOptions =3D isNull; +- +-/** +- * diagnostic.getDiagnostics params +- */ +-final Matcher isDiagnosticGetDiagnosticsParams =3D isNull; +- +-/** +- * diagnostic.getDiagnostics result +- * +- * { +- * "contexts": List +- * } +- */ +-final Matcher isDiagnosticGetDiagnosticsResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("diagnostic.getDiagnostics result", +- {"contexts": isListOf(isContextData)})); +- +-/** +- * diagnostic.getServerPort params +- */ +-final Matcher isDiagnosticGetServerPortParams =3D isNull; +- +-/** +- * diagnostic.getServerPort result +- * +- * { +- * "port": int +- * } +- */ +-final Matcher isDiagnosticGetServerPortResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("diagnostic.getServerPort result", {"port": isI= nt})); +- +-/** +- * edit.format params +- * +- * { +- * "file": FilePath +- * "selectionOffset": int +- * "selectionLength": int +- * "lineLength": optional int +- * } +- */ +-final Matcher isEditFormatParams =3D new LazyMatcher(() =3D> new MatchesJ= sonObject( +- "edit.format params", +- {"file": isFilePath, "selectionOffset": isInt, "selectionLength": isI= nt}, +- optionalFields: {"lineLength": isInt})); +- +-/** +- * edit.format result +- * +- * { +- * "edits": List +- * "selectionOffset": int +- * "selectionLength": int +- * } +- */ +-final Matcher isEditFormatResult =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("edit.format result", { +- "edits": isListOf(isSourceEdit), +- "selectionOffset": isInt, +- "selectionLength": isInt +- })); +- +-/** +- * edit.getAssists params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isEditGetAssistsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("edit.getAssists params", +- {"file": isFilePath, "offset": isInt, "length": isInt})); +- +-/** +- * edit.getAssists result +- * +- * { +- * "assists": List +- * } +- */ +-final Matcher isEditGetAssistsResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.getAssists result", {"assists": isListOf(isSourceChange)})); +- +-/** +- * edit.getAvailableRefactorings params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "length": int +- * } +- */ +-final Matcher isEditGetAvailableRefactoringsParams =3D new LazyMatcher(()= =3D> +- new MatchesJsonObject("edit.getAvailableRefactorings params", +- {"file": isFilePath, "offset": isInt, "length": isInt})); +- +-/** +- * edit.getAvailableRefactorings result +- * +- * { +- * "kinds": List +- * } +- */ +-final Matcher isEditGetAvailableRefactoringsResult =3D new LazyMatcher(()= =3D> +- new MatchesJsonObject("edit.getAvailableRefactorings result", +- {"kinds": isListOf(isRefactoringKind)})); +- +-/** +- * edit.getFixes params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- */ +-final Matcher isEditGetFixesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.getFixes params", {"file": isFilePath, "offset": isInt})); +- +-/** +- * edit.getFixes result +- * +- * { +- * "fixes": List +- * } +- */ +-final Matcher isEditGetFixesResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.getFixes result", {"fixes": isListOf(isAnalysisErrorFixes)}= )); +- +-/** +- * edit.getPostfixCompletion params +- * +- * { +- * "file": FilePath +- * "key": String +- * "offset": int +- * } +- */ +-final Matcher isEditGetPostfixCompletionParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("edit.getPostfixCompletion params", +- {"file": isFilePath, "key": isString, "offset": isInt})); +- +-/** +- * edit.getPostfixCompletion result +- * +- * { +- * "change": SourceChange +- * } +- */ +-final Matcher isEditGetPostfixCompletionResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.getPostfixCompletion result", {"change": isSourceChange})); +- +-/** +- * edit.getRefactoring params +- * +- * { +- * "kind": RefactoringKind +- * "file": FilePath +- * "offset": int +- * "length": int +- * "validateOnly": bool +- * "options": optional RefactoringOptions +- * } +- */ +-final Matcher isEditGetRefactoringParams =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("edit.getRefactoring pa= rams", { +- "kind": isRefactoringKind, +- "file": isFilePath, +- "offset": isInt, +- "length": isInt, +- "validateOnly": isBool +- }, optionalFields: { +- "options": isRefactoringOptions +- })); +- +-/** +- * edit.getRefactoring result +- * +- * { +- * "initialProblems": List +- * "optionsProblems": List +- * "finalProblems": List +- * "feedback": optional RefactoringFeedback +- * "change": optional SourceChange +- * "potentialEdits": optional List +- * } +- */ +-final Matcher isEditGetRefactoringResult =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("edit.getRefactoring re= sult", { +- "initialProblems": isListOf(isRefactoringProblem), +- "optionsProblems": isListOf(isRefactoringProblem), +- "finalProblems": isListOf(isRefactoringProblem) +- }, optionalFields: { +- "feedback": isRefactoringFeedback, +- "change": isSourceChange, +- "potentialEdits": isListOf(isString) +- })); +- +-/** +- * edit.getStatementCompletion params +- * +- * { +- * "file": FilePath +- * "offset": int +- * } +- */ +-final Matcher isEditGetStatementCompletionParams =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("edit.getStatementCompletion params", +- {"file": isFilePath, "offset": isInt})); +- +-/** +- * edit.getStatementCompletion result +- * +- * { +- * "change": SourceChange +- * "whitespaceOnly": bool +- * } +- */ +-final Matcher isEditGetStatementCompletionResult =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("edit.getStatementCompletion result", +- {"change": isSourceChange, "whitespaceOnly": isBool})); +- +-/** +- * edit.importElements params +- * +- * { +- * "file": FilePath +- * "elements": List +- * } +- */ +-final Matcher isEditImportElementsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("edit.importElements params", +- {"file": isFilePath, "elements": isListOf(isImportedElements)})); +- +-/** +- * edit.importElements result +- * +- * { +- * "edit": SourceFileEdit +- * } +- */ +-final Matcher isEditImportElementsResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.importElements result", {"edit": isSourceFileEdit})); +- +-/** +- * edit.isPostfixCompletionApplicable params +- * +- * { +- * "file": FilePath +- * "key": String +- * "offset": int +- * } +- */ +-final Matcher isEditIsPostfixCompletionApplicableParams =3D new LazyMatch= er(() =3D> +- new MatchesJsonObject("edit.isPostfixCompletionApplicable params", +- {"file": isFilePath, "key": isString, "offset": isInt})); +- +-/** +- * edit.isPostfixCompletionApplicable result +- * +- * { +- * "value": bool +- * } +- */ +-final Matcher isEditIsPostfixCompletionApplicableResult =3D new LazyMatch= er(() =3D> +- new MatchesJsonObject( +- "edit.isPostfixCompletionApplicable result", {"value": isBool})); +- +-/** +- * edit.listPostfixCompletionTemplates params +- */ +-final Matcher isEditListPostfixCompletionTemplatesParams =3D isNull; +- +-/** +- * edit.listPostfixCompletionTemplates result +- * +- * { +- * "templates": List +- * } +- */ +-final Matcher isEditListPostfixCompletionTemplatesResult =3D new LazyMatc= her(() =3D> +- new MatchesJsonObject("edit.listPostfixCompletionTemplates result", +- {"templates": isListOf(isPostfixTemplateDescriptor)})); +- +-/** +- * edit.organizeDirectives params +- * +- * { +- * "file": FilePath +- * } +- */ +-final Matcher isEditOrganizeDirectivesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.organizeDirectives params", {"file": isFilePath})); +- +-/** +- * edit.organizeDirectives result +- * +- * { +- * "edit": SourceFileEdit +- * } +- */ +-final Matcher isEditOrganizeDirectivesResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.organizeDirectives result", {"edit": isSourceFileEdit})); +- +-/** +- * edit.sortMembers params +- * +- * { +- * "file": FilePath +- * } +- */ +-final Matcher isEditSortMembersParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("edit.sortMembers params", {"file": isFilePath}= )); +- +-/** +- * edit.sortMembers result +- * +- * { +- * "edit": SourceFileEdit +- * } +- */ +-final Matcher isEditSortMembersResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "edit.sortMembers result", {"edit": isSourceFileEdit})); +- +-/** +- * execution.createContext params +- * +- * { +- * "contextRoot": FilePath +- * } +- */ +-final Matcher isExecutionCreateContextParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "execution.createContext params", {"contextRoot": isFilePath})); +- +-/** +- * execution.createContext result +- * +- * { +- * "id": ExecutionContextId +- * } +- */ +-final Matcher isExecutionCreateContextResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "execution.createContext result", {"id": isExecutionContextId})); +- +-/** +- * execution.deleteContext params +- * +- * { +- * "id": ExecutionContextId +- * } +- */ +-final Matcher isExecutionDeleteContextParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "execution.deleteContext params", {"id": isExecutionContextId})); +- +-/** +- * execution.deleteContext result +- */ +-final Matcher isExecutionDeleteContextResult =3D isNull; +- +-/** +- * execution.launchData params +- * +- * { +- * "file": FilePath +- * "kind": optional ExecutableKind +- * "referencedFiles": optional List +- * } +- */ +-final Matcher isExecutionLaunchDataParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("execution.launchData params", { +- "file": isFilePath +- }, optionalFields: { +- "kind": isExecutableKind, +- "referencedFiles": isListOf(isFilePath) +- })); +- +-/** +- * execution.mapUri params +- * +- * { +- * "id": ExecutionContextId +- * "file": optional FilePath +- * "uri": optional String +- * } +- */ +-final Matcher isExecutionMapUriParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "execution.mapUri params", {"id": isExecutionContextId}, +- optionalFields: {"file": isFilePath, "uri": isString})); +- +-/** +- * execution.mapUri result +- * +- * { +- * "file": optional FilePath +- * "uri": optional String +- * } +- */ +-final Matcher isExecutionMapUriResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("execution.mapUri result", null, +- optionalFields: {"file": isFilePath, "uri": isString})); +- +-/** +- * execution.setSubscriptions params +- * +- * { +- * "subscriptions": List +- * } +- */ +-final Matcher isExecutionSetSubscriptionsParams =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("execution.setSubscriptions params", +- {"subscriptions": isListOf(isExecutionService)})); +- +-/** +- * execution.setSubscriptions result +- */ +-final Matcher isExecutionSetSubscriptionsResult =3D isNull; +- +-/** +- * extractLocalVariable feedback +- * +- * { +- * "coveringExpressionOffsets": optional List +- * "coveringExpressionLengths": optional List +- * "names": List +- * "offsets": List +- * "lengths": List +- * } +- */ +-final Matcher isExtractLocalVariableFeedback =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("extractLocalVariable feedback", { +- "names": isListOf(isString), +- "offsets": isListOf(isInt), +- "lengths": isListOf(isInt) +- }, optionalFields: { +- "coveringExpressionOffsets": isListOf(isInt), +- "coveringExpressionLengths": isListOf(isInt) +- })); +- +-/** +- * extractLocalVariable options +- * +- * { +- * "name": String +- * "extractAll": bool +- * } +- */ +-final Matcher isExtractLocalVariableOptions =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("extractLocalVariable options", +- {"name": isString, "extractAll": isBool})); +- +-/** +- * extractMethod feedback +- * +- * { +- * "offset": int +- * "length": int +- * "returnType": String +- * "names": List +- * "canCreateGetter": bool +- * "parameters": List +- * "offsets": List +- * "lengths": List +- * } +- */ +-final Matcher isExtractMethodFeedback =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("extractMethod feedback= ", { +- "offset": isInt, +- "length": isInt, +- "returnType": isString, +- "names": isListOf(isString), +- "canCreateGetter": isBool, +- "parameters": isListOf(isRefactoringMethodParameter), +- "offsets": isListOf(isInt), +- "lengths": isListOf(isInt) +- })); +- +-/** +- * extractMethod options +- * +- * { +- * "returnType": String +- * "createGetter": bool +- * "name": String +- * "parameters": List +- * "extractAll": bool +- * } +- */ +-final Matcher isExtractMethodOptions =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("extractMethod options"= , { +- "returnType": isString, +- "createGetter": isBool, +- "name": isString, +- "parameters": isListOf(isRefactoringMethodParameter), +- "extractAll": isBool +- })); +- +-/** +- * inlineLocalVariable feedback +- * +- * { +- * "name": String +- * "occurrences": int +- * } +- */ +-final Matcher isInlineLocalVariableFeedback =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("inlineLocalVariable feedback", +- {"name": isString, "occurrences": isInt})); +- +-/** +- * inlineLocalVariable options +- */ +-final Matcher isInlineLocalVariableOptions =3D isNull; +- +-/** +- * inlineMethod feedback +- * +- * { +- * "className": optional String +- * "methodName": String +- * "isDeclaration": bool +- * } +- */ +-final Matcher isInlineMethodFeedback =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("inlineMethod feedback", +- {"methodName": isString, "isDeclaration": isBool}, +- optionalFields: {"className": isString})); +- +-/** +- * inlineMethod options +- * +- * { +- * "deleteSource": bool +- * "inlineAll": bool +- * } +- */ +-final Matcher isInlineMethodOptions =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "inlineMethod options", {"deleteSource": isBool, "inlineAll": isB= ool})); +- +-/** +- * kythe.getKytheEntries params +- * +- * { +- * "file": FilePath +- * } +- */ +-final Matcher isKytheGetKytheEntriesParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "kythe.getKytheEntries params", {"file": isFilePath})); +- +-/** +- * kythe.getKytheEntries result +- * +- * { +- * "entries": List +- * "files": List +- * } +- */ +-final Matcher isKytheGetKytheEntriesResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("kythe.getKytheEntries result", +- {"entries": isListOf(isKytheEntry), "files": isListOf(isFilePath)= })); +- +-/** +- * moveFile feedback +- */ +-final Matcher isMoveFileFeedback =3D isNull; +- +-/** +- * moveFile options +- * +- * { +- * "newFile": FilePath +- * } +- */ +-final Matcher isMoveFileOptions =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("moveFile options", {"newFile": isFileP= ath})); +- +-/** +- * rename feedback +- * +- * { +- * "offset": int +- * "length": int +- * "elementKindName": String +- * "oldName": String +- * } +- */ +-final Matcher isRenameFeedback =3D +- new LazyMatcher(() =3D> new MatchesJsonObject("rename feedback", { +- "offset": isInt, +- "length": isInt, +- "elementKindName": isString, +- "oldName": isString +- })); +- +-/** +- * rename options +- * +- * { +- * "newName": String +- * } +- */ +-final Matcher isRenameOptions =3D new LazyMatcher( +- () =3D> new MatchesJsonObject("rename options", {"newName": isString}= )); +- +-/** +- * search.findElementReferences params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "includePotential": bool +- * } +- */ +-final Matcher isSearchFindElementReferencesParams =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("search.findElementReferences params", +- {"file": isFilePath, "offset": isInt, "includePotential": isBool}= )); +- +-/** +- * search.findElementReferences result +- * +- * { +- * "id": optional SearchId +- * "element": optional Element +- * } +- */ +-final Matcher isSearchFindElementReferencesResult =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject("search.findElementReferences result", null, +- optionalFields: {"id": isSearchId, "element": isElement})); +- +-/** +- * search.findMemberDeclarations params +- * +- * { +- * "name": String +- * } +- */ +-final Matcher isSearchFindMemberDeclarationsParams =3D new LazyMatcher(()= =3D> +- new MatchesJsonObject( +- "search.findMemberDeclarations params", {"name": isString})); +- +-/** +- * search.findMemberDeclarations result +- * +- * { +- * "id": SearchId +- * } +- */ +-final Matcher isSearchFindMemberDeclarationsResult =3D new LazyMatcher(()= =3D> +- new MatchesJsonObject( +- "search.findMemberDeclarations result", {"id": isSearchId})); +- +-/** +- * search.findMemberReferences params +- * +- * { +- * "name": String +- * } +- */ +-final Matcher isSearchFindMemberReferencesParams =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject( +- "search.findMemberReferences params", {"name": isString})); +- +-/** +- * search.findMemberReferences result +- * +- * { +- * "id": SearchId +- * } +- */ +-final Matcher isSearchFindMemberReferencesResult =3D new LazyMatcher(() = =3D> +- new MatchesJsonObject( +- "search.findMemberReferences result", {"id": isSearchId})); +- +-/** +- * search.findTopLevelDeclarations params +- * +- * { +- * "pattern": String +- * } +- */ +-final Matcher isSearchFindTopLevelDeclarationsParams =3D new LazyMatcher(= () =3D> +- new MatchesJsonObject( +- "search.findTopLevelDeclarations params", {"pattern": isString})); +- +-/** +- * search.findTopLevelDeclarations result +- * +- * { +- * "id": SearchId +- * } +- */ +-final Matcher isSearchFindTopLevelDeclarationsResult =3D new LazyMatcher(= () =3D> +- new MatchesJsonObject( +- "search.findTopLevelDeclarations result", {"id": isSearchId})); +- +-/** +- * search.getTypeHierarchy params +- * +- * { +- * "file": FilePath +- * "offset": int +- * "superOnly": optional bool +- * } +- */ +-final Matcher isSearchGetTypeHierarchyParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "search.getTypeHierarchy params", {"file": isFilePath, "offset": = isInt}, +- optionalFields: {"superOnly": isBool})); +- +-/** +- * search.getTypeHierarchy result +- * +- * { +- * "hierarchyItems": optional List +- * } +- */ +-final Matcher isSearchGetTypeHierarchyResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("search.getTypeHierarchy result", null, +- optionalFields: {"hierarchyItems": isListOf(isTypeHierarchyItem)}= )); +- +-/** +- * search.results params +- * +- * { +- * "id": SearchId +- * "results": List +- * "isLast": bool +- * } +- */ +-final Matcher isSearchResultsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("search.results params", { +- "id": isSearchId, +- "results": isListOf(isSearchResult), +- "isLast": isBool +- })); +- +-/** +- * server.connected params +- * +- * { +- * "version": String +- * "pid": int +- * "sessionId": optional String +- * } +- */ +-final Matcher isServerConnectedParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject( +- "server.connected params", {"version": isString, "pid": isInt}, +- optionalFields: {"sessionId": isString})); +- +-/** +- * server.error params +- * +- * { +- * "isFatal": bool +- * "message": String +- * "stackTrace": String +- * } +- */ +-final Matcher isServerErrorParams =3D new LazyMatcher(() =3D> new Matches= JsonObject( +- "server.error params", +- {"isFatal": isBool, "message": isString, "stackTrace": isString})); +- +-/** +- * server.getVersion params +- */ +-final Matcher isServerGetVersionParams =3D isNull; +- +-/** +- * server.getVersion result +- * +- * { +- * "version": String +- * } +- */ +-final Matcher isServerGetVersionResult =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("server.getVersion result", {"version": isStrin= g})); +- +-/** +- * server.setSubscriptions params +- * +- * { +- * "subscriptions": List +- * } +- */ +-final Matcher isServerSetSubscriptionsParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("server.setSubscriptions params", +- {"subscriptions": isListOf(isServerService)})); +- +-/** +- * server.setSubscriptions result +- */ +-final Matcher isServerSetSubscriptionsResult =3D isNull; +- +-/** +- * server.shutdown params +- */ +-final Matcher isServerShutdownParams =3D isNull; +- +-/** +- * server.shutdown result +- */ +-final Matcher isServerShutdownResult =3D isNull; +- +-/** +- * server.status params +- * +- * { +- * "analysis": optional AnalysisStatus +- * "pub": optional PubStatus +- * } +- */ +-final Matcher isServerStatusParams =3D new LazyMatcher(() =3D> +- new MatchesJsonObject("server.status params", null, +- optionalFields: {"analysis": isAnalysisStatus, "pub": isPubStatus= })); +diff --git a/pkg/analysis_server/test/integration/test_all.dart b/pkg/anal= ysis_server/test/integration/test_all.dart +deleted file mode 100644 +index c69d15b695b..00000000000 +--- a/pkg/analysis_server/test/integration/test_all.dart ++++ /dev/null +@@ -1,35 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'analysis/test_all.dart' as analysis_test_all; +-import 'analytics/test_all.dart' as analytics_test_all; +-import 'completion/test_all.dart' as completion_test_all; +-import 'coverage_test.dart' as coverage_test; +-import 'diagnostic/test_all.dart' as diagnostic_test_all; +-import 'edit/test_all.dart' as edit_test_all; +-import 'execution/test_all.dart' as execution_test_all; +-import 'kythe/test_all.dart' as kythe_test_all; +-import 'search/test_all.dart' as search_test_all; +-import 'server/test_all.dart' as server_test_all; +- +-/** +- * Utility for manually running all integration tests. +- */ +-main() { +- defineReflectiveSuite(() { +- analysis_test_all.main(); +- analytics_test_all.main(); +- completion_test_all.main(); +- diagnostic_test_all.main(); +- edit_test_all.main(); +- execution_test_all.main(); +- kythe_test_all.main(); +- search_test_all.main(); +- server_test_all.main(); +- +- coverage_test.main(); +- }, name: 'analysis_server_integration'); +-} +diff --git a/pkg/analysis_server/test/mock_sdk.dart b/pkg/analysis_server/= test/mock_sdk.dart +deleted file mode 100644 +index a0719874ff6..00000000000 +--- a/pkg/analysis_server/test/mock_sdk.dart ++++ /dev/null +@@ -1,438 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library testing.mock_sdk; +- +-import 'package:analyzer/file_system/file_system.dart' as resource; +-import 'package:analyzer/file_system/memory_file_system.dart' as resource; +-import 'package:analyzer/src/context/context.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/summary/idl.dart' show PackageBundle; +-import 'package:analyzer/src/summary/summary_file_builder.dart'; +- +-class MockSdk implements DartSdk { +- static const MockSdkLibrary LIB_CORE =3D +- const MockSdkLibrary('dart:core', '/lib/core/core.dart', ''' +-library dart.core; +- +-import 'dart:async'; +-import 'dart:_internal'; +- +-class Object { +- const Object() {} +- bool operator =3D=3D(other) =3D> identical(this, other); +- String toString() =3D> 'a string'; +- int get hashCode =3D> 0; +- Type get runtimeType =3D> null; +- dynamic noSuchMethod(Invocation invocation) =3D> null; +-} +- +-class Function {} +-class StackTrace {} +-class Symbol {} +-class Type {} +- +-abstract class Comparable { +- int compareTo(T other); +-} +- +-abstract class String implements Comparable { +- external factory String.fromCharCodes(Iterable charCodes, +- [int start =3D 0, int end]); +- bool get isEmpty =3D> false; +- bool get isNotEmpty =3D> false; +- int get length =3D> 0; +- String toUpperCase(); +- List get codeUnits; +-} +- +-class bool extends Object {} +- +-abstract class num implements Comparable { +- bool operator <(num other); +- bool operator <=3D(num other); +- bool operator >(num other); +- bool operator >=3D(num other); +- num operator +(num other); +- num operator -(num other); +- num operator *(num other); +- num operator /(num other); +- int operator ^(int other); +- int operator &(int other); +- int operator |(int other); +- int operator <<(int other); +- int operator >>(int other); +- int operator ~/(num other); +- num operator %(num other); +- int operator ~(); +- int toInt(); +- double toDouble(); +- num abs(); +- int round(); +-} +- +-abstract class int extends num { +- bool get isEven =3D> false; +- int operator -(); +- external static int parse(String source, +- { int radix, +- int onError(String source) }); +-} +- +-abstract class double extends num { +- static const double NAN =3D 0.0 / 0.0; +- static const double INFINITY =3D 1.0 / 0.0; +- static const double NEGATIVE_INFINITY =3D -INFINITY; +- static const double MIN_POSITIVE =3D 5e-324; +- static const double MAX_FINITE =3D 1.7976931348623157e+308; +- +- double remainder(num other); +- double operator +(num other); +- double operator -(num other); +- double operator *(num other); +- double operator %(num other); +- double operator /(num other); +- int operator ~/(num other); +- double operator -(); +- double abs(); +- double get sign; +- int round(); +- int floor(); +- int ceil(); +- int truncate(); +- double roundToDouble(); +- double floorToDouble(); +- double ceilToDouble(); +- double truncateToDouble(); +- external static double parse(String source, +- [double onError(String source)]); +-} +- +-class DateTime extends Object {} +-class Null extends Object {} +- +-class Deprecated extends Object { +- final String expires; +- const Deprecated(this.expires); +-} +-const Object deprecated =3D const Deprecated("next release"); +- +-class Iterator { +- bool moveNext(); +- E get current; +-} +- +-abstract class Iterable { +- Iterator get iterator; +- bool get isEmpty; +- Iterable map(T f(E e)) =3D> null; +- T fold(T initialValue, T combine(T previousValue, E element)); +-} +- +-class List implements Iterable { +- List(); +- void add(E value) {} +- void addAll(Iterable iterable) {} +- E operator [](int index) =3D> null; +- void operator []=3D(int index, E value) {} +- Iterator get iterator =3D> null; +- void clear() {} +- +- bool get isEmpty =3D> false; +- E get first =3D> null; +- E get last =3D> null; +-} +- +-abstract class Map extends Object { +- bool containsKey(Object key); +- Iterable get keys; +-} +- +-external bool identical(Object a, Object b); +- +-void print(Object object) {} +- +-class Uri { +- static List parseIPv6Address(String host, [int start =3D 0, int en= d]) { +- int parseHex(int start, int end) { +- return 0; +- } +- return null; +- } +-} +-'''); +- +- static const MockSdkLibrary LIB_ASYNC =3D +- const MockSdkLibrary('dart:async', '/lib/async/async.dart', ''' +-library dart.async; +- +-import 'dart:math'; +- +-class Future { +- factory Future(computation()) =3D> null; +- factory Future.delayed(Duration duration, [T computation()]) =3D> null; +- factory Future.value([value]) =3D> null; +- static Future wait(List futures) =3D> null; +-} +- +-class FutureOr {} +- +-class Stream {} +-abstract class StreamTransformer {} +-'''); +- +- static const MockSdkLibrary LIB_COLLECTION =3D const MockSdkLibrary( +- 'dart:collection', '/lib/collection/collection.dart', ''' +-library dart.collection; +- +-abstract class HashMap implements Map {} +-abstract class LinkedHashMap implements Map {} +-'''); +- +- static const MockSdkLibrary LIB_CONVERT =3D +- const MockSdkLibrary('dart:convert', '/lib/convert/convert.dart', '= '' +-library dart.convert; +- +-import 'dart:async'; +- +-abstract class Converter implements StreamTransformer {} +-class JsonDecoder extends Converter {} +-'''); +- +- static const MockSdkLibrary LIB_MATH =3D +- const MockSdkLibrary('dart:math', '/lib/math/math.dart', ''' +-library dart.math; +-const double E =3D 2.718281828459045; +-const double PI =3D 3.1415926535897932; +-const double LN10 =3D 2.302585092994046; +-T min(T a, T b) =3D> null; +-T max(T a, T b) =3D> null; +-external double cos(num radians); +-external num pow(num x, num exponent); +-external double sin(num radians); +-external double sqrt(num x); +-class Random { +- bool nextBool() =3D> true; +- double nextDouble() =3D> 2.0; +- int nextInt() =3D> 1; +-} +-'''); +- +- static const MockSdkLibrary LIB_HTML =3D const MockSdkLibrary( +- 'dart:html', '/lib/html/dartium/html_dartium.dart', ''' +-library dart.html; +-class HtmlElement {} +-'''); +- +- static const MockSdkLibrary LIB_INTERNAL =3D +- const MockSdkLibrary('dart:_internal', '/lib/internal/internal.dart= ', ''' +-library dart._internal; +-external void printToConsole(String line); +-'''); +- +- static const List LIBRARIES =3D const [ +- LIB_CORE, +- LIB_ASYNC, +- LIB_COLLECTION, +- LIB_CONVERT, +- LIB_MATH, +- LIB_HTML, +- LIB_INTERNAL, +- ]; +- +- static const String librariesContent =3D r''' +-const Map libraries =3D const { +- "async": const LibraryInfo("async/async.dart"), +- "collection": const LibraryInfo("collection/collection.dart"), +- "convert": const LibraryInfo("convert/convert.dart"), +- "core": const LibraryInfo("core/core.dart"), +- "html": const LibraryInfo("html/dartium/html_dartium.dart"), +- "math": const LibraryInfo("math/math.dart"), +- "_internal": const LibraryInfo("internal/internal.dart"), +-}; +-'''; +- +- final resource.MemoryResourceProvider provider; +- +- /** +- * The [AnalysisContext] which is used for all of the sources. +- */ +- InternalAnalysisContext _analysisContext; +- +- /** +- * The cached linked bundle of the SDK. +- */ +- PackageBundle _bundle; +- +- MockSdk( +- {bool generateSummaryFiles: false, +- resource.ResourceProvider resourceProvider}) +- : provider =3D resourceProvider ?? new resource.MemoryResourceProvi= der() { +- LIBRARIES.forEach((SdkLibrary library) { +- provider.newFile(library.path, (library as MockSdkLibrary).content); +- }); +- provider.newFile( +- provider.convertPath( +- '/lib/_internal/sdk_library_metadata/lib/libraries.dart'), +- librariesContent); +- if (generateSummaryFiles) { +- List bytes =3D _computeLinkedBundleBytes(); +- provider.newFileWithBytes( +- provider.convertPath('/lib/_internal/spec.sum'), bytes); +- provider.newFileWithBytes( +- provider.convertPath('/lib/_internal/strong.sum'), bytes); +- } +- } +- +- @override +- AnalysisContext get context { +- if (_analysisContext =3D=3D null) { +- _analysisContext =3D new SdkAnalysisContext(null); +- SourceFactory factory =3D new SourceFactory([new DartUriResolver(th= is)]); +- _analysisContext.sourceFactory =3D factory; +- } +- return _analysisContext; +- } +- +- @override +- List get sdkLibraries =3D> LIBRARIES; +- +- @override +- String get sdkVersion =3D> throw unimplemented; +- +- UnimplementedError get unimplemented =3D> new UnimplementedError(); +- +- @override +- List get uris { +- List uris =3D []; +- for (SdkLibrary library in LIBRARIES) { +- uris.add(library.shortName); +- } +- return uris; +- } +- +- @override +- Source fromFileUri(Uri uri) { +- String filePath =3D provider.pathContext.fromUri(uri); +- for (SdkLibrary library in sdkLibraries) { +- String libraryPath =3D provider.convertPath(library.path); +- if (filePath =3D=3D libraryPath) { +- try { +- resource.File file =3D provider.getResource(filePath); +- Uri dartUri =3D Uri.parse(library.shortName); +- return file.createSource(dartUri); +- } catch (exception) { +- return null; +- } +- } +- String libraryRootPath =3D provider.pathContext.dirname(libraryPath= ) + +- provider.pathContext.separator; +- if (filePath.startsWith(libraryRootPath)) { +- String pathInLibrary =3D filePath.substring(libraryRootPath.lengt= h); +- String uriStr =3D '${library.shortName}/$pathInLibrary'; +- try { +- resource.File file =3D provider.getResource(filePath); +- Uri dartUri =3D Uri.parse(uriStr); +- return file.createSource(dartUri); +- } catch (exception) { +- return null; +- } +- } +- } +- return null; +- } +- +- @override +- PackageBundle getLinkedBundle() { +- if (_bundle =3D=3D null) { +- resource.File summaryFile =3D +- provider.getFile(provider.convertPath('/lib/_internal/spec.sum'= )); +- List bytes; +- if (summaryFile.exists) { +- bytes =3D summaryFile.readAsBytesSync(); +- } else { +- bytes =3D _computeLinkedBundleBytes(); +- } +- _bundle =3D new PackageBundle.fromBuffer(bytes); +- } +- return _bundle; +- } +- +- @override +- SdkLibrary getSdkLibrary(String dartUri) { +- // getSdkLibrary() is only used to determine whether a library is int= ernal +- // to the SDK. The mock SDK doesn't have any internals, so it's safe= to +- // return null. +- return null; +- } +- +- @override +- Source mapDartUri(String dartUri) { +- const Map uriToPath =3D const { +- "dart:core": "/lib/core/core.dart", +- "dart:html": "/lib/html/dartium/html_dartium.dart", +- "dart:async": "/lib/async/async.dart", +- "dart:collection": "/lib/collection/collection.dart", +- "dart:convert": "/lib/convert/convert.dart", +- "dart:math": "/lib/math/math.dart", +- "dart:_internal": "/lib/internal/internal.dart", +- }; +- +- String path =3D uriToPath[dartUri]; +- if (path !=3D null) { +- resource.File file =3D provider.getResource(path); +- Uri uri =3D new Uri(scheme: 'dart', path: dartUri.substring(5)); +- return file.createSource(uri); +- } +- +- // If we reach here then we tried to use a dartUri that's not in the +- // table above. +- return null; +- } +- +- /** +- * Compute the bytes of the linked bundle associated with this SDK. +- */ +- List _computeLinkedBundleBytes() { +- List librarySources =3D sdkLibraries +- .map((SdkLibrary library) =3D> mapDartUri(library.shortName)) +- .toList(); +- return new SummaryBuilder( +- librarySources, context, context.analysisOptions.strongMode) +- .build(); +- } +-} +- +-class MockSdkLibrary implements SdkLibrary { +- final String shortName; +- final String path; +- final String content; +- +- const MockSdkLibrary(this.shortName, this.path, this.content); +- +- @override +- String get category =3D> throw unimplemented; +- +- @override +- bool get isDart2JsLibrary =3D> throw unimplemented; +- +- @override +- bool get isDocumented =3D> throw unimplemented; +- +- @override +- bool get isImplementation =3D> false; +- +- @override +- bool get isInternal =3D> shortName.startsWith('dart:_'); +- +- @override +- bool get isShared =3D> throw unimplemented; +- +- @override +- bool get isVmLibrary =3D> throw unimplemented; +- +- UnimplementedError get unimplemented =3D> new UnimplementedError(); +-} +diff --git a/pkg/analysis_server/test/mocks.dart b/pkg/analysis_server/tes= t/mocks.dart +deleted file mode 100644 +index 20a5fcd6a4a..00000000000 +--- a/pkg/analysis_server/test/mocks.dart ++++ /dev/null +@@ -1,320 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/channel/channel.dart'; +-import 'package:analyzer/file_system/file_system.dart' as resource; +-import 'package:analyzer/file_system/memory_file_system.dart' as resource; +-import 'package:analyzer/source/package_map_provider.dart'; +-import 'package:analyzer/source/pub_package_map_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:mockito/mockito.dart'; +-import 'package:test/test.dart'; +- +-/** +- * Answer the absolute path the SDK relative to the currently running +- * script or throw an exception if it cannot be found. +- */ +-String get sdkPath { +- Uri sdkUri =3D Platform.script.resolve('../../../sdk/'); +- +- // Verify the directory exists +- Directory sdkDir =3D new Directory.fromUri(sdkUri); +- if (!sdkDir.existsSync()) { +- throw 'Specified Dart SDK does not exist: $sdkDir'; +- } +- +- return sdkDir.path; +-} +- +-/** +- * A [Matcher] that check that the given [Response] has an expected ident= ifier +- * and has an error. The error code may optionally be checked. +- */ +-Matcher isResponseFailure(String id, [RequestErrorCode code]) =3D> +- new _IsResponseFailure(id, code); +- +-/** +- * A [Matcher] that check that the given [Response] has an expected ident= ifier +- * and no error. +- */ +-Matcher isResponseSuccess(String id) =3D> new _IsResponseSuccess(id); +- +-/** +- * Returns a [Future] that completes after pumping the event queue [times] +- * times. By default, this should pump the event queue enough times to al= low +- * any code to run, as long as it's not waiting on some external event. +- */ +-Future pumpEventQueue([int times =3D 5000]) { +- if (times =3D=3D 0) return new Future.value(); +- // We use a delayed future to allow microtask events to finish. The +- // Future.value or Future() constructors use scheduleMicrotask themselv= es and +- // would therefore not wait for microtask callbacks that are scheduled = after +- // invoking this method. +- return new Future.delayed(Duration.ZERO, () =3D> pumpEventQueue(times -= 1)); +-} +- +-/** +- * A mock [PackageMapProvider]. +- */ +-class MockPackageMapProvider implements PubPackageMapProvider { +- /** +- * Package map that will be returned by the next call to [computePackag= eMap]. +- */ +- Map> packageMap =3D +- >{}; +- +- /** +- * Package maps that will be returned by the next call to [computePacka= geMap]. +- */ +- Map>> packageMaps =3D null; +- +- /** +- * Dependency list that will be returned by the next call to [computePa= ckageMap]. +- */ +- Set dependencies =3D new Set(); +- +- /** +- * Number of times [computePackageMap] has been called. +- */ +- int computeCount =3D 0; +- +- @override +- PackageMapInfo computePackageMap(resource.Folder folder) { +- ++computeCount; +- if (packageMaps !=3D null) { +- return new PackageMapInfo(packageMaps[folder.path], dependencies); +- } +- return new PackageMapInfo(packageMap, dependencies); +- } +- +- noSuchMethod(Invocation invocation) { +- // No other methods should be called. +- return super.noSuchMethod(invocation); +- } +-} +- +-/** +- * A mock [ServerCommunicationChannel] for testing [AnalysisServer]. +- */ +-class MockServerChannel implements ServerCommunicationChannel { +- StreamController requestController =3D new StreamController(); +- StreamController responseController =3D +- new StreamController.broadcast(); +- StreamController notificationController =3D +- new StreamController(sync: true); +- +- List responsesReceived =3D []; +- List notificationsReceived =3D []; +- bool _closed =3D false; +- +- MockServerChannel(); +- @override +- void close() { +- _closed =3D true; +- } +- +- void expectMsgCount({responseCount: 0, notificationCount: 0}) { +- expect(responsesReceived, hasLength(responseCount)); +- expect(notificationsReceived, hasLength(notificationCount)); +- } +- +- @override +- void listen(void onRequest(Request request), +- {Function onError, void onDone()}) { +- requestController.stream +- .listen(onRequest, onError: onError, onDone: onDone); +- } +- +- @override +- void sendNotification(Notification notification) { +- // Don't deliver notifications after the connection is closed. +- if (_closed) { +- return; +- } +- notificationsReceived.add(notification); +- // Wrap send notification in future to simulate websocket +- // TODO(scheglov) ask Dan why and decide what to do +-// new Future(() =3D> notificationController.add(notification)); +- notificationController.add(notification); +- } +- +- /** +- * Simulate request/response pair. +- */ +- Future sendRequest(Request request) { +- // No further requests should be sent after the connection is closed. +- if (_closed) { +- throw new Exception('sendRequest after connection closed'); +- } +- // Wrap send request in future to simulate WebSocket. +- new Future(() =3D> requestController.add(request)); +- return waitForResponse(request); +- } +- +- @override +- void sendResponse(Response response) { +- // Don't deliver responses after the connection is closed. +- if (_closed) { +- return; +- } +- responsesReceived.add(response); +- // Wrap send response in future to simulate WebSocket. +- new Future(() =3D> responseController.add(response)); +- } +- +- Future waitForResponse(Request request) { +- String id =3D request.id; +- return new Future(() =3D> responseController.stream +- .firstWhere((response) =3D> response.id =3D=3D id) as Future); +- } +-} +- +-/** +- * A mock [WebSocket] for testing. +- */ +-class MockSocket implements WebSocket { +- StreamController controller =3D new StreamController(); +- MockSocket twin; +- Stream stream; +- +- MockSocket(); +- +- factory MockSocket.pair() { +- MockSocket socket1 =3D new MockSocket(); +- MockSocket socket2 =3D new MockSocket(); +- socket1.twin =3D socket2; +- socket2.twin =3D socket1; +- socket1.stream =3D socket2.controller.stream; +- socket2.stream =3D socket1.controller.stream; +- return socket1; +- } +- +- void add(dynamic text) =3D> controller.add(text as T); +- +- void allowMultipleListeners() { +- stream =3D stream.asBroadcastStream(); +- } +- +- Future close([int code, String reason]) =3D> +- controller.close().then((_) =3D> twin.controller.close()); +- +- StreamSubscription listen(void onData(dynamic event), +- {Function onError, void onDone(), bool cancelOnError}) =3D> +- stream.listen((T data) =3D> onData(data), +- onError: onError, onDone: onDone, cancelOnError: cancelOnError); +- +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +- +- Stream where(bool test(dynamic t)) =3D> stream.where((T data) =3D> t= est(data)); +-} +- +-class MockSource extends StringTypedMock implements Source { +- MockSource([String name =3D 'mocked.dart']) : super(name); +-} +- +-class StringTypedMock extends Mock { +- String _toString; +- +- StringTypedMock(this._toString); +- +- @override +- String toString() { +- if (_toString !=3D null) { +- return _toString; +- } +- return super.toString(); +- } +-} +- +-/** +- * A [Matcher] that check that there are no `error` in a given [Response]. +- */ +-class _IsResponseFailure extends Matcher { +- final String _id; +- final RequestErrorCode _code; +- +- _IsResponseFailure(this._id, this._code); +- +- @override +- Description describe(Description description) { +- description =3D +- description.add('response with identifier "$_id" and an error'); +- if (_code !=3D null) { +- description =3D description.add(' with code ${this._code.name}'); +- } +- return description; +- } +- +- @override +- Description describeMismatch( +- item, Description mismatchDescription, Map matchState, bool verbose= ) { +- Response response =3D item; +- var id =3D response.id; +- RequestError error =3D response.error; +- mismatchDescription.add('has identifier "$id"'); +- if (error =3D=3D null) { +- mismatchDescription.add(' and has no error'); +- } else { +- mismatchDescription +- .add(' and has error code ${response.error.code.name}'); +- } +- return mismatchDescription; +- } +- +- @override +- bool matches(item, Map matchState) { +- Response response =3D item; +- if (response.id !=3D _id || response.error =3D=3D null) { +- return false; +- } +- if (_code !=3D null && response.error.code !=3D _code) { +- return false; +- } +- return true; +- } +-} +- +-/** +- * A [Matcher] that check that there are no `error` in a given [Response]. +- */ +-class _IsResponseSuccess extends Matcher { +- final String _id; +- +- _IsResponseSuccess(this._id); +- +- @override +- Description describe(Description description) { +- return description +- .addDescriptionOf('response with identifier "$_id" and without er= ror'); +- } +- +- @override +- Description describeMismatch( +- item, Description mismatchDescription, Map matchState, bool verbose= ) { +- Response response =3D item; +- if (response =3D=3D null) { +- mismatchDescription.add('is null response'); +- } else { +- var id =3D response.id; +- RequestError error =3D response.error; +- mismatchDescription.add('has identifier "$id"'); +- if (error !=3D null) { +- mismatchDescription.add(' and has error $error'); +- } +- } +- return mismatchDescription; +- } +- +- @override +- bool matches(item, Map matchState) { +- Response response =3D item; +- return response !=3D null && response.id =3D=3D _id && response.error= =3D=3D null; +- } +-} +diff --git a/pkg/analysis_server/test/plugin/protocol_dart_test.dart b/pkg= /analysis_server/test/plugin/protocol_dart_test.dart +deleted file mode 100644 +index 9a1717a9b03..00000000000 +--- a/pkg/analysis_server/test/plugin/protocol_dart_test.dart ++++ /dev/null +@@ -1,461 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/plugin/protocol/protocol_dart.dart'; +-import 'package:analyzer/dart/ast/ast.dart' as engine; +-import 'package:analyzer/dart/ast/visitor.dart' as engine; +-import 'package:analyzer/dart/element/element.dart' as engine; +-import 'package:analyzer/dart/element/type.dart' as engine; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/src/dart/ast/utilities.dart' as engine; +-import 'package:analyzer/src/dart/element/element.dart' as engine; +-import 'package:analyzer/src/error/codes.dart' as engine; +-import 'package:analyzer/src/generated/source.dart' as engine; +-import 'package:analyzer/src/generated/testing/element_search.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../abstract_context.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ElementTest); +- defineReflectiveTests(ElementKindTest); +- }); +-} +- +-@reflectiveTest +-class ElementKindTest { +- void test_fromEngine() { +- expect(convertElementKind(engine.ElementKind.CLASS), ElementKind.CLAS= S); +- expect(convertElementKind(engine.ElementKind.COMPILATION_UNIT), +- ElementKind.COMPILATION_UNIT); +- expect(convertElementKind(engine.ElementKind.CONSTRUCTOR), +- ElementKind.CONSTRUCTOR); +- expect(convertElementKind(engine.ElementKind.FIELD), ElementKind.FIEL= D); +- expect( +- convertElementKind(engine.ElementKind.FUNCTION), ElementKind.FUNC= TION); +- expect(convertElementKind(engine.ElementKind.FUNCTION_TYPE_ALIAS), +- ElementKind.FUNCTION_TYPE_ALIAS); +- expect(convertElementKind(engine.ElementKind.GETTER), ElementKind.GET= TER); +- expect(convertElementKind(engine.ElementKind.LABEL), ElementKind.LABE= L); +- expect(convertElementKind(engine.ElementKind.LIBRARY), ElementKind.LI= BRARY); +- expect(convertElementKind(engine.ElementKind.LOCAL_VARIABLE), +- ElementKind.LOCAL_VARIABLE); +- expect(convertElementKind(engine.ElementKind.METHOD), ElementKind.MET= HOD); +- expect(convertElementKind(engine.ElementKind.PARAMETER), +- ElementKind.PARAMETER); +- expect(convertElementKind(engine.ElementKind.SETTER), ElementKind.SET= TER); +- expect(convertElementKind(engine.ElementKind.TOP_LEVEL_VARIABLE), +- ElementKind.TOP_LEVEL_VARIABLE); +- expect(convertElementKind(engine.ElementKind.TYPE_PARAMETER), +- ElementKind.TYPE_PARAMETER); +- } +- +- void test_string_constructor() { +- expect(new ElementKind(ElementKind.CLASS.name), ElementKind.CLASS); +- expect(new ElementKind(ElementKind.CLASS_TYPE_ALIAS.name), +- ElementKind.CLASS_TYPE_ALIAS); +- expect(new ElementKind(ElementKind.COMPILATION_UNIT.name), +- ElementKind.COMPILATION_UNIT); +- expect( +- new ElementKind(ElementKind.CONSTRUCTOR.name), ElementKind.CONSTR= UCTOR); +- expect(new ElementKind(ElementKind.FIELD.name), ElementKind.FIELD); +- expect(new ElementKind(ElementKind.FUNCTION.name), ElementKind.FUNCTI= ON); +- expect(new ElementKind(ElementKind.FUNCTION_TYPE_ALIAS.name), +- ElementKind.FUNCTION_TYPE_ALIAS); +- expect(new ElementKind(ElementKind.GETTER.name), ElementKind.GETTER); +- expect(new ElementKind(ElementKind.LIBRARY.name), ElementKind.LIBRARY= ); +- expect(new ElementKind(ElementKind.LOCAL_VARIABLE.name), +- ElementKind.LOCAL_VARIABLE); +- expect(new ElementKind(ElementKind.METHOD.name), ElementKind.METHOD); +- expect(new ElementKind(ElementKind.PARAMETER.name), ElementKind.PARAM= ETER); +- expect(new ElementKind(ElementKind.SETTER.name), ElementKind.SETTER); +- expect(new ElementKind(ElementKind.TOP_LEVEL_VARIABLE.name), +- ElementKind.TOP_LEVEL_VARIABLE); +- expect(new ElementKind(ElementKind.TYPE_PARAMETER.name), +- ElementKind.TYPE_PARAMETER); +- expect(new ElementKind(ElementKind.UNIT_TEST_TEST.name), +- ElementKind.UNIT_TEST_TEST); +- expect(new ElementKind(ElementKind.UNIT_TEST_GROUP.name), +- ElementKind.UNIT_TEST_GROUP); +- expect(new ElementKind(ElementKind.UNKNOWN.name), ElementKind.UNKNOWN= ); +- expect(() { +- new ElementKind('no-such-kind'); +- }, throwsException); +- } +- +- void test_toString() { +- expect(ElementKind.CLASS.toString(), 'ElementKind.CLASS'); +- expect(ElementKind.COMPILATION_UNIT.toString(), +- 'ElementKind.COMPILATION_UNIT'); +- } +-} +- +-@reflectiveTest +-class ElementTest extends AbstractContextTest { +- engine.Element findElementInUnit(engine.CompilationUnit unit, String na= me, +- [engine.ElementKind kind]) { +- return findElementsByName(unit, name) +- .where((e) =3D> kind =3D=3D null || e.kind =3D=3D kind) +- .single; +- } +- +- test_fromElement_CLASS() async { +- engine.Source source =3D addSource('/test.dart', ''' +-@deprecated +-abstract class _A {} +-class B {}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- { +- engine.ClassElement engineElement =3D findElementInUnit(unit, '_A'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.CLASS); +- expect(element.name, '_A'); +- expect(element.typeParameters, isNull); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 27); +- expect(location.length, '_A'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 16); +- } +- expect(element.parameters, isNull); +- expect( +- element.flags, +- Element.FLAG_ABSTRACT | +- Element.FLAG_DEPRECATED | +- Element.FLAG_PRIVATE); +- } +- { +- engine.ClassElement engineElement =3D findElementInUnit(unit, 'B'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.CLASS); +- expect(element.name, 'B'); +- expect(element.typeParameters, ''); +- expect(element.flags, 0); +- } +- } +- +- test_fromElement_CONSTRUCTOR() async { +- engine.Source source =3D addSource('/test.dart', ''' +-class A { +- const A.myConstructor(int a, [String b]); +-}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.ConstructorElement engineElement =3D +- findElementInUnit(unit, 'myConstructor'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.CONSTRUCTOR); +- expect(element.name, 'myConstructor'); +- expect(element.typeParameters, isNull); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 20); +- expect(location.length, 'myConstructor'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 11); +- } +- expect(element.parameters, '(int a, [String b])'); +- expect(element.returnType, 'A'); +- expect(element.flags, Element.FLAG_CONST); +- } +- +- void test_fromElement_dynamic() { +- var engineElement =3D engine.DynamicElementImpl.instance; +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.UNKNOWN); +- expect(element.name, 'dynamic'); +- expect(element.location, isNull); +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- expect(element.flags, 0); +- } +- +- test_fromElement_ENUM() async { +- engine.Source source =3D addSource('/test.dart', ''' +-@deprecated +-enum _E1 { one, two } +-enum E2 { three, four }'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- { +- engine.ClassElement engineElement =3D findElementInUnit(unit, '_E1'= ); +- expect(engineElement.isDeprecated, isTrue); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.ENUM); +- expect(element.name, '_E1'); +- expect(element.typeParameters, isNull); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 17); +- expect(location.length, '_E1'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 6); +- } +- expect(element.parameters, isNull); +- expect( +- element.flags, +- (engineElement.isDeprecated ? Element.FLAG_DEPRECATED : 0) | +- Element.FLAG_PRIVATE); +- } +- { +- engine.ClassElement engineElement =3D findElementInUnit(unit, 'E2'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.ENUM); +- expect(element.name, 'E2'); +- expect(element.typeParameters, isNull); +- expect(element.flags, 0); +- } +- } +- +- test_fromElement_ENUM_CONSTANT() async { +- engine.Source source =3D addSource('/test.dart', ''' +-@deprecated +-enum _E1 { one, two } +-enum E2 { three, four }'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- { +- engine.FieldElement engineElement =3D findElementInUnit(unit, 'one'= ); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.ENUM_CONSTANT); +- expect(element.name, 'one'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 23); +- expect(location.length, 'one'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 12); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, '_E1'); +- // TODO(danrubel) determine why enum constant is not marked as depr= ecated +- //engine.ClassElement classElement =3D engineElement.enclosingEleme= nt; +- //expect(classElement.isDeprecated, isTrue); +- expect( +- element.flags, +- // Element.FLAG_DEPRECATED | +- Element.FLAG_CONST | Element.FLAG_STATIC); +- } +- { +- engine.FieldElement engineElement =3D findElementInUnit(unit, 'thre= e'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.ENUM_CONSTANT); +- expect(element.name, 'three'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 44); +- expect(location.length, 'three'.length); +- expect(location.startLine, 3); +- expect(location.startColumn, 11); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, 'E2'); +- expect(element.flags, Element.FLAG_CONST | Element.FLAG_STATIC); +- } +- { +- engine.FieldElement engineElement =3D +- unit.element.enums[1].getField('index'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, 'index'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, -1); +- expect(location.length, 'index'.length); +- expect(location.startLine, 1); +- expect(location.startColumn, 0); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, 'int'); +- expect(element.flags, Element.FLAG_FINAL); +- } +- { +- engine.FieldElement engineElement =3D +- unit.element.enums[1].getField('values'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, 'values'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, -1); +- expect(location.length, 'values'.length); +- expect(location.startLine, 1); +- expect(location.startColumn, 0); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, 'List'); +- expect(element.flags, Element.FLAG_CONST | Element.FLAG_STATIC); +- } +- } +- +- test_fromElement_FIELD() async { +- engine.Source source =3D addSource('/test.dart', ''' +-class A { +- static const myField =3D 42; +-}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.FieldElement engineElement =3D findElementInUnit(unit, 'myFiel= d'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, 'myField'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 25); +- expect(location.length, 'myField'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 16); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, 'int'); +- expect(element.flags, Element.FLAG_CONST | Element.FLAG_STATIC); +- } +- +- test_fromElement_FUNCTION_TYPE_ALIAS() async { +- engine.Source source =3D addSource('/test.dart', ''' +-typedef int F(String x); +-'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.FunctionTypeAliasElement engineElement =3D +- findElementInUnit(unit, 'F'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.FUNCTION_TYPE_ALIAS); +- expect(element.name, 'F'); +- expect(element.typeParameters, ''); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 12); +- expect(location.length, 'F'.length); +- expect(location.startLine, 1); +- expect(location.startColumn, 13); +- } +- expect(element.parameters, '(String x)'); +- expect(element.returnType, 'int'); +- expect(element.flags, 0); +- } +- +- test_fromElement_GETTER() async { +- engine.Source source =3D addSource('/test.dart', ''' +-class A { +- String get myGetter =3D> 42; +-}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.PropertyAccessorElement engineElement =3D +- findElementInUnit(unit, 'myGetter', engine.ElementKind.GETTER); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.GETTER); +- expect(element.name, 'myGetter'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 23); +- expect(location.length, 'myGetter'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 14); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, 'String'); +- expect(element.flags, 0); +- } +- +- test_fromElement_LABEL() async { +- engine.Source source =3D addSource('/test.dart', ''' +-main() { +-myLabel: +- while (true) { +- break myLabel; +- } +-}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.LabelElement engineElement =3D findElementInUnit(unit, 'myLabe= l'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.LABEL); +- expect(element.name, 'myLabel'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 9); +- expect(location.length, 'myLabel'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 1); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- expect(element.flags, 0); +- } +- +- test_fromElement_METHOD() async { +- engine.Source source =3D addSource('/test.dart', ''' +-class A { +- static List myMethod(int a, {String b, int c}) { +- return null; +- } +-}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.MethodElement engineElement =3D findElementInUnit(unit, 'myMet= hod'); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.METHOD); +- expect(element.name, 'myMethod'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 32); +- expect(location.length, 'myGetter'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 23); +- } +- expect(element.parameters, '(int a, {String b, int c})'); +- expect(element.returnType, 'List'); +- expect(element.flags, Element.FLAG_STATIC); +- } +- +- test_fromElement_SETTER() async { +- engine.Source source =3D addSource('/test.dart', ''' +-class A { +- set mySetter(String x) {} +-}'''); +- engine.CompilationUnit unit =3D await resolveLibraryUnit(source); +- engine.PropertyAccessorElement engineElement =3D +- findElementInUnit(unit, 'mySetter', engine.ElementKind.SETTER); +- // create notification Element +- Element element =3D convertElement(engineElement); +- expect(element.kind, ElementKind.SETTER); +- expect(element.name, 'mySetter'); +- { +- Location location =3D element.location; +- expect(location.file, '/test.dart'); +- expect(location.offset, 16); +- expect(location.length, 'mySetter'.length); +- expect(location.startLine, 2); +- expect(location.startColumn, 7); +- } +- expect(element.parameters, '(String x)'); +- expect(element.returnType, isNull); +- expect(element.flags, 0); +- } +-} +diff --git a/pkg/analysis_server/test/plugin/test_all.dart b/pkg/analysis_= server/test/plugin/test_all.dart +deleted file mode 100644 +index 8390a16e680..00000000000 +--- a/pkg/analysis_server/test/plugin/test_all.dart ++++ /dev/null +@@ -1,16 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'protocol_dart_test.dart' as protocol_dart_test; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- defineReflectiveSuite(() { +- protocol_dart_test.main(); +- }, name: 'plugin'); +-} +diff --git a/pkg/analysis_server/test/protocol_server_test.dart b/pkg/anal= ysis_server/test/protocol_server_test.dart +deleted file mode 100644 +index df05a2ba66b..00000000000 +--- a/pkg/analysis_server/test/protocol_server_test.dart ++++ /dev/null +@@ -1,196 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:mirrors'; +- +-import 'package:analysis_server/src/constants.dart'; +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analyzer/dart/ast/ast.dart' as engine; +-import 'package:analyzer/dart/element/element.dart' as engine; +-import 'package:analyzer/dart/element/type.dart' as engine; +-import 'package:analyzer/error/error.dart' as engine; +-import 'package:analyzer/src/error/codes.dart' as engine; +-import 'package:analyzer/src/generated/source.dart' as engine; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:mockito/mockito.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AnalysisErrorTest); +- defineReflectiveTests(EnumTest); +- }); +-} +- +-class AnalysisErrorMock extends Mock implements engine.AnalysisError {} +- +-@reflectiveTest +-class AnalysisErrorTest { +- engine.Source source =3D new MockSource(); +- engine.LineInfo lineInfo; +- engine.AnalysisError engineError =3D new AnalysisErrorMock(); +- +- void setUp() { +- // prepare Source +- when(source.fullName).thenReturn('foo.dart'); +- // prepare LineInfo +- lineInfo =3D new engine.LineInfo([0, 5, 9, 20]); +- // prepare AnalysisError +- when(engineError.source).thenReturn(source); +- when(engineError.errorCode) +- .thenReturn(engine.CompileTimeErrorCode.AMBIGUOUS_EXPORT); +- when(engineError.message).thenReturn('my message'); +- when(engineError.offset).thenReturn(10); +- when(engineError.length).thenReturn(20); +- } +- +- void tearDown() { +- source =3D null; +- engineError =3D null; +- } +- +- void test_fromEngine_hasCorrection() { +- when(engineError.correction).thenReturn('my correction'); +- AnalysisError error =3D newAnalysisError_fromEngine(lineInfo, engineE= rror); +- expect(error.toJson(), { +- SEVERITY: 'ERROR', +- TYPE: 'COMPILE_TIME_ERROR', +- LOCATION: { +- FILE: 'foo.dart', +- OFFSET: 10, +- LENGTH: 20, +- START_LINE: 3, +- START_COLUMN: 2 +- }, +- MESSAGE: 'my message', +- CORRECTION: 'my correction', +- CODE: 'ambiguous_export', +- HAS_FIX: false +- }); +- } +- +- void test_fromEngine_noCorrection() { +- when(engineError.correction).thenReturn(null); +- AnalysisError error =3D newAnalysisError_fromEngine(lineInfo, engineE= rror); +- expect(error.toJson(), { +- SEVERITY: 'ERROR', +- TYPE: 'COMPILE_TIME_ERROR', +- LOCATION: { +- FILE: 'foo.dart', +- OFFSET: 10, +- LENGTH: 20, +- START_LINE: 3, +- START_COLUMN: 2 +- }, +- MESSAGE: 'my message', +- CODE: 'ambiguous_export', +- HAS_FIX: false +- }); +- } +- +- void test_fromEngine_noLineInfo() { +- when(engineError.correction).thenReturn(null); +- AnalysisError error =3D newAnalysisError_fromEngine(null, engineError= ); +- expect(error.toJson(), { +- SEVERITY: 'ERROR', +- TYPE: 'COMPILE_TIME_ERROR', +- LOCATION: { +- FILE: 'foo.dart', +- OFFSET: 10, +- LENGTH: 20, +- START_LINE: -1, +- START_COLUMN: -1 +- }, +- MESSAGE: 'my message', +- CODE: 'ambiguous_export', +- HAS_FIX: false +- }); +- } +-} +- +-@reflectiveTest +-class EnumTest { +- void test_AnalysisErrorSeverity() { +- new EnumTester().run( +- (engine.ErrorSeverity engineErrorSeverity) =3D> +- new AnalysisErrorSeverity(engineErrorSeverity.name), +- exceptions: {engine.ErrorSeverity.NONE: null}); +- } +- +- void test_AnalysisErrorType() { +- new EnumTester().run( +- (engine.ErrorType engineErrorType) =3D> +- new AnalysisErrorType(engineErrorType.name)); +- } +- +- void test_ElementKind() { +- new EnumTester() +- .run(convertElementKind, exceptions: { +- // TODO(paulberry): do any of the exceptions below constitute bugs? +- engine.ElementKind.DYNAMIC: ElementKind.UNKNOWN, +- engine.ElementKind.ERROR: ElementKind.UNKNOWN, +- engine.ElementKind.EXPORT: ElementKind.UNKNOWN, +- engine.ElementKind.GENERIC_FUNCTION_TYPE: ElementKind.UNKNOWN, +- engine.ElementKind.IMPORT: ElementKind.UNKNOWN, +- engine.ElementKind.NAME: ElementKind.UNKNOWN, +- engine.ElementKind.UNIVERSE: ElementKind.UNKNOWN +- }); +- } +- +- void test_SearchResultKind() { +- // TODO(paulberry): why does the MatchKind class exist at all? Can't= we +- // use SearchResultKind inside the analysis server? +- new EnumTester() +- .run(newSearchResultKind_fromEngine); +- } +-} +- +-/** +- * Helper class for testing the correspondence between an analysis engine= enum +- * and an analysis server API enum. +- */ +-class EnumTester { +- /** +- * Test that the function [convert] properly converts all possible valu= es of +- * [EngineEnum] to an [ApiEnum] with the same name, with the exceptions= noted +- * in [exceptions]. For each key in [exceptions], if the corresponding= value +- * is null, then we check that converting the given key results in an e= rror. +- * If the corresponding value is an [ApiEnum], then we check that conve= rting +- * the given key results in the given value. +- */ +- void run(ApiEnum convert(EngineEnum value), +- {Map exceptions: const {}}) { +- ClassMirror engineClass =3D reflectClass(EngineEnum); +- engineClass.staticMembers.forEach((Symbol symbol, MethodMirror method= ) { +- if (symbol =3D=3D #values) { +- return; +- } +- if (!method.isGetter) { +- return; +- } +- String enumName =3D MirrorSystem.getName(symbol); +- EngineEnum engineValue =3D +- engineClass.getField(symbol).reflectee as EngineEnum; +- expect(engineValue, new isInstanceOf()); +- if (exceptions.containsKey(engineValue)) { +- ApiEnum expectedResult =3D exceptions[engineValue]; +- if (expectedResult =3D=3D null) { +- expect(() { +- convert(engineValue); +- }, throwsException); +- } else { +- ApiEnum apiValue =3D convert(engineValue); +- expect(apiValue, equals(expectedResult)); +- } +- } else { +- ApiEnum apiValue =3D convert(engineValue); +- expect((apiValue as dynamic).name, equals(enumName)); +- } +- }); +- } +-} +diff --git a/pkg/analysis_server/test/protocol_test.dart b/pkg/analysis_se= rver/test/protocol_test.dart +deleted file mode 100644 +index ff48b1e8065..00000000000 +--- a/pkg/analysis_server/test/protocol_test.dart ++++ /dev/null +@@ -1,270 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/constants.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(NotificationTest); +- defineReflectiveTests(RequestTest); +- defineReflectiveTests(RequestErrorTest); +- defineReflectiveTests(ResponseTest); +- }); +-} +- +-@reflectiveTest +-class InvalidParameterResponseMatcher extends Matcher { +- static const String ERROR_CODE =3D 'INVALID_PARAMETER'; +- +- @override +- Description describe(Description description) =3D> +- description.add("an 'invalid parameter' response (code $ERROR_CODE)= "); +- +- @override +- bool matches(item, Map matchState) { +- if (item is! RequestFailure) { +- return false; +- } +- var response =3D item.response; +- if (response is! Response) { +- return false; +- } +- if (response.error is! RequestError) { +- return false; +- } +- RequestError requestError =3D response.error; +- if (requestError.code !=3D ERROR_CODE) { +- return false; +- } +- return true; +- } +-} +- +-@reflectiveTest +-class NotificationTest { +- void test_fromJson() { +- Notification original =3D new Notification('foo'); +- Notification notification =3D new Notification.fromJson(original.toJs= on()); +- expect(notification.event, equals('foo')); +- expect(notification.toJson().keys, isNot(contains('params'))); +- } +- +- void test_fromJson_withParams() { +- Notification original =3D new Notification('foo', {'x': 'y'}); +- Notification notification =3D new Notification.fromJson(original.toJs= on()); +- expect(notification.event, equals('foo')); +- expect(notification.toJson()['params'], equals({'x': 'y'})); +- } +- +- void test_toJson_noParams() { +- Notification notification =3D new Notification('foo'); +- expect(notification.event, equals('foo')); +- expect(notification.toJson().keys, isNot(contains('params'))); +- expect(notification.toJson(), equals({'event': 'foo'})); +- } +- +- void test_toJson_withParams() { +- Notification notification =3D new Notification('foo', {'x': 'y'}); +- expect(notification.event, equals('foo')); +- expect(notification.toJson()['params'], equals({'x': 'y'})); +- expect( +- notification.toJson(), +- equals({ +- 'event': 'foo', +- 'params': {'x': 'y'} +- })); +- } +-} +- +-@reflectiveTest +-class RequestErrorTest { +- void test_create() { +- RequestError error =3D +- new RequestError(RequestErrorCode.INVALID_REQUEST, 'msg'); +- expect(error.code, RequestErrorCode.INVALID_REQUEST); +- expect(error.message, "msg"); +- expect(error.toJson(), equals({CODE: 'INVALID_REQUEST', MESSAGE: "msg= "})); +- } +- +- void test_fromJson() { +- var trace =3D 'a stack trace\r\nfoo'; +- var json =3D { +- CODE: RequestErrorCode.INVALID_PARAMETER.name, +- MESSAGE: 'foo', +- STACK_TRACE: trace +- }; +- RequestError error =3D +- new RequestError.fromJson(new ResponseDecoder(null), '', json); +- expect(error.code, RequestErrorCode.INVALID_PARAMETER); +- expect(error.message, "foo"); +- expect(error.stackTrace, trace); +- } +- +- void test_toJson() { +- var trace =3D 'a stack trace\r\nbar'; +- RequestError error =3D new RequestError( +- RequestErrorCode.UNKNOWN_REQUEST, 'msg', +- stackTrace: trace); +- expect(error.toJson(), +- {CODE: 'UNKNOWN_REQUEST', MESSAGE: 'msg', STACK_TRACE: trace}); +- } +-} +- +-@reflectiveTest +-class RequestTest { +- void test_fromJson() { +- Request original =3D new Request('one', 'aMethod'); +- String json =3D JSON.encode(original.toJson()); +- Request request =3D new Request.fromString(json); +- expect(request.id, equals('one')); +- expect(request.method, equals('aMethod')); +- expect(request.clientRequestTime, isNull); +- } +- +- void test_fromJson_invalidId() { +- String json =3D +- '{"id":{"one":"two"},"method":"aMethod","params":{"foo":"bar"}}'; +- Request request =3D new Request.fromString(json); +- expect(request, isNull); +- } +- +- void test_fromJson_invalidMethod() { +- String json =3D +- '{"id":"one","method":{"boo":"aMethod"},"params":{"foo":"bar"}}'; +- Request request =3D new Request.fromString(json); +- expect(request, isNull); +- } +- +- void test_fromJson_invalidParams() { +- String json =3D '{"id":"one","method":"aMethod","params":"foobar"}'; +- Request request =3D new Request.fromString(json); +- expect(request, isNull); +- } +- +- void test_fromJson_withBadClientTime() { +- Request original =3D new Request('one', 'aMethod', null, 347); +- Map map =3D original.toJson(); +- // Insert bad value - should be int but client sent string instead +- map[Request.CLIENT_REQUEST_TIME] =3D '347'; +- String json =3D JSON.encode(map); +- Request request =3D new Request.fromString(json); +- expect(request, isNull); +- } +- +- void test_fromJson_withClientTime() { +- Request original =3D new Request('one', 'aMethod', null, 347); +- String json =3D JSON.encode(original.toJson()); +- Request request =3D new Request.fromString(json); +- expect(request.id, equals('one')); +- expect(request.method, equals('aMethod')); +- expect(request.clientRequestTime, 347); +- } +- +- void test_fromJson_withParams() { +- Request original =3D new Request('one', 'aMethod', {'foo': 'bar'}); +- String json =3D JSON.encode(original.toJson()); +- Request request =3D new Request.fromString(json); +- expect(request.id, equals('one')); +- expect(request.method, equals('aMethod')); +- expect(request.toJson()['params'], equals({'foo': 'bar'})); +- } +- +- void test_toJson() { +- Request request =3D new Request('one', 'aMethod'); +- expect(request.toJson(), +- equals({Request.ID: 'one', Request.METHOD: 'aMethod'})); +- } +- +- void test_toJson_withParams() { +- Request request =3D new Request('one', 'aMethod', {'foo': 'bar'}); +- expect( +- request.toJson(), +- equals({ +- Request.ID: 'one', +- Request.METHOD: 'aMethod', +- Request.PARAMS: {'foo': 'bar'} +- })); +- } +-} +- +-@reflectiveTest +-class ResponseTest { +- void test_create_invalidRequestFormat() { +- Response response =3D new Response.invalidRequestFormat(); +- expect(response.id, equals('')); +- expect(response.error, isNotNull); +- expect( +- response.toJson(), +- equals({ +- Response.ID: '', +- Response.ERROR: { +- 'code': 'INVALID_REQUEST', +- 'message': 'Invalid request' +- } +- })); +- } +- +- void test_create_unanalyzedPriorityFiles() { +- Response response =3D new Response.unanalyzedPriorityFiles('0', 'file= list'); +- expect(response.id, equals('0')); +- expect(response.error, isNotNull); +- expect( +- response.toJson(), +- equals({ +- Response.ID: '0', +- Response.ERROR: { +- 'code': 'UNANALYZED_PRIORITY_FILES', +- 'message': "Unanalyzed files cannot be a priority: 'file list= '" +- } +- })); +- } +- +- void test_create_unknownRequest() { +- Response response =3D new Response.unknownRequest(new Request('0', ''= )); +- expect(response.id, equals('0')); +- expect(response.error, isNotNull); +- expect( +- response.toJson(), +- equals({ +- Response.ID: '0', +- Response.ERROR: { +- 'code': 'UNKNOWN_REQUEST', +- 'message': 'Unknown request' +- } +- })); +- } +- +- void test_fromJson() { +- Response original =3D new Response('myId'); +- Response response =3D new Response.fromJson(original.toJson()); +- expect(response.id, equals('myId')); +- } +- +- void test_fromJson_withError() { +- Response original =3D new Response.invalidRequestFormat(); +- Response response =3D new Response.fromJson(original.toJson()); +- expect(response.id, equals('')); +- expect(response.error, isNotNull); +- RequestError error =3D response.error; +- expect(error.code, equals(RequestErrorCode.INVALID_REQUEST)); +- expect(error.message, equals('Invalid request')); +- } +- +- void test_fromJson_withResult() { +- Response original =3D new Response('myId', result: {'foo': 'bar'}); +- Response response =3D new Response.fromJson(original.toJson()); +- expect(response.id, equals('myId')); +- Map result =3D +- response.toJson()['result'] as Map; +- expect(result.length, equals(1)); +- expect(result['foo'], equals('bar')); +- } +-} +diff --git a/pkg/analysis_server/test/search/abstract_search_domain.dart b= /pkg/analysis_server/test/search/abstract_search_domain.dart +deleted file mode 100644 +index dc83c5a96cd..00000000000 +--- a/pkg/analysis_server/test/search/abstract_search_domain.dart ++++ /dev/null +@@ -1,113 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/search/search_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +- +-import '../analysis_abstract.dart'; +- +-class AbstractSearchDomainTest extends AbstractAnalysisTest { +- final Map resultSets =3D {}; +- String searchId; +- List results =3D []; +- SearchResult result; +- +- void assertHasResult(SearchResultKind kind, String search, [int length]= ) { +- int offset =3D findOffset(search); +- if (length =3D=3D null) { +- length =3D findIdentifierLength(search); +- } +- findResult(kind, testFile, offset, length, true); +- } +- +- void assertNoResult(SearchResultKind kind, String search, [int length])= { +- int offset =3D findOffset(search); +- if (length =3D=3D null) { +- length =3D findIdentifierLength(search); +- } +- findResult(kind, testFile, offset, length, false); +- } +- +- void findResult(SearchResultKind kind, String file, int offset, int len= gth, +- bool expected) { +- for (SearchResult result in results) { +- Location location =3D result.location; +- if (result.kind =3D=3D kind && +- location.file =3D=3D file && +- location.offset =3D=3D offset && +- location.length =3D=3D length) { +- if (!expected) { +- fail('Unexpected result $result in\n' + results.join('\n')); +- } +- this.result =3D result; +- return; +- } +- } +- if (expected) { +- fail( +- 'Not found: "search" kind=3D$kind offset=3D$offset length=3D$le= ngth\nin\n' + +- results.join('\n')); +- } +- } +- +- String getPathString(List path) { +- return path.map((Element element) { +- String kindName =3D element.kind.name; +- String name =3D element.name; +- if (name.isEmpty) { +- return kindName; +- } else { +- return '$kindName $name'; +- } +- }).join('\n'); +- } +- +- @override +- void processNotification(Notification notification) { +- super.processNotification(notification); +- if (notification.event =3D=3D SEARCH_NOTIFICATION_RESULTS) { +- var params =3D new SearchResultsParams.fromNotification(notificatio= n); +- String id =3D params.id; +- _ResultSet resultSet =3D resultSets[id]; +- if (resultSet =3D=3D null) { +- resultSet =3D new _ResultSet(id); +- resultSets[id] =3D resultSet; +- } +- resultSet.results.addAll(params.results); +- resultSet.done =3D params.isLast; +- } +- } +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- server.handlers =3D [ +- new SearchDomainHandler(server), +- ]; +- } +- +- Future waitForSearchResults() { +- _ResultSet resultSet =3D resultSets[searchId]; +- if (resultSet !=3D null && resultSet.done) { +- results =3D resultSet.results; +- return new Future.value(); +- } +- return new Future.delayed(Duration.ZERO, waitForSearchResults); +- } +-} +- +-class _ResultSet { +- final String id; +- final List results =3D []; +- bool done =3D false; +- +- _ResultSet(this.id); +-} +diff --git a/pkg/analysis_server/test/search/element_references_test.dart = b/pkg/analysis_server/test/search/element_references_test.dart +deleted file mode 100644 +index 3e411f4496c..00000000000 +--- a/pkg/analysis_server/test/search/element_references_test.dart ++++ /dev/null +@@ -1,674 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_search_domain.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ElementReferencesTest); +- }); +-} +- +-@reflectiveTest +-class ElementReferencesTest extends AbstractSearchDomainTest { +- Element searchElement; +- +- void assertHasRef(SearchResultKind kind, String search, bool isPotentia= l) { +- assertHasResult(kind, search); +- expect(result.isPotential, isPotential); +- } +- +- Future findElementReferences( +- String search, bool includePotential) async { +- int offset =3D findOffset(search); +- await waitForTasksFinished(); +- Request request =3D new SearchFindElementReferencesParams( +- testFile, offset, includePotential) +- .toRequest('0'); +- Response response =3D await waitResponse(request); +- var result =3D new SearchFindElementReferencesResult.fromResponse(res= ponse); +- searchId =3D result.id; +- searchElement =3D result.element; +- if (searchId !=3D null) { +- await waitForSearchResults(); +- } +- expect(serverErrors, isEmpty); +- } +- +- test_constructor_named() async { +- addTestFile(''' +-class A { +- A.named(p); +-} +-main() { +- new A.named(1); +- new A.named(2); +-} +-'''); +- await findElementReferences('named(p)', false); +- expect(searchElement.kind, ElementKind.CONSTRUCTOR); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.REFERENCE, '.named(1)', 6); +- assertHasResult(SearchResultKind.REFERENCE, '.named(2)', 6); +- } +- +- test_constructor_named_potential() async { +- // Constructors in other classes shouldn't be considered potential ma= tches, +- // nor should unresolved method calls, since constructor call sites a= re +- // statically bound to their targets). +- addTestFile(''' +-class A { +- A.named(p); // A +-} +-class B { +- B.named(p); +-} +-f(x) { +- new A.named(1); +- new B.named(2); +- x.named(3); +-} +-'''); +- await findElementReferences('named(p); // A', true); +- expect(searchElement.kind, ElementKind.CONSTRUCTOR); +- expect(results, hasLength(1)); +- assertHasResult(SearchResultKind.REFERENCE, '.named(1)', 6); +- } +- +- test_constructor_unnamed() async { +- addTestFile(''' +-class A { +- A(p); +-} +-main() { +- new A(1); +- new A(2); +-} +-'''); +- await findElementReferences('A(p)', false); +- expect(searchElement.kind, ElementKind.CONSTRUCTOR); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.REFERENCE, '(1)', 0); +- assertHasResult(SearchResultKind.REFERENCE, '(2)', 0); +- } +- +- test_constructor_unnamed_potential() async { +- // Constructors in other classes shouldn't be considered potential ma= tches, +- // even if they are also unnamed (since constructor call sites are +- // statically bound to their targets). +- // Also, assignments to local variables shouldn't be considered poten= tial +- // matches. +- addTestFile(''' +-class A { +- A(p); // A +-} +-class B { +- B(p); +- foo() { +- int k; +- k =3D 3; +- } +-} +-main() { +- new A(1); +- new B(2); +-} +-'''); +- await findElementReferences('A(p)', true); +- expect(searchElement.kind, ElementKind.CONSTRUCTOR); +- expect(results, hasLength(1)); +- assertHasResult(SearchResultKind.REFERENCE, '(1)', 0); +- } +- +- test_field_explicit() async { +- addTestFile(''' +-class A { +- var fff; // declaration +- A(this.fff); // in constructor +- A.named() : fff =3D 1; +- m() { +- fff =3D 2; +- fff +=3D 3; +- print(fff); // in m() +- fff(); // in m() +- } +-} +-main(A a) { +- a.fff =3D 20; +- a.fff +=3D 30; +- print(a.fff); // in main() +- a.fff(); // in main() +-} +-'''); +- await findElementReferences('fff; // declaration', false); +- expect(searchElement.kind, ElementKind.FIELD); +- expect(results, hasLength(10)); +- assertHasResult(SearchResultKind.WRITE, 'fff); // in constructor'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 1;'); +- // m() +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 2;'); +- assertHasResult(SearchResultKind.WRITE, 'fff +=3D 3;'); +- assertHasResult(SearchResultKind.READ, 'fff); // in m()'); +- assertHasResult(SearchResultKind.INVOCATION, 'fff(); // in m()'); +- // main() +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 20;'); +- assertHasResult(SearchResultKind.WRITE, 'fff +=3D 30;'); +- assertHasResult(SearchResultKind.READ, 'fff); // in main()'); +- assertHasResult(SearchResultKind.INVOCATION, 'fff(); // in main()'); +- } +- +- test_field_implicit() async { +- addTestFile(''' +-class A { +- var get fff =3D> null; +- void set fff(x) {} +- m() { +- print(fff); // in m() +- fff =3D 1; +- } +-} +-main(A a) { +- print(a.fff); // in main() +- a.fff =3D 10; +-} +-'''); +- { +- await findElementReferences('fff =3D>', false); +- expect(searchElement.kind, ElementKind.FIELD); +- expect(results, hasLength(4)); +- assertHasResult(SearchResultKind.READ, 'fff); // in m()'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 1;'); +- assertHasResult(SearchResultKind.READ, 'fff); // in main()'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 10;'); +- } +- { +- await findElementReferences('fff(x) {}', false); +- expect(results, hasLength(4)); +- assertHasResult(SearchResultKind.READ, 'fff); // in m()'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 1;'); +- assertHasResult(SearchResultKind.READ, 'fff); // in main()'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 10;'); +- } +- } +- +- test_field_inFormalParameter() async { +- addTestFile(''' +-class A { +- var fff; // declaration +- A(this.fff); // in constructor +- m() { +- fff =3D 2; +- print(fff); // in m() +- } +-} +-'''); +- await findElementReferences('fff); // in constructor', false); +- expect(searchElement.kind, ElementKind.FIELD); +- expect(results, hasLength(3)); +- assertHasResult(SearchResultKind.WRITE, 'fff); // in constructor'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 2;'); +- assertHasResult(SearchResultKind.READ, 'fff); // in m()'); +- } +- +- test_function() async { +- addTestFile(''' +-fff(p) {} +-main() { +- fff(1); +- print(fff); +-} +-'''); +- await findElementReferences('fff(p) {}', false); +- expect(searchElement.kind, ElementKind.FUNCTION); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.INVOCATION, 'fff(1)'); +- assertHasResult(SearchResultKind.REFERENCE, 'fff);'); +- } +- +- test_hierarchy_field_explicit() async { +- addTestFile(''' +- class A { +- int fff; // in A +- } +- class B extends A { +- int fff; // in B +- } +- class C extends B { +- int fff; // in C +- } +- main(A a, B b, C c) { +- a.fff =3D 10; +- b.fff =3D 20; +- c.fff =3D 30; +- } +- '''); +- await findElementReferences('fff; // in B', false); +- expect(searchElement.kind, ElementKind.FIELD); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 10;'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 20;'); +- assertHasResult(SearchResultKind.WRITE, 'fff =3D 30;'); +- } +- +- test_hierarchy_method() async { +- addTestFile(''' +-class A { +- mmm(_) {} // in A +-} +-class B extends A { +- mmm(_) {} // in B +-} +-class C extends B { +- mmm(_) {} // in C +-} +-main(A a, B b, C c) { +- a.mmm(10); +- b.mmm(20); +- c.mmm(30); +-} +-'''); +- await findElementReferences('mmm(_) {} // in B', false); +- expect(searchElement.kind, ElementKind.METHOD); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(10)'); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(20)'); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(30)'); +- } +- +- test_hierarchy_method_static() async { +- addTestFile(''' +-class A { +- static void mmm(_) {} // in A +-} +-class B extends A { +- static void mmm(_) {} // in B +-} +-class C extends B { +- static void mmm(_) {} // in C +-} +-main() { +- A.mmm(10); +- B.mmm(20); +- C.mmm(30); +-} +-'''); +- await findElementReferences('mmm(_) {} // in B', false); +- expect(searchElement.kind, ElementKind.METHOD); +- expect(results, hasLength(1)); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(20)'); +- } +- +- test_label() async { +- addTestFile(''' +-main() { +-myLabel: +- for (int i =3D 0; i < 10; i++) { +- if (i =3D=3D 2) { +- continue myLabel; // continue +- } +- break myLabel; // break +- } +-} +-'''); +- await findElementReferences('myLabel; // break', false); +- expect(searchElement.kind, ElementKind.LABEL); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.REFERENCE, 'myLabel; // continue'); +- assertHasResult(SearchResultKind.REFERENCE, 'myLabel; // break'); +- } +- +- test_localVariable() async { +- addTestFile(''' +-main() { +- var vvv =3D 1; +- print(vvv); +- vvv +=3D 3; +- vvv =3D 2; +- vvv(); +-} +-'''); +- await findElementReferences('vvv =3D 1', false); +- expect(searchElement.kind, ElementKind.LOCAL_VARIABLE); +- expect(results, hasLength(4)); +- assertHasResult(SearchResultKind.READ, 'vvv);'); +- assertHasResult(SearchResultKind.READ_WRITE, 'vvv +=3D 3'); +- assertHasResult(SearchResultKind.WRITE, 'vvv =3D 2'); +- assertHasResult(SearchResultKind.INVOCATION, 'vvv();'); +- } +- +- test_method() async { +- addTestFile(''' +-class A { +- mmm(p) {} +- m() { +- mmm(1); +- print(mmm); // in m() +- } +-} +-main(A a) { +- a.mmm(10); +- print(a.mmm); // in main() +-} +-'''); +- await findElementReferences('mmm(p) {}', false); +- expect(searchElement.kind, ElementKind.METHOD); +- expect(results, hasLength(4)); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(1);'); +- assertHasResult(SearchResultKind.REFERENCE, 'mmm); // in m()'); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(10);'); +- assertHasResult(SearchResultKind.REFERENCE, 'mmm); // in main()'); +- } +- +- test_method_propagatedType() async { +- addTestFile(''' +-class A { +- mmm(p) {} +-} +-main() { +- var a =3D new A(); +- a.mmm(10); +- print(a.mmm); +-} +-'''); +- await findElementReferences('mmm(p) {}', false); +- expect(searchElement.kind, ElementKind.METHOD); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.INVOCATION, 'mmm(10);'); +- assertHasResult(SearchResultKind.REFERENCE, 'mmm);'); +- } +- +- test_noElement() async { +- addTestFile(''' +-main() { +- print(noElement); +-} +-'''); +- await findElementReferences('noElement', false); +- expect(searchId, isNull); +- } +- +- test_oneUnit_zeroLibraries() async { +- addTestFile(''' +-part of lib; +-fff(p) {} +-main() { +- fff(10); +-} +-'''); +- await findElementReferences('fff(p) {}', false); +- expect(results, hasLength(1)); +- assertHasResult(SearchResultKind.INVOCATION, 'fff(10);'); +- } +- +- test_parameter() async { +- addTestFile(''' +-main(ppp) { +- print(ppp); +- ppp +=3D 3; +- ppp =3D 2; +- ppp(); +-} +-'''); +- await findElementReferences('ppp) {', false); +- expect(searchElement.kind, ElementKind.PARAMETER); +- expect(results, hasLength(4)); +- assertHasResult(SearchResultKind.READ, 'ppp);'); +- assertHasResult(SearchResultKind.READ_WRITE, 'ppp +=3D 3'); +- assertHasResult(SearchResultKind.WRITE, 'ppp =3D 2'); +- assertHasResult(SearchResultKind.INVOCATION, 'ppp();'); +- } +- +- @failingTest +- test_path_inConstructor_named() async { +- // The path does not contain the first expected element. +- addTestFile(''' +-library my_lib; +-class A {} +-class B { +- B.named() { +- A a =3D null; +- } +-} +-'''); +- await findElementReferences('A {}', false); +- assertHasResult(SearchResultKind.REFERENCE, 'A a =3D null;'); +- expect(getPathString(result.path), ''' +-LOCAL_VARIABLE a +-CONSTRUCTOR named +-CLASS B +-COMPILATION_UNIT test.dart +-LIBRARY my_lib'''); +- } +- +- @failingTest +- test_path_inConstructor_unnamed() async { +- // The path does not contain the first expected element. +- addTestFile(''' +-library my_lib; +-class A {} +-class B { +- B() { +- A a =3D null; +- } +-} +-'''); +- await findElementReferences('A {}', false); +- assertHasResult(SearchResultKind.REFERENCE, 'A a =3D null;'); +- expect(getPathString(result.path), ''' +-LOCAL_VARIABLE a +-CONSTRUCTOR +-CLASS B +-COMPILATION_UNIT test.dart +-LIBRARY my_lib'''); +- } +- +- @failingTest +- test_path_inFunction() async { +- // The path does not contain the first expected element. +- addTestFile(''' +-library my_lib; +-class A {} +-main() { +- A a =3D null; +-} +-'''); +- await findElementReferences('A {}', false); +- assertHasResult(SearchResultKind.REFERENCE, 'A a =3D null;'); +- expect(getPathString(result.path), ''' +-LOCAL_VARIABLE a +-FUNCTION main +-COMPILATION_UNIT test.dart +-LIBRARY my_lib'''); +- } +- +- test_potential_disabled() async { +- addTestFile(''' +-class A { +- test(p) {} +-} +-main(A a, p) { +- a.test(1); +- p.test(2); +-} +-'''); +- await findElementReferences('test(p) {}', false); +- assertHasResult(SearchResultKind.INVOCATION, 'test(1);'); +- assertNoResult(SearchResultKind.INVOCATION, 'test(2);'); +- } +- +- test_potential_field() async { +- addTestFile(''' +-class A { +- var test; // declaration +-} +-main(A a, p) { +- a.test =3D 1; +- p.test =3D 2; +- print(p.test); // p +-} +-'''); +- await findElementReferences('test; // declaration', true); +- { +- assertHasResult(SearchResultKind.WRITE, 'test =3D 1;'); +- expect(result.isPotential, isFalse); +- } +- { +- assertHasResult(SearchResultKind.WRITE, 'test =3D 2;'); +- expect(result.isPotential, isTrue); +- } +- { +- assertHasResult(SearchResultKind.READ, 'test); // p'); +- expect(result.isPotential, isTrue); +- } +- } +- +- test_potential_method() async { +- addTestFile(''' +-class A { +- test(p) {} +-} +-main(A a, p) { +- a.test(1); +- p.test(2); +-} +-'''); +- await findElementReferences('test(p) {}', true); +- { +- assertHasResult(SearchResultKind.INVOCATION, 'test(1);'); +- expect(result.isPotential, isFalse); +- } +- { +- assertHasResult(SearchResultKind.INVOCATION, 'test(2);'); +- expect(result.isPotential, isTrue); +- } +- } +- +- test_potential_method_definedInSubclass() async { +- addTestFile(''' +-class Base { +- methodInBase() { +- test(1); +- } +-} +-class Derived extends Base { +- test(_) {} // of Derived +- methodInDerived() { +- test(2); +- } +-} +-globalFunction(Base b) { +- b.test(3); +-} +-'''); +- await findElementReferences('test(_) {} // of Derived', true); +- assertHasRef(SearchResultKind.INVOCATION, 'test(1);', true); +- assertHasRef(SearchResultKind.INVOCATION, 'test(2);', false); +- assertHasRef(SearchResultKind.INVOCATION, 'test(3);', true); +- } +- +- test_prefix() async { +- addTestFile(''' +-import 'dart:async' as ppp; +-main() { +- ppp.Future a; +- ppp.Stream b; +-} +-'''); +- await findElementReferences("ppp;", false); +- expect(searchElement.kind, ElementKind.PREFIX); +- expect(searchElement.name, 'ppp'); +- expect(searchElement.location.startLine, 1); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.REFERENCE, 'ppp.Future'); +- assertHasResult(SearchResultKind.REFERENCE, 'ppp.Stream'); +- } +- +- test_topLevelVariable_explicit() async { +- addTestFile(''' +-var vvv =3D 1; +-main() { +- print(vvv); +- vvv +=3D 3; +- vvv =3D 2; +- vvv(); +-} +-'''); +- await findElementReferences('vvv =3D 1', false); +- expect(searchElement.kind, ElementKind.TOP_LEVEL_VARIABLE); +- expect(results, hasLength(4)); +- assertHasResult(SearchResultKind.READ, 'vvv);'); +- assertHasResult(SearchResultKind.WRITE, 'vvv +=3D 3'); +- assertHasResult(SearchResultKind.WRITE, 'vvv =3D 2'); +- assertHasResult(SearchResultKind.INVOCATION, 'vvv();'); +- } +- +- test_topLevelVariable_implicit() async { +- addTestFile(''' +-get vvv =3D> null; +-set vvv(x) {} +-main() { +- print(vvv); +- vvv =3D 1; +-} +-'''); +- { +- await findElementReferences('vvv =3D>', false); +- expect(searchElement.kind, ElementKind.TOP_LEVEL_VARIABLE); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.READ, 'vvv);'); +- assertHasResult(SearchResultKind.WRITE, 'vvv =3D 1;'); +- } +- { +- await findElementReferences('vvv(x) {}', false); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.READ, 'vvv);'); +- assertHasResult(SearchResultKind.WRITE, 'vvv =3D 1;'); +- } +- } +- +- test_typeReference_class() async { +- addTestFile(''' +-main() { +- int a =3D 1; +- int b =3D 2; +-} +-'''); +- await findElementReferences('int a', false); +- expect(searchElement.kind, ElementKind.CLASS); +- assertHasResult(SearchResultKind.REFERENCE, 'int a'); +- assertHasResult(SearchResultKind.REFERENCE, 'int b'); +- } +- +- test_typeReference_functionType() async { +- addTestFile(''' +-typedef F(); +-main(F f) { +-} +-'''); +- await findElementReferences('F()', false); +- expect(searchElement.kind, ElementKind.FUNCTION_TYPE_ALIAS); +- expect(results, hasLength(1)); +- assertHasResult(SearchResultKind.REFERENCE, 'F f'); +- } +- +- test_typeReference_typeVariable() async { +- addTestFile(''' +-class A { +- T f; +- T m() =3D> null; +-} +-'''); +- await findElementReferences('T> {', false); +- expect(searchElement.kind, ElementKind.TYPE_PARAMETER); +- expect(results, hasLength(2)); +- assertHasResult(SearchResultKind.REFERENCE, 'T f;'); +- assertHasResult(SearchResultKind.REFERENCE, 'T m()'); +- } +-} +diff --git a/pkg/analysis_server/test/search/member_declarations_test.dart= b/pkg/analysis_server/test/search/member_declarations_test.dart +deleted file mode 100644 +index 644912e7b43..00000000000 +--- a/pkg/analysis_server/test/search/member_declarations_test.dart ++++ /dev/null +@@ -1,157 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_search_domain.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(MemberDeclarationsTest); +- }); +-} +- +-@reflectiveTest +-class MemberDeclarationsTest extends AbstractSearchDomainTest { +- void assertHasDeclaration(ElementKind kind, String className) { +- result =3D findTopLevelResult(kind, className); +- if (result =3D=3D null) { +- fail('Not found: kind=3D$kind in=3D"$className"\nin\n' + results.jo= in('\n')); +- } +- } +- +- Future findMemberDeclarations(String name) async { +- await waitForTasksFinished(); +- Request request =3D +- new SearchFindMemberDeclarationsParams(name).toRequest('0'); +- Response response =3D await waitResponse(request); +- var result =3D new SearchFindMemberDeclarationsResult.fromResponse(re= sponse); +- searchId =3D result.id; +- return waitForSearchResults(); +- } +- +- SearchResult findTopLevelResult(ElementKind kind, String enclosingClass= ) { +- for (SearchResult result in results) { +- Element element =3D result.path[0]; +- Element clazz =3D result.path[1]; +- if (element.kind =3D=3D kind && clazz.name =3D=3D enclosingClass) { +- return result; +- } +- } +- return null; +- } +- +- test_localVariable() async { +- addTestFile(''' +-class A { +- main() { +- var foo =3D 42; +- } +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, isEmpty); +- } +- +- test_localVariable_forIn() async { +- addTestFile(''' +-class A { +- main() { +- for (int foo in []) { +- } +- } +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, isEmpty); +- } +- +- test_methodField() async { +- addTestFile(''' +-class A { +- foo() {} +- bar() {} +-} +-class B { +- int foo; +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, hasLength(2)); +- assertHasDeclaration(ElementKind.METHOD, 'A'); +- assertHasDeclaration(ElementKind.FIELD, 'B'); +- } +- +- test_methodGetter() async { +- addTestFile(''' +-class A { +- foo() {} +- bar() {} +-} +-class B { +- get foo =3D> null; +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, hasLength(2)); +- assertHasDeclaration(ElementKind.METHOD, 'A'); +- assertHasDeclaration(ElementKind.GETTER, 'B'); +- } +- +- test_methodGetterSetter() async { +- addTestFile(''' +-class A { +- foo() {} +- bar() {} +-} +-class B { +- get foo =3D> null; +- set foo(x) {} +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, hasLength(3)); +- assertHasDeclaration(ElementKind.METHOD, 'A'); +- assertHasDeclaration(ElementKind.GETTER, 'B'); +- assertHasDeclaration(ElementKind.SETTER, 'B'); +- } +- +- test_methodMethod() async { +- addTestFile(''' +-class A { +- foo() {} +- bar() {} +-} +-class B { +- foo() {} +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, hasLength(2)); +- assertHasDeclaration(ElementKind.METHOD, 'A'); +- assertHasDeclaration(ElementKind.METHOD, 'B'); +- } +- +- test_methodSetter() async { +- addTestFile(''' +-class A { +- foo() {} +- bar() {} +-} +-class B { +- set foo(x) {} +-} +-'''); +- await findMemberDeclarations('foo'); +- expect(results, hasLength(2)); +- assertHasDeclaration(ElementKind.METHOD, 'A'); +- assertHasDeclaration(ElementKind.SETTER, 'B'); +- } +-} +diff --git a/pkg/analysis_server/test/search/member_references_test.dart b= /pkg/analysis_server/test/search/member_references_test.dart +deleted file mode 100644 +index 33be7f20920..00000000000 +--- a/pkg/analysis_server/test/search/member_references_test.dart ++++ /dev/null +@@ -1,114 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_search_domain.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(MemberReferencesTest); +- }); +-} +- +-@reflectiveTest +-class MemberReferencesTest extends AbstractSearchDomainTest { +- void assertHasRef(SearchResultKind kind, String search, bool isPotentia= l) { +- assertHasResult(kind, search); +- expect(result.isPotential, isPotential); +- } +- +- Future findMemberReferences(String name) async { +- await waitForTasksFinished(); +- Request request =3D new SearchFindMemberReferencesParams(name).toRequ= est('0'); +- Response response =3D await waitResponse(request); +- searchId =3D new SearchFindMemberReferencesResult.fromResponse(respon= se).id; +- return waitForSearchResults(); +- } +- +- test_fields_explicit() async { +- addTestFile(''' +-class A { +- var foo; +-} +-class B { +- var foo; +-} +-mainResolved(A a, B b) { +- a.foo =3D 1; +- b.foo =3D 2; +- print(a.foo); // resolved A +- print(b.foo); // resolved B +-} +-mainUnresolved(a, b) { +- a.foo =3D 10; +- b.foo =3D 20; +- print(a.foo); // unresolved A +- print(b.foo); // unresolved B +-} +-'''); +- await findMemberReferences('foo'); +- assertNoResult(SearchResultKind.WRITE, 'foo =3D 1;'); +- assertNoResult(SearchResultKind.WRITE, 'foo =3D 2;'); +- assertNoResult(SearchResultKind.READ, 'foo); // resolved A'); +- assertNoResult(SearchResultKind.READ, 'foo); // resolved B'); +- assertHasRef(SearchResultKind.WRITE, 'foo =3D 10;', true); +- assertHasRef(SearchResultKind.WRITE, 'foo =3D 20;', true); +- assertHasRef(SearchResultKind.READ, 'foo); // unresolved A', true); +- assertHasRef(SearchResultKind.READ, 'foo); // unresolved B', true); +- } +- +- test_fields_implicit() async { +- addTestFile(''' +-class A { +- get foo =3D> null; +-} +-class B { +- get foo =3D> null; +-} +-mainResolved(A a, B b) { +- print(a.foo); // resolved A +- print(b.foo); // resolved B +-} +-mainUnresolved(a, b) { +- print(a.foo); // unresolved A +- print(b.foo); // unresolved B +-} +-'''); +- await findMemberReferences('foo'); +- assertNoResult(SearchResultKind.READ, 'foo); // resolved A'); +- assertNoResult(SearchResultKind.READ, 'foo); // resolved B'); +- assertHasRef(SearchResultKind.READ, 'foo); // unresolved A', true); +- assertHasRef(SearchResultKind.READ, 'foo); // unresolved B', true); +- } +- +- test_methods() async { +- addTestFile(''' +-class A { +- foo() {} +-} +-class B { +- foo() {} +-} +-mainResolved(A a, B b) { +- a.foo(1); +- b.foo(2); +-} +-mainUnresolved(a, b) { +- a.foo(10); +- b.foo(20); +-} +-'''); +- await findMemberReferences('foo'); +- assertNoResult(SearchResultKind.INVOCATION, 'foo(1)'); +- assertNoResult(SearchResultKind.INVOCATION, 'foo(2)'); +- assertHasRef(SearchResultKind.INVOCATION, 'foo(10)', true); +- assertHasRef(SearchResultKind.INVOCATION, 'foo(20)', true); +- } +-} +diff --git a/pkg/analysis_server/test/search/search_result_test.dart b/pkg= /analysis_server/test/search/search_result_test.dart +deleted file mode 100644 +index 47a8560e003..00000000000 +--- a/pkg/analysis_server/test/search/search_result_test.dart ++++ /dev/null +@@ -1,55 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SearchResultKindTest); +- }); +-} +- +-@reflectiveTest +-class SearchResultKindTest { +- void test_fromEngine() { +- expect(newSearchResultKind_fromEngine(MatchKind.DECLARATION), +- SearchResultKind.DECLARATION); +- expect( +- newSearchResultKind_fromEngine(MatchKind.READ), SearchResultKind.= READ); +- expect(newSearchResultKind_fromEngine(MatchKind.READ_WRITE), +- SearchResultKind.READ_WRITE); +- expect(newSearchResultKind_fromEngine(MatchKind.WRITE), +- SearchResultKind.WRITE); +- expect(newSearchResultKind_fromEngine(MatchKind.REFERENCE), +- SearchResultKind.REFERENCE); +- expect(newSearchResultKind_fromEngine(MatchKind.INVOCATION), +- SearchResultKind.INVOCATION); +- expect(newSearchResultKind_fromEngine(null), SearchResultKind.UNKNOWN= ); +- } +- +- void test_fromName() { +- expect(new SearchResultKind(SearchResultKind.DECLARATION.name), +- SearchResultKind.DECLARATION); +- expect(new SearchResultKind(SearchResultKind.READ.name), +- SearchResultKind.READ); +- expect(new SearchResultKind(SearchResultKind.READ_WRITE.name), +- SearchResultKind.READ_WRITE); +- expect(new SearchResultKind(SearchResultKind.WRITE.name), +- SearchResultKind.WRITE); +- expect(new SearchResultKind(SearchResultKind.REFERENCE.name), +- SearchResultKind.REFERENCE); +- expect(new SearchResultKind(SearchResultKind.INVOCATION.name), +- SearchResultKind.INVOCATION); +- expect(new SearchResultKind(SearchResultKind.UNKNOWN.name), +- SearchResultKind.UNKNOWN); +- } +- +- void test_toString() { +- expect(SearchResultKind.DECLARATION.toString(), +- 'SearchResultKind.DECLARATION'); +- } +-} +diff --git a/pkg/analysis_server/test/search/test_all.dart b/pkg/analysis_= server/test/search/test_all.dart +deleted file mode 100644 +index a2ccb2bd80f..00000000000 +--- a/pkg/analysis_server/test/search/test_all.dart ++++ /dev/null +@@ -1,26 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'element_references_test.dart' as element_references_test; +-import 'member_declarations_test.dart' as member_declarations; +-import 'member_references_test.dart' as member_references_test; +-import 'search_result_test.dart' as search_result_test; +-import 'top_level_declarations_test.dart' as top_level_declarations_test; +-import 'type_hierarchy_test.dart' as type_hierarchy_test; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- defineReflectiveSuite(() { +- element_references_test.main(); +- member_declarations.main(); +- member_references_test.main(); +- search_result_test.main(); +- top_level_declarations_test.main(); +- type_hierarchy_test.main(); +- }, name: 'search'); +-} +diff --git a/pkg/analysis_server/test/search/top_level_declarations_test.d= art b/pkg/analysis_server/test/search/top_level_declarations_test.dart +deleted file mode 100644 +index e383ca644fe..00000000000 +--- a/pkg/analysis_server/test/search/top_level_declarations_test.dart ++++ /dev/null +@@ -1,82 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_search_domain.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(TopLevelDeclarationsTest); +- }); +-} +- +-@reflectiveTest +-class TopLevelDeclarationsTest extends AbstractSearchDomainTest { +- void assertHasDeclaration(ElementKind kind, String name) { +- result =3D findTopLevelResult(kind, name); +- if (result =3D=3D null) { +- fail('Not found: kind=3D$kind name=3D"$name"\nin\n' + results.join(= '\n')); +- } +- } +- +- void assertNoDeclaration(ElementKind kind, String name) { +- result =3D findTopLevelResult(kind, name); +- if (result !=3D null) { +- fail('Unexpected: kind=3D$kind name=3D"$name"\nin\n' + results.join= ('\n')); +- } +- } +- +- Future findTopLevelDeclarations(String pattern) async { +- await waitForTasksFinished(); +- Request request =3D +- new SearchFindTopLevelDeclarationsParams(pattern).toRequest('0'); +- Response response =3D await waitResponse(request); +- if (response.error !=3D null) { +- return response.error; +- } +- searchId =3D +- new SearchFindTopLevelDeclarationsResult.fromResponse(response).i= d; +- return waitForSearchResults(); +- } +- +- SearchResult findTopLevelResult(ElementKind kind, String name) { +- for (SearchResult result in results) { +- Element element =3D result.path[0]; +- if (element.kind =3D=3D kind && element.name =3D=3D name) { +- return result; +- } +- } +- return null; +- } +- +- test_invalidRegex() async { +- var result =3D await findTopLevelDeclarations('[A'); +- expect(result, new isInstanceOf()); +- } +- +- test_startEndPattern() async { +- addTestFile(''' +-class A {} // A +-class B =3D Object with A; +-typedef C(); +-D() {} +-var E =3D null; +-class ABC {} +-'''); +- await findTopLevelDeclarations('^[A-E]\$'); +- assertHasDeclaration(ElementKind.CLASS, 'A'); +- assertHasDeclaration(ElementKind.CLASS, 'B'); +- assertHasDeclaration(ElementKind.FUNCTION_TYPE_ALIAS, 'C'); +- assertHasDeclaration(ElementKind.FUNCTION, 'D'); +- assertHasDeclaration(ElementKind.TOP_LEVEL_VARIABLE, 'E'); +- assertNoDeclaration(ElementKind.CLASS, 'ABC'); +- } +-} +diff --git a/pkg/analysis_server/test/search/type_hierarchy_test.dart b/pk= g/analysis_server/test/search/type_hierarchy_test.dart +deleted file mode 100644 +index c2d15474a23..00000000000 +--- a/pkg/analysis_server/test/search/type_hierarchy_test.dart ++++ /dev/null +@@ -1,1055 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/search/search_domain.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(GetTypeHierarchyTest); +- }); +-} +- +-@reflectiveTest +-class GetTypeHierarchyTest extends AbstractAnalysisTest { +- static const String requestId =3D 'test-getTypeHierarchy'; +- +- @override +- void setUp() { +- super.setUp(); +- createProject(); +- server.handlers =3D [ +- new SearchDomainHandler(server), +- ]; +- } +- +- test_bad_function() async { +- addTestFile(''' +-main() { +-} +-'''); +- List items =3D await _getTypeHierarchy('main() {'); +- expect(items, isNull); +- } +- +- test_bad_noElement() async { +- addTestFile(''' +-main() { +- /* target */ +-} +-'''); +- List items =3D await _getTypeHierarchy('/* target = */'); +- expect(items, isNull); +- } +- +- test_bad_recursion() async { +- addTestFile(''' +-class A extends B { +-} +-class B extends A { +-} +-'''); +- List items =3D await _getTypeHierarchy('B extends = A'); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'B', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [1] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'A', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 0, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_class_displayName() async { +- addTestFile(''' +-class A { +-} +-class B extends A { +-} +-'''); +- List items =3D await _getTypeHierarchy('B extends'= ); +- var itemB =3D items[0]; +- var itemA =3D items[itemB.superclass]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemA.displayName, 'A'); +- } +- +- test_class_double_subclass() async { +- addTestFile(''' +-class AAA {} // A +- +-class BBB extends AAA {} +- +-class CCC extends BBB implements AAA {} +-'''); +- List items =3D await _getTypeHierarchy('AAA {} // = A'); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'AAA', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [2, 3] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'BBB', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 0, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [3] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'CCC', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 0, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- ]); +- } +- +- test_class_extends_fileAndPackageUris() async { +- // prepare packages +- String pkgFile =3D '/packages/pkgA/lib/libA.dart'; +- resourceProvider.newFile(pkgFile, ''' +-library lib_a; +-class A {} +-class B extends A {} +-'''); +- resourceProvider.newFile( +- '/packages/pkgA/.packages', 'pkgA:file:///packages/pkgA/lib'); +- // reference the package from a project +- resourceProvider.newFile( +- '$projectPath/.packages', 'pkgA:file:///packages/pkgA/lib'); +- addTestFile(''' +-import 'package:pkgA/libA.dart'; +-class C extends A {} +-'''); +- await waitForTasksFinished(); +- // configure roots +- Request request =3D +- new AnalysisSetAnalysisRootsParams([projectPath, '/packages/pkgA'= ], []) +- .toRequest('0'); +- handleSuccessfulRequest(request); +- // test A type hierarchy +- List items =3D await _getTypeHierarchy('A {}'); +- Set names =3D _toClassNames(items); +- expect(names, contains('A')); +- expect(names, contains('B')); +- expect(names, contains('C')); +- } +- +- test_class_extendsTypeA() async { +- addTestFile(''' +-class A {} +-class B extends A { +-} +-class C extends B { +-} +-'''); +- List items =3D await _getTypeHierarchy('A {}'); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'A', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [2] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'B', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 0, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [3] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'C', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 2, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_class_extendsTypeB() async { +- addTestFile(''' +-class A { +-} +-class B extends A { +-} +-class C extends B { +-} +-'''); +- List items =3D await _getTypeHierarchy('B extends'= ); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'B', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [3] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'A', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 2, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'C', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 0, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_class_extendsTypeC() async { +- addTestFile(''' +-class A { +-} +-class B extends A { +-} +-class C extends B { +-} +-'''); +- List items =3D await _getTypeHierarchy('C extends'= ); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'C', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'B', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 2, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'A', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 3, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_class_implementsTypes() async { +- addTestFile(''' +-class MA {} +-class MB {} +-class B extends A { +-} +-class T implements MA, MB { +-} +-'''); +- List items =3D await _getTypeHierarchy('T implemen= ts'); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'T', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [2, 3], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'MA', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'MB', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_class_withTypes() async { +- addTestFile(''' +-class MA {} +-class MB {} +-class B extends A { +-} +-class T extends Object with MA, MB { +-} +-'''); +- List items =3D await _getTypeHierarchy('T extends = Object'); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'T', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [2, 3], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'MA', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'MB', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_fromField_toMixinGetter() async { +- addTestFile(''' +-abstract class A { +- var test =3D 1; +-} +-class Mixin { +- get test =3D> 2; +-} +-class B extends A with Mixin {} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 1= ;'); +- var itemA =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'A= '); +- var itemB =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'B= '); +- Element memberA =3D itemA.memberElement; +- Element memberB =3D itemB.memberElement; +- expect(memberA, isNotNull); +- expect(memberB, isNotNull); +- expect(memberA.location.offset, findOffset('test =3D 1;')); +- expect(memberB.location.offset, findOffset('test =3D> 2;')); +- } +- +- test_fromField_toMixinSetter() async { +- addTestFile(''' +-abstract class A { +- var test =3D 1; +-} +-class Mixin { +- set test(m) {} +-} +-class B extends A with Mixin {} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 1= ;'); +- var itemA =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'A= '); +- var itemB =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'B= '); +- Element memberA =3D itemA.memberElement; +- Element memberB =3D itemB.memberElement; +- expect(memberA, isNotNull); +- expect(memberB, isNotNull); +- expect(memberA.location.offset, findOffset('test =3D 1;')); +- expect(memberB.location.offset, findOffset('test(m) {}')); +- } +- +- test_member_fromField_toField() async { +- addTestFile(''' +-class A { +- var test =3D 1; +-} +-class B extends A { +- var test =3D 2; +-} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 2= ;'); +- TypeHierarchyItem itemB =3D items[0]; +- TypeHierarchyItem itemA =3D items[itemB.superclass]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemA.memberElement.location.offset, findOffset('test =3D 1;')= ); +- expect(itemB.memberElement.location.offset, findOffset('test =3D 2;')= ); +- } +- +- test_member_fromField_toGetter() async { +- addTestFile(''' +-class A { +- get test =3D> 1; +-} +-class B extends A { +- var test =3D 2; +-} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 2= ;'); +- TypeHierarchyItem itemB =3D items[0]; +- TypeHierarchyItem itemA =3D items[itemB.superclass]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemA.memberElement.location.offset, findOffset('test =3D> 1')= ); +- expect(itemB.memberElement.location.offset, findOffset('test =3D 2;')= ); +- } +- +- test_member_fromField_toSetter() async { +- addTestFile(''' +-class A { +- set test(a) {} +-} +-class B extends A { +- var test =3D 2; +-} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 2= ;'); +- TypeHierarchyItem itemB =3D items[0]; +- TypeHierarchyItem itemA =3D items[itemB.superclass]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemA.memberElement.location.offset, findOffset('test(a) {}')); +- expect(itemB.memberElement.location.offset, findOffset('test =3D 2;')= ); +- } +- +- test_member_fromFinalField_toGetter() async { +- addTestFile(''' +-class A { +- get test =3D> 1; +-} +-class B extends A { +- final test =3D 2; +-} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 2= ;'); +- TypeHierarchyItem itemB =3D items[0]; +- TypeHierarchyItem itemA =3D items[itemB.superclass]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemA.memberElement.location.offset, findOffset('test =3D> 1;'= )); +- expect(itemB.memberElement.location.offset, findOffset('test =3D 2;')= ); +- } +- +- test_member_fromFinalField_toSetter() async { +- addTestFile(''' +-class A { +- set test(x) {} +-} +-class B extends A { +- final test =3D 2; +-} +-'''); +- List items =3D await _getTypeHierarchy('test =3D 2= ;'); +- TypeHierarchyItem itemB =3D items[0]; +- TypeHierarchyItem itemA =3D items[itemB.superclass]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemA.memberElement, isNull); +- expect(itemB.memberElement.location.offset, findOffset('test =3D 2;')= ); +- } +- +- test_member_getter() async { +- addTestFile(''' +-class A { +- get test =3D> null; // in A +-} +-class B extends A { +- get test =3D> null; // in B +-} +-class C extends B { +-} +-class D extends C { +- get test =3D> null; // in D +-} +-'''); +- List items =3D +- await _getTypeHierarchy('test =3D> null; // in B'); +- TypeHierarchyItem itemB =3D items[0]; +- TypeHierarchyItem itemA =3D items[itemB.superclass]; +- TypeHierarchyItem itemC =3D items[itemB.subclasses[0]]; +- TypeHierarchyItem itemD =3D items[itemC.subclasses[0]]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemC.classElement.name, 'C'); +- expect(itemD.classElement.name, 'D'); +- expect(itemA.memberElement.location.offset, +- findOffset('test =3D> null; // in A')); +- expect(itemB.memberElement.location.offset, +- findOffset('test =3D> null; // in B')); +- expect(itemC.memberElement, isNull); +- expect(itemD.memberElement.location.offset, +- findOffset('test =3D> null; // in D')); +- } +- +- test_member_method() async { +- addTestFile(''' +-class A { +- test() {} // in A +-} +-class B extends A { +- test() {} // in B +-} +-class C extends B { +-} +-class D extends C { +- test() {} // in D +-} +-'''); +- List items =3D +- await _getTypeHierarchy('test() {} // in B'); +- var itemB =3D items[0]; +- var itemA =3D items[itemB.superclass]; +- var itemC =3D items[itemB.subclasses[0]]; +- var itemD =3D items[itemC.subclasses[0]]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemC.classElement.name, 'C'); +- expect(itemD.classElement.name, 'D'); +- expect( +- itemA.memberElement.location.offset, findOffset('test() {} // in = A')); +- expect( +- itemB.memberElement.location.offset, findOffset('test() {} // in = B')); +- expect(itemC.memberElement, isNull); +- expect( +- itemD.memberElement.location.offset, findOffset('test() {} // in = D')); +- } +- +- test_member_method_private_differentLib() async { +- addFile('$testFolder/lib.dart', r''' +-import 'test.dart'; +-class A { +- void _m() {} +-} +-class C extends B { +- void _m() {} +-} +-'''); +- addTestFile(''' +-import 'lib.dart'; +-class B extends A { +- _m() {} // in B +-} +-class D extends C { +- _m() {} // in D +-} +-'''); +- List items =3D await _getTypeHierarchy('_m() {} //= in B'); +- var itemB =3D items[0]; +- var itemA =3D items[itemB.superclass]; +- var itemC =3D items[itemB.subclasses[0]]; +- var itemD =3D items[itemC.subclasses[0]]; +- expect(itemB.classElement.name, 'B'); +- expect(itemA.classElement.name, 'A'); +- expect(itemC.classElement.name, 'C'); +- expect(itemD.classElement.name, 'D'); +- expect(itemA.memberElement, isNull); +- expect(itemC.memberElement, isNull); +- expect(itemB.memberElement, isNotNull); +- expect(itemD.memberElement, isNotNull); +- } +- +- test_member_method_private_sameLib() async { +- addTestFile(''' +-class A { +- _m() {} // in A +-} +-class B extends A { +- _m() {} // in B +-} +-class C extends B { +- _m() {} // in C +-} +-'''); +- List items =3D await _getTypeHierarchy('_m() {} //= in B'); +- var itemB =3D items[0]; +- var itemA =3D items[itemB.superclass]; +- var itemC =3D items[itemB.subclasses[0]]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemC.classElement.name, 'C'); +- expect(itemA.memberElement.location.offset, findOffset('_m() {} // in= A')); +- expect(itemB.memberElement.location.offset, findOffset('_m() {} // in= B')); +- expect(itemC.memberElement.location.offset, findOffset('_m() {} // in= C')); +- } +- +- test_member_ofMixin2_method() async { +- addTestFile(''' +-class M1 { +- void test() {} // in M1 +-} +-class M2 { +- void test() {} // in M2 +-} +-class D1 extends Object with M1 {} +-class D2 extends Object with M1, M2 {} +-class D3 extends Object with M2, M1 {} +-class D4 extends Object with M2, M1 { +- void test() {} // in D4 +-} +-'''); +- List items =3D +- await _getTypeHierarchy('test() {} // in M1'); +- var itemM1 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D '= M1'); +- var item1 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= 1'); +- var item2 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= 2'); +- var item3 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= 3'); +- var item4 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= 4'); +- expect(itemM1, isNotNull); +- expect(item1, isNotNull); +- expect(item2, isNotNull); +- expect(item3, isNotNull); +- expect(item4, isNotNull); +- // D1 does not override +- { +- Element member1 =3D item1.memberElement; +- expect(member1, isNull); +- } +- // D2 mixes-in M2 last, which overrides +- { +- Element member2 =3D item2.memberElement; +- expect(member2, isNotNull); +- expect(member2.location.offset, findOffset('test() {} // in M2')); +- } +- // D3 mixes-in M1 last and does not override itself +- { +- Element member3 =3D item3.memberElement; +- expect(member3, isNull); +- } +- // D4 mixes-in M1 last, but it also overrides +- { +- Element member4 =3D item4.memberElement; +- expect(member4.location.offset, findOffset('test() {} // in D4')); +- } +- } +- +- test_member_ofMixin_getter() async { +- addTestFile(''' +-abstract class Base { +- get test; // in Base +-} +-class Mixin { +- get test =3D> null; // in Mixin +-} +-class Derived1 extends Base with Mixin {} +-class Derived2 extends Base { +- get test =3D> null; // in Derived2 +-} +-'''); +- List items =3D await _getTypeHierarchy('test; // i= n Base'); +- var itemBase =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D= 'Base'); +- var item1 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= erived1'); +- var item2 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= erived2'); +- Element memberBase =3D itemBase.memberElement; +- Element member1 =3D item1.memberElement; +- Element member2 =3D item2.memberElement; +- expect(memberBase, isNotNull); +- expect(member1, isNotNull); +- expect(member2, isNotNull); +- expect(memberBase.location.offset, findOffset('test; // in Base')); +- expect(member1.location.offset, findOffset('test =3D> null; // in Mix= in')); +- expect(member2.location.offset, findOffset('test =3D> null; // in Der= ived2')); +- } +- +- test_member_ofMixin_method() async { +- addTestFile(''' +-abstract class Base { +- void test(); // in Base +-} +-class Mixin { +- void test() {} // in Mixin +-} +-class Derived1 extends Base with Mixin {} +-class Derived2 extends Base { +- void test() {} // in Derived2 +-} +-'''); +- List items =3D +- await _getTypeHierarchy('test(); // in Base'); +- var itemBase =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D= 'Base'); +- var item1 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= erived1'); +- var item2 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= erived2'); +- Element memberBase =3D itemBase.memberElement; +- Element member1 =3D item1.memberElement; +- Element member2 =3D item2.memberElement; +- expect(memberBase, isNotNull); +- expect(member1, isNotNull); +- expect(member2, isNotNull); +- expect(memberBase.location.offset, findOffset('test(); // in Base')); +- expect(member1.location.offset, findOffset('test() {} // in Mixin')); +- expect(member2.location.offset, findOffset('test() {} // in Derived2'= )); +- } +- +- test_member_ofMixin_setter() async { +- addTestFile(''' +-abstract class Base { +- set test(x); // in Base +-} +-class Mixin { +- set test(x) {} // in Mixin +-} +-class Derived1 extends Base with Mixin {} +-class Derived2 extends Base { +- set test(x) {} // in Derived2 +-} +-'''); +- List items =3D +- await _getTypeHierarchy('test(x); // in Base'); +- var itemBase =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D= 'Base'); +- var item1 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= erived1'); +- var item2 =3D items.firstWhere((e) =3D> e.classElement.name =3D=3D 'D= erived2'); +- Element memberBase =3D itemBase.memberElement; +- Element member1 =3D item1.memberElement; +- Element member2 =3D item2.memberElement; +- expect(memberBase, isNotNull); +- expect(member1, isNotNull); +- expect(member2, isNotNull); +- expect(memberBase.location.offset, findOffset('test(x); // in Base')); +- expect(member1.location.offset, findOffset('test(x) {} // in Mixin')); +- expect(member2.location.offset, findOffset('test(x) {} // in Derived2= ')); +- } +- +- test_member_operator() async { +- addTestFile(''' +-class A { +- operator =3D=3D(x) =3D> null; // in A +-} +-class B extends A { +- operator =3D=3D(x) =3D> null; // in B +-} +-class C extends B { +-} +-class D extends C { +- operator =3D=3D(x) =3D> null; // in D +-} +-'''); +- List items =3D +- await _getTypeHierarchy('=3D=3D(x) =3D> null; // in B'); +- var itemB =3D items[0]; +- var itemA =3D items[itemB.superclass]; +- var itemC =3D items[itemB.subclasses[0]]; +- var itemD =3D items[itemC.subclasses[0]]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemC.classElement.name, 'C'); +- expect(itemD.classElement.name, 'D'); +- expect(itemA.memberElement.location.offset, +- findOffset('=3D=3D(x) =3D> null; // in A')); +- expect(itemB.memberElement.location.offset, +- findOffset('=3D=3D(x) =3D> null; // in B')); +- expect(itemC.memberElement, isNull); +- expect(itemD.memberElement.location.offset, +- findOffset('=3D=3D(x) =3D> null; // in D')); +- } +- +- test_member_setter() async { +- addTestFile(''' +-class A { +- set test(x) {} // in A +-} +-class B extends A { +- set test(x) {} // in B +-} +-class C extends B { +-} +-class D extends C { +- set test(x) {} // in D +-} +-'''); +- List items =3D +- await _getTypeHierarchy('test(x) {} // in B'); +- var itemB =3D items[0]; +- var itemA =3D items[itemB.superclass]; +- var itemC =3D items[itemB.subclasses[0]]; +- var itemD =3D items[itemC.subclasses[0]]; +- expect(itemA.classElement.name, 'A'); +- expect(itemB.classElement.name, 'B'); +- expect(itemC.classElement.name, 'C'); +- expect(itemD.classElement.name, 'D'); +- expect( +- itemA.memberElement.location.offset, findOffset('test(x) {} // in= A')); +- expect( +- itemB.memberElement.location.offset, findOffset('test(x) {} // in= B')); +- expect(itemC.memberElement, isNull); +- expect( +- itemD.memberElement.location.offset, findOffset('test(x) {} // in= D')); +- } +- +- test_superOnly() async { +- addTestFile(''' +-class A {} +-class B {} +-class C extends A implements B {} +-class D extends C {} +-'''); +- List items =3D +- await _getTypeHierarchy('C extends', superOnly: true); +- expect(_toJson(items), [ +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'C', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 1, +- 'interfaces': [3], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'A', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 2, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'Object', +- 'location': anything, +- 'flags': 0 +- }, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- }, +- { +- 'classElement': { +- 'kind': 'CLASS', +- 'name': 'B', +- 'location': anything, +- 'flags': 0 +- }, +- 'superclass': 2, +- 'interfaces': [], +- 'mixins': [], +- 'subclasses': [] +- } +- ]); +- } +- +- test_superOnly_fileDoesNotExist() async { +- Request request =3D new SearchGetTypeHierarchyParams( +- '/does/not/exist.dart', 0, +- superOnly: true) +- .toRequest(requestId); +- Response response =3D await serverChannel.sendRequest(request); +- List items =3D +- new SearchGetTypeHierarchyResult.fromResponse(response).hierarchy= Items; +- expect(items, isNull); +- } +- +- Request _createGetTypeHierarchyRequest(String search, {bool superOnly})= { +- return new SearchGetTypeHierarchyParams(testFile, findOffset(search), +- superOnly: superOnly) +- .toRequest(requestId); +- } +- +- Future> _getTypeHierarchy(String search, +- {bool superOnly}) async { +- await waitForTasksFinished(); +- Request request =3D +- _createGetTypeHierarchyRequest(search, superOnly: superOnly); +- Response response =3D await serverChannel.sendRequest(request); +- expect(serverErrors, isEmpty); +- return new SearchGetTypeHierarchyResult.fromResponse(response) +- .hierarchyItems; +- } +- +- List _toJson(List items) { +- return items.map((item) =3D> item.toJson()).toList(); +- } +- +- static Set _toClassNames(List items) { +- return items.map((TypeHierarchyItem item) { +- return item.classElement.name; +- }).toSet(); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/arglist_con= tributor_test.dart b/pkg/analysis_server/test/services/completion/dart/argl= ist_contributor_test.dart +deleted file mode 100644 +index 6ab74304758..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/arglist_contributo= r_test.dart ++++ /dev/null +@@ -1,1019 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/arglist_cont= ributor.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../../src/utilities/flutter_util.dart'; +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ArgListContributorTest); +- }); +-} +- +-@reflectiveTest +-class ArgListContributorTest extends DartCompletionContributorTest { +- void assertNoOtherSuggestions(Iterable expected) { +- for (CompletionSuggestion suggestion in suggestions) { +- if (!expected.contains(suggestion)) { +- failedCompletion('did not expect completion: ' +- '${suggestion.completion}\n $suggestion'); +- } +- } +- } +- +- /** +- * Assert that there is a suggestion with the given parameter [name] th= at has +- * the given [completion], [selectionOffset] and [selectionLength]. +- */ +- void assertSuggestArgumentAndCompletion(String name, +- {String completion, int selectionOffset, int selectionLength: 0}) { +- CompletionSuggestion suggestion =3D +- suggestions.firstWhere((s) =3D> s.parameterName =3D=3D name); +- expect(suggestion, isNotNull); +- expect(suggestion.completion, completion); +- expect(suggestion.selectionOffset, selectionOffset); +- expect(suggestion.selectionLength, selectionLength); +- } +- +- void assertSuggestArgumentList( +- List paramNames, List paramTypes) { +- // DEPRECATED... argument lists are no longer suggested. +- // See https://github.com/dart-lang/sdk/issues/25197 +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- +- // CompletionSuggestionKind csKind =3D CompletionSuggestionKind.ARGUM= ENT_LIST; +- // CompletionSuggestion cs =3D getSuggest(csKind: csKind); +- // if (cs =3D=3D null) { +- // failedCompletion('expected completion $csKind', suggestions); +- // } +- // assertSuggestArgumentList_params( +- // paramNames, paramTypes, cs.parameterNames, cs.parameterTypes); +- // expect(cs.relevance, DART_RELEVANCE_HIGH); +- // assertNoOtherSuggestions([cs]); +- } +- +- void assertSuggestArgumentList_params( +- List expectedNames, +- List expectedTypes, +- List actualNames, +- List actualTypes) { +- if (actualNames !=3D null && +- actualNames.length =3D=3D expectedNames.length && +- actualTypes !=3D null && +- actualTypes.length =3D=3D expectedTypes.length) { +- int index =3D 0; +- while (index < expectedNames.length) { +- if (actualNames[index] !=3D expectedNames[index] || +- actualTypes[index] !=3D expectedTypes[index]) { +- break; +- } +- ++index; +- } +- if (index =3D=3D expectedNames.length) { +- return; +- } +- } +- StringBuffer msg =3D new StringBuffer(); +- msg.writeln('Argument list not the same'); +- msg.writeln(' Expected names: $expectedNames'); +- msg.writeln(' found: $actualNames'); +- msg.writeln(' Expected types: $expectedTypes'); +- msg.writeln(' found: $actualTypes'); +- fail(msg.toString()); +- } +- +- /** +- * Assert that the specified named argument suggestions with their type= s are +- * the only suggestions. +- */ +- void assertSuggestArgumentsAndTypes( +- {Map namedArgumentsWithTypes, +- List requiredParamIndices: const [], +- bool includeColon: true, +- bool includeComma: false}) { +- List expected =3D new List(); +- int paramIndex =3D 0; +- namedArgumentsWithTypes.forEach((String name, String type) { +- String completion =3D includeColon ? '$name: ' : name; +- // Selection should be before any trailing commas. +- int selectionOffset =3D completion.length; +- if (includeComma) { +- completion =3D '$completion,'; +- } +- int relevance =3D requiredParamIndices.contains(paramIndex++) +- ? DART_RELEVANCE_NAMED_PARAMETER_REQUIRED +- : DART_RELEVANCE_NAMED_PARAMETER; +- expected.add(assertSuggest(completion, +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: relevance, +- paramName: name, +- paramType: type, +- selectionOffset: selectionOffset)); +- }); +- assertNoOtherSuggestions(expected); +- } +- +- /** +- * Assert that the specified suggestions are the only suggestions. +- */ +- void assertSuggestions(List suggestions) { +- List expected =3D new List(); +- for (String suggestion in suggestions) { +- // Selection offset should be before any trailing commas. +- int selectionOffset =3D +- suggestion.endsWith(',') ? suggestion.length - 1 : suggestion.l= ength; +- expected.add(assertSuggest('$suggestion', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- selectionOffset: selectionOffset)); +- } +- assertNoOtherSuggestions(expected); +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new ArgListContributor(); +- } +- +- fail_test_Annotation_local_constructor_named_param_10() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(two: '2' ^) main() { }'''); +- await computeSuggestions(); +- assertSuggestions([', one: ']); +- } +- +- fail_test_Annotation_local_constructor_named_param_9() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(two: '2'^) main() { }'''); +- await computeSuggestions(); +- assertSuggestions([', one: ']); +- } +- +- test_Annotation_imported_constructor_named_param() async { +- addSource('/libA.dart', ''' +-library libA; class A { const A({int one, String two: 'defaultValue'}); }= '''); +- addTestSource('import "/libA.dart"; @A(^) main() { }'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}); +- } +- +- test_Annotation_local_constructor_named_param() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(^) main() { }'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}); +- } +- +- test_Annotation_local_constructor_named_param_11() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(two: '2', ^) main() { }'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_Annotation_local_constructor_named_param_2() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(^ two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestions(['one: ,']); +- } +- +- test_Annotation_local_constructor_named_param_3() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(^two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestions(['one: ,']); +- } +- +- test_Annotation_local_constructor_named_param_4() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(^, two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_Annotation_local_constructor_named_param_5() async { +- addTestSource(''' +-class A { const A({int one, String two: 'defaultValue'}); } +-@A(^ , two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_Annotation_local_constructor_named_param_6() async { +- addTestSource(''' +-class A { const A(int zero, {int one, String two: 'defaultValue'}); } +-@A(0, ^, two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_Annotation_local_constructor_named_param_7() async { +- addTestSource(''' +-class A { const A(int zero, {int one, String two: 'defaultValue'}); } +-@A(0, ^ two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestions(['one: ,']); +- } +- +- test_Annotation_local_constructor_named_param_8() async { +- addTestSource(''' +-class A { const A(int zero, {int one, String two: 'defaultValue'}); } +-@A(0, ^two: '2') main() { }'''); +- await computeSuggestions(); +- assertSuggestions(['one: ,']); +- } +- +- test_Annotation_local_constructor_named_param_negative() async { +- addTestSource(''' +-class A { const A(int one, int two, int three, {int four, String five: +- 'defaultValue'}); } +-@A(1, ^, 3) main() { }'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_Flutter_InstanceCreationExpression_0() async { +- configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +-build() =3D> new Row( +- ^ +- ); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('children: [],', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- defaultArgListString: null, +- selectionOffset: 19, +- defaultArgumentListTextRanges: null); +- } +- +- test_ArgumentList_Flutter_InstanceCreationExpression_01() async { +- configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +- build() =3D> new Scaffold( +- appBar: new AppBar( +- ^ +- ), +- ); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('color: ,', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- defaultArgListString: null, // No default values. +- selectionOffset: 7); +- } +- +- test_ArgumentList_Flutter_InstanceCreationExpression_1() async { +- configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +-build() =3D> new Row( +- key: null, +- ^ +- ); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('children: [],', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- defaultArgListString: null, +- selectionOffset: 19, +- defaultArgumentListTextRanges: null); +- } +- +- test_ArgumentList_Flutter_InstanceCreationExpression_2() async { +- configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +-build() =3D> new Row( +- ^ +- key: null, +- ); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('children: [],', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- defaultArgListString: null, +- selectionOffset: 19, +- defaultArgumentListTextRanges: null); +- } +- +- test_ArgumentList_Flutter_InstanceCreationExpression_children_dynamic()= async { +- // Ensure we don't generate unneeded param if a future API = doesn't +- // type it's children. +- configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code + +- '\nclass DynamicRow extends Widget { DynamicRow({List children:= null}){}}' +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +-build() =3D> new Container( +- child: new DynamicRow(^); +- ); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('children: [],', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- defaultArgListString: null, +- selectionOffset: 11, +- defaultArgumentListTextRanges: null); +- } +- +- test_ArgumentList_Flutter_InstanceCreationExpression_children_Map() asy= nc { +- // Ensure we don't generate Map params for a future API +- configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code + +- '\nclass MapRow extends Widget { MapRow({Map chi= ldren: null}){}}' +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +-build() =3D> new Container( +- child: new MapRow(^); +- ); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('children: ,', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- selectionOffset: 10, +- defaultArgListString: null); +- } +- +- test_ArgumentList_Flutter_MethodExpression_children() async { +- // Ensure we don't generate params for a method call +- configureFlutterPkg({ +- 'src/widgets/framework.dart': +- flutter_framework_code + '\nfoo({String children})' +- }); +- +- addTestSource(''' +-import 'package:flutter/src/widgets/framework.dart'; +- +-main() { +-foo(^); +-'''); +- +- await computeSuggestions(); +- +- assertSuggest('children: ', +- csKind: CompletionSuggestionKind.NAMED_ARGUMENT, +- relevance: DART_RELEVANCE_NAMED_PARAMETER, +- defaultArgListString: null); +- } +- +- test_ArgumentList_getter() async { +- addTestSource('class A {int get foo =3D> 7; main() {foo(^)}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_constructor_named_param() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement +- addSource('/libA.dart', 'library libA; class A{A({int one}); }'); +- addTestSource('import "/libA.dart"; main() { new A(^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_ArgumentList_imported_constructor_named_param2() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement +- addSource('/libA.dart', 'library libA; class A{A.foo({int one}); }'); +- addTestSource('import "/libA.dart"; main() { new A.foo(^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_ArgumentList_imported_constructor_named_typed_param() async { +- // ArgumentList InstanceCreationExpression VariableDeclaration +- addSource( +- '/libA.dart', 'library libA; class A { A({int i, String s, d}) {}= }}'); +- addTestSource('import "/libA.dart"; main() { var a =3D new A(^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'i': 'int', 's': 'String', 'd': 'dynami= c'}); +- } +- +- test_ArgumentList_imported_factory_named_param() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement +- addSource( +- '/libA.dart', 'library libA; class A{factory A({int one}) =3D> nu= ll;}'); +- addTestSource('import "/libA.dart"; main() { new A(^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_ArgumentList_imported_factory_named_param2() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement +- addSource('/libA.dart', +- 'library libA; abstract class A{factory A.foo({int one});}'); +- addTestSource('import "/libA.dart"; main() { new A.foo(^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- } +- +- test_ArgumentList_imported_factory_named_typed_param() async { +- // ArgumentList InstanceCreationExpression VariableDeclaration +- addSource('/libA.dart', +- 'library libA; class A {factory A({int i, String s, d}) {} }}'); +- addTestSource('import "/libA.dart"; main() { var a =3D new A(^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'i': 'int', 's': 'String', 'd': 'dynami= c'}); +- } +- +- test_ArgumentList_imported_function_0() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect() { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect(a^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_function_1() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg'], ['String']); +- } +- +- test_ArgumentList_imported_function_2() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg1, int arg2) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg1', 'arg2'], ['String', 'int']); +- } +- +- test_ArgumentList_imported_function_3() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg1, int arg2, {bool arg3}) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg1', 'arg2'], ['String', 'int']); +- } +- +- test_ArgumentList_imported_function_3a() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg1, int arg2, {bool arg3}) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', ^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_function_3b() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg1, int arg2, {bool arg3}) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', ^x)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_function_3c() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg1, int arg2, {bool arg3}) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', x^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_function_3d() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(String arg1, int arg2, {bool arg3}) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', x ^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_function_named_param() async { +- // +- addTestSource('main() { int.parse("16", ^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'radix': 'int', 'onError': '(String) = =E2=86=92 int'}); +- } +- +- test_ArgumentList_imported_function_named_param1() async { +- // +- addTestSource('main() { int.parse("16", r^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'radix': 'int', 'onError': '(String) = =E2=86=92 int'}); +- } +- +- test_ArgumentList_imported_function_named_param2() async { +- // +- addTestSource('main() { int.parse("16", radix: 7, ^);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'onError': '(String) =E2=86=92 int'}); +- } +- +- test_ArgumentList_imported_function_named_param2a() async { +- // +- addTestSource('main() { int.parse("16", radix: ^);}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_imported_function_named_param_label1() async { +- // +- addTestSource('main() { int.parse("16", r^: 16);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'radix': 'int', 'onError': '(String) = =E2=86=92 int'}, +- includeColon: false); +- } +- +- test_ArgumentList_imported_function_named_param_label2() async { +- // +- addTestSource('main() { int.parse("16", ^r: 16);}'); +- await computeSuggestions(); +- assertSuggestions(['radix: ,', 'onError: ,']); +- } +- +- test_ArgumentList_imported_function_named_param_label3() async { +- // +- addTestSource('main() { int.parse("16", ^: 16);}'); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'radix': 'int', 'onError': '(String) = =E2=86=92 int'}); +- } +- +- test_ArgumentList_local_constructor_named_fieldFormal_documentation() a= sync { +- String content =3D ''' +-class A { +- /// aaa +- /// +- /// bbb +- /// ccc +- int fff; +- A({this.fff}); +-} +-main() { +- new A(^); +-} +-'''; +- addTestSource(content); +- await computeSuggestions(); +- expect(suggestions, hasLength(1)); +- +- CompletionSuggestion suggestion =3D suggestions[0]; +- expect(suggestion.docSummary, 'aaa'); +- expect(suggestion.docComplete, 'aaa\n\nbbb\nccc'); +- +- Element element =3D suggestion.element; +- expect(element, isNotNull); +- expect(element.kind, ElementKind.PARAMETER); +- expect(element.name, 'fff'); +- expect(element.location.offset, content.indexOf('fff})')); +- } +- +- test_ArgumentList_local_constructor_named_fieldFormal_noDocumentation()= async { +- String content =3D ''' +-class A { +- int fff; +- A({this.fff}); +-} +-main() { +- new A(^); +-} +-'''; +- addTestSource(content); +- await computeSuggestions(); +- expect(suggestions, hasLength(1)); +- +- CompletionSuggestion suggestion =3D suggestions[0]; +- expect(suggestion.docSummary, isNull); +- expect(suggestion.docComplete, isNull); +- +- Element element =3D suggestion.element; +- expect(element, isNotNull); +- expect(element.kind, ElementKind.PARAMETER); +- expect(element.name, 'fff'); +- expect(element.location.offset, content.indexOf('fff})')); +- } +- +- test_ArgumentList_local_constructor_named_param() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(^);}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_1() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(o^);}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_2() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(^o,);}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_3() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(two: 'foo', ^);}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_4() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(two: 'foo', o^);}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_5() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(two: 'foo', o^,);}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'= }); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_6() async { +- // +- addTestSource(''' +-class A { A.foo({int one, String two: 'defaultValue'}) { } } +-main() { new A.foo(^);}'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}); +- } +- +- test_ArgumentList_local_constructor_named_param_prefixed_prepend() asyn= c { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(o^ two: 'foo');}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int'}, includeComma: true); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ,', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_prepend() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(^ two: 'foo');}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int'}, includeComma: true); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ,', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_prepend_1() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(o^, two: 'foo');}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int'}, includeComma: false); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_named_param_prepend_2() async { +- // +- addTestSource(''' +-class A { A({int one, String two: 'defaultValue'}) { } } +-main() { new A(^, two: 'foo');}'''); +- await computeSuggestions(); +- +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int'}, includeComma: false); +- assertSuggestArgumentAndCompletion('one', +- completion: 'one: ', selectionOffset: 5); +- } +- +- test_ArgumentList_local_constructor_required_param_0() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +-class A { A({int one, @required String two: 'defaultValue'}) { } } +-main() { new A(^);}'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'one': 'int', 'two': 'String'}, +- requiredParamIndices: [1]); +- } +- +- test_ArgumentList_local_function_1() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg) { } +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg'], ['dynamic']); +- } +- +- test_ArgumentList_local_function_2() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg1, int arg2) { } +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg1', 'arg2'], ['dynamic', 'int']); +- } +- +- test_ArgumentList_local_function_3() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg1, int arg2) { } +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg1', 'arg2'], ['dynamic', 'int']); +- } +- +- test_ArgumentList_local_function_3a() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg1, int arg2, {bool arg3}) { } +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', ^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_local_function_3b() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg1, int arg2, {bool arg3}) { } +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', ^x)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_local_function_3c() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg1, int arg2, {bool arg3}) { } +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', x^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_local_function_3d() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addTestSource(''' +- import '/libA.dart' +- expect(arg1, int arg2, {bool arg3}) { } +- class B { } +- String bar() =3D> true; +- void main() {expect('hello', x ^)}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_local_function_named_param() async { +- // +- addTestSource(''' +-f(v,{int radix, int onError(String s)}){} +-main() { f("16", ^);}'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'radix': 'int', 'onError': '(String) = =E2=86=92 int'}); +- } +- +- test_ArgumentList_local_function_named_param1() async { +- // +- addTestSource(''' +-f(v,{int radix, int onError(String s)}){} +-main() { f("16", r^);}'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'radix': 'int', 'onError': '(String) = =E2=86=92 int'}); +- } +- +- test_ArgumentList_local_function_named_param2() async { +- // +- addTestSource(''' +-f(v,{int radix, int onError(String s)}){} +-main() { f("16", radix: 7, ^);}'''); +- await computeSuggestions(); +- assertSuggestArgumentsAndTypes( +- namedArgumentsWithTypes: {'onError': '(String) =E2=86=92 int'}); +- } +- +- test_ArgumentList_local_function_named_param2a() async { +- // +- addTestSource(''' +-f(v,{int radix, int onError(String s)}){} +-main() { f("16", radix: ^);}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_local_method_0() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { +- expect() { } +- void foo() {expect(^)}} +- String bar() =3D> true;'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ArgumentList_local_method_2() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { +- expect(arg, int blat) { } +- void foo() {expect(^)}} +- String bar() =3D> true;'''); +- await computeSuggestions(); +- assertSuggestArgumentList(['arg', 'blat'], ['dynamic', 'int']); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/combinator_= contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/c= ombinator_contributor_test.dart +deleted file mode 100644 +index 0bc60b753b1..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/combinator_contrib= utor_test.dart ++++ /dev/null +@@ -1,153 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/combinator_c= ontributor.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(CombinatorContributorTest); +- }); +-} +- +-@reflectiveTest +-class CombinatorContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new CombinatorContributor(); +- } +- +- test_Block_inherited_local() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addTestSource(''' +- class F { var f1; f2() { } } +- class E extends F { var e1; e2() { } } +- class I { int i1; i2() { } } +- class M { var m1; int m2() { } } +- class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_Combinator_hide() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +- library libAB; +- part '/partAB.dart'; +- class A { } +- class B { }'''); +- addSource('/partAB.dart', ''' +- part of libAB; +- var T1; +- PB F1() =3D> new PB(); +- class PB { }'''); +- addSource('/testCD.dart', ''' +- class C { } +- class D { }'''); +- addTestSource(''' +- import "/testAB.dart" hide ^; +- import "/testCD.dart"; +- class X {}'''); +- +- await computeSuggestions(); +- assertSuggestClass('A', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('B', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('PB', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestTopLevelVar('T1', null, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunction('F1', 'PB', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('C'); +- assertNotSuggested('D'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- } +- +- test_Combinator_show() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +- library libAB; +- part '/partAB.dart'; +- class A { } +- class B { } +- class _AB'''); +- addSource('/partAB.dart', ''' +- part of libAB; +- var T1; +- PB F1() =3D> new PB(); +- typedef PB2 F2(int blat); +- class Clz =3D Object with Object; +- class PB { }'''); +- addSource('/testCD.dart', ''' +- class C { } +- class D { }'''); +- addTestSource(''' +- import "/testAB.dart" show ^; +- import "/testCD.dart"; +- class X {}'''); +- +- await computeSuggestions(); +- assertSuggestClass('A', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('B', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('_AB'); +- assertSuggestClass('PB', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestTopLevelVar('T1', null, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunction('F1', 'PB', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('Clz', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunctionTypeAlias('F2', null, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('C'); +- assertNotSuggested('D'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- } +- +- test_Combinator_show_PI() async { +- addTestSource('import "dart:math" show ^;'); +- await computeSuggestions(); +- assertSuggestTopLevelVar('PI', 'double', +- kind: CompletionSuggestionKind.IDENTIFIER); +- } +- +- test_Combinator_show_recursive() async { +- addSource('/testA.dart', ''' +-class A {} +-'''); +- addSource('/testB.dart', ''' +-export 'testA.dart'; +-export 'testB.dart'; +-class B {} +-'''); +- addTestSource(''' +-import "/testB.dart" show ^; +-'''); +- await computeSuggestions(); +- assertSuggestClass('A', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('B', +- relevance: DART_RELEVANCE_DEFAULT, +- kind: CompletionSuggestionKind.IDENTIFIER); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/common_usag= e_sorter_test.dart b/pkg/analysis_server/test/services/completion/dart/comm= on_usage_sorter_test.dart +deleted file mode 100644 +index 3aa6d41a222..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/common_usage_sorte= r_test.dart ++++ /dev/null +@@ -1,148 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/common_usage= _sorter.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../../domain_completion_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(CommonUsageSorterTest); +- }); +-} +- +-@reflectiveTest +-class CommonUsageSorterTest extends AbstractCompletionDomainTest { +- Future getSuggestionsWith(Map> selectorRelevance) = async { +- var originalSorter =3D DartCompletionManager.contributionSorter; +- DartCompletionManager.contributionSorter =3D +- new CommonUsageSorter(selectorRelevance); +- try { +- return await getSuggestions(); +- } finally { +- DartCompletionManager.contributionSorter =3D originalSorter; +- } +- } +- +- test_ConstructorName() async { +- // SimpleIdentifier ConstructorName InstanceCreationExpression +- addTestFile('import "dart:async"; class A {x() {new Future.^}}'); +- await getSuggestionsWith({ +- 'dart.async.Future': ['value', 'wait'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'delayed'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'value', +- relevance: DART_RELEVANCE_COMMON_USAGE); +- assertNoResult('Future'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +- +- test_PrefixedIdentifier_field() async { +- // SimpleIdentifier PrefixedIdentifeir ExpressionStatement +- addTestFile('class A {static int s1; static int s2; x() {A.^}}'); +- await getSuggestionsWith({ +- '.A': ['s2'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 's1'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 's2', +- relevance: DART_RELEVANCE_COMMON_USAGE); +- assertNoResult('Future'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +- +- test_PrefixedIdentifier_field_inPart() async { +- // SimpleIdentifier PrefixedIdentifeir ExpressionStatement +- addFile('/project/bin/myLib.dart', +- 'library L; part "$testFile"; class A {static int s2;}'); +- addTestFile('part of L; foo() {A.^}'); +- await getSuggestionsWith({ +- 'L.A': ['s2'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 's2', +- relevance: DART_RELEVANCE_COMMON_USAGE); +- assertNoResult('Future'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +- +- test_PrefixedIdentifier_getter() async { +- // SimpleIdentifier PrefixedIdentifeir ExpressionStatement +- addTestFile('class A {int get g1 =3D> 1; int get g2 =3D> 2; x() {new = A().^}}'); +- await getSuggestionsWith({ +- '.A': ['g2'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'g1'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'g2', +- relevance: DART_RELEVANCE_COMMON_USAGE); +- assertNoResult('Future'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +- +- test_PrefixedIdentifier_setter() async { +- // SimpleIdentifier PrefixedIdentifeir ExpressionStatement +- addTestFile('class A {set s1(v) {}; set s2(v) {}; x() {new A().^}}'); +- await getSuggestionsWith({ +- '.A': ['s2'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 's1'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 's2', +- relevance: DART_RELEVANCE_COMMON_USAGE); +- assertNoResult('Future'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +- +- test_PrefixedIdentifier_static_method() async { +- // SimpleIdentifier PrefixedIdentifeir ExpressionStatement +- addTestFile('import "dart:async"; class A {x() {Future.^}}'); +- await getSuggestionsWith({ +- 'dart.async.Future': ['value', 'wait'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'wait', +- relevance: DART_RELEVANCE_COMMON_USAGE - 1); +- assertNoResult('Future'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +- +- test_PropertyAccess() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addTestFile('import "dart:math"; class A {x() {new Random().^}}'); +- await getSuggestionsWith({ +- 'dart.math.Random': ['nextInt', 'nextDouble'] +- }); +- expect(replacementOffset, equals(completionOffset)); +- expect(replacementLength, equals(0)); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'nextBool'); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'nextDouble', +- relevance: DART_RELEVANCE_COMMON_USAGE - 1); +- assertHasResult(CompletionSuggestionKind.INVOCATION, 'nextInt', +- relevance: DART_RELEVANCE_COMMON_USAGE); +- assertNoResult('Random'); +- assertNoResult('Object'); +- assertNoResult('A'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/completion_= contributor_util.dart b/pkg/analysis_server/test/services/completion/dart/c= ompletion_contributor_util.dart +deleted file mode 100644 +index 469bc3a938c..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/completion_contrib= utor_util.dart ++++ /dev/null +@@ -1,589 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/completion_core.d= art'; +-import 'package:analysis_server/src/services/completion/completion_perfor= mance.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart' +- show DartCompletionRequestImpl; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +- +-import '../../../abstract_context.dart'; +-import '../../../src/utilities/flutter_util.dart'; +- +-int suggestionComparator(CompletionSuggestion s1, CompletionSuggestion s2= ) { +- String c1 =3D s1.completion.toLowerCase(); +- String c2 =3D s2.completion.toLowerCase(); +- return c1.compareTo(c2); +-} +- +-abstract class DartCompletionContributorTest extends AbstractContextTest { +- static const String _UNCHECKED =3D '__UNCHECKED__'; +- String testFile; +- Source testSource; +- int completionOffset; +- int replacementOffset; +- int replacementLength; +- DartCompletionContributor contributor; +- DartCompletionRequest request; +- List suggestions; +- +- /** +- * If `true` and `null` is specified as the suggestion's expected retur= nType +- * then the actual suggestion is expected to have a `dynamic` returnTyp= e. +- * Newer tests return `false` so that they can distinguish between +- * `dynamic` and `null`. +- * Eventually all tests should be converted and this getter removed. +- */ +- bool get isNullExpectedReturnTypeConsideredDynamic =3D> true; +- +- void addTestSource(String content) { +- expect(completionOffset, isNull, reason: 'Call addTestUnit exactly on= ce'); +- completionOffset =3D content.indexOf('^'); +- expect(completionOffset, isNot(equals(-1)), reason: 'missing ^'); +- int nextOffset =3D content.indexOf('^', completionOffset + 1); +- expect(nextOffset, equals(-1), reason: 'too many ^'); +- content =3D content.substring(0, completionOffset) + +- content.substring(completionOffset + 1); +- testSource =3D addSource(testFile, content); +- } +- +- void assertHasNoParameterInfo(CompletionSuggestion suggestion) { +- expect(suggestion.parameterNames, isNull); +- expect(suggestion.parameterTypes, isNull); +- expect(suggestion.requiredParameterCount, isNull); +- expect(suggestion.hasNamedParameters, isNull); +- } +- +- void assertHasParameterInfo(CompletionSuggestion suggestion) { +- expect(suggestion.parameterNames, isNotNull); +- expect(suggestion.parameterTypes, isNotNull); +- expect(suggestion.parameterNames.length, suggestion.parameterTypes.le= ngth); +- expect(suggestion.requiredParameterCount, +- lessThanOrEqualTo(suggestion.parameterNames.length)); +- expect(suggestion.hasNamedParameters, isNotNull); +- } +- +- void assertNoSuggestions({CompletionSuggestionKind kind: null}) { +- if (kind =3D=3D null) { +- if (suggestions.length > 0) { +- failedCompletion('Expected no suggestions', suggestions); +- } +- return; +- } +- CompletionSuggestion suggestion =3D suggestions.firstWhere( +- (CompletionSuggestion cs) =3D> cs.kind =3D=3D kind, +- orElse: () =3D> null); +- if (suggestion !=3D null) { +- failedCompletion('did not expect completion: $completion\n $sugges= tion'); +- } +- } +- +- void assertNotSuggested(String completion) { +- CompletionSuggestion suggestion =3D suggestions.firstWhere( +- (CompletionSuggestion cs) =3D> cs.completion =3D=3D completion, +- orElse: () =3D> null); +- if (suggestion !=3D null) { +- failedCompletion('did not expect completion: $completion\n $sugges= tion'); +- } +- } +- +- CompletionSuggestion assertSuggest(String completion, +- {CompletionSuggestionKind csKind: CompletionSuggestionKind.INVOCATI= ON, +- int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- ElementKind elemKind: null, +- bool isDeprecated: false, +- bool isPotential: false, +- String elemFile, +- int elemOffset, +- int selectionOffset, +- String paramName, +- String paramType, +- String defaultArgListString: _UNCHECKED, +- List defaultArgumentListTextRanges}) { +- CompletionSuggestion cs =3D +- getSuggest(completion: completion, csKind: csKind, elemKind: elem= Kind); +- if (cs =3D=3D null) { +- failedCompletion('expected $completion $csKind $elemKind', suggesti= ons); +- } +- expect(cs.kind, equals(csKind)); +- if (isDeprecated) { +- expect(cs.relevance, equals(DART_RELEVANCE_LOW)); +- } else { +- expect(cs.relevance, equals(relevance), reason: completion); +- } +- expect(cs.importUri, importUri); +- expect(cs.selectionOffset, equals(selectionOffset ?? completion.lengt= h)); +- expect(cs.selectionLength, equals(0)); +- expect(cs.isDeprecated, equals(isDeprecated)); +- expect(cs.isPotential, equals(isPotential)); +- if (cs.element !=3D null) { +- expect(cs.element.location, isNotNull); +- expect(cs.element.location.file, isNotNull); +- expect(cs.element.location.offset, isNotNull); +- expect(cs.element.location.length, isNotNull); +- expect(cs.element.location.startColumn, isNotNull); +- expect(cs.element.location.startLine, isNotNull); +- } +- if (elemFile !=3D null) { +- expect(cs.element.location.file, elemFile); +- } +- if (elemOffset !=3D null) { +- expect(cs.element.location.offset, elemOffset); +- } +- if (paramName !=3D null) { +- expect(cs.parameterName, paramName); +- } +- if (paramType !=3D null) { +- expect(cs.parameterType, paramType); +- } +- if (defaultArgListString !=3D _UNCHECKED) { +- expect(cs.defaultArgumentListString, defaultArgListString); +- } +- if (defaultArgumentListTextRanges !=3D null) { +- expect(cs.defaultArgumentListTextRanges, defaultArgumentListTextRan= ges); +- } +- return cs; +- } +- +- CompletionSuggestion assertSuggestClass(String name, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- bool isDeprecated: false, +- String elemFile, +- String elemName, +- int elemOffset}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- isDeprecated: isDeprecated, +- elemFile: elemFile, +- elemOffset: elemOffset); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.CLASS)); +- expect(element.name, equals(elemName ?? name)); +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestClassTypeAlias(String name, +- {int relevance: DART_RELEVANCE_DEFAULT, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION}= ) { +- CompletionSuggestion cs =3D +- assertSuggest(name, csKind: kind, relevance: relevance); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.CLASS_TYPE_ALIAS)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestConstructor(String name, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- int elemOffset, +- String defaultArgListString: _UNCHECKED, +- List defaultArgumentListTextRanges}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- relevance: relevance, +- importUri: importUri, +- elemOffset: elemOffset, +- defaultArgListString: defaultArgListString, +- defaultArgumentListTextRanges: defaultArgumentListTextRanges); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.CONSTRUCTOR)); +- int index =3D name.indexOf('.'); +- expect(element.name, index >=3D 0 ? name.substring(index + 1) : ''); +- return cs; +- } +- +- CompletionSuggestion assertSuggestEnum(String completion, +- {bool isDeprecated: false}) { +- CompletionSuggestion suggestion =3D +- assertSuggest(completion, isDeprecated: isDeprecated); +- expect(suggestion.isDeprecated, isDeprecated); +- expect(suggestion.element.kind, ElementKind.ENUM); +- return suggestion; +- } +- +- CompletionSuggestion assertSuggestEnumConst(String completion, +- {int relevance: DART_RELEVANCE_DEFAULT, bool isDeprecated: false}) { +- CompletionSuggestion suggestion =3D assertSuggest(completion, +- relevance: relevance, isDeprecated: isDeprecated); +- expect(suggestion.completion, completion); +- expect(suggestion.isDeprecated, isDeprecated); +- expect(suggestion.element.kind, ElementKind.ENUM_CONSTANT); +- return suggestion; +- } +- +- CompletionSuggestion assertSuggestField(String name, String type, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- bool isDeprecated: false}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- elemKind: ElementKind.FIELD, +- isDeprecated: isDeprecated); +- // The returnType represents the type of a field +- expect(cs.returnType, type !=3D null ? type : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.FIELD)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- // The returnType represents the type of a field +- expect(element.returnType, type !=3D null ? type : 'dynamic'); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestFunction(String name, String returnTy= pe, +- {CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- bool isDeprecated: false, +- int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- String defaultArgListString: _UNCHECKED, +- List defaultArgumentListTextRanges}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- isDeprecated: isDeprecated, +- defaultArgListString: defaultArgListString, +- defaultArgumentListTextRanges: defaultArgumentListTextRanges); +- if (returnType !=3D null) { +- expect(cs.returnType, returnType); +- } else if (isNullExpectedReturnTypeConsideredDynamic) { +- expect(cs.returnType, 'dynamic'); +- } +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.FUNCTION)); +- expect(element.name, equals(name)); +- expect(element.isDeprecated, equals(isDeprecated)); +- String param =3D element.parameters; +- expect(param, isNotNull); +- expect(param[0], equals('(')); +- expect(param[param.length - 1], equals(')')); +- if (returnType !=3D null) { +- expect(element.returnType, returnType); +- } else if (isNullExpectedReturnTypeConsideredDynamic) { +- expect(element.returnType, 'dynamic'); +- } +- assertHasParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestFunctionTypeAlias( +- String name, String returnType, +- {bool isDeprecated: false, +- int relevance: DART_RELEVANCE_DEFAULT, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- String importUri}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- isDeprecated: isDeprecated); +- if (returnType !=3D null) { +- expect(cs.returnType, returnType); +- } else if (isNullExpectedReturnTypeConsideredDynamic) { +- expect(cs.returnType, 'dynamic'); +- } else { +- expect(cs.returnType, isNull); +- } +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.FUNCTION_TYPE_ALIAS)); +- expect(element.name, equals(name)); +- expect(element.isDeprecated, equals(isDeprecated)); +- // TODO (danrubel) Determine why params are null +- // String param =3D element.parameters; +- // expect(param, isNotNull); +- // expect(param[0], equals('(')); +- // expect(param[param.length - 1], equals(')')); +- expect(element.returnType, +- equals(returnType !=3D null ? returnType : 'dynamic')); +- // TODO (danrubel) Determine why param info is missing +- // assertHasParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestGetter(String name, String returnType, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- bool isDeprecated: false}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- elemKind: ElementKind.GETTER, +- isDeprecated: isDeprecated); +- expect(cs.returnType, returnType !=3D null ? returnType : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.GETTER)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, +- equals(returnType !=3D null ? returnType : 'dynamic')); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestMethod( +- String name, String declaringType, String returnType, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- bool isDeprecated: false, +- String defaultArgListString: _UNCHECKED, +- List defaultArgumentListTextRanges}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- isDeprecated: isDeprecated, +- defaultArgListString: defaultArgListString, +- defaultArgumentListTextRanges: defaultArgumentListTextRanges); +- expect(cs.declaringType, equals(declaringType)); +- expect(cs.returnType, returnType !=3D null ? returnType : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.METHOD)); +- expect(element.name, equals(name)); +- String param =3D element.parameters; +- expect(param, isNotNull); +- expect(param[0], equals('(')); +- expect(param[param.length - 1], equals(')')); +- expect(element.returnType, returnType !=3D null ? returnType : 'dynam= ic'); +- assertHasParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestName(String name, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- CompletionSuggestionKind kind: CompletionSuggestionKind.IDENTIFIER, +- bool isDeprecated: false}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- isDeprecated: isDeprecated); +- expect(cs.completion, equals(name)); +- expect(cs.element, isNull); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestSetter(String name, +- {int relevance: DART_RELEVANCE_DEFAULT, +- String importUri, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION}= ) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, +- relevance: relevance, +- importUri: importUri, +- elemKind: ElementKind.SETTER); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.SETTER)); +- expect(element.name, equals(name)); +- // TODO (danrubel) assert setter param +- //expect(element.parameters, isNull); +- // TODO (danrubel) it would be better if this was always null +- if (element.returnType !=3D null) { +- expect(element.returnType, 'dynamic'); +- } +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestTopLevelVar(String name, String retur= nType, +- {int relevance: DART_RELEVANCE_DEFAULT, +- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION, +- String importUri}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: kind, relevance: relevance, importUri: importUri); +- if (returnType !=3D null) { +- expect(cs.returnType, returnType); +- } else if (isNullExpectedReturnTypeConsideredDynamic) { +- expect(cs.returnType, 'dynamic'); +- } +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.TOP_LEVEL_VARIABLE)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- if (returnType !=3D null) { +- expect(element.returnType, returnType); +- } else if (isNullExpectedReturnTypeConsideredDynamic) { +- expect(element.returnType, 'dynamic'); +- } +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- /** +- * Return a [Future] that completes with the containing library informa= tion +- * after it is accessible via [context.getLibrariesContaining]. +- */ +- Future computeLibrariesContaining([int times =3D 200]) { +- return driver.getResult(testFile).then((result) =3D> null); +- } +- +- Future computeSuggestions({int times =3D 200}) async { +- AnalysisResult analysisResult =3D await driver.getResult(testFile); +- testSource =3D analysisResult.unit.element.source; +- CompletionRequestImpl baseRequest =3D new CompletionRequestImpl( +- analysisResult, +- provider, +- testSource, +- completionOffset, +- new CompletionPerformance()); +- +- // Build the request +- Completer requestCompleter =3D +- new Completer(); +- DartCompletionRequestImpl +- .from(baseRequest) +- .then((DartCompletionRequest request) { +- requestCompleter.complete(request); +- }); +- request =3D await performAnalysis(times, requestCompleter); +- +- var range =3D request.target.computeReplacementRange(request.offset); +- replacementOffset =3D range.offset; +- replacementLength =3D range.length; +- Completer> suggestionCompleter =3D +- new Completer>(); +- +- // Request completions +- contributor +- .computeSuggestions(request) +- .then((List computedSuggestions) { +- suggestionCompleter.complete(computedSuggestions); +- }); +- +- // Perform analysis until the suggestions have been computed +- // or the max analysis cycles ([times]) has been reached +- suggestions =3D await performAnalysis(times, suggestionCompleter); +- expect(suggestions, isNotNull, reason: 'expected suggestions'); +- } +- +- /** +- * Configures the [SourceFactory] to have the `flutter` package in +- * `/packages/flutter/lib` folder. +- */ +- void configureFlutterPkg(Map pathToCode) { +- pathToCode.forEach((path, code) { +- provider.newFile('$flutterPkgLibPath/$path', code); +- }); +- // configure SourceFactory +- Folder myPkgFolder =3D provider.getResource(flutterPkgLibPath); +- UriResolver pkgResolver =3D new PackageMapUriResolver(provider, { +- 'flutter': [myPkgFolder] +- }); +- SourceFactory sourceFactory =3D new SourceFactory( +- [new DartUriResolver(sdk), pkgResolver, resourceResolver]); +- driver.configure(sourceFactory: sourceFactory); +- // force 'flutter' resolution +- addSource( +- '/tmp/other.dart', +- pathToCode.keys +- .map((path) =3D> "import 'package:flutter/$path';") +- .join('\n')); +- } +- +- DartCompletionContributor createContributor(); +- +- void failedCompletion(String message, +- [Iterable completions]) { +- StringBuffer sb =3D new StringBuffer(message); +- if (completions !=3D null) { +- sb.write('\n found'); +- completions.toList() +- ..sort(suggestionComparator) +- ..forEach((CompletionSuggestion suggestion) { +- sb.write('\n ${suggestion.completion} -> $suggestion'); +- }); +- } +- fail(sb.toString()); +- } +- +- CompletionSuggestion getSuggest( +- {String completion: null, +- CompletionSuggestionKind csKind: null, +- ElementKind elemKind: null}) { +- CompletionSuggestion cs; +- if (suggestions !=3D null) { +- suggestions.forEach((CompletionSuggestion s) { +- if (completion !=3D null && completion !=3D s.completion) { +- return; +- } +- if (csKind !=3D null && csKind !=3D s.kind) { +- return; +- } +- if (elemKind !=3D null) { +- Element element =3D s.element; +- if (element =3D=3D null || elemKind !=3D element.kind) { +- return; +- } +- } +- if (cs =3D=3D null) { +- cs =3D s; +- } else { +- failedCompletion('expected exactly one $cs', +- suggestions.where((s) =3D> s.completion =3D=3D completion)); +- } +- }); +- } +- return cs; +- } +- +- Future performAnalysis(int times, Completer completer) async { +- if (completer.isCompleted) { +- return completer.future; +- } +- // We use a delayed future to allow microtask events to finish. The +- // Future.value or Future() constructors use scheduleMicrotask themse= lves and +- // would therefore not wait for microtask callbacks that are schedule= d after +- // invoking this method. +- return new Future.delayed( +- Duration.ZERO, () =3D> performAnalysis(times - 1, completer)); +- } +- +- void resolveSource(String path, String content) { +- addSource(path, content); +- } +- +- @override +- void setUp() { +- super.setUp(); +- testFile =3D provider.convertPath('/completionTest.dart'); +- contributor =3D createContributor(); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/completion_= manager_test.dart b/pkg/analysis_server/test/services/completion/dart/compl= etion_manager_test.dart +deleted file mode 100644 +index 462d7872ff6..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/completion_manager= _test.dart ++++ /dev/null +@@ -1,91 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/completion_core.d= art'; +-import 'package:analysis_server/src/services/completion/completion_perfor= mance.dart'; +-import 'package:analysis_server/src/services/completion/dart/completion_m= anager.dart'; +-import 'package:analysis_server/src/services/completion/dart/imported_ref= erence_contributor.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/task/dart.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(CompletionManagerTest); +- }); +-} +- +-@reflectiveTest +-class CompletionManagerTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new ImportedReferenceContributor(); +- } +- +- test_resolveDirectives() async { +- addSource('/libA.dart', ''' +-library libA; +-/// My class. +-/// Short description. +-/// +-/// Longer description. +-class A {} +-'''); +- addSource('/libB.dart', ''' +-library libB; +-import "/libA.dart" as foo; +-part '$testFile'; +-'''); +- addTestSource('part of libB; main() {^}'); +- +- // Build the request +- CompletionRequestImpl baseRequest =3D new CompletionRequestImpl( +- await driver.getResult(testFile), +- provider, +- testSource, +- completionOffset, +- new CompletionPerformance()); +- Completer requestCompleter =3D +- new Completer(); +- DartCompletionRequestImpl +- .from(baseRequest, resultDescriptor: RESOLVED_UNIT1) +- .then((DartCompletionRequest request) { +- requestCompleter.complete(request); +- }); +- request =3D await performAnalysis(200, requestCompleter); +- +- var directives =3D request.target.unit.directives; +- +- List imports =3D request.libraryElement.imports; +- expect(imports, hasLength(directives.length + 1)); +- +- ImportElement importNamed(String expectedUri) { +- List uriList =3D []; +- for (ImportElement importElement in imports) { +- String uri =3D importElement.importedLibrary.source.uri.toString(= ); +- uriList.add(uri); +- if (uri.endsWith(expectedUri)) { +- return importElement; +- } +- } +- fail('Failed to find $expectedUri in $uriList'); +- return null; +- } +- +- void assertImportedLib(String expectedUri) { +- ImportElement importElem =3D importNamed(expectedUri); +- expect(importElem.importedLibrary.exportNamespace, isNotNull); +- } +- +- // Assert that the new imports each have an export namespace +- assertImportedLib('dart:core'); +- assertImportedLib('libA.dart'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/field_forma= l_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart= /field_formal_contributor_test.dart +deleted file mode 100644 +index 28fcdbec8c1..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/field_formal_contr= ibutor_test.dart ++++ /dev/null +@@ -1,197 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/field_formal= _contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FieldFormalContributorTest); +- }); +-} +- +-@reflectiveTest +-class FieldFormalContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new FieldFormalContributor(); +- } +- +- test_ThisExpression_constructor_param() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.^) {} +- A.z() {} +- var b; X _c; static sb; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('sb'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param2() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.b^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param3() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.^b) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param4() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.b, this.^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param_optional() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class Point { +- int x; +- int y; +- Point({this.x, this.^}) {} +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('y', 'int', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('x'); +- } +- +- test_ThisExpression_constructor_param_positional() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class Point { +- int x; +- int y; +- Point({this.x, this.^}) {} +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('y', 'int', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('x'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/imported_re= ference_contributor_test.dart b/pkg/analysis_server/test/services/completio= n/dart/imported_reference_contributor_test.dart +deleted file mode 100644 +index 11847a6ff5e..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/imported_reference= _contributor_test.dart ++++ /dev/null +@@ -1,4294 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/imported_ref= erence_contributor.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ImportedReferenceContributorTest); +- }); +-} +- +-@reflectiveTest +-class ImportedReferenceContributorTest extends DartCompletionContributorT= est { +- @override +- bool get isNullExpectedReturnTypeConsideredDynamic =3D> false; +- +- @override +- DartCompletionContributor createContributor() { +- return new ImportedReferenceContributor(); +- } +- +- /// Sanity check. Permutations tested in local_ref_contributor. +- test_ArgDefaults_function_with_required_named() async { +- addMetaPackageSource(); +- +- resolveSource('/testB.dart', ''' +-lib B; +-import 'package:meta/meta.dart'; +- +-bool foo(int bar, {bool boo, @required int baz}) =3D> false; +-'''); +- +- addTestSource(''' +-import "/testB.dart"; +- +-void main() {f^}'''); +- await computeSuggestions(); +- +- assertSuggestFunction('foo', 'bool', +- defaultArgListString: 'bar, baz: null'); +- } +- +- test_ArgumentList() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- resolveSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart'; +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool'); +- assertSuggestFunction('identical', 'bool'); +- assertNotSuggested('B'); +- assertSuggestClass('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_imported_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- resolveSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(arg) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool'); +- assertSuggestFunction('identical', 'bool'); +- assertNotSuggested('B'); +- assertSuggestClass('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_functionalArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +- library A; +- class A { A(f()) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { } +- String bar() =3D> true; +- void main() {new A(^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunction('identical', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('B'); +- assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('Object', kind: CompletionSuggestionKind.IDENTIFIE= R); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_typedefArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +- library A; +- typedef Funct(); +- class A { A(Funct f) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { } +- String bar() =3D> true; +- void main() {new A(^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunction('identical', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('B'); +- assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('Object', kind: CompletionSuggestionKind.IDENTIFIE= R); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- resolveSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- expect(arg) { } +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool'); +- assertSuggestFunction('identical', 'bool'); +- assertNotSuggested('B'); +- assertSuggestClass('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_method() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- resolveSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { +- expect(arg) { } +- void foo() {expect(^)}} +- String bar() =3D> true;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool'); +- assertSuggestFunction('identical', 'bool'); +- assertNotSuggested('B'); +- assertSuggestClass('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_functionalArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- class A { A(f()) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { } +- String bar(f()) =3D> true; +- void main() {bar(^);}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertSuggestFunction('hasLength', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunction('identical', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('B'); +- assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('Object', kind: CompletionSuggestionKind.IDENTIFIE= R); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_methodArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- class A { A(f()) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { String bar(f()) =3D> true; } +- void main() {new B().bar(^);}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('hasLength', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestFunction('identical', 'bool', +- kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('B'); +- assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER); +- assertSuggestClass('Object', kind: CompletionSuggestionKind.IDENTIFIE= R); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_namedParam() async { +- // SimpleIdentifier NamedExpression ArgumentList MethodInvocation +- // ExpressionStatement +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { }'''); +- addTestSource(''' +- import '/libA.dart' +- String bar() =3D> true; +- void main() {expect(foo: ^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('bar'); +- // An unresolved imported library will produce suggestions +- // with a null returnType +- // The current DartCompletionRequest#resolveExpression resolves +- // the world (which it should not) and causes the imported library +- // to be resolved. +- assertSuggestFunction('hasLength', /* null */ 'bool'); +- assertNotSuggested('main'); +- } +- +- test_AsExpression() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +- class A {var b; X _c; foo() {var a; (a as ^).foo();}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertSuggestClass('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_AsExpression_type_subtype_extends_filter() async { +- // SimpleIdentifier TypeName AsExpression IfStatement +- addSource('/testB.dart', ''' +- foo() { } +- class A {} class B extends A {} class C extends B {} +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- main(){A a; if (a as ^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- } +- +- test_AsExpression_type_subtype_implements_filter() async { +- // SimpleIdentifier TypeName AsExpression IfStatement +- addSource('/testB.dart', ''' +- foo() { } +- class A {} class B implements A {} class C implements B {} +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- main(){A a; if (a as ^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- } +- +- test_AssignmentExpression_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int ^b =3D 1;}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_AssignmentExpression_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int b =3D ^}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_AssignmentExpression_type() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- ^ b =3D 1;}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertSuggestClass('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- ^ +- b =3D 1;}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertSuggestClass('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertSuggestFunction('identical', 'bool'); +- } +- +- test_AssignmentExpression_type_partial() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- int^ b =3D 1;}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('A'); +- assertSuggestClass('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- i^ +- b =3D 1;}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertSuggestClass('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertSuggestFunction('identical', 'bool'); +- } +- +- test_AwaitExpression() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main() async {A a; await ^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_AwaitExpression_function() async { +- resolveSource('/libA.dart', ''' +-Future y() async {return 0;} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- int x; +- foo() async {await ^} +-} +-'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestFunction('y', 'dynamic'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_AwaitExpression_inherited() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- addSource('/testB.dart', ''' +-lib libB; +-class A { +- Future y() async { return 0; } +-}'''); +- addTestSource(''' +-import "/testB.dart"; +-class B extends A { +- foo() async {await ^} +-} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertSuggestClass('A'); +- assertSuggestClass('Object'); +- assertNotSuggested('y'); +- } +- +- test_BinaryExpression_LHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D ^ + 2;}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertSuggestClass('Object'); +- assertNotSuggested('b'); +- } +- +- test_BinaryExpression_RHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D 2 + ^;}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertSuggestClass('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- ^ var r; +- } +- void b() { }} +- class Z { }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertSuggestClass('A', elemFile: '/testAB.dart'); +- assertNotSuggested('_B'); +- assertSuggestClass('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertSuggestClass('D', COMPLETION_RELEVANCE_LOW); +- //assertSuggestFunction( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertSuggestClass('EE'); +- // hidden element suggested as low relevance +- //assertSuggestClass('F', COMPLETION_RELEVANCE_LOW); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertSuggestClass('g.G', elemName: 'G'); +- assertNotSuggested('G'); +- //assertSuggestClass('H', COMPLETION_RELEVANCE_LOW); +- assertSuggestClass('Object'); +-// assertSuggestFunction('min', 'T'); +- //assertSuggestFunction( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertSuggestTopLevelVar('T1', null); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertSuggestClass('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- final ^ +- } +- void b() { }} +- class Z { }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertSuggestClass('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertSuggestClass('D', COMPLETION_RELEVANCE_LOW); +- //assertSuggestFunction( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertSuggestClass('EE'); +- // hidden element suggested as low relevance +- //assertSuggestClass('F', COMPLETION_RELEVANCE_LOW); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertSuggestClass('g.G', elemName: 'G'); +- //assertSuggestClass('H', COMPLETION_RELEVANCE_LOW); +- assertSuggestClass('Object'); +- assertNotSuggested('min'); +- //assertSuggestFunction( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertSuggestClass('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final2() async { +- addTestSource('main() {final S^ v;}'); +- +- await computeSuggestions(); +- assertSuggestClass('String'); +- } +- +- test_Block_final3() async { +- addTestSource('main() {final ^ v;}'); +- +- await computeSuggestions(); +- assertSuggestClass('String'); +- } +- +- test_Block_final_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g hide G; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- final var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +- class Z { }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertSuggestClass('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertSuggestClass('D', COMPLETION_RELEVANCE_LOW); +- //assertSuggestFunction( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertSuggestClass('EE'); +- // hidden element suggested as low relevance +- //assertSuggestClass('F', COMPLETION_RELEVANCE_LOW); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- // Hidden elements not suggested +- assertNotSuggested('g.G'); +- //assertSuggestClass('H', COMPLETION_RELEVANCE_LOW); +- assertSuggestClass('Object'); +- assertNotSuggested('min'); +- //assertSuggestFunction( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertSuggestClass('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final_var() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +- class Z { }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertSuggestClass('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertSuggestClass('D', COMPLETION_RELEVANCE_LOW); +- //assertSuggestFunction( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertSuggestClass('EE'); +- // hidden element suggested as low relevance +- //assertSuggestClass('F', COMPLETION_RELEVANCE_LOW); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertSuggestClass('g.G', elemName: 'G'); +- //assertSuggestClass('H', COMPLETION_RELEVANCE_LOW); +- assertSuggestClass('Object'); +- assertNotSuggested('min'); +- //assertSuggestFunction( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertSuggestClass('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_identifier_partial() async { +- resolveSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B { }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class DF { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- class D3 { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g; +- int T5; +- var _T6; +- Z D2() {int x;} +- class X {a() {var f; {var x;} D^ var r;} void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- +- // imported elements are portially filtered +- //assertSuggestClass('A'); +- assertNotSuggested('_B'); +- // hidden element not suggested +- assertNotSuggested('D'); +- assertSuggestFunction('D1', 'dynamic', +- isDeprecated: true, relevance: DART_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- // Not imported, so not suggested +- assertNotSuggested('D3'); +- //assertSuggestClass('EE'); +- // hidden element not suggested +- assertNotSuggested('DF'); +- //assertSuggestLibraryPrefix('g'); +- assertSuggestClass('g.G', elemName: 'G'); +- //assertSuggestClass('H', COMPLETION_RELEVANCE_LOW); +- //assertSuggestClass('Object'); +- //assertSuggestFunction('min', 'num', false); +- //assertSuggestFunction( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- //assertSuggestTopLevelVarGetterSetter('T1', 'String'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- //assertNotSuggested('T5'); +- //assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- } +- +- test_Block_inherited_imported() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addSource('/testB.dart', ''' +- lib B; +- class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } var _pf;= } +- class E extends F { var e1; e2() { } } +- class I { int i1; i2() { } } +- class M { var m1; int m2() { } }'''); +- addTestSource(''' +- import "/testB.dart"; +- class A extends E implements I with M {a() {^}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // TODO (danrubel) prefer fields over getters +- // If add `get e1;` to interface I +- // then suggestions include getter e1 rather than field e1 +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- //assertNotSuggested('m2', null, null); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block_inherited_local() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addTestSource(''' +- class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } } +- class E extends F { var e1; e2() { } } +- class I { int i1; i2() { } } +- class M { var m1; int m2() { } } +- class A extends E implements I with M {a() {^}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- assertNotSuggested('m2'); +- } +- +- test_Block_local_function() async { +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- p^ var r; +- } +- void b() { }} +- class Z { }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertNotSuggested('partT8'); +- assertNotSuggested('partBoo'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_partial_results() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B { }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "/testAB.dart"; +- import "/testCD.dart" hide D; +- import "/testEEF.dart" show EE; +- import "/testG.dart" as g; +- int T5; +- var _T6; +- Z D2() {int x;} +- class X {a() {var f; {var x;} ^ var r;} void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- assertSuggestClass('C'); +- assertNotSuggested('H'); +- } +- +- test_Block_unimported() async { +- addPackageSource('myBar', 'bar.dart', 'class Foo2 { Foo2() { } }'); +- addSource( +- '/proj/testAB.dart', 'import "package:myBar/bar.dart"; class Foo = { }'); +- testFile =3D '/proj/completionTest.dart'; +- addTestSource('class C {foo(){F^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Not imported, so not suggested +- assertNotSuggested('Foo'); +- assertNotSuggested('Foo2'); +- assertNotSuggested('Future'); +- } +- +- test_CascadeExpression_selector1() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "/testB.dart"; +- class A {var b; X _c;} +- class X{} +- // looks like a cascade to the parser +- // but the user is trying to get completions for a non-cascade +- main() {A a; a.^.z}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2() async { +- // SimpleIdentifier PropertyAccess CascadeExpression ExpressionSta= tement +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "/testB.dart"; +- class A {var b; X _c;} +- class X{} +- main() {A a; a..^z}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2_withTrailingReturn() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "/testB.dart"; +- class A {var b; X _c;} +- class X{} +- main() {A a; a..^ return}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_target() async { +- // SimpleIdentifier CascadeExpression ExpressionStatement +- addTestSource(''' +- class A {var b; X _c;} +- class X{} +- main() {A a; a^..b}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- // top level results are partially filtered +- //assertSuggestClass('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CatchClause_onType() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^ {}}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_onType_noBrackets() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_typed() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on E catch (e) {^}}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e'); +- assertNotSuggested('a'); +- assertSuggestClass('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_untyped() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} catch (e, s) {^}}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e'); +- assertNotSuggested('s'); +- assertNotSuggested('a'); +- assertSuggestClass('Object'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- @deprecated class A {^} +- class _B {} +- A T;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- CompletionSuggestion suggestionO =3D assertSuggestClass('Object'); +- if (suggestionO !=3D null) { +- expect(suggestionO.element.isDeprecated, isFalse); +- expect(suggestionO.element.isPrivate, isFalse); +- } +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^} +- class _B {} +- A T;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^ A(){}} +- class _B {} +- A T;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('String'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field2() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as Soo; +- class A {final S^ A();} +- class _B {} +- A Sew;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('String'); +- assertNotSuggested('Sew'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('Soo'); +- } +- +- test_ClassDeclaration_body_final_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^ final foo;} +- class _B {} +- A T;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_var() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^ var foo;} +- class _B {} +- A T;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertSuggestClass('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_Combinator_hide() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +- library libAB; +- part '/partAB.dart'; +- class A { } +- class B { }'''); +- addSource('/partAB.dart', ''' +- part of libAB; +- var T1; +- PB F1() =3D> new PB(); +- class PB { }'''); +- addSource('/testCD.dart', ''' +- class C { } +- class D { }'''); +- addTestSource(''' +- import "/testAB.dart" hide ^; +- import "/testCD.dart"; +- class X {}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_Combinator_show() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +- library libAB; +- part '/partAB.dart'; +- class A { } +- class B { }'''); +- addSource('/partAB.dart', ''' +- part of libAB; +- var T1; +- PB F1() =3D> new PB(); +- typedef PB2 F2(int blat); +- class Clz =3D Object with Object; +- class PB { }'''); +- addSource('/testCD.dart', ''' +- class C { } +- class D { }'''); +- addTestSource(''' +- import "/testAB.dart" show ^; +- import "/testCD.dart"; +- class X {}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ConditionalExpression_elseExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T1 : T^}}'''); +- +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_elseExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T1 : ^}}'''); +- +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertSuggestClass('A'); +- assertSuggestFunction('F1', 'dynamic'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_partial_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T^}}'''); +- +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_partial_thenExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? ^}}'''); +- +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertSuggestClass('A'); +- assertSuggestFunction('F1', 'dynamic'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T^ : c}}'''); +- +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConstructorName_importedClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- var m; +- main() {new X.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- var m; +- main() {new X.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- main() {new String.fr^omCharCodes([]);}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 13); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('fromCharCodes'); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('isNotEmpty'); +- assertNotSuggested('length'); +- assertNotSuggested('Object'); +- assertNotSuggested('String'); +- } +- +- test_ConstructorName_localClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}} +- main() {new X.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_localFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- int T1; +- F1() { } +- class X {factory X.c(); factory X._d(); z() {}} +- main() {new X.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_DefaultFormalParameter_named_expression() async { +- // DefaultFormalParameter FormalParameterList MethodDeclaration +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {a(blat: ^) { }}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertSuggestClass('String'); +- assertSuggestFunction('identical', 'bool'); +- assertNotSuggested('bar'); +- } +- +- test_doc_class() async { +- addSource('/libA.dart', r''' +-library A; +-/// My class. +-/// Short description. +-/// +-/// Longer description. +-class A {} +-'''); +- addTestSource('import "/libA.dart"; main() {^}'); +- +- await computeSuggestions(); +- +- CompletionSuggestion suggestion =3D assertSuggestClass('A'); +- expect(suggestion.docSummary, 'My class.\nShort description.'); +- expect(suggestion.docComplete, +- 'My class.\nShort description.\n\nLonger description.'); +- } +- +- test_doc_function() async { +- resolveSource('/libA.dart', r''' +-library A; +-/// My function. +-/// Short description. +-/// +-/// Longer description. +-int myFunc() {} +-'''); +- addTestSource('import "/libA.dart"; main() {^}'); +- +- await computeSuggestions(); +- +- CompletionSuggestion suggestion =3D assertSuggestFunction('myFunc', '= int'); +- expect(suggestion.docSummary, 'My function.\nShort description.'); +- expect(suggestion.docComplete, +- 'My function.\nShort description.\n\nLonger description.'); +- } +- +- test_doc_function_c_style() async { +- resolveSource('/libA.dart', r''' +-library A; +-/** +- * My function. +- * Short description. +- * +- * Longer description. +- */ +-int myFunc() {} +-'''); +- addTestSource('import "/libA.dart"; main() {^}'); +- +- await computeSuggestions(); +- +- CompletionSuggestion suggestion =3D assertSuggestFunction('myFunc', '= int'); +- expect(suggestion.docSummary, 'My function.\nShort description.'); +- expect(suggestion.docComplete, +- 'My function.\nShort description.\n\nLonger description.'); +- } +- +- test_enum() async { +- addSource('/libA.dart', 'library A; enum E { one, two }'); +- addTestSource('import "/libA.dart"; main() {^}'); +- await computeSuggestions(); +- assertSuggestEnum('E'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- } +- +- test_enum_deprecated() async { +- addSource('/libA.dart', 'library A; @deprecated enum E { one, two }'); +- addTestSource('import "/libA.dart"; main() {^}'); +- await computeSuggestions(); +- // TODO(danrube) investigate why suggestion/element is not deprecated +- // when AST node has correct @deprecated annotation +- assertSuggestEnum('E', isDeprecated: true); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- } +- +- test_ExpressionStatement_identifier() async { +- // SimpleIdentifier ExpressionStatement Block +- resolveSource('/testA.dart', ''' +- _B F1() { } +- class A {int x;} +- class _B { }'''); +- addTestSource(''' +- import "/testA.dart"; +- typedef int F2(int blat); +- class Clz =3D Object with Object; +- class C {foo(){^} void bar() {}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestFunction('F1', '_B'); +- assertNotSuggested('C'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('F2'); +- assertNotSuggested('Clz'); +- assertNotSuggested('C'); +- assertNotSuggested('x'); +- assertNotSuggested('_B'); +- } +- +- test_ExpressionStatement_name() async { +- // ExpressionStatement Block BlockFunctionBody MethodDeclaration +- addSource('/testA.dart', ''' +- B T1; +- class B{}'''); +- addTestSource(''' +- import "/testA.dart"; +- class C {a() {C ^}}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_typed() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "/testA.dart"; +- class C {A ^}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_var() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "/testA.dart"; +- class C {var ^}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_FieldFormalParameter_in_non_constructor() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource('class A {B(this.^foo) {}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 3); +- assertNoSuggestions(); +- } +- +- test_ForEachStatement_body_typed() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (int foo in bar) {^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertSuggestClass('Object'); +- } +- +- test_ForEachStatement_body_untyped() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (foo in bar) {^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertSuggestClass('Object'); +- } +- +- test_ForEachStatement_iterable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (int foo in ^) {}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertSuggestClass('Object'); +- } +- +- test_ForEachStatement_loopVariable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ in args) {}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertSuggestClass('String'); +- } +- +- test_ForEachStatement_loopVariable_type() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ foo in args) {}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertSuggestClass('String'); +- } +- +- test_ForEachStatement_loopVariable_type2() async { +- // DeclaredIdentifier ForEachStatement Block +- addTestSource('main(args) {for (S^ foo in args) {}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertSuggestClass('String'); +- } +- +- test_FormalParameterList() async { +- // FormalParameterList MethodDeclaration +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {a(^) { }}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertSuggestClass('String'); +- assertNotSuggested('identical'); +- assertNotSuggested('bar'); +- } +- +- test_ForStatement_body() async { +- // Block ForStatement +- addTestSource('main(args) {for (int i; i < 10; ++i) {^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('i'); +- assertSuggestClass('Object'); +- } +- +- test_ForStatement_condition() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; i^)}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- } +- +- test_ForStatement_initializer() async { +- addTestSource(''' +-import 'dart:math'; +-main() { +- List localVar; +- for (^) {} +-} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('localVar'); +- assertNotSuggested('PI'); +- assertSuggestClass('Object'); +- assertSuggestClass('int'); +- } +- +- test_ForStatement_initializer_variableName_afterType() async { +- addTestSource('main() { for (String ^) }'); +- await computeSuggestions(); +- assertNotSuggested('int'); +- } +- +- test_ForStatement_typing_inKeyword() async { +- addTestSource('main() { for (var v i^) }'); +- await computeSuggestions(); +- assertNotSuggested('int'); +- } +- +- test_ForStatement_updaters() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; index < 10; i^)}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- } +- +- test_ForStatement_updaters_prefix_expression() async { +- // SimpleIdentifier PrefixExpression ForStatement +- addTestSource(''' +- void bar() { } +- main() {for (int index =3D 0; index < 10; ++i^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- assertNotSuggested('main'); +- assertNotSuggested('bar'); +- } +- +- test_function_parameters_mixed_required_and_named() async { +- resolveSource('/libA.dart', ''' +-int m(x, {int y}) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'int'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_function_parameters_mixed_required_and_positional() async { +- resolveSource('/libA.dart', ''' +-void m(x, [int y]) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_function_parameters_named() async { +- resolveSource('/libA.dart', ''' +-void m({x, int y}) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_function_parameters_none() async { +- resolveSource('/libA.dart', ''' +-void m() {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, isEmpty); +- expect(suggestion.parameterTypes, isEmpty); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_function_parameters_positional() async { +- resolveSource('/libA.dart', ''' +-void m([x, int y]) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_function_parameters_required() async { +- resolveSource('/libA.dart', ''' +-void m(x, int y) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 2); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_FunctionDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- /* */ ^ zoo(z) { } String name;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment2() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- /** */ ^ zoo(z) { } String name;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment3() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- /// some dartdoc +- class C2 { } +- ^ zoo(z) { } String name;'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionExpression_body_function() async { +- // Block BlockFunctionBody FunctionExpression +- addTestSource(''' +- void bar() { } +- String foo(List args) {x.then((R b) {^});}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('args'); +- assertNotSuggested('b'); +- assertSuggestClass('Object'); +- } +- +- test_IfStatement() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (true) ^}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertSuggestClass('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_condition() async { +- // SimpleIdentifier IfStatement Block BlockFunctionBody +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main(){var a; if (^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_IfStatement_empty() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (^) something}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertSuggestClass('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_invocation() async { +- // SimpleIdentifier PrefixIdentifier IfStatement +- addTestSource(''' +- main() {var a; if (a.^) something}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('toString'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_typing_isKeyword() async { +- addTestSource('main() { if (v i^) }'); +- await computeSuggestions(); +- assertNotSuggested('int'); +- } +- +- test_ImportDirective_dart() async { +- // SimpleStringLiteral ImportDirective +- addTestSource(''' +- import "dart^"; +- main() {}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_IndexExpression() async { +- // ExpressionStatement Block +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} f[^]}}'''); +- +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertSuggestClass('A'); +- assertSuggestFunction('F1', 'dynamic'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_IndexExpression2() async { +- // SimpleIdentifier IndexExpression ExpressionStatement Block +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} f[T^]}}'''); +- +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_InstanceCreationExpression() async { +- resolveSource('/testA.dart', ''' +-class A {foo(){var f; {var x;}}} +-class B {B(this.x, [String boo]) { } int x;} +-class C {C.bar({boo: 'hoo', int z: 0}) { } }'''); +- addTestSource(''' +-import "/testA.dart"; +-import "dart:math" as math; +-main() {new ^ String x =3D "hello";}'''); +- +- await computeSuggestions(); +- CompletionSuggestion suggestion; +- +- suggestion =3D assertSuggestConstructor('Object'); +- expect(suggestion.element.parameters, '()'); +- expect(suggestion.parameterNames, hasLength(0)); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- +- suggestion =3D assertSuggestConstructor('A'); +- expect(suggestion.element.parameters, '()'); +- expect(suggestion.parameterNames, hasLength(0)); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- +- suggestion =3D assertSuggestConstructor('B'); +- expect(suggestion.element.parameters, '(int x, [String boo])'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'int'); +- expect(suggestion.parameterNames[1], 'boo'); +- expect(suggestion.parameterTypes[1], 'String'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- +- suggestion =3D assertSuggestConstructor('C.bar'); +- expect(suggestion.element.parameters, "({dynamic boo: 'hoo', int z: 0= })"); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'boo'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'z'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('math'); +- } +- +- test_InstanceCreationExpression_imported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {A(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- import "dart:async"; +- int T2; +- F2() { } +- class B {B(this.x, [String boo]) { } int x;} +- class C {foo(){var f; {var x;} new ^}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestConstructor('Object'); +- assertSuggestConstructor('Future'); +- assertSuggestConstructor('A'); +- // Suggested by ConstructorContributor +- assertNotSuggested('B'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('foo'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- // An unresolved imported library will produce suggestions +- // with a null returnType +- // The current DartCompletionRequest#resolveExpression resolves +- // the world (which it should not) and causes the imported library +- // to be resolved. +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- } +- +- test_InstanceCreationExpression_unimported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){new F^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Not imported, so not suggested +- assertNotSuggested('Future'); +- assertNotSuggested('Foo'); +- } +- +- test_internal_sdk_libs() async { +- addTestSource('main() {p^}'); +- +- await computeSuggestions(); +- assertSuggest('print'); +- // Not imported, so not suggested +- assertNotSuggested('pow'); +- // Do not suggest completions from internal SDK library +- assertNotSuggested('printToConsole'); +- } +- +- test_InterpolationExpression() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- main() {String name; print("hello \$^");}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertSuggestTopLevelVar('T1', null); +- assertSuggestFunction('F1', null); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_InterpolationExpression_block() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- main() {String name; print("hello \${^}");}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- // Simulate unresolved imported library +- // in which case suggestions will have null (unresolved) returnType +- assertSuggestTopLevelVar('T1', null); +- assertSuggestFunction('F1', null); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_InterpolationExpression_block2() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addTestSource('main() {String name; print("hello \${n^}");}'); +- +- await computeSuggestions(); +- assertNotSuggested('name'); +- // top level results are partially filtered +- //assertSuggestClass('Object'); +- } +- +- test_InterpolationExpression_prefix_selector() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${name.^}");}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('length'); +- assertNotSuggested('name'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_InterpolationExpression_prefix_selector2() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \$name.^");}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_InterpolationExpression_prefix_target() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${nam^e.length}");}= '); +- +- await computeSuggestions(); +- assertNotSuggested('name'); +- // top level results are partially filtered +- //assertSuggestClass('Object'); +- assertNotSuggested('length'); +- } +- +- test_IsExpression() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addSource('/testB.dart', ''' +- lib B; +- foo() { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- class Y {Y.c(); Y._d(); z() {}} +- main() {var x; if (x is ^) { }}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('x'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- } +- +- test_IsExpression_target() async { +- // IfStatement Block BlockFunctionBody +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {int x; int y() =3D> 0;} +- main(){var a; if (^ is A)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_IsExpression_type() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main(){var a; if (a is ^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_IsExpression_type_partial() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main(){var a; if (a is Obj^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertSuggestClass('Object'); +- } +- +- test_IsExpression_type_subtype_extends_filter() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addSource('/testB.dart', ''' +- foo() { } +- class A {} class B extends A {} class C extends B {} +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- main(){A a; if (a is ^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- } +- +- test_IsExpression_type_subtype_implements_filter() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addSource('/testB.dart', ''' +- foo() { } +- class A {} class B implements A {} class C implements B {} +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- main(){A a; if (a is ^)}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- } +- +- test_keyword() async { +- resolveSource('/testB.dart', ''' +- lib B; +- int newT1; +- int T1; +- nowIsIt() { } +- class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- String newer() {} +- var m; +- main() {new^ X.c();}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- // Imported suggestion are filtered by 1st character +- assertSuggestFunction('nowIsIt', 'dynamic'); +- assertSuggestTopLevelVar('T1', 'int'); +- assertSuggestTopLevelVar('newT1', 'int'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- assertNotSuggested('newer'); +- } +- +- test_Literal_list() async { +- // ']' ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([^]);}'); +- +- await computeSuggestions(); +- assertNotSuggested('Some'); +- assertSuggestClass('String'); +- } +- +- test_Literal_list2() async { +- // SimpleIdentifier ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([S^]);}'); +- +- await computeSuggestions(); +- assertNotSuggested('Some'); +- assertSuggestClass('String'); +- } +- +- test_Literal_string() async { +- // SimpleStringLiteral ExpressionStatement Block +- addTestSource('class A {a() {"hel^lo"}}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_localVariableDeclarationName() async { +- addTestSource('main() {String m^}'); +- await computeSuggestions(); +- assertNotSuggested('main'); +- assertNotSuggested('min'); +- } +- +- test_MapLiteralEntry() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- foo =3D {^'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- // Simulate unresolved imported library, +- // in which case suggestions will have null return types (unresolved) +- // The current DartCompletionRequest#resolveExpression resolves +- // the world (which it should not) and causes the imported library +- // to be resolved. +- assertSuggestTopLevelVar('T1', /* null */ 'int'); +- assertSuggestFunction('F1', /* null */ 'dynamic'); +- assertSuggestFunctionTypeAlias('D1', /* null */ 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- } +- +- test_MapLiteralEntry1() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- foo =3D {T^'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Simulate unresolved imported library, +- // in which case suggestions will have null return types (unresolved) +- // The current DartCompletionRequest#resolveExpression resolves +- // the world (which it should not) and causes the imported library +- // to be resolved. +- assertSuggestTopLevelVar('T1', /* null */ 'int'); +- assertNotSuggested('T2'); +- } +- +- test_MapLiteralEntry2() async { +- // SimpleIdentifier MapLiteralEntry MapLiteral VariableDeclaration +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- foo =3D {7:T^};'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestTopLevelVar('T1', 'int'); +- assertNotSuggested('T2'); +- } +- +- test_method_parameters_mixed_required_and_named() async { +- resolveSource('/libA.dart', ''' +-void m(x, {int y}) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_mixed_required_and_positional() async { +- resolveSource('/libA.dart', ''' +-void m(x, [int y]) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_named() async { +- resolveSource('/libA.dart', ''' +-void m({x, int y}) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_none() async { +- resolveSource('/libA.dart', ''' +-void m() {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, isEmpty); +- expect(suggestion.parameterTypes, isEmpty); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_positional() async { +- resolveSource('/libA.dart', ''' +-void m([x, int y]) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_required() async { +- resolveSource('/libA.dart', ''' +-void m(x, int y) {} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void'= ); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 2); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_MethodDeclaration_body_getters() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X get f =3D> 0; Z a() {^} get _g = =3D> 1;}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- } +- +- test_MethodDeclaration_body_static() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testC.dart', ''' +- class C { +- c1() {} +- var c2; +- static c3() {} +- static var c4;}'''); +- addTestSource(''' +- import "/testC.dart"; +- class B extends C { +- b1() {} +- var b2; +- static b3() {} +- static var b4;} +- class A extends B { +- a1() {} +- var a2; +- static a3() {} +- static var a4; +- static a() {^}}'''); +- +- await computeSuggestions(); +- assertNotSuggested('a1'); +- assertNotSuggested('a2'); +- assertNotSuggested('a3'); +- assertNotSuggested('a4'); +- assertNotSuggested('b1'); +- assertNotSuggested('b2'); +- assertNotSuggested('b3'); +- assertNotSuggested('b4'); +- assertNotSuggested('c1'); +- assertNotSuggested('c2'); +- assertNotSuggested('c3'); +- assertNotSuggested('c4'); +- } +- +- test_MethodDeclaration_members() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X f; Z _a() {^} var _g;}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('_a'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertSuggestClass('bool'); +- } +- +- test_MethodDeclaration_parameters_named() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated Z a(X x, _, b, {y: boo}) {^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('b'); +- assertSuggestClass('int'); +- assertNotSuggested('_'); +- } +- +- test_MethodDeclaration_parameters_positional() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {Z a(X x, [int y=3D1]) {^}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertSuggestClass('String'); +- } +- +- test_MethodDeclaration_returnType() async { +- // ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 {^ zoo(z) { } String name; }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 {/* */ ^ zoo(z) { } String name; }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment2() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 {/** */ ^ zoo(z) { } String name; }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment3() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- resolveSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "/testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { +- /// some dartdoc +- ^ zoo(z) { } String name; }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertSuggestFunctionTypeAlias('D1', 'dynamic'); +- assertSuggestClass('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodInvocation_no_semicolon() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {x.^ m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_mixin_ordering() async { +- addSource('/libA.dart', ''' +-class B {} +-class M1 { +- void m() {} +-} +-class M2 { +- void m() {} +-} +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class C extends B with M1, M2 { +- void f() { +- ^ +- } +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- /** +- * Ensure that completions in one context don't appear in another +- */ +- test_multiple_contexts() async { +- // Create a 2nd context with source +- var context2 =3D AnalysisEngine.instance.createAnalysisContext(); +- context2.sourceFactory =3D +- new SourceFactory([new DartUriResolver(sdk), resourceResolver]); +- String content2 =3D 'class ClassFromAnotherContext { }'; +- Source source2 =3D +- provider.newFile('/context2/foo.dart', content2).createSource(); +- ChangeSet changeSet =3D new ChangeSet(); +- changeSet.addedSource(source2); +- context2.applyChanges(changeSet); +- context2.setContents(source2, content2); +- +- // Resolve the source in the 2nd context and update the index +- var result =3D context2.performAnalysisTask(); +- while (result.hasMoreWork) { +- result =3D context2.performAnalysisTask(); +- } +- +- // Check that source in 2nd context does not appear in completion in = 1st +- addSource('/context1/libA.dart', ''' +- library libA; +- class ClassInLocalContext {int x;}'''); +- testFile =3D '/context1/completionTest.dart'; +- addTestSource(''' +- import "/context1/libA.dart"; +- import "/foo.dart"; +- main() {C^} +- '''); +- +- await computeSuggestions(); +- assertSuggestClass('ClassInLocalContext'); +- // Assert contributor does not include results from 2nd context. +- assertNotSuggested('ClassFromAnotherContext'); +- } +- +- test_new_instance() async { +- addTestSource('import "dart:math"; class A {x() {new Random().^}}'); +- +- await computeSuggestions(); +- assertNotSuggested('nextBool'); +- assertNotSuggested('nextDouble'); +- assertNotSuggested('nextInt'); +- assertNotSuggested('Random'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- } +- +- test_no_parameters_field() async { +- addSource('/libA.dart', ''' +-int x; +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestTopLevelVar('x', nul= l); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_no_parameters_getter() async { +- resolveSource('/libA.dart', ''' +-int get x =3D> null; +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestGetter('x', 'int'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_no_parameters_setter() async { +- addSource('/libA.dart', ''' +-set x(int value) {}; +-'''); +- addTestSource(''' +-import '/libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestSetter('x'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_parameterName_excludeTypes() async { +- addTestSource('m(int ^) {}'); +- await computeSuggestions(); +- assertNotSuggested('int'); +- assertNotSuggested('bool'); +- } +- +- test_partFile_TypeName() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- library libA; +- import "/testB.dart"; +- part "$testFile"; +- class A { } +- var m;'''); +- addTestSource(''' +- part of libA; +- class B { factory B.bar(int x) =3D> null; } +- main() {new ^}'''); +- +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by ConstructorContributor +- assertNotSuggested('B.bar'); +- assertSuggestConstructor('Object'); +- assertSuggestConstructor('X.c'); +- assertNotSuggested('X._d'); +- // Suggested by LocalLibraryContributor +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_TypeName2() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +- lib libB; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- part of libA; +- class B { }'''); +- addTestSource(''' +- library libA; +- import "/testB.dart"; +- part "/testA.dart"; +- class A { A({String boo: 'hoo'}) { } } +- main() {new ^} +- var m;'''); +- +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by ConstructorContributor +- assertNotSuggested('A'); +- assertSuggestConstructor('Object'); +- assertSuggestConstructor('X.c'); +- assertNotSuggested('X._d'); +- // Suggested by LocalLibraryContributor +- assertNotSuggested('B'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_PrefixedIdentifier_class_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block +- addSource('/testB.dart', ''' +- lib B; +- class I { +- static const scI =3D 'boo'; +- X get f =3D> new A(); +- get _g =3D> new A();} +- class B implements I { +- static const int scB =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- addTestSource(''' +- import "/testB.dart"; +- class A extends B { +- static const String scA =3D 'foo'; +- w() { }} +- main() {A.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by StaticMemberContributor +- assertNotSuggested('scA'); +- assertNotSuggested('scB'); +- assertNotSuggested('scI'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('w'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_imported() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- static const int sc =3D 12; +- @deprecated var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- addTestSource(''' +- import "/testB.dart"; +- main() {A a; a.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_local() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +- main() {A a; a.^} +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- static const int sc =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_library() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "/testB.dart" as b; +- var T2; +- class A { } +- main() {b.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "/testB.dart" as b; +- var T2; +- class A { } +- foo(b.^ f) {}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "/testB.dart" as b; +- var T2; +- class A { } +- foo(b.^) {}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_parameter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- class _W {M y; var _z;} +- class X extends _W {} +- class M{}'''); +- addTestSource(''' +- import "/testB.dart"; +- foo(X x) {x.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('y'); +- assertNotSuggested('_z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_prefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testA.dart', ''' +- class A {static int bar =3D 10;} +- _B() {}'''); +- addTestSource(''' +- import "/testA.dart"; +- class X {foo(){A^.bar}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestClass('A'); +- assertNotSuggested('X'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('_B'); +- } +- +- test_PrefixedIdentifier_propertyAccess() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('compareTo'); +- } +- +- test_PrefixedIdentifier_propertyAccess_newStmt() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('compareTo'); +- } +- +- test_PrefixedIdentifier_trailingStmt_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('const String g =3D "hello"; f() {g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_field() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g; f() {g.^ int y =3D 0;}}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_function() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g() =3D> "one"; f() {g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_functionTypeAlias() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('typedef String g(); f() {g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_typed() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {String g; g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_untyped() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {var g =3D "hello"; g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_method() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g() {}; f() {g.^ int y =3D 0;}}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {f(String g) {g.^ int y =3D 0;}}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param2() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f(String g) {g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_topLevelVar() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g; f() {g.^ int y =3D 0;}'); +- +- await computeSuggestions(); +- assertNotSuggested('length'); +- } +- +- test_PropertyAccess_expression() async { +- // SimpleIdentifier MethodInvocation PropertyAccess ExpressionStat= ement +- addTestSource('class A {a() {"hello".to^String().length}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 8); +- assertNotSuggested('length'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PropertyAccess_noTarget() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){.^}}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_noTarget2() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('main() {.^}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_selector() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement Block +- addTestSource('class A {a() {"hello".length.^}}'); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEven'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_SwitchStatement_c() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {c^}}}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_SwitchStatement_case() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {var t; switch(x) {case 0: ^}= }}'); +- +- await computeSuggestions(); +- assertNotSuggested('A'); +- assertNotSuggested('g'); +- assertNotSuggested('t'); +- assertSuggestClass('String'); +- } +- +- test_SwitchStatement_empty() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {^}}}'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ThisExpression_block() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A() {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {this.^ m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A() {this.^} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.^) {} +- A.z() {} +- var b; X _c; static sb; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('sb'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param2() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.b^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param3() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.^b) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param4() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.b, this.^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_TopLevelVariableDeclaration_typed_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} B ^'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_TopLevelVariableDeclaration_untyped_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} var ^'); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_TypeArgumentList() async { +- // SimpleIdentifier BinaryExpression ExpressionStatement +- resolveSource('/testA.dart', ''' +- class C1 {int x;} +- F1() =3D> 0; +- typedef String T1(int blat);'''); +- addTestSource(''' +- import "/testA.dart";' +- class C2 {int x;} +- F2() =3D> 0; +- typedef int T2(int blat); +- class C {} +- main() { C<^> c; }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('Object'); +- assertSuggestClass('C1'); +- assertSuggestFunctionTypeAlias('T1', 'String'); +- assertNotSuggested('C2'); +- assertNotSuggested('T2'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- } +- +- test_TypeArgumentList2() async { +- // TypeName TypeArgumentList TypeName +- addSource('/testA.dart', ''' +- class C1 {int x;} +- F1() =3D> 0; +- typedef String T1(int blat);'''); +- addTestSource(''' +- import "/testA.dart";' +- class C2 {int x;} +- F2() =3D> 0; +- typedef int T2(int blat); +- class C {} +- main() { C c; }'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestClass('C1'); +- assertNotSuggested('C2'); +- } +- +- test_TypeArgumentList_recursive() async { +- resolveSource('/testA.dart', ''' +-class A {} +-'''); +- resolveSource('/testB.dart', ''' +-export 'testA.dart'; +-export 'testB.dart'; +-class B {} +-'''); +- addTestSource(''' +-import '/testB.dart'; +-List<^> x; +-'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestClass('B'); +- } +- +- test_VariableDeclaration_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addSource('/testB.dart', ''' +- lib B; +- foo() { } +- class _B { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- class Y {Y.c(); Y._d(); z() {}} +- main() {var ^}'''); +- +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_VariableDeclarationList_final() async { +- // VariableDeclarationList VariableDeclarationStatement Block +- addTestSource('main() {final ^} class C { }'); +- +- await computeSuggestions(); +- assertSuggestClass('Object'); +- assertNotSuggested('C'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_VariableDeclarationStatement_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +- lib B; +- foo() { } +- class _B { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- class Y {Y.c(); Y._d(); z() {}} +- class C {bar(){var f; {var x;} var e =3D ^}}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertNotSuggested('_B'); +- assertNotSuggested('Y'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +- +- test_VariableDeclarationStatement_RHS_missing_semicolon() async { +- // VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- resolveSource('/testB.dart', ''' +- lib B; +- foo1() { } +- void bar1() { } +- class _B { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- foo2() { } +- void bar2() { } +- class Y {Y.c(); Y._d(); z() {}} +- class C {bar(){var f; {var x;} var e =3D ^ var g}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertSuggestFunction('foo1', 'dynamic'); +- assertNotSuggested('bar1'); +- assertNotSuggested('foo2'); +- assertNotSuggested('bar2'); +- assertNotSuggested('_B'); +- assertNotSuggested('Y'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/inherited_r= eference_contributor_test.dart b/pkg/analysis_server/test/services/completi= on/dart/inherited_reference_contributor_test.dart +deleted file mode 100644 +index bd52c9e09c9..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/inherited_referenc= e_contributor_test.dart ++++ /dev/null +@@ -1,607 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/inherited_re= ference_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(InheritedReferenceContributorTest); +- }); +-} +- +-@reflectiveTest +-class InheritedReferenceContributorTest extends DartCompletionContributor= Test { +- @override +- bool get isNullExpectedReturnTypeConsideredDynamic =3D> false; +- +- @override +- DartCompletionContributor createContributor() { +- return new InheritedReferenceContributor(); +- } +- +- /// Sanity check. Permutations tested in local_ref_contributor. +- test_ArgDefaults_inherited_method_with_required_named() async { +- addMetaPackageSource(); +- resolveSource('/testB.dart', ''' +-import 'package:meta/meta.dart'; +- +-lib libB; +-class A { +- bool foo(int bar, {bool boo, @required int baz}) =3D> false; +-}'''); +- addTestSource(''' +-import "testB.dart"; +-class B extends A { +- b() =3D> f^ +-} +-'''); +- await computeSuggestions(); +- +- assertSuggestMethod('foo', 'A', 'bool', +- defaultArgListString: 'bar, baz: null'); +- } +- +- test_AwaitExpression_inherited() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- resolveSource('/testB.dart', ''' +-lib libB; +-class A { +- Future y() async {return 0;} +-}'''); +- addTestSource(''' +-import "testB.dart"; +-class B extends A { +- Future a() async {return 0;} +- foo() async {await ^} +-} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('foo'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertSuggestMethod('y', 'A', 'dynamic'); +- } +- +- test_Block_inherited_imported() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- resolveSource('/testB.dart', ''' +- lib B; +- class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } var _pf; } +- class E extends F { var e1; e2() { } } +- class I { int i1; i2() { } } +- class M { var m1; int m2() { } }'''); +- addTestSource(''' +- import "testB.dart"; +- class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('e1', null); +- assertSuggestField('f1', null); +- assertSuggestField('i1', 'int'); +- assertSuggestField('m1', null); +- assertSuggestGetter('f3', null); +- assertSuggestSetter('f4'); +- assertSuggestMethod('e2', 'E', null); +- assertSuggestMethod('f2', 'F', null); +- assertSuggestMethod('i2', 'I', null); +- assertSuggestMethod('m2', 'M', 'int'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block_inherited_local() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addTestSource(''' +-class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } } +-class E extends F { var e1; e2() { } } +-class I { int i1; i2() { } } +-class M { var m1; int m2() { } } +-class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('e1', null); +- assertSuggestField('f1', null); +- assertSuggestField('i1', 'int'); +- assertSuggestField('m1', null); +- assertSuggestGetter('f3', null); +- assertSuggestSetter('f4'); +- assertSuggestMethod('e2', 'E', null); +- assertSuggestMethod('f2', 'F', null); +- assertSuggestMethod('i2', 'I', null); +- assertSuggestMethod('m2', 'M', 'int'); +- } +- +- test_inherited() async { +- resolveSource('/testB.dart', ''' +-lib libB; +-class A2 { +- int x; +- int y() {return 0;} +- int x2; +- int y2() {return 0;} +-}'''); +- addTestSource(''' +-import "testB.dart"; +-class A1 { +- int x; +- int y() {return 0;} +- int x1; +- int y1() {return 0;} +-} +-class B extends A1 with A2 { +- int a; +- int b() {return 0;} +- foo() {^} +-} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('B'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('foo'); +- assertNotSuggested('A'); +- assertSuggestField('x', 'int'); +- assertSuggestMethod('y', 'A1', 'int'); +- assertSuggestField('x1', 'int'); +- assertSuggestMethod('y1', 'A1', 'int'); +- assertSuggestField('x2', 'int'); +- assertSuggestMethod('y2', 'A2', 'int'); +- } +- +- test_method_in_class() async { +- addTestSource(''' +-class A { +- void m(x, int y) {} +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_mixed_required_and_named() async { +- resolveSource('/libA.dart', ''' +-class A { +- void m(x, {int y}) {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_mixed_required_and_named_local() async { +- addTestSource(''' +-class A { +- void m(x, {int y}) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_mixed_required_and_positional() async { +- resolveSource('/libA.dart', ''' +-class A { +- void m(x, [int y]) {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_mixed_required_and_positional_local() async { +- addTestSource(''' +-class A { +- void m(x, [int y]) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_named() async { +- resolveSource('/libA.dart', ''' +-class A { +- void m({x, int y}) {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_named_local() async { +- addTestSource(''' +-class A { +- void m({x, int y}) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_none() async { +- resolveSource('/libA.dart', ''' +-class A { +- void m() {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, isEmpty); +- expect(suggestion.parameterTypes, isEmpty); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_none_local() async { +- addTestSource(''' +-class A { +- void m() {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, isEmpty); +- expect(suggestion.parameterTypes, isEmpty); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_positional() async { +- resolveSource('/libA.dart', ''' +-class A { +- void m([x, int y]) {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_positional_local() async { +- addTestSource(''' +-class A { +- void m([x, int y]) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_required() async { +- resolveSource('/libA.dart', ''' +-class A { +- void m(x, int y) {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'A', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 2); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_mixin_ordering() async { +- resolveSource('/libA.dart', ''' +-class B {} +-class M1 { +- void m() {} +-} +-class M2 { +- void m() {} +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class C extends B with M1, M2 { +- void f() { +- ^ +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestMethod('m', 'M1', 'void'); +- } +- +- test_no_parameters_field() async { +- resolveSource('/libA.dart', ''' +-class A { +- int x; +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestField('x', 'int'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_no_parameters_getter() async { +- resolveSource('/libA.dart', ''' +-class A { +- int get x =3D> null; +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestGetter('x', 'int'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_no_parameters_setter() async { +- resolveSource('/libA.dart', ''' +-class A { +- set x(int value) {}; +-} +-'''); +- addTestSource(''' +-import 'libA.dart'; +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestSetter('x'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_outside_class() async { +- resolveSource('/testB.dart', ''' +-lib libB; +-class A2 { +- int x; +- int y() {return 0;} +- int x2; +- int y2() {return 0;} +-}'''); +- addTestSource(''' +-import "testB.dart"; +-class A1 { +- int x; +- int y() {return 0;} +- int x1; +- int y1() {return 0;} +-} +-class B extends A1 with A2 { +- int a; +- int b() {return 0;} +-} +-foo() {^} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('B'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('foo'); +- assertNotSuggested('A'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('x1'); +- assertNotSuggested('y1'); +- assertNotSuggested('x2'); +- assertNotSuggested('y2'); +- } +- +- test_static_field() async { +- resolveSource('/testB.dart', ''' +-lib libB; +-class A2 { +- int x; +- int y() {return 0;} +- int x2; +- int y2() {return 0;} +-}'''); +- addTestSource(''' +-import "testB.dart"; +-class A1 { +- int x; +- int y() {return 0;} +- int x1; +- int y1() {return 0;} +-} +-class B extends A1 with A2 { +- int a; +- int b() {return 0;} +- static foo =3D ^ +-} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('B'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('foo'); +- assertNotSuggested('A'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('x1'); +- assertNotSuggested('y1'); +- assertNotSuggested('x2'); +- assertNotSuggested('y2'); +- } +- +- test_static_method() async { +- resolveSource('/testB.dart', ''' +-lib libB; +-class A2 { +- int x; +- int y() {return 0;} +- int x2; +- int y2() {return 0;} +-}'''); +- addTestSource(''' +-import "testB.dart"; +-class A1 { +- int x; +- int y() {return 0;} +- int x1; +- int y1() {return 0;} +-} +-class B extends A1 with A2 { +- int a; +- int b() {return 0;} +- static foo() {^} +-} +-'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('B'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('foo'); +- assertNotSuggested('A'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('x1'); +- assertNotSuggested('y1'); +- assertNotSuggested('x2'); +- assertNotSuggested('y2'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/keyword_con= tributor_test.dart b/pkg/analysis_server/test/services/completion/dart/keyw= ord_contributor_test.dart +deleted file mode 100644 +index 3bac1adfdc1..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/keyword_contributo= r_test.dart ++++ /dev/null +@@ -1,1826 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/keyword_cont= ributor.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(KeywordContributorTest); +- }); +-} +- +-@reflectiveTest +-class KeywordContributorTest extends DartCompletionContributorTest { +- static const List CLASS_BODY_KEYWORDS =3D const [ +- Keyword.CONST, +- Keyword.DYNAMIC, +- Keyword.FACTORY, +- Keyword.FINAL, +- Keyword.GET, +- Keyword.OPERATOR, +- Keyword.SET, +- Keyword.STATIC, +- Keyword.VAR, +- Keyword.VOID +- ]; +- +- static const List DECLARATION_KEYWORDS =3D const [ +- Keyword.ABSTRACT, +- Keyword.CLASS, +- Keyword.CONST, +- Keyword.DYNAMIC, +- Keyword.FINAL, +- Keyword.TYPEDEF, +- Keyword.VAR, +- Keyword.VOID +- ]; +- +- static const List DIRECTIVE_AND_DECLARATION_KEYWORDS =3D const= [ +- Keyword.ABSTRACT, +- Keyword.CLASS, +- Keyword.CONST, +- Keyword.DYNAMIC, +- Keyword.EXPORT, +- Keyword.FINAL, +- Keyword.IMPORT, +- Keyword.PART, +- Keyword.TYPEDEF, +- Keyword.VAR, +- Keyword.VOID +- ]; +- +- static const List DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS = =3D +- const [ +- Keyword.ABSTRACT, +- Keyword.CLASS, +- Keyword.CONST, +- Keyword.DYNAMIC, +- Keyword.EXPORT, +- Keyword.FINAL, +- Keyword.IMPORT, +- Keyword.LIBRARY, +- Keyword.PART, +- Keyword.TYPEDEF, +- Keyword.VAR, +- Keyword.VOID +- ]; +- +- static const List NO_PSEUDO_KEYWORDS =3D const []; +- +- static const List STMT_START_IN_CLASS =3D const [ +- Keyword.ASSERT, +- Keyword.CONST, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SUPER, +- Keyword.SWITCH, +- Keyword.THIS, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]; +- +- static const List STMT_START_IN_LOOP_IN_CLASS =3D const [ +- Keyword.ASSERT, +- Keyword.BREAK, +- Keyword.CONST, +- Keyword.CONTINUE, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SUPER, +- Keyword.SWITCH, +- Keyword.THIS, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]; +- +- static const List STMT_START_IN_SWITCH_IN_CLASS =3D const [ +- Keyword.ASSERT, +- Keyword.BREAK, +- Keyword.CASE, +- Keyword.CONST, +- Keyword.DEFAULT, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SUPER, +- Keyword.SWITCH, +- Keyword.THIS, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]; +- +- static const List STMT_START_IN_SWITCH_OUTSIDE_CLASS =3D const= [ +- Keyword.ASSERT, +- Keyword.BREAK, +- Keyword.CASE, +- Keyword.CONST, +- Keyword.DEFAULT, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SWITCH, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]; +- +- static const List STMT_START_OUTSIDE_CLASS =3D const [ +- Keyword.ASSERT, +- Keyword.CONST, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SWITCH, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]; +- +- static const List STMT_START_IN_LOOP_OUTSIDE_CLASS =3D const [ +- Keyword.ASSERT, +- Keyword.BREAK, +- Keyword.CONST, +- Keyword.CONTINUE, +- Keyword.DO, +- Keyword.FINAL, +- Keyword.FOR, +- Keyword.IF, +- Keyword.NEW, +- Keyword.RETURN, +- Keyword.SWITCH, +- Keyword.THROW, +- Keyword.TRY, +- Keyword.VAR, +- Keyword.VOID, +- Keyword.WHILE +- ]; +- +- static const List EXPRESSION_START_INSTANCE =3D const [ +- Keyword.CONST, +- Keyword.FALSE, +- Keyword.NEW, +- Keyword.NULL, +- Keyword.SUPER, +- Keyword.THIS, +- Keyword.TRUE, +- ]; +- +- static const List EXPRESSION_START_NO_INSTANCE =3D const [ +- Keyword.CONST, +- Keyword.FALSE, +- Keyword.NEW, +- Keyword.NULL, +- Keyword.TRUE, +- ]; +- +- void assertSuggestKeywords(Iterable expectedKeywords, +- {List pseudoKeywords: NO_PSEUDO_KEYWORDS, +- int relevance: DART_RELEVANCE_KEYWORD}) { +- Set expectedCompletions =3D new Set(); +- Map expectedOffsets =3D {}; +- Set actualCompletions =3D new Set(); +- expectedCompletions.addAll(expectedKeywords.map((k) =3D> k.lexeme)); +- ['import', 'export', 'part'].forEach((s) { +- if (expectedCompletions.contains(s)) { +- expectedCompletions.remove(s); +- expectedCompletions.add('$s \'\';'); +- } +- }); +- +- expectedCompletions.addAll(pseudoKeywords); +- for (CompletionSuggestion s in suggestions) { +- if (s.kind =3D=3D CompletionSuggestionKind.KEYWORD) { +- Keyword k =3D Keyword.keywords[s.completion]; +- if (k =3D=3D null && !expectedCompletions.contains(s.completion))= { +- fail('Invalid keyword suggested: ${s.completion}'); +- } else { +- if (!actualCompletions.add(s.completion)) { +- fail('Duplicate keyword suggested: ${s.completion}'); +- } +- } +- } +- } +- if (!_equalSets(expectedCompletions, actualCompletions)) { +- StringBuffer msg =3D new StringBuffer(); +- msg.writeln('Expected:'); +- _appendCompletions(msg, expectedCompletions, actualCompletions); +- msg.writeln('but found:'); +- _appendCompletions(msg, actualCompletions, expectedCompletions); +- fail(msg.toString()); +- } +- for (CompletionSuggestion s in suggestions) { +- if (s.kind =3D=3D CompletionSuggestionKind.KEYWORD) { +- if (s.completion.startsWith(Keyword.IMPORT.lexeme)) { +- int importRelevance =3D relevance; +- expect(s.relevance, equals(importRelevance), reason: s.completi= on); +- } else { +- if (s.completion =3D=3D Keyword.RETHROW.lexeme) { +- expect(s.relevance, equals(relevance - 1), reason: s.completi= on); +- } else { +- expect(s.relevance, equals(relevance), reason: s.completion); +- } +- } +- int expectedOffset =3D expectedOffsets[s.completion]; +- if (expectedOffset =3D=3D null) { +- expectedOffset =3D s.completion.length; +- } +- expect( +- s.selectionOffset, +- equals(s.completion.endsWith('\'\';') +- ? expectedOffset - 2 +- : expectedOffset)); +- expect(s.selectionLength, equals(0)); +- expect(s.isDeprecated, equals(false)); +- expect(s.isPotential, equals(false)); +- } +- } +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new KeywordContributor(); +- } +- +- fail_import_partial() async { +- addTestSource('imp^ import "package:foo/foo.dart"; import "bar.dart";= '); +- await computeSuggestions(); +- // TODO(danrubel) should not suggest declaration keywords +- assertNotSuggested('class'); +- } +- +- fail_import_partial4() async { +- addTestSource('^ imp import "package:foo/foo.dart";'); +- await computeSuggestions(); +- // TODO(danrubel) should not suggest declaration keywords +- assertNotSuggested('class'); +- } +- +- fail_import_partial5() async { +- addTestSource('library libA; imp^ import "package:foo/foo.dart";'); +- await computeSuggestions(); +- // TODO(danrubel) should not suggest declaration keywords +- assertNotSuggested('class'); +- } +- +- fail_import_partial6() async { +- addTestSource( +- 'library bar; import "zoo.dart"; imp^ import "package:foo/foo.dar= t";'); +- await computeSuggestions(); +- // TODO(danrubel) should not suggest declaration keywords +- assertNotSuggested('class'); +- } +- +- test_after_class() async { +- addTestSource('class A {} ^'); +- await computeSuggestions(); +- assertSuggestKeywords(DECLARATION_KEYWORDS, relevance: DART_RELEVANCE= _HIGH); +- } +- +- test_after_class2() async { +- addTestSource('class A {} c^'); +- await computeSuggestions(); +- assertSuggestKeywords(DECLARATION_KEYWORDS, relevance: DART_RELEVANCE= _HIGH); +- } +- +- test_after_import() async { +- addTestSource('import "foo"; ^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_after_import2() async { +- addTestSource('import "foo"; c^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_anonymous_function_async() async { +- addTestSource('main() {foo(() ^ {}}}'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_anonymous_function_async2() async { +- addTestSource('main() {foo(() a^ {}}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_anonymous_function_async3() async { +- addTestSource('main() {foo(() async ^ {}}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_anonymous_function_async4() async { +- addTestSource('main() {foo(() ^ =3D> 2}}'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async'], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_anonymous_function_async5() async { +- addTestSource('main() {foo(() ^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_anonymous_function_async6() async { +- addTestSource('main() {foo("bar", () as^{}}'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_anonymous_function_async7() async { +- addTestSource('main() {foo("bar", () as^ =3D> null'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_argument() async { +- addTestSource('main() {foo(^);}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_argument2() async { +- addTestSource('main() {foo(n^);}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_argument_literal() async { +- addTestSource('main() {foo("^");}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_argument_named() async { +- addTestSource('main() {foo(bar: ^);}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_argument_named2() async { +- addTestSource('main() {foo(bar: n^);}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_argument_named_literal() async { +- addTestSource('main() {foo(bar: "^");}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_assignment_field() async { +- addTestSource('class A {var foo =3D ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_assignment_field2() async { +- addTestSource('class A {var foo =3D n^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_assignment_local() async { +- addTestSource('main() {var foo =3D ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_assignment_local2() async { +- addTestSource('main() {var foo =3D n^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_assignment_local2_async() async { +- addTestSource('main() async {var foo =3D n^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE, +- pseudoKeywords: ['await']); +- } +- +- test_assignment_local_async() async { +- addTestSource('main() async {var foo =3D ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE, +- pseudoKeywords: ['await']); +- } +- +- test_before_import() async { +- addTestSource('^ import foo;'); +- await computeSuggestions(); +- assertSuggestKeywords( +- [Keyword.EXPORT, Keyword.IMPORT, Keyword.LIBRARY, Keyword.PART], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_catch_1a() async { +- // '}' Block BlockFunctionBody FunctionExpression +- addTestSource('main() {try {} ^}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_1b() async { +- // [ExpressionStatement 'c'] Block BlockFunctionBody FunctionExpre= ssion +- addTestSource('main() {try {} c^}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_1c() async { +- // [EmptyStatement] Block BlockFunction FunctionExpression +- addTestSource('main() {try {} ^;}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_1d() async { +- // [EmptyStatement] Block BlockFunction FunctionExpression +- addTestSource('main() {try {} ^ Foo foo;}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_2a() async { +- // '}' Block BlockFunctionBody FunctionExpression +- addTestSource('main() {try {} on SomeException {} ^}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_2b() async { +- // [ExpressionStatement 'c'] Block BlockFunctionBody FunctionExpre= ssion +- addTestSource('main() {try {} on SomeException {} c^}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_2c() async { +- // [EmptyStatement] Block BlockFunction FunctionExpression +- addTestSource('main() {try {} on SomeException {} ^;}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_2d() async { +- // [EmptyStatement] Block BlockFunction FunctionExpression +- addTestSource('main() {try {} on SomeException {} ^ Foo foo;}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_3a() async { +- // '}' Block BlockFunctionBody FunctionExpression +- addTestSource('main() {try {} catch (e) {} ^}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_3b() async { +- // [ExpressionStatement 'c'] Block BlockFunctionBody FunctionExpre= ssion +- addTestSource('main() {try {} catch (e) {} c^}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_3c() async { +- // [EmptyStatement] Block BlockFunction FunctionExpression +- addTestSource('main() {try {} catch (e) {} ^;}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_3d() async { +- // [EmptyStatement] Block BlockFunction FunctionExpression +- addTestSource('main() {try {} catch (e) {} ^ Foo foo;}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- keywords.add(Keyword.FINALLY); +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_4a1() async { +- // [CatchClause] TryStatement Block +- addTestSource('main() {try {} ^ on SomeException {}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_4a2() async { +- // ['c' VariableDeclarationStatement] Block BlockFunctionBody +- addTestSource('main() {try {} c^ on SomeException {}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- // TODO(danrubel) finally should not be suggested here +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_4b1() async { +- // [CatchClause] TryStatement Block +- addTestSource('main() {try {} ^ catch (e) {}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_4b2() async { +- // ['c' ExpressionStatement] Block BlockFunctionBody +- addTestSource('main() {try {} c^ catch (e) {}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- // TODO(danrubel) finally should not be suggested here +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_4c1() async { +- // ['finally'] TryStatement Block +- addTestSource('main() {try {} ^ finally {}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_4c2() async { +- // ['c' ExpressionStatement] Block BlockFunctionBody +- addTestSource('main() {try {} c^ finally {}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.add(Keyword.CATCH); +- // TODO(danrubel) finally should not be suggested here +- keywords.add(Keyword.FINALLY); +- assertSuggestKeywords(keywords, pseudoKeywords: ['on']); +- } +- +- test_catch_block() async { +- // '}' Block CatchClause TryStatement Block +- addTestSource('main() {try {} catch (e) {^}}}'); +- await computeSuggestions(); +- var keywords =3D []; +- keywords.addAll(STMT_START_OUTSIDE_CLASS); +- keywords.add(Keyword.RETHROW); +- assertSuggestKeywords(keywords); +- } +- +- test_class() async { +- addTestSource('class A e^ { }'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_body() async { +- addTestSource('class A {^}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS); +- } +- +- test_class_body_beginning() async { +- addTestSource('class A {^ var foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS); +- } +- +- test_class_body_between() async { +- addTestSource('class A {var bar; ^ var foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS); +- } +- +- test_class_body_end() async { +- addTestSource('class A {var foo; ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS); +- } +- +- test_class_extends() async { +- addTestSource('class A extends foo ^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_extends2() async { +- addTestSource('class A extends foo i^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_extends3() async { +- addTestSource('class A extends foo i^ { }'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_extends_name() async { +- addTestSource('class A extends ^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_class_implements() async { +- addTestSource('class A ^ implements foo'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.EXTENDS], relevance: DART_RELEVANCE_HI= GH); +- } +- +- test_class_implements2() async { +- addTestSource('class A e^ implements foo'); +- await computeSuggestions(); +- // TODO (danrubel) refinement: don't suggest implements +- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_implements3() async { +- addTestSource('class A e^ implements foo { }'); +- await computeSuggestions(); +- // TODO (danrubel) refinement: don't suggest implements +- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_implements_name() async { +- addTestSource('class A implements ^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_class_member_const_afterStatic() async { +- addTestSource(''' +-class C { +- static c^ +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.CONST, Keyword.FINAL]); +- } +- +- test_class_member_final_afterStatic() async { +- addTestSource(''' +-class C { +- static f^ +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.CONST, Keyword.FINAL]); +- } +- +- test_class_name() async { +- addTestSource('class ^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_class_noBody() async { +- addTestSource('class A ^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_noBody2() async { +- addTestSource('class A e^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_noBody3() async { +- addTestSource('class A e^ String foo;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_class_with() async { +- addTestSource('class A extends foo with bar ^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE= _HIGH); +- } +- +- test_class_with2() async { +- addTestSource('class A extends foo with bar i^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE= _HIGH); +- } +- +- test_class_with3() async { +- addTestSource('class A extends foo with bar i^ { }'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE= _HIGH); +- } +- +- test_class_with_name() async { +- addTestSource('class A extends foo with ^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_constructor_param() async { +- addTestSource('class A { A(^) {});}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.COVARIANT, Keyword.THIS]); +- } +- +- test_constructor_param2() async { +- addTestSource('class A { A(t^) {});}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.COVARIANT, Keyword.THIS]); +- } +- +- test_do_break_continue() async { +- addTestSource('main() {do {^} while (true);}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_LOOP_OUTSIDE_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_do_break_continue2() async { +- addTestSource('class A {foo() {do {^} while (true);}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_LOOP_IN_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_empty() async { +- addTestSource('^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_for_break_continue() async { +- addTestSource('main() {for (int x in myList) {^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_LOOP_OUTSIDE_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_for_break_continue2() async { +- addTestSource('class A {foo() {for (int x in myList) {^}}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_LOOP_IN_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_for_expression_in() async { +- addTestSource('main() {for (int x i^)}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IN], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_for_expression_in2() async { +- addTestSource('main() {for (int x in^)}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IN], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_for_expression_in_inInitializer() async { +- addTestSource('main() {for (int i^)}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_for_expression_init() async { +- addTestSource('main() {for (int x =3D i^)}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_for_expression_init2() async { +- addTestSource('main() {for (int x =3D in^)}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_for_initialization_var() async { +- addTestSource('main() {for (^)}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.VAR], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_function_async() async { +- addTestSource('main()^'); +- await computeSuggestions(); +- assertSuggestKeywords(DECLARATION_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_function_async2() async { +- addTestSource('main()^{}'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_function_async3() async { +- addTestSource('main()a^'); +- await computeSuggestions(); +- assertSuggestKeywords(DECLARATION_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_function_async4() async { +- addTestSource('main()a^{}'); +- await computeSuggestions(); +- assertSuggestKeywords(DECLARATION_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_function_async5() async { +- addTestSource('main()a^ Foo foo;'); +- await computeSuggestions(); +- assertSuggestKeywords(DECLARATION_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_function_body_inClass_constructorInitializer() async { +- addTestSource(r''' +-foo(p) {} +-class A { +- final f; +- A() : f =3D foo(() {^}); +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_function_body_inClass_constructorInitializer_async() async { +- addTestSource(r''' +-foo(p) {} +-class A { +- final f; +- A() : f =3D foo(() async {^}); +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, pseudoKeywords: ['awa= it']); +- } +- +- test_function_body_inClass_constructorInitializer_async_star() async { +- addTestSource(r''' +- foo(p) {} +- class A { +- final f; +- A() : f =3D foo(() async* {^}); +- } +- '''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_function_body_inClass_field() async { +- addTestSource(r''' +-class A { +- var f =3D () {^}; +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_function_body_inClass_methodBody() async { +- addTestSource(r''' +-class A { +- m() { +- f() {^}; +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_function_body_inClass_methodBody_inFunction() async { +- addTestSource(r''' +-class A { +- m() { +- f() { +- f2() {^}; +- }; +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_function_body_inClass_methodBody_inFunction_async() async { +- addTestSource(r''' +-class A { +- m() { +- f() { +- f2() async {^}; +- }; +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS, pseudoKeywords: ['await']); +- } +- +- test_function_body_inClass_methodBody_inFunction_async_star() async { +- addTestSource(r''' +- class A { +- m() { +- f() { +- f2() async* {^}; +- }; +- } +- } +- '''); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_function_body_inUnit() async { +- addTestSource('main() {^}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_function_body_inUnit_afterBlock() async { +- addTestSource('main() {{}^}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_function_body_inUnit_async() async { +- addTestSource('main() async {^}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, pseudoKeywords: ['awa= it']); +- } +- +- test_function_body_inUnit_async_star() async { +- addTestSource('main() async* {n^}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_function_body_inUnit_async_star2() async { +- addTestSource('main() async* {n^ foo}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_function_body_inUnit_sync_star() async { +- addTestSource('main() sync* {n^}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_function_body_inUnit_sync_star2() async { +- addTestSource('main() sync* {n^ foo}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_if_after_else() async { +- addTestSource('main() { if (true) {} else ^ }'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_if_afterThen_nextCloseCurlyBrace0() async { +- addTestSource('main() { if (true) {} ^ }'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS.toList()..add(Keyword.= ELSE), +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_if_afterThen_nextCloseCurlyBrace1() async { +- addTestSource('main() { if (true) {} e^ }'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS.toList()..add(Keyword.= ELSE), +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_if_afterThen_nextStatement0() async { +- addTestSource('main() { if (true) {} ^ print(0); }'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS.toList()..add(Keyword.= ELSE), +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_if_condition_isKeyword() async { +- addTestSource('main() { if (v i^) {} }'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_if_condition_isKeyword2() async { +- addTestSource('main() { if (v i^ && false) {} }'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_if_expression_in_class() async { +- addTestSource('class A {foo() {if (^) }}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_if_expression_in_class2() async { +- addTestSource('class A {foo() {if (n^) }}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_if_expression_in_function() async { +- addTestSource('foo() {if (^) }'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_if_expression_in_function2() async { +- addTestSource('foo() {if (n^) }'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_if_in_class() async { +- addTestSource('class A {foo() {if (true) ^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_if_in_class2() async { +- addTestSource('class A {foo() {if (true) ^;}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_if_in_class3() async { +- addTestSource('class A {foo() {if (true) r^;}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_if_in_class4() async { +- addTestSource('class A {foo() {if (true) ^ go();}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_if_outside_class() async { +- addTestSource('foo() {if (true) ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_if_outside_class2() async { +- addTestSource('foo() {if (true) ^;}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_if_outside_class3() async { +- addTestSource('foo() {if (true) r^;}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_if_outside_class4() async { +- addTestSource('foo() {if (true) ^ go();}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_OUTSIDE_CLASS); +- } +- +- test_import() async { +- addTestSource('import "foo" deferred as foo ^;'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['show', 'hide'], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_as() async { +- addTestSource('import "foo" deferred ^;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_as2() async { +- addTestSource('import "foo" deferred a^;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_as3() async { +- addTestSource('import "foo" deferred a^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred() async { +- addTestSource('import "foo" ^ as foo;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.DEFERRED], relevance: DART_RELEVANCE_H= IGH); +- } +- +- test_import_deferred2() async { +- addTestSource('import "foo" d^ as foo;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.DEFERRED], relevance: DART_RELEVANCE_H= IGH); +- } +- +- test_import_deferred3() async { +- addTestSource('import "foo" d^ show foo;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as'], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred4() async { +- addTestSource('import "foo" d^ hide foo;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as'], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred5() async { +- addTestSource('import "foo" d^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred6() async { +- addTestSource('import "foo" d^ import'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_as() async { +- addTestSource('import "foo" ^;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_as2() async { +- addTestSource('import "foo" d^;'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_as3() async { +- addTestSource('import "foo" ^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_as4() async { +- addTestSource('import "foo" d^'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_as5() async { +- addTestSource('import "foo" sh^ import "bar"; import "baz";'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.AS], +- pseudoKeywords: ['deferred as', 'show', 'hide'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_not() async { +- addTestSource('import "foo" as foo ^;'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['show', 'hide'], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_deferred_partial() async { +- addTestSource('import "package:foo/foo.dart" def^ as foo;'); +- await computeSuggestions(); +- expect(replacementOffset, 30); +- expect(replacementLength, 3); +- assertSuggestKeywords([Keyword.DEFERRED], relevance: DART_RELEVANCE_H= IGH); +- expect(suggestions[0].selectionOffset, 8); +- expect(suggestions[0].selectionLength, 0); +- } +- +- test_import_incomplete() async { +- addTestSource('import "^"'); +- await computeSuggestions(); +- expect(suggestions, isEmpty); +- } +- +- test_import_partial() async { +- addTestSource('imp^ import "package:foo/foo.dart"; import "bar.dart";= '); +- await computeSuggestions(); +- expect(replacementOffset, 0); +- expect(replacementLength, 3); +- // TODO(danrubel) should not suggest declaration keywords +- assertSuggestKeywords(DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_partial2() async { +- addTestSource('^imp import "package:foo/foo.dart";'); +- await computeSuggestions(); +- expect(replacementOffset, 0); +- expect(replacementLength, 3); +- // TODO(danrubel) should not suggest declaration keywords +- assertSuggestKeywords(DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_partial3() async { +- addTestSource(' ^imp import "package:foo/foo.dart"; import "bar.dart"= ;'); +- await computeSuggestions(); +- expect(replacementOffset, 1); +- expect(replacementLength, 3); +- // TODO(danrubel) should not suggest declaration keywords +- assertSuggestKeywords(DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_partial4() async { +- addTestSource('^ imp import "package:foo/foo.dart";'); +- await computeSuggestions(); +- expect(replacementOffset, 0); +- expect(replacementLength, 0); +- // TODO(danrubel) should not suggest declaration keywords +- assertSuggestKeywords(DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_partial5() async { +- addTestSource('library libA; imp^ import "package:foo/foo.dart";'); +- await computeSuggestions(); +- expect(replacementOffset, 14); +- expect(replacementLength, 3); +- // TODO(danrubel) should not suggest declaration keywords +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_import_partial6() async { +- addTestSource( +- 'library bar; import "zoo.dart"; imp^ import "package:foo/foo.dar= t";'); +- await computeSuggestions(); +- expect(replacementOffset, 32); +- expect(replacementLength, 3); +- // TODO(danrubel) should not suggest declaration keywords +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_is_expression() async { +- addTestSource('main() {if (x is^)}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_is_expression_partial() async { +- addTestSource('main() {if (x i^)}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_library() async { +- addTestSource('library foo;^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_library_declaration() async { +- addTestSource('library ^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_library_declaration2() async { +- addTestSource('library a^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_library_declaration3() async { +- addTestSource('library a.^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_library_name() async { +- addTestSource('library ^'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_method_async() async { +- addTestSource('class A { foo() ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_method_async2() async { +- addTestSource('class A { foo() ^{}}'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async', 'async*', 'sync*'], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_method_async3() async { +- addTestSource('class A { foo() a^}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_method_async4() async { +- addTestSource('class A { foo() a^{}}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_method_async5() async { +- addTestSource('class A { foo() ^ Foo foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_method_async6() async { +- addTestSource('class A { foo() a^ Foo foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_method_async7() async { +- addTestSource('class A { foo() ^ =3D> Foo foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords([], +- pseudoKeywords: ['async'], relevance: DART_RELEVANCE_HIGH); +- } +- +- test_method_async8() async { +- addTestSource('class A { foo() a^ Foo foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(CLASS_BODY_KEYWORDS, +- pseudoKeywords: ['async', 'async*', 'sync*']); +- } +- +- test_method_body() async { +- addTestSource('class A { foo() {^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS); +- } +- +- test_method_body2() async { +- addTestSource('class A { foo() =3D> ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_method_body3() async { +- addTestSource('class A { foo() =3D> ^ Foo foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_method_body4() async { +- addTestSource('class A { foo() =3D> ^;}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_method_body_async() async { +- addTestSource('class A { foo() async {^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS, pseudoKeywords: ['await']); +- } +- +- test_method_body_async2() async { +- addTestSource('class A { foo() async =3D> ^}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE, pseudoKeywords: ['aw= ait']); +- } +- +- test_method_body_async3() async { +- addTestSource('class A { foo() async =3D> ^ Foo foo;}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE, pseudoKeywords: ['aw= ait']); +- } +- +- test_method_body_async4() async { +- addTestSource('class A { foo() async =3D> ^;}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE, pseudoKeywords: ['aw= ait']); +- } +- +- test_method_body_async_star() async { +- addTestSource('class A { foo() async* {^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_CLASS, +- pseudoKeywords: ['await', 'yield', 'yield*']); +- } +- +- test_method_body_expression1() async { +- addTestSource('class A { foo() {return b =3D=3D true ? ^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_method_body_expression2() async { +- addTestSource('class A { foo() {return b =3D=3D true ? 1 : ^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_method_body_return() async { +- addTestSource('class A { foo() {return ^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_INSTANCE); +- } +- +- test_method_invocation() async { +- addTestSource('class A { foo() {bar.^}}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_method_invocation2() async { +- addTestSource('class A { foo() {bar.as^}}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_method_param() async { +- addTestSource('class A { foo(^) {});}'); +- await computeSuggestions(); +- expect(suggestions, isNotEmpty); +- assertSuggestKeywords([Keyword.COVARIANT]); +- } +- +- test_method_param2() async { +- addTestSource('class A { foo(t^) {});}'); +- await computeSuggestions(); +- expect(suggestions, isNotEmpty); +- assertSuggestKeywords([Keyword.COVARIANT]); +- } +- +- test_method_param_named_init() async { +- addTestSource('class A { foo({bool bar: ^}) {}}'); +- await computeSuggestions(); +- expect(suggestions, isNotEmpty); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_method_param_named_init2() async { +- addTestSource('class A { foo({bool bar: f^}) {}}'); +- await computeSuggestions(); +- expect(suggestions, isNotEmpty); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_method_param_positional_init() async { +- addTestSource('class A { foo([bool bar =3D ^]) {}}'); +- await computeSuggestions(); +- expect(suggestions, isNotEmpty); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_method_param_positional_init2() async { +- addTestSource('class A { foo([bool bar =3D f^]) {}}'); +- await computeSuggestions(); +- expect(suggestions, isNotEmpty); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_named_constructor_invocation() async { +- addTestSource('void main() {new Future.^}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_newInstance() async { +- addTestSource('class A { foo() {new ^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_newInstance2() async { +- addTestSource('class A { foo() {new ^ print("foo");}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_newInstance_prefixed() async { +- addTestSource('class A { foo() {new A.^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_newInstance_prefixed2() async { +- addTestSource('class A { foo() {new A.^ print("foo");}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_part_of() async { +- addTestSource('part of foo;^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_partial_class() async { +- addTestSource('cl^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_DECLARATION_AND_LIBRARY_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_partial_class2() async { +- addTestSource('library a; cl^'); +- await computeSuggestions(); +- assertSuggestKeywords(DIRECTIVE_AND_DECLARATION_KEYWORDS, +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_prefixed_field() async { +- addTestSource('class A { int x; foo() {x.^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_prefixed_field2() async { +- addTestSource('class A { int x; foo() {x.^ print("foo");}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_prefixed_library() async { +- addTestSource('import "b" as b; class A { foo() {b.^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_prefixed_local() async { +- addTestSource('class A { foo() {int x; x.^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_prefixed_local2() async { +- addTestSource('class A { foo() {int x; x.^ print("foo");}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_property_access() async { +- addTestSource('class A { get x =3D> 7; foo() {new A().^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([]); +- } +- +- test_switch_expression() async { +- addTestSource('main() {switch(^) {}}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_switch_expression2() async { +- addTestSource('main() {switch(n^) {}}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_switch_expression3() async { +- addTestSource('main() {switch(n^)}'); +- await computeSuggestions(); +- assertSuggestKeywords(EXPRESSION_START_NO_INSTANCE); +- } +- +- test_switch_start() async { +- addTestSource('main() {switch(1) {^}}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_start2() async { +- addTestSource('main() {switch(1) {^ case 1:}}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_start3() async { +- addTestSource('main() {switch(1) {^default:}}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_start4() async { +- addTestSource('main() {switch(1) {^ default:}}'); +- await computeSuggestions(); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_start5() async { +- addTestSource('main() {switch(1) {c^ default:}}'); +- await computeSuggestions(); +- expect(replacementOffset, 19); +- expect(replacementLength, 1); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_start6() async { +- addTestSource('main() {switch(1) {c^}}'); +- await computeSuggestions(); +- expect(replacementOffset, 19); +- expect(replacementLength, 1); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_start7() async { +- addTestSource('main() {switch(1) { c^ }}'); +- await computeSuggestions(); +- expect(replacementOffset, 20); +- expect(replacementLength, 1); +- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT], +- relevance: DART_RELEVANCE_HIGH); +- } +- +- test_switch_statement() async { +- addTestSource('main() {switch(1) {case 1:^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_SWITCH_OUTSIDE_CLASS); +- } +- +- test_switch_statement2() async { +- addTestSource('class A{foo() {switch(1) {case 1:^}}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_SWITCH_IN_CLASS); +- } +- +- test_while_break_continue() async { +- addTestSource('main() {while (true) {^}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_LOOP_OUTSIDE_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- test_while_break_continue2() async { +- addTestSource('class A {foo() {while (true) {^}}}'); +- await computeSuggestions(); +- assertSuggestKeywords(STMT_START_IN_LOOP_IN_CLASS, +- relevance: DART_RELEVANCE_KEYWORD); +- } +- +- void _appendCompletions( +- StringBuffer msg, Iterable completions, Iterable ot= her) { +- List sorted =3D completions.toList(); +- sorted.sort((c1, c2) =3D> c1.compareTo(c2)); +- sorted.forEach( +- (c) =3D> msg.writeln(' $c, ${other.contains(c) ? '' : '<<<<<<<<<= <<'}')); +- } +- +- bool _equalSets(Iterable iter1, Iterable iter2) { +- if (iter1.length !=3D iter2.length) return false; +- if (iter1.any((c) =3D> !iter2.contains(c))) return false; +- if (iter2.any((c) =3D> !iter1.contains(c))) return false; +- return true; +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/label_contr= ibutor_test.dart b/pkg/analysis_server/test/services/completion/dart/label_= contributor_test.dart +deleted file mode 100644 +index 0cd20680cc5..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/label_contributor_= test.dart ++++ /dev/null +@@ -1,320 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/label_contri= butor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LabelContributorTest); +- }); +-} +- +-@reflectiveTest +-class LabelContributorTest extends DartCompletionContributorTest { +- CompletionSuggestion assertSuggestLabel(String name, +- {int relevance: DART_RELEVANCE_DEFAULT, +- CompletionSuggestionKind kind: CompletionSuggestionKind.IDENTIFIER}= ) { +- CompletionSuggestion cs =3D +- assertSuggest(name, csKind: kind, relevance: relevance); +- expect(cs.returnType, isNull); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.flags, 0); +- expect(element.kind, equals(ElementKind.LABEL)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new LabelContributor(); +- } +- +- test_break_ignores_outer_functions_using_closure() async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- var f =3D () { +- bar: while (true) { break ^ } +- }; +- } +-} +-'''); +- await computeSuggestions(); +- // Labels in outer functions are never accessible. +- assertSuggestLabel('bar'); +- assertNotSuggested('foo'); +- } +- +- test_break_ignores_outer_functions_using_local_function() async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- void f() { +- bar: while (true) { break ^ } +- }; +- } +-} +-'''); +- await computeSuggestions(); +- // Labels in outer functions are never accessible. +- assertSuggestLabel('bar'); +- assertNotSuggested('foo'); +- } +- +- test_break_ignores_toplevel_variables() async { +- addTestSource(''' +-int x; +-void main() { +- while (true) { +- break ^ +- } +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('x'); +- } +- +- test_break_ignores_unrelated_statements() async { +- addTestSource(''' +-void main() { +- foo: while (true) {} +- while (true) { break ^ } +- bar: while (true) {} +-} +-'''); +- await computeSuggestions(); +- // The scope of the label defined by a labeled statement is just the +- // statement itself, so neither "foo" nor "bar" are in scope at the c= aret +- // position. +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- } +- +- test_break_to_enclosing_loop() async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- bar: while (true) { +- break ^ +- } +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- assertSuggestLabel('bar'); +- } +- +- test_continue_from_loop_to_switch() async { +- addTestSource(''' +-void main() { +- switch (x) { +- foo: case 1: +- break; +- bar: case 2: +- while (true) { +- continue ^; +- } +- break; +- baz: case 3: +- break; +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- assertSuggestLabel('bar'); +- assertSuggestLabel('baz'); +- } +- +- test_continue_from_switch_to_loop() async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- switch (x) { +- case 1: +- continue ^; +- } +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- } +- +- test_continue_ignores_outer_functions_using_closure_with_loop() async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- var f =3D () { +- bar: while (true) { continue ^ } +- }; +- } +-} +-'''); +- await computeSuggestions(); +- // Labels in outer functions are never accessible. +- assertSuggestLabel('bar'); +- assertNotSuggested('foo'); +- } +- +- test_continue_ignores_outer_functions_using_closure_with_switch() async= { +- addTestSource(''' +-void main() { +- switch (x) { +- foo: case 1: +- var f =3D () { +- bar: while (true) { continue ^ } +- }; +- } +-} +-'''); +- await computeSuggestions(); +- // Labels in outer functions are never accessible. +- assertSuggestLabel('bar'); +- assertNotSuggested('foo'); +- } +- +- test_continue_ignores_outer_functions_using_local_function_with_loop() = async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- void f() { +- bar: while (true) { continue ^ } +- }; +- } +-} +-'''); +- await computeSuggestions(); +- // Labels in outer functions are never accessible. +- assertSuggestLabel('bar'); +- assertNotSuggested('foo'); +- } +- +- test_continue_ignores_outer_functions_using_local_function_with_switch(= ) async { +- addTestSource(''' +-void main() { +- switch (x) { +- foo: case 1: +- void f() { +- bar: while (true) { continue ^ } +- }; +- } +-} +-'''); +- await computeSuggestions(); +- // Labels in outer functions are never accessible. +- assertSuggestLabel('bar'); +- assertNotSuggested('foo'); +- } +- +- test_continue_ignores_unrelated_statements() async { +- addTestSource(''' +-void main() { +- foo: while (true) {} +- while (true) { continue ^ } +- bar: while (true) {} +-} +-'''); +- await computeSuggestions(); +- // The scope of the label defined by a labeled statement is just the +- // statement itself, so neither "foo" nor "bar" are in scope at the c= aret +- // position. +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- } +- +- test_continue_to_earlier_case() async { +- addTestSource(''' +-void main() { +- switch (x) { +- foo: case 1: +- break; +- case 2: +- continue ^; +- case 3: +- break; +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- } +- +- test_continue_to_enclosing_loop() async { +- addTestSource(''' +-void main() { +- foo: while (true) { +- bar: while (true) { +- continue ^ +- } +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- assertSuggestLabel('bar'); +- } +- +- test_continue_to_enclosing_switch() async { +- addTestSource(''' +-void main() { +- switch (x) { +- foo: case 1: +- break; +- bar: case 2: +- switch (y) { +- case 1: +- continue ^; +- } +- break; +- baz: case 3: +- break; +- } +-} +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- assertSuggestLabel('bar'); +- assertSuggestLabel('baz'); +- } +- +- test_continue_to_later_case() async { +- addTestSource(''' +-void main() { +- switch (x) { +- case 1: +- break; +- case 2: +- continue ^; +- foo: case 3: +- break; +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- } +- +- test_continue_to_same_case() async { +- addTestSource(''' +-void main() { +- switch (x) { +- case 1: +- break; +- foo: case 2: +- continue ^; +- case 3: +- break; +-'''); +- await computeSuggestions(); +- assertSuggestLabel('foo'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/library_mem= ber_contributor_test.dart b/pkg/analysis_server/test/services/completion/da= rt/library_member_contributor_test.dart +deleted file mode 100644 +index 2c49eca8a03..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/library_member_con= tributor_test.dart ++++ /dev/null +@@ -1,251 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/library_memb= er_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LibraryMemberContributorTest); +- }); +-} +- +-@reflectiveTest +-class LibraryMemberContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new LibraryMemberContributor(); +- } +- +- test_libraryPrefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('import "dart:async" as bar; foo() {bar.^}'); +- await computeSuggestions(); +- assertSuggestClass('Future'); +- assertNotSuggested('loadLibrary'); +- } +- +- test_libraryPrefix2() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource('import "dart:async" as bar; foo() {bar.^ print("f")}'); +- await computeSuggestions(); +- assertSuggestClass('Future'); +- } +- +- test_libraryPrefix3() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource('import "dart:async" as bar; foo() {new bar.F^ print("f= ")}'); +- await computeSuggestions(); +- assertSuggestConstructor('Future'); +- assertSuggestConstructor('Future.delayed'); +- } +- +- test_libraryPrefix_cascade() async { +- addTestSource(''' +- import "dart:math" as math; +- main() {math..^}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_libraryPrefix_cascade2() async { +- addTestSource(''' +- import "dart:math" as math; +- main() {math.^.}'''); +- await computeSuggestions(); +- assertSuggestFunction('min', 'T'); +- } +- +- test_libraryPrefix_cascade3() async { +- addTestSource(''' +- import "dart:math" as math; +- main() {math..^a}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_libraryPrefix_cascade4() async { +- addTestSource(''' +- import "dart:math" as math; +- main() {math.^.a}'''); +- await computeSuggestions(); +- assertSuggestFunction('min', 'T'); +- } +- +- test_libraryPrefix_deferred() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('import "dart:async" deferred as bar; foo() {bar.^}'); +- await computeSuggestions(); +- assertSuggestClass('Future'); +- assertSuggestFunction('loadLibrary', 'Future'); +- } +- +- test_libraryPrefix_deferred_inPart() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- var libFile =3D '${testFile.substring(0, testFile.length - 5)}A.dart'; +- addSource(libFile, ''' +- library testA; +- import "dart:async" deferred as bar; +- part "$testFile";'''); +- addTestSource('part of testA; foo() {bar.^}'); +- // Assume that libraries containing has been computed for part files +- await computeLibrariesContaining(); +- await computeSuggestions(); +- assertSuggestClass('Future'); +- assertSuggestFunction('loadLibrary', 'Future'); +- assertNotSuggested('foo'); +- } +- +- test_libraryPrefix_with_exports() async { +- addSource('/libA.dart', 'library libA; class A { }'); +- addSource('/libB.dart', ''' +- library libB; +- export "/libA.dart"; +- class B { } +- @deprecated class B1 { }'''); +- addTestSource('import "/libB.dart" as foo; main() {foo.^} class C { }= '); +- await computeSuggestions(); +- assertSuggestClass('B'); +- assertSuggestClass('B1', relevance: DART_RELEVANCE_LOW, isDeprecated:= true); +- assertSuggestClass('A'); +- assertNotSuggested('C'); +- } +- +- test_PrefixedIdentifier_library() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "/testB.dart" as b; +- var T2; +- class A { } +- main() {b.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertSuggestClass('Y'); +- assertSuggestTopLevelVar('T1', null); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_inPart() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- var libFile =3D '${testFile.substring(0, testFile.length - 5)}A.dart'; +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addSource(libFile, ''' +- library testA; +- import "/testB.dart" as b; +- part "$testFile"; +- var T2; +- class A { }'''); +- addTestSource(''' +- part of testA; +- main() {b.^}'''); +- // Assume that libraries containing has been computed for part files +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertSuggestClass('Y'); +- assertSuggestTopLevelVar('T1', null); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "/testB.dart" as b; +- var T2; +- class A { } +- foo(b.^ f) {}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertSuggestClass('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "/testB.dart" as b; +- var T2; +- class A { } +- foo(b.^) {}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('X'); +- assertSuggestClass('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_parameter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- class _W {M y; var _z;} +- class X extends _W {} +- class M{}'''); +- addTestSource(''' +- import "/testB.dart"; +- foo(X x) {x.^}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_PrefixedIdentifier_prefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testA.dart', ''' +- class A {static int bar =3D 10;} +- _B() {}'''); +- addTestSource(''' +- import "/testA.dart"; +- class X {foo(){A^.bar}}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/library_pre= fix_contributor_test.dart b/pkg/analysis_server/test/services/completion/da= rt/library_prefix_contributor_test.dart +deleted file mode 100644 +index 3343e5e5166..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/library_prefix_con= tributor_test.dart ++++ /dev/null +@@ -1,329 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/library_pref= ix_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LibraryPrefixContributorTest); +- }); +-} +- +-@reflectiveTest +-class LibraryPrefixContributorTest extends DartCompletionContributorTest { +- void assertSuggestLibraryPrefixes(List expectedPrefixes) { +- for (String prefix in expectedPrefixes) { +- CompletionSuggestion cs =3D assertSuggest(prefix, +- csKind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_DEFAULT); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.LIBRARY)); +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- assertHasNoParameterInfo(cs); +- } +- if (suggestions.length !=3D expectedPrefixes.length) { +- failedCompletion('expected only ${expectedPrefixes.length} suggesti= ons'); +- } +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new LibraryPrefixContributor(); +- } +- +- test_Block() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- ^ var r; +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['g']); +- } +- +- test_Block_final_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- final var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['g']); +- } +- +- test_Block_final_var() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['g']); +- } +- +- test_ClassDeclaration_body() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-@deprecated class A {^} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['x']); +- } +- +- test_ClassDeclaration_body_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['x']); +- } +- +- test_ClassDeclaration_body_final_field() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ A(){}} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['x']); +- } +- +- test_ClassDeclaration_body_final_field2() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as Soo; +-class A {final S^ A();} +-class _B {} +-A Sew;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestLibraryPrefixes(['Soo']); +- } +- +- test_ClassDeclaration_body_final_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ final foo;} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['x']); +- } +- +- test_ClassDeclaration_body_final_var() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ var foo;} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLibraryPrefixes(['x']); +- } +- +- test_InstanceCreationExpression() async { +- addSource('/testA.dart', ''' +-class A {foo(){var f; {var x;}}} +-class B {B(this.x, [String boo]) { } int x;} +-class C {C.bar({boo: 'hoo', int z: 0}) { } }'''); +- addTestSource(''' +-import "/testA.dart" as t; +-import "dart:math" as math; +-main() {new ^ String x =3D "hello";}'''); +- await computeSuggestions(); +- assertSuggestLibraryPrefixes(['math', 't']); +- } +- +- test_InstanceCreationExpression2() async { +- addTestSource('import "dart:convert" as json;f() {var x=3Dnew js^}'); +- await computeSuggestions(); +- assertSuggestLibraryPrefixes(['json']); +- } +- +- test_InstanceCreationExpression_inPart() async { +- addSource('/testA.dart', ''' +-class A {foo(){var f; {var x;}}} +-class B {B(this.x, [String boo]) { } int x;} +-class C {C.bar({boo: 'hoo', int z: 0}) { } }'''); +- addSource('/testB.dart', ''' +-library testB; +-import "/testA.dart" as t; +-import "dart:math" as math; +-part "$testFile" +-main() {new ^ String x =3D "hello";}'''); +- addTestSource(''' +-part of testB; +-main() {new ^ String x =3D "hello";}'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- assertSuggestLibraryPrefixes(['math', 't']); +- } +- +- test_InstanceCreationExpression_inPart_detached() async { +- addSource('/testA.dart', ''' +-class A {foo(){var f; {var x;}}} +-class B {B(this.x, [String boo]) { } int x;} +-class C {C.bar({boo: 'hoo', int z: 0}) { } }'''); +- addSource('/testB.dart', ''' +-library testB; +-import "/testA.dart" as t; +-import "dart:math" as math; +-//part "$testFile" +-main() {new ^ String x =3D "hello";}'''); +- addTestSource(''' +-//part of testB; +-main() {new ^ String x =3D "hello";}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/local_const= ructor_contributor_test.dart b/pkg/analysis_server/test/services/completion= /dart/local_constructor_contributor_test.dart +deleted file mode 100644 +index 89c378da9e2..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/local_constructor_= contributor_test.dart ++++ /dev/null +@@ -1,3975 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_constr= uctor_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LocalConstructorContributorTest); +- }); +-} +- +-@reflectiveTest +-class LocalConstructorContributorTest extends DartCompletionContributorTe= st { +- CompletionSuggestion assertSuggestLocalVariable( +- String name, String returnType, +- {int relevance: DART_RELEVANCE_LOCAL_VARIABLE}) { +- // Local variables should only be suggested by LocalReferenceContribu= tor +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: CompletionSuggestionKind.INVOCATION, relevance: relevance= ); +- expect(cs.returnType, returnType !=3D null ? returnType : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.LOCAL_VARIABLE)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, returnType !=3D null ? returnType : 'dynam= ic'); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestParameter(String name, String returnT= ype, +- {int relevance: DART_RELEVANCE_PARAMETER}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: CompletionSuggestionKind.INVOCATION, relevance: relevance= ); +- expect(cs.returnType, returnType !=3D null ? returnType : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.PARAMETER)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, +- equals(returnType !=3D null ? returnType : 'dynamic')); +- return cs; +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new LocalConstructorContributor(); +- } +- +- /// Sanity check. Permutations tested in local_ref_contributor. +- test_ArgDefaults_cons_with_required_named() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +- +-class A { +- A(int bar, {bool boo, @required int baz}); +- baz() { +- new A^ +- } +-}'''); +- await computeSuggestions(); +- +- assertSuggestConstructor('A', defaultArgListString: 'bar, baz: null'); +- } +- +- test_ArgumentList() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart'; +-class B { } +-String bar() =3D> true; +-void main() {expect(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_imported_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-expect(arg) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart' +-class B { } +-String bar() =3D> true; +-void main() {expect(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_functionalArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar() =3D> true; +-void main() {new A(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_typedefArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +-library A; +-typedef Funct(); +-class A { A(Funct f) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar() =3D> true; +-void main() {new A(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart' +-expect(arg) { } +-class B { } +-String bar() =3D> true; +-void main() {expect(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_method() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart' +-class B { +- expect(arg) { } +- void foo() {expect(^)}} +-String bar() =3D> true;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_functionalArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar(f()) =3D> true; +-void main() {bar(^);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_methodArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { String bar(f()) =3D> true; } +-void main() {new B().bar(^);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_namedParam() async { +- // SimpleIdentifier NamedExpression ArgumentList MethodInvocation +- // ExpressionStatement +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { }'''); +- addTestSource(''' +-import '/libA.dart' +-String bar() =3D> true; +-void main() {expect(foo: ^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('main'); +- } +- +- test_AsExpression() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +- class A {var b; X _c; foo() {var a; (a as ^).foo();}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_AssignmentExpression_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int ^b =3D 1;}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_AssignmentExpression_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int b =3D ^}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_AssignmentExpression_type() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- ^ b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- ^ +- b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- int^ b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- i^ +- b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('identical'); +- } +- +- test_AwaitExpression() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main() async {A a; await ^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_BinaryExpression_LHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D ^ + 2;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- } +- +- test_BinaryExpression_RHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D 2 + ^;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- ^ var r; +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- final ^ +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final2() async { +- addTestSource('main() {final S^ v;}'); +- await computeSuggestions(); +- +- assertNotSuggested('String'); +- } +- +- test_Block_final3() async { +- addTestSource('main() {final ^ v;}'); +- await computeSuggestions(); +- +- assertNotSuggested('String'); +- } +- +- test_Block_final_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- final var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final_var() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_identifier_partial() async { +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B { }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-class D3 { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-Z D2() {int x;} +-class X {a() {var f; {var x;} D^ var r;} void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- +- // imported elements are portially filtered +- //assertNotSuggested('A'); +- assertNotSuggested('_B'); +- //assertNotSuggested('C'); +- // hidden element suggested as low relevance +- assertNotSuggested('D'); +- assertNotSuggested('D1'); +- assertNotSuggested('D2'); +- // unimported elements suggested with low relevance +- assertNotSuggested('D3'); +- //assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- //assertSuggestLibraryPrefix('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- //assertNotSuggested('Object'); +- //assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- //assertSuggestTopLevelVarGetterSetter('T1', 'String'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- //assertNotSuggested('T5'); +- //assertSuggestTopLevelVar('_T6', null); +- assertNotSuggested('=3D=3D'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- } +- +- test_Block_inherited_imported() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addSource('/testB.dart', ''' +-lib B; +-class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } var _pf; } +-class E extends F { var e1; e2() { } } +-class I { int i1; i2() { } } +-class M { var m1; int m2() { } }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // TODO (danrubel) prefer fields over getters +- // If add `get e1;` to interface I +- // then suggestions include getter e1 rather than field e1 +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- //assertNotSuggested('m2'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block_inherited_local() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addTestSource(''' +-class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } } +-class E extends F { var e1; e2() { } } +-class I { int i1; i2() { } } +-class M { var m1; int m2() { } } +-class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- assertNotSuggested('m2'); +- } +- +- test_Block_local_function() async { +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- p^ var r; +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertNotSuggested('partT8'); +- assertNotSuggested('partBoo'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_unimported() async { +- addPackageSource('myBar', 'bar.dart', 'class Foo2 { Foo2() { } }'); +- addSource( +- '/proj/testAB.dart', 'import "package:myBar/bar.dart"; class Foo = { }'); +- testFile =3D '/proj/completionTest.dart'; +- addTestSource('class C {foo(){F^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('Foo'); +- // TODO(danrubel) implement +- assertNotSuggested('Foo2'); +- assertNotSuggested('Future'); +- } +- +- test_CascadeExpression_selector1() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A {var b; X _c;} +-class X{} +-// looks like a cascade to the parser +-// but the user is trying to get completions for a non-cascade +-main() {A a; a.^.z}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2() async { +- // SimpleIdentifier PropertyAccess CascadeExpression ExpressionSta= tement +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A {var b; X _c;} +-class X{} +-main() {A a; a..^z}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2_withTrailingReturn() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A {var b; X _c;} +-class X{} +-main() {A a; a..^ return}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_target() async { +- // SimpleIdentifier CascadeExpression ExpressionStatement +- addTestSource(''' +-class A {var b; X _c;} +-class X{} +-main() {A a; a^..b}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CatchClause_onType() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^ {}}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_onType_noBrackets() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_typed() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on E catch (e) {^}}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_untyped() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} catch (e, s) {^}}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e'); +- assertNotSuggested('s'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-@deprecated class A {^} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ A(){}} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('String'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field2() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as Soo; +-class A {final S^ A();} +-class _B {} +-A Sew;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('String'); +- assertNotSuggested('Sew'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('Soo'); +- } +- +- test_ClassDeclaration_body_final_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ final foo;} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_var() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ var foo;} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_Combinator_hide() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +-library libAB; +-part '/partAB.dart'; +-class A { } +-class B { }'''); +- addSource('/partAB.dart', ''' +-part of libAB; +-var T1; +-PB F1() =3D> new PB(); +-class PB { }'''); +- addSource('/testCD.dart', ''' +-class C { } +-class D { }'''); +- addTestSource(''' +-import "/testAB.dart" hide ^; +-import "/testCD.dart"; +-class X {}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_Combinator_show() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +-library libAB; +-part '/partAB.dart'; +-class A { } +-class B { }'''); +- addSource('/partAB.dart', ''' +-part of libAB; +-var T1; +-PB F1() =3D> new PB(); +-typedef PB2 F2(int blat); +-class Clz =3D Object with Object; +-class PB { }'''); +- addSource('/testCD.dart', ''' +-class C { } +-class D { }'''); +- addTestSource(''' +-import "/testAB.dart" show ^; +-import "/testCD.dart"; +-class X {}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_ConditionalExpression_elseExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T1 : T^}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_elseExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T1 : ^}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_partial_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T^}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_partial_thenExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? ^}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T^ : c}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_constructor_parameters_mixed_required_and_named() async { +- addTestSource('class A {A(x, {int y}) {^}}'); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- } +- +- test_constructor_parameters_mixed_required_and_positional() async { +- addTestSource('class A {A(x, [int y]) {^}}'); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- } +- +- test_constructor_parameters_named() async { +- addTestSource('class A {A({x, int y}) {^}}'); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- } +- +- test_constructor_parameters_positional() async { +- addTestSource('class A {A([x, int y]) {^}}'); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- } +- +- test_constructor_parameters_required() async { +- addTestSource('class A {A(x, int y) {^}}'); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- } +- +- test_ConstructorName_importedClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-var m; +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-var m; +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- main() {new String.fr^omCharCodes([]);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 13); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('fromCharCodes'); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('isNotEmpty'); +- assertNotSuggested('length'); +- assertNotSuggested('Object'); +- assertNotSuggested('String'); +- } +- +- test_ConstructorName_localClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}} +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_localFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +-int T1; +-F1() { } +-class X {factory X.c(); factory X._d(); z() {}} +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_DefaultFormalParameter_named_expression() async { +- // DefaultFormalParameter FormalParameterList MethodDeclaration +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {a(blat: ^) { }}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('String'); +- assertNotSuggested('identical'); +- assertNotSuggested('bar'); +- } +- +- test_enum() async { +- addTestSource('enum E { one, two } main() {^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- } +- +- test_enum_deprecated() async { +- addTestSource('@deprecated enum E { one, two } main() {^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- } +- +- test_ExpressionStatement_identifier() async { +- // SimpleIdentifier ExpressionStatement Block +- addSource('/testA.dart', ''' +-_B F1() { } +-class A {int x;} +-class _B { }'''); +- addTestSource(''' +-import "/testA.dart"; +-typedef int F2(int blat); +-class Clz =3D Object with Object; +-class C {foo(){^} void bar() {}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertNotSuggested('C'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('F2'); +- assertNotSuggested('Clz'); +- assertNotSuggested('C'); +- assertNotSuggested('x'); +- assertNotSuggested('_B'); +- } +- +- test_ExpressionStatement_name() async { +- // ExpressionStatement Block BlockFunctionBody MethodDeclaration +- addSource('/testA.dart', ''' +- B T1; +- class B{}'''); +- addTestSource(''' +- import "/testA.dart"; +- class C {a() {C ^}}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_typed() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "/testA.dart"; +- class C {A ^}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_var() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "/testA.dart"; +- class C {var ^}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_FieldFormalParameter_in_non_constructor() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource('class A {B(this.^foo) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 3); +- assertNoSuggestions(); +- } +- +- test_ForEachStatement_body_typed() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (int foo in bar) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_body_untyped() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (foo in bar) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_iterable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (int foo in ^) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_loopVariable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ in args) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('String'); +- } +- +- test_ForEachStatement_loopVariable_type() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ foo in args) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('String'); +- } +- +- test_ForEachStatement_loopVariable_type2() async { +- // DeclaredIdentifier ForEachStatement Block +- addTestSource('main(args) {for (S^ foo in args) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('String'); +- } +- +- test_FormalParameterList() async { +- // FormalParameterList MethodDeclaration +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {a(^) { }}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('String'); +- assertNotSuggested('identical'); +- assertNotSuggested('bar'); +- } +- +- test_ForStatement_body() async { +- // Block ForStatement +- addTestSource('main(args) {for (int i; i < 10; ++i) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('i'); +- assertNotSuggested('Object'); +- } +- +- test_ForStatement_condition() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; i^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- } +- +- test_ForStatement_initializer() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {List a; for (^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('int'); +- } +- +- test_ForStatement_updaters() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; index < 10; i^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- } +- +- test_ForStatement_updaters_prefix_expression() async { +- // SimpleIdentifier PrefixExpression ForStatement +- addTestSource(''' +-void bar() { } +-main() {for (int index =3D 0; index < 10; ++i^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- assertNotSuggested('main'); +- assertNotSuggested('bar'); +- } +- +- test_function_parameters_mixed_required_and_named() async { +- addTestSource(''' +-void m(x, {int y}) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_function_parameters_mixed_required_and_positional() async { +- addTestSource(''' +-void m(x, [int y]) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_function_parameters_named() async { +- addTestSource(''' +-void m({x, int y}) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_function_parameters_none() async { +- addTestSource(''' +-void m() {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_function_parameters_positional() async { +- addTestSource(''' +-void m([x, int y]) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_function_parameters_required() async { +- addTestSource(''' +-void m(x, int y) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_FunctionDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-/* */ ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment2() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-/** */ ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment3() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-/// some dartdoc +-class C2 { } +-^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionExpression_body_function() async { +- // Block BlockFunctionBody FunctionExpression +- addTestSource(''' +- void bar() { } +- String foo(List args) {x.then((R b) {^});}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('args'); +- assertNotSuggested('b'); +- assertNotSuggested('Object'); +- } +- +- test_IfStatement() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (true) ^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_condition() async { +- // SimpleIdentifier IfStatement Block BlockFunctionBody +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main(){var a; if (^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_IfStatement_empty() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (^) something}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_invocation() async { +- // SimpleIdentifier PrefixIdentifier IfStatement +- addTestSource(''' +-main() {var a; if (a.^) something}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('toString'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ignore_symbol_being_completed() async { +- addTestSource('class MyClass { } main(MC^) { }'); +- await computeSuggestions(); +- assertNotSuggested('MyClass'); +- assertNotSuggested('MC'); +- } +- +- test_ImportDirective_dart() async { +- // SimpleStringLiteral ImportDirective +- addTestSource(''' +-import "dart^"; +-main() {}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_inDartDoc_reference1() async { +- addTestSource(''' +-/// The [^ +-main(aaa, bbb) {}'''); +- await computeSuggestions(); +- assertNotSuggested('main'); +- } +- +- test_inDartDoc_reference2() async { +- addTestSource(''' +-/// The [m^ +-main(aaa, bbb) {}'''); +- await computeSuggestions(); +- assertNotSuggested('main'); +- } +- +- test_inDartDoc_reference3() async { +- addTestSource(''' +-/// The [^] +-main(aaa, bbb) {}'''); +- await computeSuggestions(); +- assertNotSuggested('main'); +- } +- +- test_inDartDoc_reference4() async { +- addTestSource(''' +-/// The [m^] +-main(aaa, bbb) {}'''); +- await computeSuggestions(); +- assertNotSuggested('main'); +- } +- +- test_IndexExpression() async { +- // ExpressionStatement Block +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} f[^]}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_IndexExpression2() async { +- // SimpleIdentifier IndexExpression ExpressionStatement Block +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} f[T^]}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_InstanceCreationExpression() async { +- addTestSource(''' +-class A {foo(){var f; {var x;}}} +-class B {B(this.x, [String boo]) { } int x;} +-class C {C.bar({boo: 'hoo', int z: 0}) { } } +-main() {new ^ String x =3D "hello";}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion; +- +- suggestion =3D assertSuggestConstructor('A', elemOffset: -1); +- expect(suggestion.element.parameters, '()'); +- expect(suggestion.element.returnType, 'A'); +- expect(suggestion.declaringType, 'A'); +- expect(suggestion.parameterNames, hasLength(0)); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- +- suggestion =3D assertSuggestConstructor('B'); +- expect(suggestion.element.parameters, '(int x, [String boo])'); +- expect(suggestion.element.returnType, 'B'); +- expect(suggestion.declaringType, 'B'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'int'); +- expect(suggestion.parameterNames[1], 'boo'); +- expect(suggestion.parameterTypes[1], 'String'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- +- suggestion =3D assertSuggestConstructor('C.bar'); +- expect(suggestion.element.parameters, '({dynamic boo: \'hoo\', int z:= 0})'); +- expect(suggestion.element.returnType, 'C'); +- expect(suggestion.declaringType, 'C'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'boo'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'z'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_InstanceCreationExpression_assignment_expression_filter() async { +- addTestSource(''' +-class A {} class B extends A {} class C implements A {} class D {} +-main() { +- A a; +- a =3D new ^ +-}'''); +- await computeSuggestions(); +- +- assertSuggestConstructor('A', +- elemOffset: -1, +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestConstructor('B', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertSuggestConstructor('C', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertNotSuggested('D'); +- } +- +- test_InstanceCreationExpression_assignment_expression_filter2() async { +- addTestSource(''' +-class A {} class B extends A {} class C implements A {} class D {} +-main() { +- A a; +- a =3D new ^; +-}'''); +- await computeSuggestions(); +- +- assertSuggestConstructor('A', +- elemOffset: -1, +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestConstructor('B', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertSuggestConstructor('C', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertNotSuggested('D'); +- } +- +- test_InstanceCreationExpression_imported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {A(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-import "dart:async"; +-int T2; +-F2() { } +-class B {B(this.x, [String boo]) { } int x;} +-class C {foo(){var f; {var x;} new ^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('Future'); +- assertNotSuggested('A'); +- assertSuggestConstructor('B'); +- assertSuggestConstructor('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('foo'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- } +- +- test_InstanceCreationExpression_unimported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){new F^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('Future'); +- assertNotSuggested('Foo'); +- } +- +- test_InstanceCreationExpression_variable_declaration_filter() async { +- addTestSource(''' +-class A {} class B extends A {} class C implements A {} class D {} +-main() { +- A a =3D new ^ +-}'''); +- await computeSuggestions(); +- +- assertSuggestConstructor('A', +- elemOffset: -1, +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestConstructor('B', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertSuggestConstructor('C', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertNotSuggested('D'); +- } +- +- test_InstanceCreationExpression_variable_declaration_filter2() async { +- addTestSource(''' +-class A {} class B extends A {} class C implements A {} class D {} +-main() { +- A a =3D new ^; +-}'''); +- await computeSuggestions(); +- +- assertSuggestConstructor('A', +- elemOffset: -1, +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestConstructor('B', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertSuggestConstructor('C', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertNotSuggested('D'); +- } +- +- test_InterpolationExpression() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-main() {String name; print("hello \$^");}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_InterpolationExpression_block() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-main() {String name; print("hello \${^}");}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_InterpolationExpression_block2() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addTestSource('main() {String name; print("hello \${n^}");}'); +- await computeSuggestions(); +- +- assertNotSuggested('name'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- } +- +- test_InterpolationExpression_prefix_selector() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${name.^}");}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('length'); +- assertNotSuggested('name'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_InterpolationExpression_prefix_selector2() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \$name.^");}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_InterpolationExpression_prefix_target() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${nam^e.length}");}= '); +- await computeSuggestions(); +- +- assertNotSuggested('name'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- assertNotSuggested('length'); +- } +- +- test_IsExpression() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addSource('/testB.dart', ''' +-lib B; +-foo() { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-class Y {Y.c(); Y._d(); z() {}} +-main() {var x; if (x is ^) { }}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('x'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- } +- +- test_IsExpression_target() async { +- // IfStatement Block BlockFunctionBody +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {int x; int y() =3D> 0;} +-main(){var a; if (^ is A)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main(){var a; if (a is ^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type_partial() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main(){var a; if (a is Obj^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_keyword() async { +- addSource('/testB.dart', ''' +-lib B; +-int newT1; +-int T1; +-nowIsIt() { } +-class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-String newer() {} +-var m; +-main() {new^ X.c();}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- // Imported suggestion are filtered by 1st character +- assertNotSuggested('nowIsIt'); +- assertNotSuggested('T1'); +- assertNotSuggested('newT1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- assertNotSuggested('newer'); +- } +- +- test_Literal_list() async { +- // ']' ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([^]);}'); +- await computeSuggestions(); +- +- assertNotSuggested('Some'); +- assertNotSuggested('String'); +- } +- +- test_Literal_list2() async { +- // SimpleIdentifier ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([S^]);}'); +- await computeSuggestions(); +- +- assertNotSuggested('Some'); +- assertNotSuggested('String'); +- } +- +- test_Literal_string() async { +- // SimpleStringLiteral ExpressionStatement Block +- addTestSource('class A {a() {"hel^lo"}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_localVariableDeclarationName() async { +- addTestSource('main() {String m^}'); +- await computeSuggestions(); +- +- assertNotSuggested('main'); +- assertNotSuggested('min'); +- } +- +- test_MapLiteralEntry() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-foo =3D {^'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- } +- +- test_MapLiteralEntry1() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-foo =3D {T^'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- } +- +- test_MapLiteralEntry2() async { +- // SimpleIdentifier MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-foo =3D {7:T^};'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- } +- +- test_method_parameters_mixed_required_and_named() async { +- addTestSource(''' +-class A { +- void m(x, {int y}) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_mixed_required_and_positional() async { +- addTestSource(''' +-class A { +- void m(x, [int y]) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_named() async { +- addTestSource(''' +-class A { +- void m({x, int y}) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_none() async { +- addTestSource(''' +-class A { +- void m() {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_positional() async { +- addTestSource(''' +-class A { +- void m([x, int y]) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_required() async { +- addTestSource(''' +-class A { +- void m(x, int y) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_MethodDeclaration_body_getters() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X get f =3D> 0; Z a() {^} get _g = =3D> 1;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- } +- +- test_MethodDeclaration_body_static() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testC.dart', ''' +-class C { +- c1() {} +- var c2; +- static c3() {} +- static var c4;}'''); +- addTestSource(''' +-import "/testC.dart"; +-class B extends C { +- b1() {} +- var b2; +- static b3() {} +- static var b4;} +-class A extends B { +- a1() {} +- var a2; +- static a3() {} +- static var a4; +- static a() {^}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('a1'); +- assertNotSuggested('a2'); +- assertNotSuggested('a3'); +- assertNotSuggested('a4'); +- assertNotSuggested('b1'); +- assertNotSuggested('b2'); +- assertNotSuggested('b3'); +- assertNotSuggested('b4'); +- assertNotSuggested('c1'); +- assertNotSuggested('c2'); +- assertNotSuggested('c3'); +- assertNotSuggested('c4'); +- } +- +- test_MethodDeclaration_members() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X f; Z _a() {^} var _g;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('_a'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('bool'); +- } +- +- test_MethodDeclaration_parameters_named() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated Z a(X x, _, b, {y: boo}) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('b'); +- assertNotSuggested('int'); +- assertNotSuggested('_'); +- } +- +- test_MethodDeclaration_parameters_positional() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {Z a(X x, [int y=3D1]) {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('String'); +- } +- +- test_MethodDeclaration_returnType() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 {^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 {/* */ ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment2() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 {/** */ ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment3() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { +- /// some dartdoc +- ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodInvocation_no_semicolon() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {x.^ m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_missing_params_constructor() async { +- addTestSource('class C1{C1{} main(){C^}}'); +- await computeSuggestions(); +- } +- +- test_missing_params_function() async { +- addTestSource('int f1{} main(){f^}'); +- await computeSuggestions(); +- } +- +- test_missing_params_method() async { +- addTestSource('class C1{int f1{} main(){f^}}'); +- await computeSuggestions(); +- } +- +- test_new_instance() async { +- addTestSource('import "dart:math"; class A {x() {new Random().^}}'); +- await computeSuggestions(); +- +- assertNotSuggested('nextBool'); +- assertNotSuggested('nextDouble'); +- assertNotSuggested('nextInt'); +- assertNotSuggested('Random'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- } +- +- test_overrides() async { +- addTestSource(''' +-class A {m() {}} +-class B extends A {m() {^}} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_parameterName_excludeTypes() async { +- addTestSource('m(int ^) {}'); +- await computeSuggestions(); +- +- assertNotSuggested('int'); +- assertNotSuggested('bool'); +- } +- +- test_partFile_TypeName() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +-library libA; +-import "/testB.dart"; +-part "$testFile"; +-class A { } +-var m;'''); +- addTestSource(''' +-part of libA; +-class B { factory B.bar(int x) =3D> null; } +-main() {new ^}'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestConstructor('B.bar'); +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_TypeName2() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +-part of libA; +-class B { }'''); +- addTestSource(''' +-library libA; +-import "/testB.dart"; +-part "/testA.dart"; +-class A { A({String boo: 'hoo'}) { } } +-main() {new ^} +-var m;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestConstructor('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('B'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_PrefixedIdentifier_class_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block +- addSource('/testB.dart', ''' +-lib B; +-class I { +- static const scI =3D 'boo'; +- X get f =3D> new A(); +- get _g =3D> new A();} +-class B implements I { +- static const int scB =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- addTestSource(''' +-import "/testB.dart"; +-class A extends B { +- static const String scA =3D 'foo'; +- w() { }} +-main() {A.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by StaticMemberContributor +- assertNotSuggested('scA'); +- assertNotSuggested('scB'); +- assertNotSuggested('scI'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('w'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_imported() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +-lib B; +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- static const int sc =3D 12; +- @deprecated var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- addTestSource(''' +-import "/testB.dart"; +-main() {A a; a.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_local() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-main() {A a; a.^} +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- static const int sc =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_library() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +-lib B; +-var T1; +-class X { } +-class Y { }'''); +- addTestSource(''' +-import "/testB.dart" as b; +-var T2; +-class A { } +-main() {b.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +-lib B; +-var T1; +-class X { } +-class Y { }'''); +- addTestSource(''' +-import "/testB.dart" as b; +-var T2; +-class A { } +-foo(b.^ f) {}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +-lib B; +-var T1; +-class X { } +-class Y { }'''); +- addTestSource(''' +-import "/testB.dart" as b; +-var T2; +-class A { } +-foo(b.^) {}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_parameter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +-lib B; +-class _W {M y; var _z;} +-class X extends _W {} +-class M{}'''); +- addTestSource(''' +-import "/testB.dart"; +-foo(X x) {x.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('y'); +- assertNotSuggested('_z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_prefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testA.dart', ''' +-class A {static int bar =3D 10;} +-_B() {}'''); +- addTestSource(''' +-import "/testA.dart"; +-class X {foo(){A^.bar}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('_B'); +- } +- +- test_PrefixedIdentifier_propertyAccess() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('compareTo'); +- } +- +- test_PrefixedIdentifier_propertyAccess_newStmt() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('compareTo'); +- } +- +- test_PrefixedIdentifier_trailingStmt_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('const String g =3D "hello"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_field() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g; f() {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_function() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g() =3D> "one"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_functionTypeAlias() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('typedef String g(); f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_typed() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {String g; g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_untyped() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {var g =3D "hello"; g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_method() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g() {}; f() {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {f(String g) {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param2() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f(String g) {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_topLevelVar() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_prioritization() async { +- addTestSource('main() {var ab; var _ab; ^}'); +- await computeSuggestions(); +- assertNotSuggested('ab'); +- assertNotSuggested('_ab'); +- } +- +- test_prioritization_private() async { +- addTestSource('main() {var ab; var _ab; _^}'); +- await computeSuggestions(); +- assertNotSuggested('ab'); +- assertNotSuggested('_ab'); +- } +- +- test_prioritization_public() async { +- addTestSource('main() {var ab; var _ab; a^}'); +- await computeSuggestions(); +- assertNotSuggested('ab'); +- assertNotSuggested('_ab'); +- } +- +- test_PropertyAccess_expression() async { +- // SimpleIdentifier MethodInvocation PropertyAccess ExpressionStat= ement +- addTestSource('class A {a() {"hello".to^String().length}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 8); +- assertNotSuggested('length'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PropertyAccess_noTarget() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){.^}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_noTarget2() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('main() {.^}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_selector() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement Block +- addTestSource('class A {a() {"hello".length.^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEven'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_shadowed_name() async { +- addTestSource('var a; class A { var a; m() { ^ } }'); +- await computeSuggestions(); +- assertNotSuggested('a'); +- } +- +- test_SwitchStatement_c() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {c^}}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_SwitchStatement_case() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {var t; switch(x) {case 0: ^}= }}'); +- await computeSuggestions(); +- +- assertNotSuggested('A'); +- assertNotSuggested('g'); +- assertNotSuggested('t'); +- assertNotSuggested('String'); +- } +- +- test_SwitchStatement_empty() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {^}}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_ThisExpression_block() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A() {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {this.^ m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A() {this.^} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.^) {} +- A.z() {} +- var b; X _c; static sb; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('sb'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param2() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.b^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param3() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.^b) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param4() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.b, this.^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_TopLevelVariableDeclaration_typed_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} B ^'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_TopLevelVariableDeclaration_untyped_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} var ^'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_TypeArgumentList() async { +- // SimpleIdentifier BinaryExpression ExpressionStatement +- addSource('/testA.dart', ''' +-class C1 {int x;} +-F1() =3D> 0; +-typedef String T1(int blat);'''); +- addTestSource(''' +-import "/testA.dart";' +-class C2 {int x;} +-F2() =3D> 0; +-typedef int T2(int blat); +-class C {} +-main() { C<^> c; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('C1'); +- assertNotSuggested('T1'); +- assertNotSuggested('C2'); +- assertNotSuggested('T2'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- } +- +- test_TypeArgumentList2() async { +- // TypeName TypeArgumentList TypeName +- addSource('/testA.dart', ''' +-class C1 {int x;} +-F1() =3D> 0; +-typedef String T1(int blat);'''); +- addTestSource(''' +-import "/testA.dart";' +-class C2 {int x;} +-F2() =3D> 0; +-typedef int T2(int blat); +-class C {} +-main() { C c; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('C1'); +- assertNotSuggested('C2'); +- } +- +- test_VariableDeclaration_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addSource('/testB.dart', ''' +-lib B; +-foo() { } +-class _B { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-class Y {Y.c(); Y._d(); z() {}} +-main() {var ^}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_VariableDeclarationList_final() async { +- // VariableDeclarationList VariableDeclarationStatement Block +- addTestSource('main() {final ^} class C { }'); +- await computeSuggestions(); +- +- assertNotSuggested('Object'); +- assertNotSuggested('C'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_VariableDeclarationStatement_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +-lib B; +-foo() { } +-class _B { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-class Y {Y.c(); Y._d(); z() {}} +-class C {bar(){var f; {var x;} var e =3D ^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('_B'); +- assertNotSuggested('Y'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +- +- test_VariableDeclarationStatement_RHS_missing_semicolon() async { +- // VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +-lib B; +-foo1() { } +-void bar1() { } +-class _B { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-foo2() { } +-void bar2() { } +-class Y {Y.c(); Y._d(); z() {}} +-class C {bar(){var f; {var x;} var e =3D ^ var g}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('foo1'); +- assertNotSuggested('bar1'); +- assertNotSuggested('foo2'); +- assertNotSuggested('bar2'); +- assertNotSuggested('_B'); +- assertNotSuggested('Y'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/local_libra= ry_contributor_test.dart b/pkg/analysis_server/test/services/completion/dar= t/local_library_contributor_test.dart +deleted file mode 100644 +index 9d776dce62e..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/local_library_cont= ributor_test.dart ++++ /dev/null +@@ -1,282 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_librar= y_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LocalLibraryContributorTest); +- }); +-} +- +-@reflectiveTest +-class LocalLibraryContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new LocalLibraryContributor(); +- } +- +- test_partFile_Constructor() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- library libA; +- import "/testB.dart"; +- part "$testFile"; +- class A { } +- var m;'''); +- addTestSource(''' +- part of libA; +- class B { factory B.bar(int x) =3D> null; } +- main() {new ^}'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestConstructor('A'); +- // Suggested by LocalConstructorContributor +- assertNotSuggested('B.bar'); +- // Suggested by ImportedReferenceContributor +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_Constructor2() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- part of libA; +- class B { }'''); +- addTestSource(''' +- library libA; +- import "/testB.dart"; +- part "/testA.dart"; +- class A { A({String boo: 'hoo'}) { } } +- main() {new ^} +- var m;'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestConstructor('B'); +- // Suggested by ConstructorContributor +- assertNotSuggested('A'); +- // Suggested by ImportedReferenceContributor +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_InstanceCreationExpression_assignment_filter() async { +- // ConstructorName InstanceCreationExpression VariableDeclarationLi= st +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- part of libA; +- class A {} class B extends A {} class C implements A {} class D {} +- '''); +- addTestSource(''' +- library libA; +- import "/testB.dart"; +- part "/testA.dart"; +- class Local { } +- main() { +- A a; +- // FAIL: +- a =3D new ^ +- } +- var m;'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // A is suggested with a higher relevance +- assertSuggestConstructor('A', +- elemOffset: -1, +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestConstructor('B', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertSuggestConstructor('C', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- // D is sorted out +- assertNotSuggested('D'); +- +- // Suggested by ConstructorContributor +- assertNotSuggested('Local'); +- +- // Suggested by ImportedReferenceContributor +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_InstanceCreationExpression_variable_declaration_filter() = async { +- // ConstructorName InstanceCreationExpression VariableDeclarationLi= st +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- part of libA; +- class A {} class B extends A {} class C implements A {} class D {} +- '''); +- addTestSource(''' +- library libA; +- import "/testB.dart"; +- part "/testA.dart"; +- class Local { } +- main() { +- A a =3D new ^ +- } +- var m;'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // A is suggested with a higher relevance +- assertSuggestConstructor('A', +- elemOffset: -1, +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestConstructor('B', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- assertSuggestConstructor('C', +- elemOffset: -1, relevance: DART_RELEVANCE_DEFAULT); +- // D is sorted out +- assertNotSuggested('D'); +- +- // Suggested by ConstructorContributor +- assertNotSuggested('Local'); +- +- // Suggested by ImportedReferenceContributor +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_TypeName() async { +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- library libA; +- import "/testB.dart"; +- part "$testFile"; +- class A { var a1; a2(){}} +- var m; +- typedef t1(int blue); +- int af() {return 0;}'''); +- addTestSource(''' +- part of libA; +- class B { factory B.bar(int x) =3D> null; } +- main() {^}'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestFunction('af', 'int', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestTopLevelVar('m', null, +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestFunctionTypeAlias('t1', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('a1'); +- assertNotSuggested('a2'); +- // Suggested by LocalConstructorContributor +- assertNotSuggested('B.bar'); +- // Suggested by ImportedReferenceContributor +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- } +- +- test_partFile_TypeName2() async { +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- part of libA; +- class B { var b1; b2(){}} +- int bf() =3D> 0; +- typedef t1(int blue); +- var n;'''); +- addTestSource(''' +- library libA; +- import "/testB.dart"; +- part "/testA.dart"; +- class A { A({String boo: 'hoo'}) { } } +- main() {^} +- var m;'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestFunction('bf', 'int', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestTopLevelVar('n', null, +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestFunctionTypeAlias('t1', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('b1'); +- assertNotSuggested('b2'); +- // Suggested by ConstructorContributor +- assertNotSuggested('A'); +- // Suggested by ImportedReferenceContributor +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/local_refer= ence_contributor_test.dart b/pkg/analysis_server/test/services/completion/d= art/local_reference_contributor_test.dart +deleted file mode 100644 +index 64f561ff66f..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/local_reference_co= ntributor_test.dart ++++ /dev/null +@@ -1,4585 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/local_refere= nce_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LocalReferenceContributorTest); +- }); +-} +- +-@reflectiveTest +-class LocalReferenceContributorTest extends DartCompletionContributorTest= { +- CompletionSuggestion assertSuggestLocalVariable( +- String name, String returnType, +- {int relevance: DART_RELEVANCE_LOCAL_VARIABLE}) { +- // Local variables should only be suggested by LocalReferenceContribu= tor +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: CompletionSuggestionKind.INVOCATION, relevance: relevance= ); +- expect(cs.returnType, returnType !=3D null ? returnType : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.LOCAL_VARIABLE)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, returnType !=3D null ? returnType : 'dynam= ic'); +- assertHasNoParameterInfo(cs); +- return cs; +- } +- +- CompletionSuggestion assertSuggestParameter(String name, String returnT= ype, +- {int relevance: DART_RELEVANCE_PARAMETER}) { +- CompletionSuggestion cs =3D assertSuggest(name, +- csKind: CompletionSuggestionKind.INVOCATION, relevance: relevance= ); +- expect(cs.returnType, returnType !=3D null ? returnType : 'dynamic'); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.PARAMETER)); +- expect(element.name, equals(name)); +- expect(element.parameters, isNull); +- expect(element.returnType, +- equals(returnType !=3D null ? returnType : 'dynamic')); +- return cs; +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new LocalReferenceContributor(); +- } +- +- test_ArgDefaults_function() async { +- addTestSource(''' +-bool hasLength(int a, bool b) =3D> false; +-void main() {h^}'''); +- await computeSuggestions(); +- +- assertSuggestFunction('hasLength', 'bool', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION, +- defaultArgListString: 'a, b', +- defaultArgumentListTextRanges: [0, 1, 3, 1]); +- } +- +- test_ArgDefaults_function_none() async { +- addTestSource(''' +-bool hasLength() =3D> false; +-void main() {h^}'''); +- await computeSuggestions(); +- +- assertSuggestFunction('hasLength', 'bool', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION, +- defaultArgListString: null, +- defaultArgumentListTextRanges: null); +- } +- +- test_ArgDefaults_function_with_optional_positional() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +- +-bool foo(int bar, [bool boo, int baz]) =3D> false; +-void main() {h^}'''); +- await computeSuggestions(); +- +- assertSuggestFunction('foo', 'bool', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION, +- defaultArgListString: 'bar', +- defaultArgumentListTextRanges: [0, 3]); +- } +- +- test_ArgDefaults_function_with_required_named() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +- +-bool foo(int bar, {bool boo, @required int baz}) =3D> false; +-void main() {h^}'''); +- await computeSuggestions(); +- +- assertSuggestFunction('foo', 'bool', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION, +- defaultArgListString: 'bar, baz: null', +- defaultArgumentListTextRanges: [0, 3, 10, 4]); +- } +- +- test_ArgDefaults_method_with_required_named() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +- +-class A { +- bool foo(int bar, {bool boo, @required int baz}) =3D> false; +- baz() { +- f^ +- } +-}'''); +- await computeSuggestions(); +- +- assertSuggestMethod('foo', 'A', 'bool', +- relevance: DART_RELEVANCE_LOCAL_METHOD, +- defaultArgListString: 'bar, baz: null', +- defaultArgumentListTextRanges: [0, 3, 10, 4]); +- } +- +- test_ArgumentList() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart'; +-class B { } +-String bar() =3D> true; +-void main() {expect(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_imported_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-expect(arg) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart' +-class B { } +-String bar() =3D> true; +-void main() {expect(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_functionalArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar() =3D> true; +-void main() {new A(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_typedefArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +-library A; +-typedef Funct(); +-class A { A(Funct f) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar() =3D> true; +-void main() {new A(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart' +-expect(arg) { } +-class B { } +-String bar() =3D> true; +-void main() {expect(^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_method() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import '/libA.dart' +-class B { +- expect(arg) { } +- void foo() {expect(^)}} +-String bar() =3D> true;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_functionalArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar(f()) =3D> true; +-void main() {boo(){} bar(^);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestFunction('boo', 'dynamic', +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_functionalArg2() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { } +-String bar({inc()}) =3D> true; +-void main() {boo(){} bar(inc: ^);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertSuggestFunction('bar', 'String', +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION + DART_RELEVANCE_INCREME= NT); +- assertSuggestFunction('boo', 'dynamic', +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION + DART_RELEVANCE_INCREME= NT); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_methodArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +-library A; +-class A { A(f()) { } } +-bool hasLength(int expected) { } +-void baz() { }'''); +- addTestSource(''' +-import 'dart:async'; +-import '/libA.dart'; +-class B { String bar(f()) =3D> true; } +-void main() {new B().bar(^);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_namedFieldParam_tear_off() async { +- addSource('/libA.dart', ''' +-typedef void VoidCallback(); +-=20=20=20=20=20=20=20=20 +-class Button { +- final VoidCallback onPressed; +- Button({this.onPressed}); +-} +-'''); +- addTestSource(''' +-import '/libA.dart'; +- +-class PageState { +- void _incrementCounter() { } +- build() =3D> +- new Button( +- onPressed: ^ +- );=20=20 +-}=20=20=20=20 +-'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggest('_incrementCounter', +- csKind: CompletionSuggestionKind.IDENTIFIER); +- } +- +- test_ArgumentList_namedParam() async { +- // SimpleIdentifier NamedExpression ArgumentList MethodInvocation +- // ExpressionStatement +- addSource('/libA.dart', ''' +-library A; +-bool hasLength(int expected) { }'''); +- addTestSource(''' +-import '/libA.dart' +-String bar() =3D> true; +-void main() {expect(foo: ^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestFunction('bar', 'String', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('hasLength'); +- assertNotSuggested('main'); +- } +- +- test_ArgumentList_namedParam_filter() async { +- // SimpleIdentifier NamedExpression ArgumentList +- // InstanceCreationExpression +- addTestSource(''' +- class A {} +- class B extends A {} +- class C implements A {} +- class D {} +- class E { +- A a; +- E({A someA}); +- } +- A a =3D new A(); +- B b =3D new B(); +- C c =3D new C(); +- D d =3D new D(); +- E e =3D new E(someA: ^); +- '''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestTopLevelVar('a', 'A', +- relevance: +- DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE + DART_RELEVANCE_INCR= EMENT); +- assertSuggestTopLevelVar('b', 'B', +- relevance: +- DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE + DART_RELEVANCE_INCR= EMENT); +- assertSuggestTopLevelVar('c', 'C', +- relevance: +- DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE + DART_RELEVANCE_INCR= EMENT); +- assertSuggestTopLevelVar('d', 'D', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestTopLevelVar('e', 'E', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- } +- +- test_ArgumentList_namedParam_tear_off() async { +- addSource('/libA.dart', ''' +-typedef void VoidCallback(); +-=20=20=20=20=20=20=20=20 +-class Button { +- Button({VoidCallback onPressed}); +-} +-'''); +- addTestSource(''' +-import '/libA.dart'; +- +-class PageState { +- void _incrementCounter() { } +- build() =3D> +- new Button( +- onPressed: ^ +- );=20=20 +-}=20=20=20=20 +-'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggest('_incrementCounter', +- csKind: CompletionSuggestionKind.IDENTIFIER); +- } +- +- test_ArgumentList_namedParam_tear_off_1() async { +- addSource('/libA.dart', ''' +-typedef void VoidCallback(); +-=20=20=20=20=20=20=20=20 +-class Button { +- Button({VoidCallback onPressed, int x}); +-} +-'''); +- addTestSource(''' +-import '/libA.dart'; +- +-class PageState { +- void _incrementCounter() { } +- build() =3D> +- new Button( +- onPressed: ^ +- );=20=20 +-}=20=20=20=20 +-'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggest('_incrementCounter', +- csKind: CompletionSuggestionKind.IDENTIFIER); +- } +- +- test_ArgumentList_namedParam_tear_off_2() async { +- addSource('/libA.dart', ''' +-typedef void VoidCallback(); +-=20=20=20=20=20=20=20=20 +-class Button { +- Button({ int x, VoidCallback onPressed); +-} +-'''); +- addTestSource(''' +-import '/libA.dart'; +- +-class PageState { +- void _incrementCounter() { } +- build() =3D> +- new Button( +- onPressed: ^ +- );=20=20 +-}=20=20=20=20 +-'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggest('_incrementCounter', +- csKind: CompletionSuggestionKind.IDENTIFIER); +- } +- +- test_AsExpression_type() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +- class A {var b; X _c; foo() {var a; (a as ^).foo();}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertSuggestClass('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_AsExpression_type_filter_extends() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +-class A {} class B extends A {} class C extends A {} class D {} +-f(A a){ (a as ^) }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('D'); +- assertNotSuggested('Object'); +- } +- +- test_AsExpression_type_filter_implements() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +-class A {} class B implements A {} class C implements A {} class D {} +-f(A a){ (a as ^) }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('D'); +- assertNotSuggested('Object'); +- } +- +- test_AsExpression_type_filter_undefined_type() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +-class A {} +-f(U u){ (u as ^) }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- } +- +- test_AssignmentExpression_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int ^b =3D 1;}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_AssignmentExpression_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int b =3D ^}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('a', 'int'); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_AssignmentExpression_type() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- ^ b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertNotSuggested('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- ^ +- b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertNotSuggested('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertSuggestLocalVariable('a', 'int'); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- int^ b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertSuggestClass('A'); +- assertNotSuggested('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +-class A {} main() { +- int a; +- i^ +- b =3D 1; +-}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestClass('A'); +- assertNotSuggested('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertSuggestLocalVariable('a', 'int'); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('identical'); +- } +- +- test_AwaitExpression() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main() async {A a; await ^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('a', 'A'); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_AwaitExpression2() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- addTestSource(''' +- class A { +- int x; +- Future y() async {return 0;} +- foo() async {await ^ await y();} +- } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestMethod('y', 'A', 'Future', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_BinaryExpression_LHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D ^ + 2;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('a', 'int'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- } +- +- test_BinaryExpression_RHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D 2 + ^;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('a', 'int'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- ^ var r; +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggestClass('X', elemFile: testFile); +- assertSuggestClass('Z'); +- assertSuggestMethod('a', 'X', null, relevance: DART_RELEVANCE_LOCAL_M= ETHOD); +- assertSuggestMethod('b', 'X', 'void', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestFunction('localF', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestLocalVariable('f', null); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertSuggestFunction('D2', 'Z', relevance: DART_RELEVANCE_LOCAL_FUNC= TION); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertSuggestTopLevelVar('T5', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestTopLevelVar('_T6', null, relevance: DART_RELEVANCE_DEFAU= LT); +- assertNotSuggested('=3D=3D'); +- assertSuggestGetter('T7', 'String', +- relevance: DART_RELEVANCE_LOCAL_ACCESSOR); +- assertSuggestSetter('T8', relevance: DART_RELEVANCE_LOCAL_ACCESSOR); +- assertSuggestGetter('clog', 'int', +- relevance: DART_RELEVANCE_LOCAL_ACCESSOR); +- assertSuggestSetter('blog', relevance: DART_RELEVANCE_LOCAL_ACCESSOR); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- final ^ +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggestClass('X'); +- assertSuggestClass('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final2() async { +- addTestSource('main() {final S^ v;}'); +- await computeSuggestions(); +- +- assertNotSuggested('String'); +- } +- +- test_Block_final3() async { +- addTestSource('main() {final ^ v;}'); +- await computeSuggestions(); +- +- assertNotSuggested('String'); +- } +- +- test_Block_final_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- final var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggestClass('X'); +- assertSuggestClass('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final_var() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertSuggestClass('X'); +- assertSuggestClass('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_identifier_partial() async { +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B { }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-class D3 { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-Z D2() {int x;} +-class X {a() {var f; {var x;} D^ var r;} void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertSuggestClass('X'); +- assertSuggestClass('Z'); +- assertSuggestMethod('a', 'X', null, relevance: DART_RELEVANCE_LOCAL_M= ETHOD); +- assertSuggestMethod('b', 'X', 'void', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestLocalVariable('f', null); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- +- // imported elements are portially filtered +- //assertNotSuggested('A'); +- assertNotSuggested('_B'); +- //assertNotSuggested('C'); +- // hidden element suggested as low relevance +- assertNotSuggested('D'); +- assertNotSuggested('D1'); +- assertSuggestFunction('D2', 'Z', relevance: DART_RELEVANCE_LOCAL_FUNC= TION); +- // unimported elements suggested with low relevance +- assertNotSuggested('D3'); +- //assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- //assertSuggestLibraryPrefix('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- //assertNotSuggested('Object'); +- //assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- //assertSuggestTopLevelVarGetterSetter('T1', 'String'); +- assertNotSuggested('_T2'); +- //assertNotSuggested('T3'); +- assertNotSuggested('_T4'); +- //assertSuggestTopLevelVar('T5', 'int', relevance: DART_RELEVANCE_LOC= AL_TOP_LEVEL_VARIABLE); +- //assertSuggestTopLevelVar('_T6', null); +- assertNotSuggested('=3D=3D'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- } +- +- test_Block_inherited_imported() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- resolveSource('/testB.dart', ''' +-lib B; +-class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } var _pf; } +-class E extends F { var e1; e2() { } } +-class I { int i1; i2() { } } +-class M { var m1; int m2() { } }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // TODO (danrubel) prefer fields over getters +- // If add `get e1;` to interface I +- // then suggestions include getter e1 rather than field e1 +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- //assertNotSuggested('m2'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block_inherited_local() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addTestSource(''' +-class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } } +-class E extends F { var e1; e2() { } } +-class I { int i1; i2() { } } +-class M { var m1; int m2() { } } +-class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- assertNotSuggested('m2'); +- } +- +- test_Block_local_function() async { +- addSource('/testAB.dart', ''' +-export "dart:math" hide max; +-class A {int x;} +-@deprecated D1() {int x;} +-class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +-String T1; +-var _T2; +-class C { } +-class D { }'''); +- addSource('/testEEF.dart', ''' +-class EE { } +-class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +-class H { } +-int T3; +-var _T4;'''); // not imported +- addTestSource(''' +-import "/testAB.dart"; +-import "/testCD.dart" hide D; +-import "/testEEF.dart" show EE; +-import "/testG.dart" as g; +-int T5; +-var _T6; +-String get T7 =3D> 'hello'; +-set T8(int value) { partT8() {} } +-Z D2() {int x;} +-class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- p^ var r; +- } +- void b() { }} +-class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertNotSuggested('partT8'); +- assertNotSuggested('partBoo'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_unimported() async { +- addPackageSource('myBar', 'bar.dart', 'class Foo2 { Foo2() { } }'); +- addSource( +- '/proj/testAB.dart', 'import "package:myBar/bar.dart"; class Foo = { }'); +- testFile =3D '/proj/completionTest.dart'; +- addTestSource('class C {foo(){F^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('Foo'); +- // TODO(danrubel) implement +- assertNotSuggested('Foo2'); +- assertNotSuggested('Future'); +- } +- +- test_CascadeExpression_selector1() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A {var b; X _c;} +-class X{} +-// looks like a cascade to the parser +-// but the user is trying to get completions for a non-cascade +-main() {A a; a.^.z}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2() async { +- // SimpleIdentifier PropertyAccess CascadeExpression ExpressionSta= tement +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A {var b; X _c;} +-class X{} +-main() {A a; a..^z}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2_withTrailingReturn() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "/testB.dart"; +-class A {var b; X _c;} +-class X{} +-main() {A a; a..^ return}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_target() async { +- // SimpleIdentifier CascadeExpression ExpressionStatement +- addTestSource(''' +-class A {var b; X _c;} +-class X{} +-main() {A a; a^..b}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertSuggestLocalVariable('a', 'A'); +- assertSuggestClass('A'); +- assertSuggestClass('X'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CatchClause_onType() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^ {}}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_onType_noBrackets() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A', elemOffset: 6); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_typed() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on E catch (e) {^}}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestParameter('e', 'E'); +- assertSuggestMethod('a', 'A', null, relevance: DART_RELEVANCE_LOCAL_M= ETHOD); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_untyped() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} catch (e, s) {^}}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestParameter('e', null); +- assertSuggestParameter('s', 'StackTrace'); +- assertSuggestMethod('a', 'A', null, relevance: DART_RELEVANCE_LOCAL_M= ETHOD); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-@deprecated class A {^} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- CompletionSuggestion suggestionA =3D assertSuggestClass('A', +- relevance: DART_RELEVANCE_LOW, isDeprecated: true); +- if (suggestionA !=3D null) { +- expect(suggestionA.element.isDeprecated, isTrue); +- expect(suggestionA.element.isPrivate, isFalse); +- } +- CompletionSuggestion suggestionB =3D assertSuggestClass('_B'); +- if (suggestionB !=3D null) { +- expect(suggestionB.element.isDeprecated, isFalse); +- expect(suggestionB.element.isPrivate, isTrue); +- } +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestClass('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ A(){}} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestClass('_B'); +- assertNotSuggested('String'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field2() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as Soo; +-class A {final S^ A();} +-class _B {} +-A Sew;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestClass('A'); +- assertSuggestClass('_B'); +- assertNotSuggested('String'); +- assertNotSuggested('Sew'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('Soo'); +- } +- +- test_ClassDeclaration_body_final_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ final foo;} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestClass('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_var() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +-class B { }'''); +- addTestSource(''' +-import "testB.dart" as x; +-class A {final ^ var foo;} +-class _B {} +-A T;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- assertSuggestClass('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- // Suggested by LibraryPrefixContributor +- assertNotSuggested('x'); +- } +- +- test_Combinator_hide() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +-library libAB; +-part '/partAB.dart'; +-class A { } +-class B { }'''); +- addSource('/partAB.dart', ''' +-part of libAB; +-var T1; +-PB F1() =3D> new PB(); +-class PB { }'''); +- addSource('/testCD.dart', ''' +-class C { } +-class D { }'''); +- addTestSource(''' +-import "/testAB.dart" hide ^; +-import "/testCD.dart"; +-class X {}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_Combinator_show() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +-library libAB; +-part '/partAB.dart'; +-class A { } +-class B { }'''); +- addSource('/partAB.dart', ''' +-part of libAB; +-var T1; +-PB F1() =3D> new PB(); +-typedef PB2 F2(int blat); +-class Clz =3D Object with Object; +-class PB { }'''); +- addSource('/testCD.dart', ''' +-class C { } +-class D { }'''); +- addTestSource(''' +-import "/testAB.dart" show ^; +-import "/testCD.dart"; +-class X {}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_ConditionalExpression_elseExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T1 : T^}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_elseExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T1 : ^}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('x'); +- assertSuggestLocalVariable('f', null); +- assertSuggestMethod('foo', 'C', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestClass('C'); +- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUN= CTION); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_partial_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T^}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_partial_thenExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? ^}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('x'); +- assertSuggestLocalVariable('f', null); +- assertSuggestMethod('foo', 'C', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestClass('C'); +- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUN= CTION); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_ConditionalExpression_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} return a ? T^ : c}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_constructor_parameters_mixed_required_and_named() async { +- addTestSource('class A {A(x, {int y}) {^}}'); +- await computeSuggestions(); +- assertSuggestParameter('x', null); +- assertSuggestParameter('y', 'int'); +- } +- +- test_constructor_parameters_mixed_required_and_positional() async { +- addTestSource('class A {A(x, [int y]) {^}}'); +- await computeSuggestions(); +- assertSuggestParameter('x', null); +- assertSuggestParameter('y', 'int'); +- } +- +- test_constructor_parameters_named() async { +- addTestSource('class A {A({x, int y}) {^}}'); +- await computeSuggestions(); +- assertSuggestParameter('x', null); +- assertSuggestParameter('y', 'int'); +- } +- +- test_constructor_parameters_positional() async { +- addTestSource('class A {A([x, int y]) {^}}'); +- await computeSuggestions(); +- assertSuggestParameter('x', null); +- assertSuggestParameter('y', 'int'); +- } +- +- test_constructor_parameters_required() async { +- addTestSource('class A {A(x, int y) {^}}'); +- await computeSuggestions(); +- assertSuggestParameter('x', null); +- assertSuggestParameter('y', 'int'); +- } +- +- test_ConstructorName_importedClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-var m; +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-var m; +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- main() {new String.fr^omCharCodes([]);}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 13); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('fromCharCodes'); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('isNotEmpty'); +- assertNotSuggested('length'); +- assertNotSuggested('Object'); +- assertNotSuggested('String'); +- } +- +- test_ConstructorName_localClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}} +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_localFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +-int T1; +-F1() { } +-class X {factory X.c(); factory X._d(); z() {}} +-main() {new X.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_DefaultFormalParameter_named_expression() async { +- // DefaultFormalParameter FormalParameterList MethodDeclaration +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {a(blat: ^) { }}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestFunction('foo', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestMethod('a', 'A', null, relevance: DART_RELEVANCE_LOCAL_M= ETHOD); +- assertSuggestClass('A'); +- assertNotSuggested('String'); +- assertNotSuggested('identical'); +- } +- +- test_doc_classMember() async { +- String docLines =3D r''' +- /// My documentation. +- /// Short description. +- /// +- /// Longer description. +-'''; +- void assertDoc(CompletionSuggestion suggestion) { +- expect(suggestion.docSummary, 'My documentation.\nShort description= .'); +- expect(suggestion.docComplete, +- 'My documentation.\nShort description.\n\nLonger description.'); +- } +- +- addTestSource(''' +-class C { +-$docLines +- int myField; +- +-$docLines +- myMethod() {} +- +-$docLines +- int get myGetter =3D> 0; +- +- main() {^} +-}'''); +- await computeSuggestions(); +- { +- CompletionSuggestion suggestion =3D assertSuggestField('myField', '= int', +- relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertDoc(suggestion); +- } +- { +- CompletionSuggestion suggestion =3D assertSuggestMethod( +- 'myMethod', 'C', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertDoc(suggestion); +- } +- { +- CompletionSuggestion suggestion =3D assertSuggestGetter('myGetter',= 'int', +- relevance: DART_RELEVANCE_LOCAL_ACCESSOR); +- assertDoc(suggestion); +- } +- } +- +- test_doc_topLevel() async { +- String docLines =3D r''' +-/// My documentation. +-/// Short description. +-/// +-/// Longer description. +-'''; +- void assertDoc(CompletionSuggestion suggestion) { +- expect(suggestion.docSummary, 'My documentation.\nShort description= .'); +- expect(suggestion.docComplete, +- 'My documentation.\nShort description.\n\nLonger description.'); +- } +- +- addTestSource(''' +-$docLines +-class MyClass {} +- +-$docLines +-class MyClassTypeAlias =3D Object with MyClass; +- +-$docLines +-enum MyEnum {A, B, C} +- +-$docLines +-void myFunction() {} +- +-$docLines +-int myVariable; +- +-main() {^} +-'''); +- await computeSuggestions(); +- { +- CompletionSuggestion suggestion =3D assertSuggestClass('MyClass'); +- assertDoc(suggestion); +- } +- { +- CompletionSuggestion suggestion =3D +- assertSuggestClassTypeAlias('MyClassTypeAlias'); +- assertDoc(suggestion); +- } +- { +- CompletionSuggestion suggestion =3D assertSuggestEnum('MyEnum'); +- assertDoc(suggestion); +- } +- { +- CompletionSuggestion suggestion =3D assertSuggestFunction( +- 'myFunction', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertDoc(suggestion); +- } +- { +- CompletionSuggestion suggestion =3D assertSuggestTopLevelVar( +- 'myVariable', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertDoc(suggestion); +- } +- } +- +- test_enum() async { +- addTestSource('enum E { one, two } main() {^}'); +- await computeSuggestions(); +- assertSuggestEnum('E'); +- assertSuggestEnumConst('E.one'); +- assertSuggestEnumConst('E.two'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- } +- +- test_enum_deprecated() async { +- addTestSource('@deprecated enum E { one, two } main() {^}'); +- await computeSuggestions(); +- assertSuggestEnum('E', isDeprecated: true); +- assertSuggestEnumConst('E.one', isDeprecated: true); +- assertSuggestEnumConst('E.two', isDeprecated: true); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- } +- +- test_enum_filter() async { +- // SimpleIdentifier NamedExpression ArgumentList +- // InstanceCreationExpression +- addTestSource(''' +- enum E { one, two } +- enum F { three, four } +- class A {} +- class B { +- B({E someE}); +- } +- A a =3D new A(); +- B b =3D new B(someE: ^); +- '''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestEnumConst('E.one', +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertSuggestEnumConst('E.two', +- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_INCREMENT); +- assertNotSuggested('a'); +- assertNotSuggested('F.three'); +- assertNotSuggested('F.four'); +- } +- +- test_ExpressionStatement_identifier() async { +- // SimpleIdentifier ExpressionStatement Block +- addSource('/testA.dart', ''' +-_B F1() { } +-class A {int x;} +-class _B { }'''); +- addTestSource(''' +-import "/testA.dart"; +-typedef int F2(int blat); +-class Clz =3D Object with Object; +-class C {foo(){^} void bar() {}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertSuggestClass('C'); +- assertSuggestMethod('foo', 'C', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestMethod('bar', 'C', 'void', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestFunctionTypeAlias('F2', 'int'); +- assertSuggestClassTypeAlias('Clz'); +- assertSuggestClass('C'); +- assertNotSuggested('x'); +- assertNotSuggested('_B'); +- } +- +- test_ExpressionStatement_name() async { +- // ExpressionStatement Block BlockFunctionBody MethodDeclaration +- addSource('/testA.dart', ''' +- B T1; +- class B{}'''); +- addTestSource(''' +- import "/testA.dart"; +- class C {a() {C ^}}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_typed() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "/testA.dart"; +- class C {A ^}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_var() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "/testA.dart"; +- class C {var ^}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_FieldFormalParameter_in_non_constructor() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource('class A {B(this.^foo) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 3); +- assertNoSuggestions(); +- } +- +- test_ForEachStatement() async { +- // SimpleIdentifier ForEachStatement +- addTestSource('main() {List values; for (int index in ^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('values', 'List'); +- assertNotSuggested('index'); +- } +- +- test_ForEachStatement2() async { +- // SimpleIdentifier ForEachStatement +- addTestSource('main() {List values; for (int index in i^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestLocalVariable('values', 'List'); +- assertNotSuggested('index'); +- } +- +- test_ForEachStatement3() async { +- // SimpleIdentifier ParenthesizedExpression ForEachStatement +- addTestSource('main() {List values; for (int index in (i^))}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestLocalVariable('values', 'List'); +- assertNotSuggested('index'); +- } +- +- test_ForEachStatement_body_typed() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (int foo in bar) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestParameter('args', null); +- assertSuggestLocalVariable('foo', 'int'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_body_untyped() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (foo in bar) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestParameter('args', null); +- assertSuggestLocalVariable('foo', null); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_iterable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (int foo in ^) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestParameter('args', null); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_loopVariable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ in args) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('String'); +- } +- +- test_ForEachStatement_loopVariable_type() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ foo in args) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('String'); +- } +- +- test_ForEachStatement_loopVariable_type2() async { +- // DeclaredIdentifier ForEachStatement Block +- addTestSource('main(args) {for (S^ foo in args) {}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('String'); +- } +- +- test_FormalParameterList() async { +- // FormalParameterList MethodDeclaration +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {a(^) { }}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertSuggestClass('A'); +- assertNotSuggested('String'); +- assertNotSuggested('identical'); +- assertNotSuggested('bar'); +- } +- +- test_ForStatement_body() async { +- // Block ForStatement +- addTestSource('main(args) {for (int i; i < 10; ++i) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('i', 'int'); +- assertNotSuggested('Object'); +- } +- +- test_ForStatement_condition() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; i^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestLocalVariable('index', 'int'); +- } +- +- test_ForStatement_initializer() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {List a; for (^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('int'); +- } +- +- test_ForStatement_updaters() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; index < 10; i^)}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestLocalVariable('index', 'int'); +- } +- +- test_ForStatement_updaters_prefix_expression() async { +- // SimpleIdentifier PrefixExpression ForStatement +- addTestSource(''' +-void bar() { } +-main() {for (int index =3D 0; index < 10; ++i^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestLocalVariable('index', 'int'); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('bar'); +- } +- +- test_function_parameters_mixed_required_and_named() async { +- addTestSource(''' +-void m(x, {int y}) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_function_parameters_mixed_required_and_positional() async { +- addTestSource(''' +-void m(x, [int y]) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_function_parameters_named() async { +- addTestSource(''' +-void m({x, int y}) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_function_parameters_none() async { +- addTestSource(''' +-void m() {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- expect(suggestion.parameterNames, isEmpty); +- expect(suggestion.parameterTypes, isEmpty); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_function_parameters_positional() async { +- addTestSource(''' +-void m([x, int y]) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_function_parameters_required() async { +- addTestSource(''' +-void m(x, int y) {} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestFunction('m', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 2); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_FunctionDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-/* */ ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment2() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-/** */ ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment3() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-/// some dartdoc +-class C2 { } +-^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionExpression_body_function() async { +- // Block BlockFunctionBody FunctionExpression +- addTestSource(''' +- void bar() { } +- String foo(List args) {x.then((R b) {^});}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- var f =3D assertSuggestFunction('foo', 'String', +- isDeprecated: false, relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- if (f !=3D null) { +- expect(f.element.isPrivate, isFalse); +- } +- assertSuggestFunction('bar', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestParameter('args', 'List'); +- assertSuggestParameter('b', 'R'); +- assertNotSuggested('Object'); +- } +- +- test_IfStatement() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (true) ^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_DEFAULT); +- assertNotSuggested('Object'); +- assertSuggestClass('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_condition() async { +- // SimpleIdentifier IfStatement Block BlockFunctionBody +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main(){var a; if (^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('a', null); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_IfStatement_empty() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (^) something}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_DEFAULT); +- assertNotSuggested('Object'); +- assertSuggestClass('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_empty_private() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (_^) something}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('Object'); +- assertSuggestClass('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_invocation() async { +- // SimpleIdentifier PrefixIdentifier IfStatement +- addTestSource(''' +-main() {var a; if (a.^) something}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('toString'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ignore_symbol_being_completed() async { +- addTestSource('class MyClass { } main(MC^) { }'); +- await computeSuggestions(); +- assertSuggestClass('MyClass'); +- assertNotSuggested('MC'); +- } +- +- test_ImportDirective_dart() async { +- // SimpleStringLiteral ImportDirective +- addTestSource(''' +-import "dart^"; +-main() {}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_inDartDoc_reference3() async { +- addTestSource(''' +-/// The [^] +-main(aaa, bbb) {}'''); +- await computeSuggestions(); +- assertSuggestFunction('main', null, +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- } +- +- test_inDartDoc_reference4() async { +- addTestSource(''' +-/// The [m^] +-main(aaa, bbb) {}'''); +- await computeSuggestions(); +- assertSuggestFunction('main', null, +- kind: CompletionSuggestionKind.IDENTIFIER, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- } +- +- test_IndexExpression() async { +- // ExpressionStatement Block +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} f[^]}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('x'); +- assertSuggestLocalVariable('f', null); +- assertSuggestMethod('foo', 'C', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestClass('C'); +- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUN= CTION); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_IndexExpression2() async { +- // SimpleIdentifier IndexExpression ExpressionStatement Block +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-class B {int x;} +-class C {foo(){var f; {var x;} f[T^]}}'''); +- await computeSuggestions(); +- +- // top level results are partially filtered based on first char +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertNotSuggested('T1'); +- } +- +- test_InstanceCreationExpression() async { +- addTestSource(''' +-class A {foo(){var f; {var x;}}} +-class B {B(this.x, [String boo]) { } int x;} +-class C {C.bar({boo: 'hoo', int z: 0}) { } } +-main() {new ^ String x =3D "hello";}'''); +- await computeSuggestions(); +- // Suggested by LocalConstructorContributor +- assertNoSuggestions(); +- } +- +- test_InstanceCreationExpression_imported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-class A {A(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-import "dart:async"; +-int T2; +-F2() { } +-class B {B(this.x, [String boo]) { } int x;} +-class C {foo(){var f; {var x;} new ^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('Future'); +- assertNotSuggested('A'); +- // Suggested by LocalConstructorContributor +- assertNotSuggested('B'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('foo'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- } +- +- test_InstanceCreationExpression_unimported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){new F^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('Future'); +- assertNotSuggested('Foo'); +- } +- +- test_InterpolationExpression() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-main() {String name; print("hello \$^");}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUN= CTION); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertSuggestLocalVariable('name', 'String'); +- } +- +- test_InterpolationExpression_block() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-main() {String name; print("hello \${^}");}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUN= CTION); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertSuggestLocalVariable('name', 'String'); +- } +- +- test_InterpolationExpression_block2() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addTestSource('main() {String name; print("hello \${n^}");}'); +- await computeSuggestions(); +- +- assertSuggestLocalVariable('name', 'String'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- } +- +- test_InterpolationExpression_prefix_selector() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${name.^}");}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('length'); +- assertNotSuggested('name'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_InterpolationExpression_prefix_selector2() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \$name.^");}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_InterpolationExpression_prefix_target() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${nam^e.length}");}= '); +- await computeSuggestions(); +- +- assertSuggestLocalVariable('name', 'String'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- assertNotSuggested('length'); +- } +- +- test_IsExpression() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addSource('/testB.dart', ''' +-lib B; +-foo() { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-class Y {Y.c(); Y._d(); z() {}} +-main() {var x; if (x is ^) { }}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertSuggestClass('Y'); +- assertNotSuggested('x'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- } +- +- test_IsExpression_target() async { +- // IfStatement Block BlockFunctionBody +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {int x; int y() =3D> 0;} +-main(){var a; if (^ is A)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestLocalVariable('a', null); +- assertSuggestFunction('main', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestFunction('foo', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('bar'); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main(){var a; if (a is ^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type_filter_extends() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +-class A {} class B extends A {} class C extends A {} class D {} +-f(A a){ if (a is ^) {}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('D'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type_filter_implements() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +-class A {} class B implements A {} class C implements A {} class D {} +-f(A a){ if (a is ^) {}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('B'); +- assertSuggestClass('C'); +- assertNotSuggested('A'); +- assertNotSuggested('D'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type_filter_undefined_type() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +-class A {} +-f(U u){ (u as ^) }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestClass('A'); +- } +- +- test_IsExpression_type_partial() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +-class A {int x; int y() =3D> 0;} +-main(){var a; if (a is Obj^)}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertSuggestClass('A'); +- assertNotSuggested('Object'); +- } +- +- test_keyword() async { +- addSource('/testB.dart', ''' +-lib B; +-int newT1; +-int T1; +-nowIsIt() { } +-class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-String newer() {} +-var m; +-main() {new^ X.c();}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- // Imported suggestion are filtered by 1st character +- assertNotSuggested('nowIsIt'); +- assertNotSuggested('T1'); +- assertNotSuggested('newT1'); +- assertNotSuggested('z'); +- assertSuggestTopLevelVar('m', 'dynamic', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestFunction('newer', 'String', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- } +- +- test_Literal_list() async { +- // ']' ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([^]);}'); +- await computeSuggestions(); +- +- assertSuggestLocalVariable('Some', null); +- assertNotSuggested('String'); +- } +- +- test_Literal_list2() async { +- // SimpleIdentifier ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([S^]);}'); +- await computeSuggestions(); +- +- assertSuggestLocalVariable('Some', null); +- assertNotSuggested('String'); +- } +- +- test_Literal_string() async { +- // SimpleStringLiteral ExpressionStatement Block +- addTestSource('class A {a() {"hel^lo"}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_localVariableDeclarationName() async { +- addTestSource('main() {String m^}'); +- await computeSuggestions(); +- +- assertNotSuggested('main'); +- assertNotSuggested('min'); +- } +- +- test_MapLiteralEntry() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-foo =3D {^'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUN= CTION); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- } +- +- test_MapLiteralEntry1() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-foo =3D {T^'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('T1'); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- } +- +- test_MapLiteralEntry2() async { +- // SimpleIdentifier MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { } +-foo =3D {7:T^};'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('T1'); +- assertSuggestTopLevelVar('T2', 'int', +- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE); +- } +- +- test_method_parameters_mixed_required_and_named() async { +- addTestSource(''' +-class A { +- void m(x, {int y}) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_mixed_required_and_positional() async { +- addTestSource(''' +-class A { +- void m(x, [int y]) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_named() async { +- addTestSource(''' +-class A { +- void m({x, int y}) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_none() async { +- addTestSource(''' +-class A { +- void m() {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_positional() async { +- addTestSource(''' +-class A { +- void m([x, int y]) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_method_parameters_required() async { +- addTestSource(''' +-class A { +- void m(x, int y) {} +-} +-class B extends A { +- main() {^} +-} +-'''); +- await computeSuggestions(); +- assertNotSuggested('m'); +- } +- +- test_MethodDeclaration_body_getters() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X get f =3D> 0; Z a() {^} get _g = =3D> 1;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- CompletionSuggestion methodA =3D assertSuggestMethod('a', 'A', 'Z', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- if (methodA !=3D null) { +- expect(methodA.element.isDeprecated, isFalse); +- expect(methodA.element.isPrivate, isFalse); +- } +- CompletionSuggestion getterF =3D assertSuggestGetter('f', 'X', +- relevance: DART_RELEVANCE_LOW, isDeprecated: true); +- if (getterF !=3D null) { +- expect(getterF.element.isDeprecated, isTrue); +- expect(getterF.element.isPrivate, isFalse); +- } +- CompletionSuggestion getterG =3D +- assertSuggestGetter('_g', null, relevance: DART_RELEVANCE_DEFAULT= ); +- if (getterG !=3D null) { +- expect(getterG.element.isDeprecated, isFalse); +- expect(getterG.element.isPrivate, isTrue); +- } +- } +- +- test_MethodDeclaration_body_static() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testC.dart', ''' +-class C { +- c1() {} +- var c2; +- static c3() {} +- static var c4;}'''); +- addTestSource(''' +-import "/testC.dart"; +-class B extends C { +- b1() {} +- var b2; +- static b3() {} +- static var b4;} +-class A extends B { +- a1() {} +- var a2; +- static a3() {} +- static var a4; +- static a() {^}}'''); +- await computeSuggestions(); +- +- assertNotSuggested('a1'); +- assertNotSuggested('a2'); +- assertSuggestMethod('a3', 'A', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestField('a4', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- assertNotSuggested('b1'); +- assertNotSuggested('b2'); +- assertNotSuggested('b3'); +- assertNotSuggested('b4'); +- assertNotSuggested('c1'); +- assertNotSuggested('c2'); +- assertNotSuggested('c3'); +- assertNotSuggested('c4'); +- } +- +- test_MethodDeclaration_members() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X f; Z _a() {^} var _g;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- CompletionSuggestion methodA =3D +- assertSuggestMethod('_a', 'A', 'Z', relevance: DART_RELEVANCE_DEF= AULT); +- if (methodA !=3D null) { +- expect(methodA.element.isDeprecated, isFalse); +- expect(methodA.element.isPrivate, isTrue); +- } +- CompletionSuggestion getterF =3D assertSuggestField('f', 'X', +- relevance: DART_RELEVANCE_LOW, isDeprecated: true); +- if (getterF !=3D null) { +- expect(getterF.element.isDeprecated, isTrue); +- expect(getterF.element.isPrivate, isFalse); +- expect(getterF.element.parameters, isNull); +- } +- // If user did not type '_' then relevance of private members is not = raised +- CompletionSuggestion getterG =3D +- assertSuggestField('_g', null, relevance: DART_RELEVANCE_DEFAULT); +- if (getterG !=3D null) { +- expect(getterG.element.isDeprecated, isFalse); +- expect(getterG.element.isPrivate, isTrue); +- expect(getterF.element.parameters, isNull); +- } +- assertNotSuggested('bool'); +- } +- +- test_MethodDeclaration_members_private() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X f; Z _a() {_^} var _g;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- CompletionSuggestion methodA =3D assertSuggestMethod('_a', 'A', 'Z', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- if (methodA !=3D null) { +- expect(methodA.element.isDeprecated, isFalse); +- expect(methodA.element.isPrivate, isTrue); +- } +- CompletionSuggestion getterF =3D assertSuggestField('f', 'X', +- relevance: DART_RELEVANCE_LOW, isDeprecated: true); +- if (getterF !=3D null) { +- expect(getterF.element.isDeprecated, isTrue); +- expect(getterF.element.isPrivate, isFalse); +- expect(getterF.element.parameters, isNull); +- } +- // If user prefixed completion with '_' then suggestion of private me= mbers +- // should be the same as public members +- CompletionSuggestion getterG =3D +- assertSuggestField('_g', null, relevance: DART_RELEVANCE_LOCAL_FI= ELD); +- if (getterG !=3D null) { +- expect(getterG.element.isDeprecated, isFalse); +- expect(getterG.element.isPrivate, isTrue); +- expect(getterF.element.parameters, isNull); +- } +- assertNotSuggested('bool'); +- } +- +- test_MethodDeclaration_parameters_named() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated Z a(X x, _, b, {y: boo}) {^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- CompletionSuggestion methodA =3D assertSuggestMethod('a', 'A', 'Z', +- relevance: DART_RELEVANCE_LOW, isDeprecated: true); +- if (methodA !=3D null) { +- expect(methodA.element.isDeprecated, isTrue); +- expect(methodA.element.isPrivate, isFalse); +- } +- assertSuggestParameter('x', 'X'); +- assertSuggestParameter('y', null); +- assertSuggestParameter('b', null); +- assertNotSuggested('int'); +- assertNotSuggested('_'); +- } +- +- test_MethodDeclaration_parameters_positional() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource(''' +-foo() { } +-void bar() { } +-class A {Z a(X x, [int y=3D1]) {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestFunction('foo', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestFunction('bar', 'void', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestMethod('a', 'A', 'Z', relevance: DART_RELEVANCE_LOCAL_ME= THOD); +- assertSuggestParameter('x', 'X'); +- assertSuggestParameter('y', 'int'); +- assertNotSuggested('String'); +- } +- +- test_MethodDeclaration_returnType() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 {^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 {/* */ ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment2() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 {/** */ ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment3() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +-int T1; +-F1() { } +-typedef D1(); +-class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +-import "/testA.dart"; +-int T2; +-F2() { } +-typedef D2(); +-class C2 { +- /// some dartdoc +- ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertSuggestFunctionTypeAlias('D2', null); +- assertSuggestClass('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodInvocation_no_semicolon() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {x.^ m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_missing_params_constructor() async { +- addTestSource('class C1{C1{} main(){C^}}'); +- await computeSuggestions(); +- } +- +- test_missing_params_function() async { +- addTestSource('int f1{} main(){f^}'); +- await computeSuggestions(); +- } +- +- test_missing_params_method() async { +- addTestSource('class C1{int f1{} main(){f^}}'); +- await computeSuggestions(); +- } +- +- test_new_instance() async { +- addTestSource('import "dart:math"; class A {x() {new Random().^}}'); +- await computeSuggestions(); +- +- assertNotSuggested('nextBool'); +- assertNotSuggested('nextDouble'); +- assertNotSuggested('nextInt'); +- assertNotSuggested('Random'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- } +- +- test_overrides() async { +- addTestSource(''' +-class A {m() {}} +-class B extends A {m() {^}} +-'''); +- await computeSuggestions(); +- assertSuggestMethod('m', 'B', null, relevance: DART_RELEVANCE_LOCAL_M= ETHOD); +- } +- +- test_parameterName_excludeTypes() async { +- addTestSource('m(int ^) {}'); +- await computeSuggestions(); +- +- assertNotSuggested('int'); +- assertNotSuggested('bool'); +- } +- +- test_partFile_TypeName() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +-library libA; +-import "/testB.dart"; +-part "$testFile"; +-class A { } +-var m;'''); +- addTestSource(''' +-part of libA; +-class B { factory B.bar(int x) =3D> null; } +-main() {new ^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LocalConstructorContributor +- assertNotSuggested('B.bar'); +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_TypeName2() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +-lib B; +-int T1; +-F1() { } +-class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +-part of libA; +-class B { }'''); +- addTestSource(''' +-library libA; +-import "/testB.dart"; +-part "/testA.dart"; +-class A { A({String boo: 'hoo'}) { } } +-main() {new ^} +-var m;'''); +- await computeLibrariesContaining(); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LocalConstructorContributor +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('B'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_PrefixedIdentifier_class_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block +- addSource('/testB.dart', ''' +-lib B; +-class I { +- static const scI =3D 'boo'; +- X get f =3D> new A(); +- get _g =3D> new A();} +-class B implements I { +- static const int scB =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- addTestSource(''' +-import "/testB.dart"; +-class A extends B { +- static const String scA =3D 'foo'; +- w() { }} +-main() {A.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by StaticMemberContributor +- assertNotSuggested('scA'); +- assertNotSuggested('scB'); +- assertNotSuggested('scI'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('w'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_imported() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +-lib B; +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- static const int sc =3D 12; +- @deprecated var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- addTestSource(''' +-import "/testB.dart"; +-main() {A a; a.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_local() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-main() {A a; a.^} +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- static const int sc =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_library() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +-lib B; +-var T1; +-class X { } +-class Y { }'''); +- addTestSource(''' +-import "/testB.dart" as b; +-var T2; +-class A { } +-main() {b.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +-lib B; +-var T1; +-class X { } +-class Y { }'''); +- addTestSource(''' +-import "/testB.dart" as b; +-var T2; +-class A { } +-foo(b.^ f) {}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +-lib B; +-var T1; +-class X { } +-class Y { }'''); +- addTestSource(''' +-import "/testB.dart" as b; +-var T2; +-class A { } +-foo(b.^) {}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_parameter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +-lib B; +-class _W {M y; var _z;} +-class X extends _W {} +-class M{}'''); +- addTestSource(''' +-import "/testB.dart"; +-foo(X x) {x.^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('y'); +- assertNotSuggested('_z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_prefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testA.dart', ''' +-class A {static int bar =3D 10;} +-_B() {}'''); +- addTestSource(''' +-import "/testA.dart"; +-class X {foo(){A^.bar}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertSuggestClass('X'); +- assertSuggestMethod('foo', 'X', null, +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertNotSuggested('bar'); +- assertNotSuggested('_B'); +- } +- +- test_PrefixedIdentifier_propertyAccess() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('compareTo'); +- } +- +- test_PrefixedIdentifier_propertyAccess_newStmt() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('compareTo'); +- } +- +- test_PrefixedIdentifier_trailingStmt_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('const String g =3D "hello"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_field() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g; f() {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_function() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g() =3D> "one"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_functionTypeAlias() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('typedef String g(); f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_typed() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {String g; g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_untyped() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {var g =3D "hello"; g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_method() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g() {}; f() {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {f(String g) {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param2() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f(String g) {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_PrefixedIdentifier_trailingStmt_topLevelVar() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- +- assertNotSuggested('length'); +- } +- +- test_prioritization() async { +- addTestSource('main() {var ab; var _ab; ^}'); +- await computeSuggestions(); +- assertSuggestLocalVariable('ab', null); +- assertSuggestLocalVariable('_ab', null, relevance: DART_RELEVANCE_DEF= AULT); +- } +- +- test_prioritization_private() async { +- addTestSource('main() {var ab; var _ab; _^}'); +- await computeSuggestions(); +- assertSuggestLocalVariable('ab', null); +- assertSuggestLocalVariable('_ab', null); +- } +- +- test_prioritization_public() async { +- addTestSource('main() {var ab; var _ab; a^}'); +- await computeSuggestions(); +- assertSuggestLocalVariable('ab', null); +- assertSuggestLocalVariable('_ab', null, relevance: DART_RELEVANCE_DEF= AULT); +- } +- +- test_PropertyAccess_expression() async { +- // SimpleIdentifier MethodInvocation PropertyAccess ExpressionStat= ement +- addTestSource('class A {a() {"hello".to^String().length}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 8); +- assertNotSuggested('length'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PropertyAccess_noTarget() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){.^}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_noTarget2() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('main() {.^}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_selector() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement Block +- addTestSource('class A {a() {"hello".length.^}}'); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('isEven'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_shadowed_name() async { +- addTestSource('var a; class A { var a; m() { ^ } }'); +- await computeSuggestions(); +- assertSuggestField('a', null, relevance: DART_RELEVANCE_LOCAL_FIELD); +- } +- +- test_SwitchStatement_c() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {c^}}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_SwitchStatement_case() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {var t; switch(x) {case 0: ^}= }}'); +- await computeSuggestions(); +- +- assertSuggestClass('A'); +- assertSuggestMethod('g', 'A', 'String', +- relevance: DART_RELEVANCE_LOCAL_METHOD); +- assertSuggestLocalVariable('t', null); +- assertNotSuggested('String'); +- } +- +- test_SwitchStatement_case_var() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('g(int x) {var t; switch(x) {case 0: var bar; b^}}'); +- await computeSuggestions(); +- +- assertSuggestFunction('g', 'dynamic', +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertSuggestLocalVariable('t', 'dynamic', +- relevance: DART_RELEVANCE_LOCAL_VARIABLE); +- assertSuggestParameter('x', 'int', relevance: DART_RELEVANCE_PARAMETE= R); +- assertSuggestLocalVariable('bar', 'dynamic', +- relevance: DART_RELEVANCE_LOCAL_VARIABLE); +- assertNotSuggested('String'); +- } +- +- test_SwitchStatement_empty() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {^}}}'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_ThisExpression_block() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A() {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {this.^ m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A() {this.^} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.^) {} +- A.z() {} +- var b; X _c; static sb; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Contributed by FieldFormalContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('sb'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param2() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.b^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Contributed by FieldFormalContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param3() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.^b) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- // Contributed by FieldFormalContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param4() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +-main() { } +-class I {X get f =3D> new A();get _g =3D> new A();} +-class A implements I { +- A(this.b, this.^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +-class X{}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- // Contributed by FieldFormalContributor +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_TopLevelVariableDeclaration_typed_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} B ^'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_TopLevelVariableDeclaration_untyped_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} var ^'); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_TypeArgumentList() async { +- // SimpleIdentifier BinaryExpression ExpressionStatement +- addSource('/testA.dart', ''' +-class C1 {int x;} +-F1() =3D> 0; +-typedef String T1(int blat);'''); +- addTestSource(''' +-import "/testA.dart";' +-class C2 {int x;} +-F2() =3D> 0; +-typedef int T2(int blat); +-class C {} +-main() { C<^> c; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('C1'); +- assertNotSuggested('T1'); +- assertSuggestClass('C2'); +- assertSuggestFunctionTypeAlias('T2', 'int'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- } +- +- test_TypeArgumentList2() async { +- // TypeName TypeArgumentList TypeName +- addSource('/testA.dart', ''' +-class C1 {int x;} +-F1() =3D> 0; +-typedef String T1(int blat);'''); +- addTestSource(''' +-import "/testA.dart";' +-class C2 {int x;} +-F2() =3D> 0; +-typedef int T2(int blat); +-class C {} +-main() { C c; }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('C1'); +- assertSuggestClass('C2'); +- } +- +- test_VariableDeclaration_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addSource('/testB.dart', ''' +-lib B; +-foo() { } +-class _B { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-class Y {Y.c(); Y._d(); z() {}} +-main() {var ^}'''); +- await computeSuggestions(); +- +- assertNoSuggestions(); +- } +- +- test_VariableDeclarationList_final() async { +- // VariableDeclarationList VariableDeclarationStatement Block +- addTestSource('main() {final ^} class C { }'); +- await computeSuggestions(); +- +- assertNotSuggested('Object'); +- assertSuggestClass('C'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_VariableDeclarationStatement_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +-lib B; +-foo() { } +-class _B { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-class Y {Y.c(); Y._d(); z() {}} +-class C {bar(){var f; {var x;} var e =3D ^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('_B'); +- assertSuggestClass('Y'); +- assertSuggestClass('C'); +- assertSuggestLocalVariable('f', null); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +- +- test_VariableDeclarationStatement_RHS_missing_semicolon() async { +- // VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +-lib B; +-foo1() { } +-void bar1() { } +-class _B { } +-class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +-import "/testB.dart"; +-foo2() { } +-void bar2() { } +-class Y {Y.c(); Y._d(); z() {}} +-class C {bar(){var f; {var x;} var e =3D ^ var g}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('foo1'); +- assertNotSuggested('bar1'); +- assertSuggestFunction('foo2', null, +- relevance: DART_RELEVANCE_LOCAL_FUNCTION); +- assertNotSuggested('bar2'); +- assertNotSuggested('_B'); +- assertSuggestClass('Y'); +- assertSuggestClass('C'); +- assertSuggestLocalVariable('f', null); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/named_const= ructor_contributor_test.dart b/pkg/analysis_server/test/services/completion= /dart/named_constructor_contributor_test.dart +deleted file mode 100644 +index f753d8a99b9..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/named_constructor_= contributor_test.dart ++++ /dev/null +@@ -1,171 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/named_constr= uctor_contributor.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(NamedConstructorContributorTest); +- }); +-} +- +-@reflectiveTest +-class NamedConstructorContributorTest extends DartCompletionContributorTe= st { +- CompletionSuggestion assertSuggestNamedConstructor( +- String name, String returnType, +- [int relevance =3D DART_RELEVANCE_DEFAULT, +- CompletionSuggestionKind kind =3D CompletionSuggestionKind.INVOCATI= ON]) { +- CompletionSuggestion cs =3D +- assertSuggest(name, csKind: kind, relevance: relevance); +- Element element =3D cs.element; +- expect(element, isNotNull); +- expect(element.kind, equals(ElementKind.CONSTRUCTOR)); +- expect(element.name, equals(name)); +- String param =3D element.parameters; +- expect(param, isNotNull); +- expect(param[0], equals('(')); +- expect(param[param.length - 1], equals(')')); +- expect(element.returnType, equals(returnType)); +- assertHasParameterInfo(cs); +- return cs; +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new NamedConstructorContributor(); +- } +- +- test_ConstructorName_importedClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- var m; +- main() {new X.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestNamedConstructor('c', 'X'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedClass_unresolved() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- var m; +- main() {new X.^}'''); +- // Assume that imported libraries are NOT resolved +- //await resolveLibraryUnit(libSource); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestNamedConstructor('c', 'X'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +- import "/testB.dart"; +- var m; +- main() {new X.^}'''); +- +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestNamedConstructor('c', 'X'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- main() {new String.fr^omCharCodes([]);}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 13); +- assertSuggestNamedConstructor('fromCharCodes', 'String'); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('isNotEmpty'); +- assertNotSuggested('length'); +- assertNotSuggested('Object'); +- assertNotSuggested('String'); +- } +- +- test_ConstructorName_localClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}} +- main() {new X.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestNamedConstructor('c', 'X'); +- assertSuggestNamedConstructor('_d', 'X'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_localFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- int T1; +- F1() { } +- class X {factory X.c(); factory X._d(); z() {}} +- main() {new X.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestNamedConstructor('c', 'X'); +- assertSuggestNamedConstructor('_d', 'X'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/override_co= ntributor_test.dart b/pkg/analysis_server/test/services/completion/dart/ove= rride_contributor_test.dart +deleted file mode 100644 +index e0d356c12b2..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/override_contribut= or_test.dart ++++ /dev/null +@@ -1,112 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/override_con= tributor.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- // Revisit this contributor and these tests +- // once DartChangeBuilder API has solidified. +- // initializeTestEnvironment(); +- // defineReflectiveTests(InheritedContributorTest); +-} +- +-@reflectiveTest +-class OverrideContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new OverrideContributor(); +- } +- +- test_fromMultipleSuperclasses() async { +- addTestSource(r''' +-class A { +- A suggested1(int x) =3D> null; +- B suggested2(String y) =3D> null; +-} +-class B extends A { +- B suggested2(String y) =3D> null; +- C suggested3([String z]) =3D> null; +-} +-class C extends B { +- sugg^ +-} +-'''); +- await computeSuggestions(); +- _assertOverride('''@override +- A suggested1(int x) { +- // TODO: implement suggested1 +- return null; +- }'''); +- _assertOverride( +- '''@override\n A suggested1(int x) {\n // TODO: implement sug= gested1\n return null;\n }'''); +- _assertOverride( +- '''@override\n B suggested2(String y) {\n // TODO: implement = suggested2\n return null;\n }'''); +- _assertOverride( +- '''@override\n C suggested3([String z]) {\n // TODO: implemen= t suggested3\n return null;\n }'''); +- } +- +- test_fromPart() async { +- addSource('/myLib.dart', ''' +-library myLib; +-part '$testFile' +-part '/otherPart.dart' +-class A { +- A suggested1(int x) =3D> null; +- B suggested2(String y) =3D> null; +-} +-'''); +- addSource('/otherPart.dart', ''' +-part of myLib; +-class B extends A { +- B suggested2(String y) =3D> null; +- C suggested3([String z]) =3D> null; +-} +-'''); +- addTestSource(r''' +-part of myLib; +-class C extends B { +- sugg^ +-} +-'''); +- // assume information for context.getLibrariesContaining has been cac= hed +- await computeLibrariesContaining(); +- await computeSuggestions(); +- _assertOverride('''@override +- A suggested1(int x) { +- // TODO: implement suggested1 +- return null; +- }'''); +- _assertOverride( +- '''@override\n A suggested1(int x) {\n // TODO: implement sug= gested1\n return null;\n }'''); +- _assertOverride( +- '''@override\n B suggested2(String y) {\n // TODO: implement = suggested2\n return null;\n }'''); +- _assertOverride( +- '''@override\n C suggested3([String z]) {\n // TODO: implemen= t suggested3\n return null;\n }'''); +- } +- +- CompletionSuggestion _assertOverride(String completion) { +- CompletionSuggestion cs =3D getSuggest( +- completion: completion, +- csKind: CompletionSuggestionKind.IDENTIFIER, +- elemKind: null); +- if (cs =3D=3D null) { +- failedCompletion('expected $completion', suggestions); +- } +- expect(cs.kind, equals(CompletionSuggestionKind.IDENTIFIER)); +- expect(cs.relevance, equals(DART_RELEVANCE_HIGH)); +- expect(cs.importUri, null); +-// expect(cs.selectionOffset, equals(completion.length)); +-// expect(cs.selectionLength, equals(0)); +- expect(cs.isDeprecated, isFalse); +- expect(cs.isPotential, isFalse); +- expect(cs.element, isNotNull); +- return cs; +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/static_memb= er_contributor_test.dart b/pkg/analysis_server/test/services/completion/dar= t/static_member_contributor_test.dart +deleted file mode 100644 +index 8df73bdd194..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/static_member_cont= ributor_test.dart ++++ /dev/null +@@ -1,285 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/static_membe= r_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(StaticMemberContributorTest); +- }); +-} +- +-@reflectiveTest +-class StaticMemberContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new StaticMemberContributor(); +- } +- +- fail_enumConst_deprecated() async { +- addTestSource('@deprecated enum E { one, two } main() {E.^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- // TODO(danrubel) Investigate why enum suggestion is not marked +- // as deprecated if enum ast element is deprecated +- assertSuggestEnumConst('one', isDeprecated: true); +- assertSuggestEnumConst('two', isDeprecated: true); +- assertNotSuggested('index'); +- assertSuggestField('values', 'List', isDeprecated: true); +- } +- +- test_enumConst() async { +- addTestSource('enum E { one, two } main() {E.^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertSuggestEnumConst('one'); +- assertSuggestEnumConst('two'); +- assertNotSuggested('index'); +- assertSuggestField('values', 'List'); +- } +- +- test_enumConst2() async { +- addTestSource('enum E { one, two } main() {E.o^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertSuggestEnumConst('one'); +- assertSuggestEnumConst('two'); +- assertNotSuggested('index'); +- assertSuggestField('values', 'List'); +- } +- +- test_enumConst3() async { +- addTestSource('enum E { one, two } main() {E.^ int g;}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertSuggestEnumConst('one'); +- assertSuggestEnumConst('two'); +- assertNotSuggested('index'); +- assertSuggestField('values', 'List'); +- } +- +- test_enumConst_cascade1() async { +- addTestSource('enum E { one, two } main() {E..^}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_enumConst_cascade2() async { +- addTestSource('enum E { one, two } main() {E.^.}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertSuggestEnumConst('one'); +- assertSuggestEnumConst('two'); +- assertNotSuggested('index'); +- assertSuggestField('values', 'List'); +- } +- +- test_enumConst_cascade3() async { +- addTestSource('enum E { one, two } main() {E..o^}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_enumConst_cascade4() async { +- addTestSource('enum E { one, two } main() {E.^.o}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertSuggestEnumConst('one'); +- assertSuggestEnumConst('two'); +- assertNotSuggested('index'); +- assertSuggestField('values', 'List'); +- } +- +- test_keyword() async { +- addTestSource('class C { static C get instance =3D> null; } main() {C= .in^}'); +- await computeSuggestions(); +- assertSuggestGetter('instance', 'C'); +- } +- +- test_only_static() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-class B { +- static int b1; +-} +-class C extends B { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C.^}'''); +- await computeSuggestions(); +- assertNotSuggested('b1'); +- assertNotSuggested('f1'); +- assertSuggestField('f2', 'int'); +- assertNotSuggested('m1'); +- assertSuggestMethod('m2', 'C', null); +- } +- +- test_only_static2() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource(''' +-class B { +- static int b1; +-} +-class C extends B { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C.^ print("something");}'''); +- await computeSuggestions(); +- assertNotSuggested('b1'); +- assertNotSuggested('f1'); +- assertSuggestField('f2', 'int'); +- assertNotSuggested('m1'); +- assertSuggestMethod('m2', 'C', null); +- } +- +- test_only_static_cascade1() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-class B { +- static int b1; +-} +-class C extends B { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C..^}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_only_static_cascade2() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-class B { +- static int b1; +-} +-class C extends B { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C.^.}'''); +- await computeSuggestions(); +- assertNotSuggested('b1'); +- assertNotSuggested('f1'); +- assertSuggestField('f2', 'int'); +- assertNotSuggested('m1'); +- assertSuggestMethod('m2', 'C', null); +- } +- +- test_only_static_cascade3() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-class B { +- static int b1; +-} +-class C extends B { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C..m^()}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_only_static_cascade4() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-class B { +- static int b1; +-} +-class C extends B { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C.^.m()}'''); +- await computeSuggestions(); +- assertNotSuggested('b1'); +- assertNotSuggested('f1'); +- assertSuggestField('f2', 'int'); +- assertNotSuggested('m1'); +- assertSuggestMethod('m2', 'C', null); +- } +- +- test_only_static_cascade_prefixed1() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-import "dart:async" as async; +-void main() {async.Future..w^()}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_only_static_cascade_prefixed2() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-import "dart:async" as async; +-void main() {async.Future.^.w()}'''); +- await computeSuggestions(); +- assertSuggestMethod('wait', 'Future', 'Future'); +- } +- +- test_PrefixedIdentifier_class_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block +- addSource('/testB.dart', ''' +- lib B; +- class I { +- static const scI =3D 'boo'; +- X get f =3D> new A(); +- get _g =3D> new A();} +- class B implements I { +- static const int scB =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- addTestSource(''' +- import "/testB.dart"; +- class A extends B { +- static const String scA =3D 'foo'; +- w() { }} +- main() {A.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('scA', 'String'); +- assertNotSuggested('scB'); +- assertNotSuggested('scI'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('w'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/test_all.da= rt b/pkg/analysis_server/test/services/completion/dart/test_all.dart +deleted file mode 100644 +index 72c879315a7..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/test_all.dart ++++ /dev/null +@@ -1,52 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'arglist_contributor_test.dart' as arglist_test; +-import 'combinator_contributor_test.dart' as combinator_test; +-import 'common_usage_sorter_test.dart' as common_usage_test; +-import 'completion_manager_test.dart' as completion_manager; +-import 'field_formal_contributor_test.dart' as field_formal_contributor_t= est; +-import 'imported_reference_contributor_test.dart' as imported_ref_test; +-import 'inherited_reference_contributor_test.dart' as inherited_ref_test; +-import 'keyword_contributor_test.dart' as keyword_test; +-import 'label_contributor_test.dart' as label_contributor_test; +-import 'library_member_contributor_test.dart' as library_member_test; +-import 'library_prefix_contributor_test.dart' as library_prefix_test; +-import 'local_constructor_contributor_test.dart' as local_constructor_tes= t; +-import 'local_library_contributor_test.dart' as local_lib_test; +-import 'local_reference_contributor_test.dart' as local_ref_test; +-import 'named_constructor_contributor_test.dart' as named_contributor_tes= t; +-import 'override_contributor_test.dart' as override_contributor_test; +-import 'static_member_contributor_test.dart' as static_contributor_test; +-import 'type_member_contributor_test.dart' as type_member_contributor_tes= t; +-import 'uri_contributor_test.dart' as uri_contributor_test; +-import 'variable_name_contributor_test.dart' as variable_name_contributor= _test; +- +-/// Utility for manually running all tests. +-main() { +- defineReflectiveSuite(() { +- arglist_test.main(); +- combinator_test.main(); +- common_usage_test.main(); +- completion_manager.main(); +- field_formal_contributor_test.main(); +- imported_ref_test.main(); +- inherited_ref_test.main(); +- keyword_test.main(); +- label_contributor_test.main(); +- library_member_test.main(); +- library_prefix_test.main(); +- local_constructor_test.main(); +- local_lib_test.main(); +- local_ref_test.main(); +- named_contributor_test.main(); +- override_contributor_test.main(); +- static_contributor_test.main(); +- type_member_contributor_test.main(); +- uri_contributor_test.main(); +- variable_name_contributor_test.main(); +- }, name: 'dart'); +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/type_member= _contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/= type_member_contributor_test.dart +deleted file mode 100644 +index a47714ce074..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/type_member_contri= butor_test.dart ++++ /dev/null +@@ -1,4027 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/type_member_= contributor.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(TypeMemberContributorTest); +- }); +-} +- +-@reflectiveTest +-class TypeMemberContributorTest extends DartCompletionContributorTest { +- /** +- * Check whether a declaration of the form [shadower] in a derived class +- * shadows a declaration of the form [shadowee] in a base class, for the +- * purposes of what is shown during completion. [shouldBeShadowed] ind= icates +- * whether shadowing is expected. +- */ +- Future check_shadowing( +- String shadower, String shadowee, bool shouldBeShadowed) async { +- addTestSource(''' +-class Base { +- $shadowee +-} +-class Derived extends Base { +- $shadower +-} +-void f(Derived d) { +- d.^ +-} +-'''); +- await computeSuggestions(); +- List suggestionsForX =3D suggestions +- .where((CompletionSuggestion s) =3D> s.completion =3D=3D 'x') +- .toList(); +- expect(suggestionsForX, hasLength(1)); +- if (shouldBeShadowed) { +- expect(suggestionsForX[0].declaringType, 'Derived'); +- } else { +- expect(suggestionsForX[0].declaringType, 'Base'); +- } +- } +- +- @override +- DartCompletionContributor createContributor() { +- return new TypeMemberContributor(); +- } +- +- test_ArgDefaults_method() async { +- addTestSource(''' +-class A { +- bool a(int b, bool c) =3D> false; +-} +- +-void main() {new A().a^}'''); +- await computeSuggestions(); +- +- assertSuggestMethod('a', 'A', 'bool', defaultArgListString: 'b, c'); +- } +- +- test_ArgDefaults_method_none() async { +- addTestSource(''' +-class A { +- bool a() =3D> false; +-} +- +-void main() {new A().a^}'''); +- await computeSuggestions(); +- +- assertSuggestMethod('a', 'A', 'bool', defaultArgListString: null); +- } +- +- test_ArgDefaults_method_with_optional_positional() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +- +-class A { +- bool foo(int bar, [bool boo, int baz]) =3D> false; +-} +- +-void main() {new A().f^}'''); +- await computeSuggestions(); +- +- assertSuggestMethod('foo', 'A', 'bool', defaultArgListString: 'bar'); +- } +- +- test_ArgDefaults_method_with_required_named() async { +- addMetaPackageSource(); +- addTestSource(''' +-import 'package:meta/meta.dart'; +- +-class A { +- bool foo(int bar, {bool boo, @required int baz}) =3D> false; +-} +- +-void main() {new A().f^}'''); +- await computeSuggestions(); +- +- assertSuggestMethod('foo', 'A', 'bool', +- defaultArgListString: 'bar, baz: null'); +- } +- +- test_ArgumentList() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart'; +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_imported_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- expect(arg) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_functionalArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +- library A; +- class A { A(f()) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { } +- String bar() =3D> true; +- void main() {new A(^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_InstanceCreationExpression_typedefArg() async { +- // ArgumentList InstanceCreationExpression ExpressionStatement Blo= ck +- addSource('/libA.dart', ''' +- library A; +- typedef Funct(); +- class A { A(Funct f) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { } +- String bar() =3D> true; +- void main() {new A(^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_function() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- expect(arg) { } +- class B { } +- String bar() =3D> true; +- void main() {expect(^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_local_method() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import '/libA.dart' +- class B { +- expect(arg) { } +- void foo() {expect(^)}} +- String bar() =3D> true;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_functionalArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- class A { A(f()) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { } +- String bar(f()) =3D> true; +- void main() {bar(^);}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_MethodInvocation_methodArg() async { +- // ArgumentList MethodInvocation ExpressionStatement Block +- addSource('/libA.dart', ''' +- library A; +- class A { A(f()) { } } +- bool hasLength(int expected) { } +- void baz() { }'''); +- addTestSource(''' +- import 'dart:async'; +- import '/libA.dart'; +- class B { String bar(f()) =3D> true; } +- void main() {new B().bar(^);}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(kind: CompletionSuggestionKind.ARGUMENT_LIST); +- assertNotSuggested('hasLength'); +- assertNotSuggested('identical'); +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('main'); +- assertNotSuggested('baz'); +- assertNotSuggested('print'); +- } +- +- test_ArgumentList_namedParam() async { +- // SimpleIdentifier NamedExpression ArgumentList MethodInvocation +- // ExpressionStatement +- addSource('/libA.dart', ''' +- library A; +- bool hasLength(int expected) { }'''); +- addTestSource(''' +- import '/libA.dart' +- String bar() =3D> true; +- void main() {expect(foo: ^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('bar'); +- assertNotSuggested('hasLength'); +- assertNotSuggested('main'); +- } +- +- test_AsExpression() async { +- // SimpleIdentifier TypeName AsExpression +- addTestSource(''' +- class A {var b; X _c; foo() {var a; (a as ^).foo();}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_AssignmentExpression_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int ^b =3D 1;}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_AssignmentExpression_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource('class A {} main() {int a; int b =3D ^}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_AssignmentExpression_type() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- ^ b =3D 1;}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- ^ +- b =3D 1;}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- int^ b =3D 1;}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // TODO (danrubel) When entering 1st of 2 identifiers on assignment L= HS +- // the user may be either (1) entering a type for the assignment +- // or (2) starting a new statement. +- // Consider suggesting only types +- // if only spaces separates the 1st and 2nd identifiers. +- //assertNotSuggested('a'); +- //assertNotSuggested('main'); +- //assertNotSuggested('identical'); +- } +- +- test_AssignmentExpression_type_partial_newline() async { +- // SimpleIdentifier TypeName VariableDeclarationList +- // VariableDeclarationStatement Block +- addTestSource(''' +- class A {} main() { +- int a; +- i^ +- b =3D 1;}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('int'); +- // Allow non-types preceding an identifier on LHS of assignment +- // if newline follows first identifier +- // because user is probably starting a new statement +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('identical'); +- } +- +- test_AwaitExpression() async { +- // SimpleIdentifier AwaitExpression ExpressionStatement +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main() async {A a; await ^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_BinaryExpression_LHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D ^ + 2;}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- } +- +- test_BinaryExpression_RHS() async { +- // SimpleIdentifier BinaryExpression VariableDeclaration +- // VariableDeclarationList VariableDeclarationStatement +- addTestSource('main() {int a =3D 1, b =3D 2 + ^;}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "testAB.dart"; +- import "testCD.dart" hide D; +- import "testEEF.dart" show EE; +- import "testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- ^ var r; +- } +- void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "testAB.dart"; +- import "testCD.dart" hide D; +- import "testEEF.dart" show EE; +- import "testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- final ^ +- } +- void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final2() async { +- addTestSource('main() {final S^ v;}'); +- await computeSuggestions(); +- +- assertNotSuggested('String'); +- } +- +- test_Block_final3() async { +- addTestSource('main() {final ^ v;}'); +- await computeSuggestions(); +- +- assertNotSuggested('String'); +- } +- +- test_Block_final_final() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "testAB.dart"; +- import "testCD.dart" hide D; +- import "testEEF.dart" show EE; +- import "testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- final var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_final_var() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "testAB.dart"; +- import "testCD.dart" hide D; +- import "testEEF.dart" show EE; +- import "testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- final ^ +- var f; +- localF(int arg1) { } +- {var x;} +- } +- void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('localF'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- assertNotSuggested('partT8'); +- +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('C'); +- assertNotSuggested('partBoo'); +- // hidden element suggested as low relevance +- // but imported results are partially filtered +- //assertNotSuggested('D'); +- //assertNotSuggested( +- // 'D1', null, true, COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('D2'); +- assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- assertNotSuggested('Object'); +- assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- assertNotSuggested('T1'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- assertNotSuggested('T5'); +- assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- assertNotSuggested('T7'); +- assertNotSuggested('T8'); +- assertNotSuggested('clog'); +- assertNotSuggested('blog'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- assertNotSuggested('Uri'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_identifier_partial() async { +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B { }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- class D3 { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "testAB.dart"; +- import "testCD.dart" hide D; +- import "testEEF.dart" show EE; +- import "testG.dart" as g; +- int T5; +- var _T6; +- Z D2() {int x;} +- class X {a() {var f; {var x;} D^ var r;} void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- +- assertNotSuggested('X'); +- assertNotSuggested('Z'); +- assertNotSuggested('a'); +- assertNotSuggested('b'); +- assertNotSuggested('f'); +- // Don't suggest locals out of scope +- assertNotSuggested('r'); +- assertNotSuggested('x'); +- +- // imported elements are portially filtered +- //assertNotSuggested('A'); +- assertNotSuggested('_B'); +- //assertNotSuggested('C'); +- // hidden element suggested as low relevance +- assertNotSuggested('D'); +- assertNotSuggested('D1'); +- assertNotSuggested('D2'); +- // unimported elements suggested with low relevance +- assertNotSuggested('D3'); +- //assertNotSuggested('EE'); +- // hidden element suggested as low relevance +- //assertNotSuggested('F'); +- //assertNotSuggested('g'); +- assertNotSuggested('G'); +- //assertNotSuggested('H'); +- //assertNotSuggested('Object'); +- //assertNotSuggested('min'); +- //assertNotSuggested( +- // 'max', +- // 'num', +- // false, +- // COMPLETION_RELEVANCE_LOW); +- //assertSuggestTopLevelVarGetterSetter('T1', 'String'); +- assertNotSuggested('_T2'); +- //assertSuggestImportedTopLevelVar('T3', 'int', COMPLETION_RELEVANCE_= LOW); +- assertNotSuggested('_T4'); +- //assertNotSuggested('T5'); +- //assertNotSuggested('_T6'); +- assertNotSuggested('=3D=3D'); +- // TODO (danrubel) suggest HtmlElement as low relevance +- assertNotSuggested('HtmlElement'); +- } +- +- test_Block_inherited_imported() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addSource('/testB.dart', ''' +- lib B; +- class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } var _pf;= } +- class E extends F { var e1; e2() { } } +- class I { int i1; i2() { } } +- class M { var m1; int m2() { } }'''); +- addTestSource(''' +- import "testB.dart"; +- class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // TODO (danrubel) prefer fields over getters +- // If add `get e1;` to interface I +- // then suggestions include getter e1 rather than field e1 +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- //assertNotSuggested('m2'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_Block_inherited_local() async { +- // Block BlockFunctionBody MethodDeclaration ClassDeclaration +- addTestSource(''' +- class F { var f1; f2() { } get f3 =3D> 0; set f4(fx) { } } +- class E extends F { var e1; e2() { } } +- class I { int i1; i2() { } } +- class M { var m1; int m2() { } } +- class A extends E implements I with M {a() {^}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e1'); +- assertNotSuggested('f1'); +- assertNotSuggested('i1'); +- assertNotSuggested('m1'); +- assertNotSuggested('f3'); +- assertNotSuggested('f4'); +- assertNotSuggested('e2'); +- assertNotSuggested('f2'); +- assertNotSuggested('i2'); +- assertNotSuggested('m2'); +- } +- +- test_Block_local_function() async { +- addSource('/testAB.dart', ''' +- export "dart:math" hide max; +- class A {int x;} +- @deprecated D1() {int x;} +- class _B {boo() { partBoo() {}} }'''); +- addSource('/testCD.dart', ''' +- String T1; +- var _T2; +- class C { } +- class D { }'''); +- addSource('/testEEF.dart', ''' +- class EE { } +- class F { }'''); +- addSource('/testG.dart', 'class G { }'); +- addSource('/testH.dart', ''' +- class H { } +- int T3; +- var _T4;'''); // not imported +- addTestSource(''' +- import "testAB.dart"; +- import "testCD.dart" hide D; +- import "testEEF.dart" show EE; +- import "testG.dart" as g; +- int T5; +- var _T6; +- String get T7 =3D> 'hello'; +- set T8(int value) { partT8() {} } +- Z D2() {int x;} +- class X { +- int get clog =3D> 8; +- set blog(value) { } +- a() { +- var f; +- localF(int arg1) { } +- {var x;} +- p^ var r; +- } +- void b() { }} +- class Z { }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('partT8'); +- assertNotSuggested('partBoo'); +- assertNotSuggested('parseIPv6Address'); +- assertNotSuggested('parseHex'); +- } +- +- test_Block_unimported() async { +- addPackageSource('myBar', 'bar.dart', 'class Foo2 { Foo2() { } }'); +- addSource( +- '/proj/testAB.dart', 'import "package:myBar/bar.dart"; class Foo = { }'); +- testFile =3D provider.convertPath('/proj/completionTest.dart'); +- addTestSource('class C {foo(){F^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('Foo'); +- // TODO(danrubel) implement +- assertNotSuggested('Foo2'); +- assertNotSuggested('Future'); +- } +- +- test_CascadeExpression_method1() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart"; +- class A {var b; X _c;} +- class X{} +- // looks like a cascade to the parser +- // but the user is trying to get completions for a non-cascade +- main() {A a; a.^.z()}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector1() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart"; +- class A {var b; X _c;} +- class X{} +- // looks like a cascade to the parser +- // but the user is trying to get completions for a non-cascade +- main() {A a; a.^.z}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2() async { +- // SimpleIdentifier PropertyAccess CascadeExpression ExpressionSta= tement +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart"; +- class A {var b; X _c;} +- class X{} +- main() {A a; a..^z}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_selector2_withTrailingReturn() async { +- // PropertyAccess CascadeExpression ExpressionStatement Block +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart"; +- class A {var b; X _c;} +- class X{} +- main() {A a; a..^ return}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('X'); +- assertNotSuggested('z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CascadeExpression_target() async { +- // SimpleIdentifier CascadeExpression ExpressionStatement +- addTestSource(''' +- class A {var b; X _c;} +- class X{} +- main() {A a; a^..b}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_CatchClause_onType() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^ {}}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_onType_noBrackets() async { +- // TypeName CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on ^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_typed() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} on E catch (e) {^}}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_CatchClause_untyped() async { +- // Block CatchClause TryStatement +- addTestSource('class A {a() {try{var x;} catch (e, s) {^}}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('e'); +- assertNotSuggested('s'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- @deprecated class A {^} +- class _B {} +- A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^} +- class _B {} +- A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^ A(){}} +- class _B {} +- A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('String'); +- assertNotSuggested('T'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_field2() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as Soo; +- class A {final S^ A();} +- class _B {} +- A Sew;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('String'); +- assertNotSuggested('Sew'); +- assertNotSuggested('Soo'); +- } +- +- test_ClassDeclaration_body_final_final() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^ final foo;} +- class _B {} +- A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- assertNotSuggested('x'); +- } +- +- test_ClassDeclaration_body_final_var() async { +- // ClassDeclaration CompilationUnit +- addSource('/testB.dart', ''' +- class B { }'''); +- addTestSource(''' +- import "testB.dart" as x; +- class A {final ^ var foo;} +- class _B {} +- A T;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('_B'); +- assertNotSuggested('Object'); +- assertNotSuggested('T'); +- assertNotSuggested('x'); +- } +- +- test_Combinator_hide() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +- library libAB; +- part '/partAB.dart'; +- class A { } +- class B { }'''); +- addSource('/partAB.dart', ''' +- part of libAB; +- var T1; +- PB F1() =3D> new PB(); +- class PB { }'''); +- addSource('/testCD.dart', ''' +- class C { } +- class D { }'''); +- addTestSource(''' +- import "testAB.dart" hide ^; +- import "testCD.dart"; +- class X {}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_Combinator_show() async { +- // SimpleIdentifier HideCombinator ImportDirective +- addSource('/testAB.dart', ''' +- library libAB; +- part '/partAB.dart'; +- class A { } +- class B { }'''); +- addSource('/partAB.dart', ''' +- part of libAB; +- var T1; +- PB F1() =3D> new PB(); +- typedef PB2 F2(int blat); +- class Clz =3D Object with Object; +- class PB { }'''); +- addSource('/testCD.dart', ''' +- class C { } +- class D { }'''); +- addTestSource(''' +- import "testAB.dart" show ^; +- import "testCD.dart"; +- class X {}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ConditionalExpression_elseExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T1 : T^}}'''); +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_elseExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T1 : ^}}'''); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_partial_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T^}}'''); +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_partial_thenExpression_empty() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? ^}}'''); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConditionalExpression_thenExpression() async { +- // SimpleIdentifier ConditionalExpression ReturnStatement +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} return a ? T^ : c}}'''); +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_ConstructorName_importedClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- var m; +- main() {new X.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- var m; +- main() {new X.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_importedFactory2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- main() {new String.fr^omCharCodes([]);}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 13); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('fromCharCodes'); +- assertNotSuggested('isEmpty'); +- assertNotSuggested('isNotEmpty'); +- assertNotSuggested('length'); +- assertNotSuggested('Object'); +- assertNotSuggested('String'); +- } +- +- test_ConstructorName_localClass() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}} +- main() {new X.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_ConstructorName_localFactory() async { +- // SimpleIdentifier PrefixedIdentifier TypeName ConstructorName +- // InstanceCreationExpression +- addTestSource(''' +- int T1; +- F1() { } +- class X {factory X.c(); factory X._d(); z() {}} +- main() {new X.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by NamedConstructorContributor +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_DefaultFormalParameter_named_expression() async { +- // DefaultFormalParameter FormalParameterList MethodDeclaration +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {a(blat: ^) { }}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('String'); +- assertNotSuggested('identical'); +- assertNotSuggested('bar'); +- } +- +- test_enumConst() async { +- addTestSource('enum E { one, two } main() {E.^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- // Suggested by StaticMemberContributor +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- assertNotSuggested('index'); +- assertNotSuggested('values'); +- } +- +- test_enumConst2() async { +- addTestSource('enum E { one, two } main() {E.o^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- // Suggested by StaticMemberContributor +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- assertNotSuggested('index'); +- assertNotSuggested('values'); +- } +- +- test_enumConst3() async { +- addTestSource('enum E { one, two } main() {E.^ int g;}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- // Suggested by StaticMemberContributor +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- assertNotSuggested('index'); +- assertNotSuggested('values'); +- } +- +- test_enumConst_index() async { +- addTestSource('enum E { one, two } main() {E.one.^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- assertSuggestField('index', 'int'); +- assertNotSuggested('values'); +- } +- +- test_enumConst_index2() async { +- addTestSource('enum E { one, two } main() {E.one.i^}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- assertSuggestField('index', 'int'); +- assertNotSuggested('values'); +- } +- +- test_enumConst_index3() async { +- addTestSource('enum E { one, two } main() {E.one.^ int g;}'); +- await computeSuggestions(); +- assertNotSuggested('E'); +- assertNotSuggested('one'); +- assertNotSuggested('two'); +- assertSuggestField('index', 'int'); +- assertNotSuggested('values'); +- } +- +- test_ExpressionStatement_identifier() async { +- // SimpleIdentifier ExpressionStatement Block +- addSource('/testA.dart', ''' +- _B F1() { } +- class A {int x;} +- class _B { }'''); +- addTestSource(''' +- import "testA.dart"; +- typedef int F2(int blat); +- class Clz =3D Object with Object; +- class C {foo(){^} void bar() {}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertNotSuggested('C'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('F2'); +- assertNotSuggested('Clz'); +- assertNotSuggested('C'); +- assertNotSuggested('x'); +- assertNotSuggested('_B'); +- } +- +- test_ExpressionStatement_name() async { +- // ExpressionStatement Block BlockFunctionBody MethodDeclaration +- addSource('/testA.dart', ''' +- B T1; +- class B{}'''); +- addTestSource(''' +- import "testA.dart"; +- class C {a() {C ^}}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_typed() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "testA.dart"; +- class C {A ^}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_FieldDeclaration_name_var() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // FieldDeclaration +- addSource('/testA.dart', 'class A { }'); +- addTestSource(''' +- import "testA.dart"; +- class C {var ^}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_FieldFormalParameter_in_non_constructor() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource('class A {B(this.^foo) {}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 3); +- assertNoSuggestions(); +- } +- +- test_ForEachStatement_body_typed() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (int foo in bar) {^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_body_untyped() async { +- // Block ForEachStatement +- addTestSource('main(args) {for (foo in bar) {^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_iterable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (int foo in ^) {}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('Object'); +- } +- +- test_ForEachStatement_loopVariable() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ in args) {}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('String'); +- } +- +- test_ForEachStatement_loopVariable_type() async { +- // SimpleIdentifier ForEachStatement Block +- addTestSource('main(args) {for (^ foo in args) {}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('String'); +- } +- +- test_ForEachStatement_loopVariable_type2() async { +- // DeclaredIdentifier ForEachStatement Block +- addTestSource('main(args) {for (S^ foo in args) {}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('args'); +- assertNotSuggested('foo'); +- assertNotSuggested('String'); +- } +- +- test_FormalParameterList() async { +- // FormalParameterList MethodDeclaration +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {a(^) { }}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('String'); +- assertNotSuggested('identical'); +- assertNotSuggested('bar'); +- } +- +- test_ForStatement_body() async { +- // Block ForStatement +- addTestSource('main(args) {for (int i; i < 10; ++i) {^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('i'); +- assertNotSuggested('Object'); +- } +- +- test_ForStatement_condition() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; i^)}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- } +- +- test_ForStatement_initializer() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {List a; for (^)}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('int'); +- } +- +- test_ForStatement_updaters() async { +- // SimpleIdentifier ForStatement +- addTestSource('main() {for (int index =3D 0; index < 10; i^)}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- } +- +- test_ForStatement_updaters_prefix_expression() async { +- // SimpleIdentifier PrefixExpression ForStatement +- addTestSource(''' +- void bar() { } +- main() {for (int index =3D 0; index < 10; ++i^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('index'); +- assertNotSuggested('main'); +- assertNotSuggested('bar'); +- } +- +- test_FunctionDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- /* */ ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment2() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- /** */ ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionDeclaration_returnType_afterComment3() async { +- // FunctionDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- /// some dartdoc +- class C2 { } +- ^ zoo(z) { } String name;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_FunctionExpression_body_function() async { +- // Block BlockFunctionBody FunctionExpression +- addTestSource(''' +- void bar() { } +- String foo(List args) {x.then((R b) {^}'''); +- await computeSuggestions(); +- +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('args'); +- assertNotSuggested('b'); +- assertNotSuggested('Object'); +- } +- +- test_generic_field() async { +- addTestSource(''' +-class C { +- T t; +-} +-void f(C c) { +- c.^ +-} +-'''); +- await computeSuggestions(); +- assertSuggestField('t', 'int'); +- } +- +- test_generic_getter() async { +- addTestSource(''' +-class C { +- T get t =3D> null; +-} +-void f(C c) { +- c.^ +-} +-'''); +- await computeSuggestions(); +- assertSuggestGetter('t', 'int'); +- } +- +- test_generic_method() async { +- addTestSource(''' +-class C { +- T m(T t) {} +-} +-void f(C c) { +- c.^ +-} +-'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'in= t'); +- expect(suggestion.parameterTypes[0], 'int'); +- expect(suggestion.element.returnType, 'int'); +- expect(suggestion.element.parameters, '(int t)'); +- } +- +- test_generic_setter() async { +- addTestSource(''' +-class C { +- set t(T value) {} +-} +-void f(C c) { +- c.^ +-} +-'''); +- await computeSuggestions(); +- // TODO(paulberry): modify assertSuggestSetter so that we can pass 'i= nt' +- // as a parmeter to it, and it will check the appropriate field in +- // the suggestion object. +- CompletionSuggestion suggestion =3D assertSuggestSetter('t'); +- expect(suggestion.element.parameters, '(int value)'); +- } +- +- test_IfStatement() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (true) ^}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_condition() async { +- // SimpleIdentifier IfStatement Block BlockFunctionBody +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main(){var a; if (^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_IfStatement_empty() async { +- // SimpleIdentifier IfStatement +- addTestSource(''' +- class A {var b; X _c; foo() {A a; if (^) something}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_IfStatement_invocation() async { +- // SimpleIdentifier PrefixIdentifier IfStatement +- addTestSource(''' +- main() {var a; if (a.^) something}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestMethod('toString', 'Object', 'String'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ImportDirective_dart() async { +- // SimpleStringLiteral ImportDirective +- addTestSource(''' +- import "dart^"; +- main() {}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_IndexExpression() async { +- // ExpressionStatement Block +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} f[^]}}'''); +- await computeSuggestions(); +- assertNotSuggested('x'); +- assertNotSuggested('f'); +- assertNotSuggested('foo'); +- assertNotSuggested('C'); +- assertNotSuggested('F2'); +- assertNotSuggested('T2'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_IndexExpression2() async { +- // SimpleIdentifier IndexExpression ExpressionStatement Block +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- class B {int x;} +- class C {foo(){var f; {var x;} f[T^]}}'''); +- await computeSuggestions(); +- // top level results are partially filtered based on first char +- assertNotSuggested('T2'); +- // TODO (danrubel) getter is being suggested instead of top level var +- //assertSuggestImportedTopLevelVar('T1', 'int'); +- } +- +- test_InstanceCreationExpression_imported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- class A {A(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- import "dart:async"; +- int T2; +- F2() { } +- class B {B(this.x, [String boo]) { } int x;} +- class C {foo(){var f; {var x;} new ^}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('Future'); +- assertNotSuggested('A'); +- assertNotSuggested('B'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('foo'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- } +- +- test_InstanceCreationExpression_unimported() async { +- // SimpleIdentifier TypeName ConstructorName InstanceCreationExpre= ssion +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){new F^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('Future'); +- assertNotSuggested('Foo'); +- } +- +- test_InterpolationExpression() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- main() {String name; print("hello \$^");}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- // TODO(danrubel) should return top level var rather than getter +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_InterpolationExpression_block() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- main() {String name; print("hello \${^}");}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_InterpolationExpression_block2() async { +- // SimpleIdentifier InterpolationExpression StringInterpolation +- addTestSource('main() {String name; print("hello \${n^}");}'); +- await computeSuggestions(); +- assertNotSuggested('name'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- } +- +- test_InterpolationExpression_prefix_selector() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${name.^}");}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestGetter('length', 'int'); +- assertNotSuggested('name'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_InterpolationExpression_prefix_selector2() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \$name.^");}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_InterpolationExpression_prefix_target() async { +- // SimpleIdentifier PrefixedIdentifier InterpolationExpression +- addTestSource('main() {String name; print("hello \${nam^e.length}");}= '); +- await computeSuggestions(); +- assertNotSuggested('name'); +- // top level results are partially filtered +- //assertNotSuggested('Object'); +- assertNotSuggested('length'); +- } +- +- test_IsExpression() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addSource('/testB.dart', ''' +- lib B; +- foo() { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- class Y {Y.c(); Y._d(); z() {}} +- main() {var x; if (x is ^) { }}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('x'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- } +- +- test_IsExpression_target() async { +- // IfStatement Block BlockFunctionBody +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {int x; int y() =3D> 0;} +- main(){var a; if (^ is A)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main(){var a; if (a is ^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_IsExpression_type_partial() async { +- // SimpleIdentifier TypeName IsExpression IfStatement +- addTestSource(''' +- class A {int x; int y() =3D> 0;} +- main(){var a; if (a is Obj^)}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('a'); +- assertNotSuggested('main'); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- } +- +- test_keyword() async { +- addTestSource('class C { static C get instance =3D> null; } main() {C= .in^}'); +- await computeSuggestions(); +- // Suggested by StaticMemberContributor +- assertNotSuggested('instance'); +- } +- +- test_keyword2() async { +- addSource('/testB.dart', ''' +- lib B; +- int newT1; +- int T1; +- nowIsIt() { } +- class X {factory X.c(); factory X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- String newer() {} +- var m; +- main() {new^ X.c();}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('c'); +- assertNotSuggested('_d'); +- // Imported suggestion are filtered by 1st character +- assertNotSuggested('nowIsIt'); +- assertNotSuggested('T1'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- assertNotSuggested('newer'); +- } +- +- test_libraryPrefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('import "dart:async" as bar; foo() {bar.^}'); +- await computeSuggestions(); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('Future'); +- assertNotSuggested('loadLibrary'); +- } +- +- test_libraryPrefix2() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource('import "dart:async" as bar; foo() {bar.^ print("f")}'); +- await computeSuggestions(); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('Future'); +- } +- +- test_libraryPrefix3() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource('import "dart:async" as bar; foo() {new bar.F^ print("f= ")}'); +- await computeSuggestions(); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('Future'); +- assertNotSuggested('Future.delayed'); +- } +- +- test_libraryPrefix_deferred() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('import "dart:async" deferred as bar; foo() {bar.^}'); +- await computeSuggestions(); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('Future'); +- assertNotSuggested('loadLibrary'); +- } +- +- test_libraryPrefix_with_exports() async { +- addSource('/libA.dart', 'library libA; class A { }'); +- addSource('/libB.dart', 'library libB; export "/libA.dart"; class B {= }'); +- addTestSource('import "libB.dart" as foo; main() {foo.^} class C { }'= ); +- await computeSuggestions(); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('B'); +- assertNotSuggested('A'); +- } +- +- test_Literal_list() async { +- // ']' ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([^]);}'); +- await computeSuggestions(); +- assertNotSuggested('Some'); +- assertNotSuggested('String'); +- } +- +- test_Literal_list2() async { +- // SimpleIdentifier ListLiteral ArgumentList MethodInvocation +- addTestSource('main() {var Some; print([S^]);}'); +- await computeSuggestions(); +- assertNotSuggested('Some'); +- assertNotSuggested('String'); +- } +- +- test_Literal_string() async { +- // SimpleStringLiteral ExpressionStatement Block +- addTestSource('class A {a() {"hel^lo"}}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_local() async { +- addTestSource('foo() {String x =3D "bar"; x.^}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_local_is() async { +- addTestSource('foo() {var x; if (x is String) x.^}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_local_propogatedType() async { +- addTestSource('foo() {var x =3D "bar"; x.^}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_localVariableDeclarationName() async { +- addTestSource('main() {String m^}'); +- await computeSuggestions(); +- assertNotSuggested('main'); +- assertNotSuggested('min'); +- } +- +- test_MapLiteralEntry() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- foo =3D {^'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- } +- +- test_MapLiteralEntry1() async { +- // MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- foo =3D {T^'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('T2'); +- } +- +- test_MapLiteralEntry2() async { +- // SimpleIdentifier MapLiteralEntry MapLiteral VariableDeclaration +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { } +- foo =3D {7:T^};'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('T2'); +- } +- +- test_method_parameters_mixed_required_and_named() async { +- addTestSource(''' +-class C { +- void m(x, {int y}) {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_mixed_required_and_positional() async { +- addTestSource(''' +-class C { +- void m(x, [int y]) {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 1); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_named() async { +- addTestSource(''' +-class C { +- void m({x, int y}) {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, true); +- } +- +- test_method_parameters_none() async { +- addTestSource(''' +-class C { +- void m() {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'vo= id'); +- expect(suggestion.parameterNames, isEmpty); +- expect(suggestion.parameterTypes, isEmpty); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_positional() async { +- addTestSource(''' +-class C { +- void m([x, int y]) {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 0); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_method_parameters_required() async { +- addTestSource(''' +-class C { +- void m(x, int y) {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestMethod('m', 'C', 'vo= id'); +- expect(suggestion.parameterNames, hasLength(2)); +- expect(suggestion.parameterNames[0], 'x'); +- expect(suggestion.parameterTypes[0], 'dynamic'); +- expect(suggestion.parameterNames[1], 'y'); +- expect(suggestion.parameterTypes[1], 'int'); +- expect(suggestion.requiredParameterCount, 2); +- expect(suggestion.hasNamedParameters, false); +- } +- +- test_MethodDeclaration_body_getters() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X get f =3D> 0; Z a() {^} get _g = =3D> 1;}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- } +- +- test_MethodDeclaration_body_static() async { +- // Block BlockFunctionBody MethodDeclaration +- addSource('/testC.dart', ''' +- class C { +- c1() {} +- var c2; +- static c3() {} +- static var c4;}'''); +- addTestSource(''' +- import "testC.dart"; +- class B extends C { +- b1() {} +- var b2; +- static b3() {} +- static var b4;} +- class A extends B { +- a1() {} +- var a2; +- static a3() {} +- static var a4; +- static a() {^}}'''); +- await computeSuggestions(); +- assertNotSuggested('a1'); +- assertNotSuggested('a2'); +- assertNotSuggested('a3'); +- assertNotSuggested('a4'); +- assertNotSuggested('b1'); +- assertNotSuggested('b2'); +- assertNotSuggested('b3'); +- assertNotSuggested('b4'); +- assertNotSuggested('c1'); +- assertNotSuggested('c2'); +- assertNotSuggested('c3'); +- assertNotSuggested('c4'); +- } +- +- test_MethodDeclaration_members() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated X f; Z _a() {^} var _g;}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('_a'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('bool'); +- } +- +- test_MethodDeclaration_parameters_named() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {@deprecated Z a(X x, _, b, {y: boo}) {^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('b'); +- assertNotSuggested('int'); +- assertNotSuggested('_'); +- } +- +- test_MethodDeclaration_parameters_positional() async { +- // Block BlockFunctionBody MethodDeclaration +- addTestSource(''' +- foo() { } +- void bar() { } +- class A {Z a(X x, [int y=3D1]) {^}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('a'); +- assertNotSuggested('x'); +- assertNotSuggested('y'); +- assertNotSuggested('String'); +- } +- +- test_MethodDeclaration_returnType() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 {^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment() async { +- // ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 {/* */ ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment2() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 {/** */ ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodDeclaration_returnType_afterComment3() async { +- // MethodDeclaration ClassDeclaration CompilationUnit +- addSource('/testA.dart', ''' +- int T1; +- F1() { } +- typedef D1(); +- class C1 {C1(this.x) { } int x;}'''); +- addTestSource(''' +- import "testA.dart"; +- int T2; +- F2() { } +- typedef D2(); +- class C2 { +- /// some dartdoc +- ^ zoo(z) { } String name; }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('T1'); +- assertNotSuggested('F1'); +- assertNotSuggested('D1'); +- assertNotSuggested('C1'); +- assertNotSuggested('T2'); +- assertNotSuggested('F2'); +- assertNotSuggested('D2'); +- assertNotSuggested('C2'); +- assertNotSuggested('name'); +- } +- +- test_MethodInvocation_no_semicolon() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(r''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A(); F $p; void $q(= ){}} +- class A implements I { +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {x.^ m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestGetter('f', 'X'); +- assertSuggestGetter('_g', null); +- assertSuggestField(r'$p', 'dynamic', relevance: DART_RELEVANCE_LOW); +- assertSuggestMethod(r'$q', 'I', 'void', relevance: DART_RELEVANCE_LOW= ); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_new_instance() async { +- addTestSource('import "dart:math"; class A {x() {new Random().^}}'); +- await computeSuggestions(); +- assertSuggestMethod('nextBool', 'Random', 'bool'); +- assertSuggestMethod('nextDouble', 'Random', 'double'); +- assertSuggestMethod('nextInt', 'Random', 'int'); +- assertNotSuggested('Random'); +- assertNotSuggested('Object'); +- assertNotSuggested('A'); +- } +- +- test_no_parameters_field() async { +- addTestSource(''' +-class C { +- int x; +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestField('x', 'int'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_no_parameters_getter() async { +- addTestSource(''' +-class C { +- int get x =3D> null; +-} +-void main() {int y =3D new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestGetter('x', 'int'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_no_parameters_setter() async { +- addTestSource(''' +-class C { +- set x(int value) {}; +-} +-void main() {int y =3D new C().^}'''); +- await computeSuggestions(); +- CompletionSuggestion suggestion =3D assertSuggestSetter('x'); +- assertHasNoParameterInfo(suggestion); +- } +- +- test_only_instance() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addTestSource(''' +-class C { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {new C().^}'''); +- await computeSuggestions(); +- assertSuggestField('f1', 'int'); +- assertNotSuggested('f2'); +- assertSuggestMethod('m1', 'C', null); +- assertNotSuggested('m2'); +- } +- +- test_only_instance2() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource(''' +-class C { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {new C().^ print("something");}'''); +- await computeSuggestions(); +- assertSuggestField('f1', 'int'); +- assertNotSuggested('f2'); +- assertSuggestMethod('m1', 'C', null); +- assertNotSuggested('m2'); +- } +- +- test_only_static() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +-class C { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C.^}'''); +- await computeSuggestions(); +- assertNotSuggested('f1'); +- // Suggested by StaticMemberContributor +- assertNotSuggested('f2'); +- assertNotSuggested('m1'); +- assertNotSuggested('m2'); +- } +- +- test_only_static2() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource(''' +-class C { +- int f1; +- static int f2; +- m1() {} +- static m2() {} +-} +-void main() {C.^ print("something");}'''); +- await computeSuggestions(); +- assertNotSuggested('f1'); +- // Suggested by StaticMemberContributor +- assertNotSuggested('f2'); +- assertNotSuggested('m1'); +- assertNotSuggested('m2'); +- } +- +- test_param() async { +- addTestSource('foo(String x) {x.^}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_param_is() async { +- addTestSource('foo(x) {if (x is String) x.^}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_parameterName_excludeTypes() async { +- addTestSource('m(int ^) {}'); +- await computeSuggestions(); +- assertNotSuggested('int'); +- assertNotSuggested('bool'); +- } +- +- test_partFile_TypeName() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- library libA; +- import "testB.dart"; +- part "$testFile"; +- class A { } +- var m;'''); +- addTestSource(''' +- part of libA; +- class B { factory B.bar(int x) =3D> null; } +- main() {new ^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('B.bar'); +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('A'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_partFile_TypeName2() async { +- // SimpleIdentifier TypeName ConstructorName +- addSource('/testB.dart', ''' +- lib B; +- int T1; +- F1() { } +- class X {X.c(); X._d(); z() {}}'''); +- addSource('/testA.dart', ''' +- part of libA; +- class B { }'''); +- addTestSource(''' +- library libA; +- import "testB.dart"; +- part "/testA.dart"; +- class A { A({String boo: 'hoo'}) { } } +- main() {new ^} +- var m;'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('A'); +- assertNotSuggested('Object'); +- assertNotSuggested('X.c'); +- assertNotSuggested('X._d'); +- assertNotSuggested('B'); +- assertNotSuggested('F1'); +- assertNotSuggested('T1'); +- assertNotSuggested('_d'); +- assertNotSuggested('z'); +- assertNotSuggested('m'); +- } +- +- test_PrefixedIdentifier_class_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block +- addSource('/testB.dart', ''' +- lib B; +- class I { +- static const scI =3D 'boo'; +- X get f =3D> new A(); +- get _g =3D> new A();} +- class B implements I { +- static const int scB =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- addTestSource(''' +- import "testB.dart"; +- class A extends B { +- static const String scA =3D 'foo'; +- w() { }} +- main() {A.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by StaticMemberContributor +- assertNotSuggested('scA'); +- assertNotSuggested('scB'); +- assertNotSuggested('scI'); +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('w'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_imported() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- static const int sc =3D 12; +- @deprecated var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- addTestSource(''' +- import "testB.dart"; +- main() {A a; a.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertSuggestField('b', null, isDeprecated: true); +- assertNotSuggested('_c'); +- assertSuggestGetter('d', 'X'); +- assertNotSuggested('_e'); +- assertSuggestGetter('f', 'X'); +- assertNotSuggested('_g'); +- assertSuggestSetter('s1'); +- assertNotSuggested('_s2'); +- assertSuggestMethod('m', 'A', null); +- assertNotSuggested('_n'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_class_local() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource(''' +- main() {A a; a.^} +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- static const int sc =3D 12; +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- set s1(I x) {} set _s2(I x) {} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('sc'); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertSuggestGetter('d', 'X'); +- assertSuggestGetter('_e', null); +- assertSuggestGetter('f', 'X'); +- assertSuggestGetter('_g', null); +- assertSuggestSetter('s1'); +- assertSuggestSetter('_s2'); +- assertSuggestMethod('m', 'A', null); +- assertSuggestMethod('_n', 'A', 'I'); +- assertNotSuggested('a'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_library() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "testB.dart" as b; +- var T2; +- class A { } +- main() {b.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "testB.dart" as b; +- var T2; +- class A { } +- foo(b.^ f) {}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_library_typesOnly2() async { +- // SimpleIdentifier PrefixedIdentifier TypeName +- addSource('/testB.dart', ''' +- lib B; +- var T1; +- class X { } +- class Y { }'''); +- addTestSource(''' +- import "testB.dart" as b; +- var T2; +- class A { } +- foo(b.^) {}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Suggested by LibraryMemberContributor +- assertNotSuggested('X'); +- assertNotSuggested('Y'); +- assertNotSuggested('T1'); +- assertNotSuggested('T2'); +- assertNotSuggested('Object'); +- assertNotSuggested('b'); +- assertNotSuggested('A'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_parameter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testB.dart', ''' +- lib B; +- class _W {M y; var _z;} +- class X extends _W {} +- class M{}'''); +- addTestSource(''' +- import "testB.dart"; +- foo(X x) {x.^}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('y', 'M'); +- assertNotSuggested('_z'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PrefixedIdentifier_prefix() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addSource('/testA.dart', ''' +- class A {static int bar =3D 10;} +- _B() {}'''); +- addTestSource(''' +- import "testA.dart"; +- class X {foo(){A^.bar}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('foo'); +- assertNotSuggested('bar'); +- assertNotSuggested('_B'); +- } +- +- test_PrefixedIdentifier_propertyAccess() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestGetter('isEmpty', 'bool'); +- assertSuggestMethod('compareTo', 'Comparable', 'int'); +- } +- +- test_PrefixedIdentifier_propertyAccess_newStmt() async { +- // PrefixedIdentifier ExpressionStatement Block BlockFunctionBody +- addTestSource('class A {String x; int get foo {x.^ int y =3D 0;}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestGetter('isEmpty', 'bool'); +- assertSuggestMethod('compareTo', 'Comparable', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_const() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('const String g =3D "hello"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_const_untyped() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('const g =3D "hello"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestMethod('toString', 'Object', 'String'); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_field() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g; f() {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_function() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g() =3D> "one"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_functionTypeAlias() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('typedef String g(); f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_getter() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String get g =3D> "one"; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_typed() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {String g; g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_local_untyped() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f() {var g =3D "hello"; g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_method() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {String g() {}; f() {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('class A {f(String g) {g.^ int y =3D 0;}}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_param2() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('f(String g) {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PrefixedIdentifier_trailingStmt_topLevelVar() async { +- // SimpleIdentifier PrefixedIdentifier ExpressionStatement +- addTestSource('String g; f() {g.^ int y =3D 0;}'); +- await computeSuggestions(); +- assertSuggestGetter('length', 'int'); +- } +- +- test_PropertyAccess_expression() async { +- // SimpleIdentifier MethodInvocation PropertyAccess ExpressionStat= ement +- addTestSource('class A {a() {"hello".to^String().length}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 8); +- assertSuggestGetter('length', 'int'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_PropertyAccess_noTarget() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('class C {foo(){.^}}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_noTarget2() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement +- addSource('/testAB.dart', 'class Foo { }'); +- addTestSource('main() {.^}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_PropertyAccess_selector() async { +- // SimpleIdentifier PropertyAccess ExpressionStatement Block +- addTestSource('class A {a() {"hello".length.^}}'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestGetter('isEven', 'bool'); +- assertNotSuggested('A'); +- assertNotSuggested('a'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_shadowing_field_over_field() =3D> +- check_shadowing('int x;', 'int x;', true); +- +- test_shadowing_field_over_getter() =3D> +- check_shadowing('int x;', 'int get x =3D> null;', true); +- +- test_shadowing_field_over_method() =3D> +- check_shadowing('int x;', 'void x() {}', true); +- +- test_shadowing_field_over_setter() =3D> +- check_shadowing('int x;', 'set x(int value) {}', true); +- +- test_shadowing_getter_over_field() =3D> +- check_shadowing('int get x =3D> null;', 'int x;', false); +- +- test_shadowing_getter_over_getter() =3D> +- check_shadowing('int get x =3D> null;', 'int get x =3D> null;', tru= e); +- +- test_shadowing_getter_over_method() =3D> +- check_shadowing('int get x =3D> null;', 'void x() {}', true); +- +- test_shadowing_getter_over_setter() =3D> +- check_shadowing('int get x =3D> null;', 'set x(int value) {}', fals= e); +- +- test_shadowing_method_over_field() =3D> +- check_shadowing('void x() {}', 'int x;', true); +- +- test_shadowing_method_over_getter() =3D> +- check_shadowing('void x() {}', 'int get x =3D> null;', true); +- +- test_shadowing_method_over_method() =3D> +- check_shadowing('void x() {}', 'void x() {}', true); +- +- test_shadowing_method_over_setter() =3D> +- check_shadowing('void x() {}', 'set x(int value) {}', true); +- +- test_shadowing_mixin_order() async { +- addTestSource(''' +-class Base { +-} +-class Mixin1 { +- void f() {} +-} +-class Mixin2 { +- void f() {} +-} +-class Derived extends Base with Mixin1, Mixin2 { +-} +-void test(Derived d) { +- d.^ +-} +-'''); +- await computeSuggestions(); +- // Note: due to dartbug.com/22069, analyzer currently analyzes mixins= in +- // reverse order. The correct order is that Derived inherits from +- // "Base with Mixin1, Mixin2", which inherits from "Base with Mixin1", +- // which inherits from "Base". So the definition of f in Mixin2 shou= ld +- // shadow the definition in Mixin1. +- assertSuggestMethod('f', 'Mixin2', 'void'); +- } +- +- test_shadowing_mixin_over_superclass() async { +- addTestSource(''' +-class Base { +- void f() {} +-} +-class Mixin { +- void f() {} +-} +-class Derived extends Base with Mixin { +-} +-void test(Derived d) { +- d.^ +-} +-'''); +- await computeSuggestions(); +- assertSuggestMethod('f', 'Mixin', 'void'); +- } +- +- test_shadowing_setter_over_field() =3D> +- check_shadowing('set x(int value) {}', 'int x;', false); +- +- test_shadowing_setter_over_getter() =3D> +- check_shadowing('set x(int value) {}', 'int get x =3D> null;', fals= e); +- +- test_shadowing_setter_over_method() =3D> +- check_shadowing('set x(int value) {}', 'void x() {}', true); +- +- test_shadowing_setter_over_setter() =3D> +- check_shadowing('set x(int value) {}', 'set x(int value) {}', true); +- +- test_shadowing_superclass_over_interface() async { +- addTestSource(''' +-class Base { +- void f() {} +-} +-class Interface { +- void f() {} +-} +-class Derived extends Base implements Interface { +-} +-void test(Derived d) { +- d.^ +-} +-'''); +- await computeSuggestions(); +- assertSuggestMethod('f', 'Base', 'void'); +- } +- +- test_super() async { +- // SimpleIdentifier MethodInvocation ExpressionStatement +- addTestSource(''' +-class C3 { +- int fi3; +- static int fs3; +- m() {} +- mi3() {} +- static ms3() {} +-} +-class C2 { +- int fi2; +- static int fs2; +- m() {} +- mi2() {} +- static ms2() {} +-} +-class C1 extends C2 implements C3 { +- int fi1; +- static int fs1; +- m() {super.^} +- mi1() {} +- static ms1() {} +-}'''); +- await computeSuggestions(); +- assertNotSuggested('fi1'); +- assertNotSuggested('fs1'); +- assertNotSuggested('mi1'); +- assertNotSuggested('ms1'); +- assertSuggestField('fi2', 'int'); +- assertNotSuggested('fs2'); +- assertSuggestMethod('mi2', 'C2', null); +- assertNotSuggested('ms2'); +- assertSuggestMethod('m', 'C2', null, relevance: DART_RELEVANCE_HIGH); +- assertNotSuggested('fi3'); +- assertNotSuggested('fs3'); +- assertNotSuggested('mi3'); +- assertNotSuggested('ms3'); +- } +- +- test_SwitchStatement_c() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {c^}}}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_SwitchStatement_case() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {var t; switch(x) {case 0: ^}= }}'); +- await computeSuggestions(); +- assertNotSuggested('A'); +- assertNotSuggested('g'); +- assertNotSuggested('t'); +- assertNotSuggested('String'); +- } +- +- test_SwitchStatement_empty() async { +- // SwitchStatement Block BlockFunctionBody MethodDeclaration +- addTestSource('class A {String g(int x) {switch(x) {^}}}'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_ThisExpression_block() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A() {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {this.^ m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertSuggestGetter('d', 'X'); +- assertSuggestGetter('_e', null); +- assertSuggestGetter('f', 'X'); +- assertSuggestGetter('_g', null); +- assertSuggestMethod('m', 'A', null); +- assertSuggestMethod('_n', 'A', 'I'); +- assertSuggestSetter('s1'); +- assertSuggestSetter('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor() async { +- // MethodInvocation ExpressionStatement Block +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A() {this.^} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestField('b', null); +- assertSuggestField('_c', 'X'); +- assertSuggestGetter('d', 'X'); +- assertSuggestGetter('_e', null); +- assertSuggestGetter('f', 'X'); +- assertSuggestGetter('_g', null); +- assertSuggestMethod('m', 'A', null); +- assertSuggestMethod('_n', 'A', 'I'); +- assertSuggestSetter('s1'); +- assertSuggestSetter('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.^) {} +- A.z() {} +- var b; X _c; static sb; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('sb'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param2() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.b^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param3() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.^b) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('b'); +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_ThisExpression_constructor_param4() async { +- // SimpleIdentifier FieldFormalParameter FormalParameterList +- addTestSource(''' +- main() { } +- class I {X get f =3D> new A();get _g =3D> new A();} +- class A implements I { +- A(this.b, this.^) {} +- A.z() {} +- var b; X _c; +- X get d =3D> new A();get _e =3D> new A(); +- // no semicolon between completion point and next statement +- set s1(I x) {} set _s2(I x) {m(null);} +- m(X x) {} I _n(X x) {}} +- class X{}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('b'); +- // Contributed by FieldFormalConstructorContributor +- assertNotSuggested('_c'); +- assertNotSuggested('d'); +- assertNotSuggested('_e'); +- assertNotSuggested('f'); +- assertNotSuggested('_g'); +- assertNotSuggested('m'); +- assertNotSuggested('_n'); +- assertNotSuggested('s1'); +- assertNotSuggested('_s2'); +- assertNotSuggested('z'); +- assertNotSuggested('I'); +- assertNotSuggested('A'); +- assertNotSuggested('X'); +- assertNotSuggested('Object'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_TopLevelVariableDeclaration_typed_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} B ^'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_TopLevelVariableDeclaration_untyped_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // TopLevelVariableDeclaration +- addTestSource('class A {} var ^'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_TypeArgumentList() async { +- // SimpleIdentifier BinaryExpression ExpressionStatement +- addSource('/testA.dart', ''' +- class C1 {int x;} +- F1() =3D> 0; +- typedef String T1(int blat);'''); +- addTestSource(''' +- import "testA.dart";' +- class C2 {int x;} +- F2() =3D> 0; +- typedef int T2(int blat); +- class C {} +- main() { C<^> c; }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('Object'); +- assertNotSuggested('C1'); +- assertNotSuggested('T1'); +- assertNotSuggested('C2'); +- assertNotSuggested('T2'); +- assertNotSuggested('F1'); +- assertNotSuggested('F2'); +- } +- +- test_TypeArgumentList2() async { +- // TypeName TypeArgumentList TypeName +- addSource('/testA.dart', ''' +- class C1 {int x;} +- F1() =3D> 0; +- typedef String T1(int blat);'''); +- addTestSource(''' +- import "testA.dart";' +- class C2 {int x;} +- F2() =3D> 0; +- typedef int T2(int blat); +- class C {} +- main() { C c; }'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertNotSuggested('C1'); +- assertNotSuggested('C2'); +- } +- +- test_VariableDeclaration_name() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement Block +- addSource('/testB.dart', ''' +- lib B; +- foo() { } +- class _B { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- class Y {Y.c(); Y._d(); z() {}} +- main() {var ^}'''); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_VariableDeclarationList_final() async { +- // VariableDeclarationList VariableDeclarationStatement Block +- addTestSource('main() {final ^} class C { }'); +- await computeSuggestions(); +- assertNotSuggested('Object'); +- assertNotSuggested('C'); +- assertNotSuggested('=3D=3D'); +- } +- +- test_VariableDeclarationStatement_RHS() async { +- // SimpleIdentifier VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +- lib B; +- foo() { } +- class _B { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- class Y {Y.c(); Y._d(); z() {}} +- class C {bar(){var f; {var x;} var e =3D ^}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('_B'); +- assertNotSuggested('Y'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +- +- test_VariableDeclarationStatement_RHS_missing_semicolon() async { +- // VariableDeclaration VariableDeclarationList +- // VariableDeclarationStatement +- addSource('/testB.dart', ''' +- lib B; +- foo1() { } +- void bar1() { } +- class _B { } +- class X {X.c(); X._d(); z() {}}'''); +- addTestSource(''' +- import "testB.dart"; +- foo2() { } +- void bar2() { } +- class Y {Y.c(); Y._d(); z() {}} +- class C {bar(){var f; {var x;} var e =3D ^ var g}}'''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('X'); +- assertNotSuggested('foo1'); +- assertNotSuggested('bar1'); +- assertNotSuggested('foo2'); +- assertNotSuggested('bar2'); +- assertNotSuggested('_B'); +- assertNotSuggested('Y'); +- assertNotSuggested('C'); +- assertNotSuggested('f'); +- assertNotSuggested('x'); +- assertNotSuggested('e'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/uri_contrib= utor_test.dart b/pkg/analysis_server/test/services/completion/dart/uri_cont= ributor_test.dart +deleted file mode 100644 +index 008498450d6..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/uri_contributor_te= st.dart ++++ /dev/null +@@ -1,682 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/uri_contribu= tor.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:path/path.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(UriContributorTest); +- defineReflectiveTests(UriContributorWindowsTest); +- }); +-} +- +-@reflectiveTest +-class UriContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new UriContributor(); +- } +- +- test_after_import() async { +- addTestSource('import "p"^'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_after_import_raw() async { +- addTestSource('import r"p"^'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_before_import() async { +- addTestSource('import ^"p"'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_before_import_raw() async { +- addTestSource('import ^r"p"'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_before_import_raw2() async { +- addTestSource('import r^"p"'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_export_package2() async { +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('export "package:foo/baz/^" import'); +- await computeSuggestions(); +- assertSuggest('package:foo/baz/too.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_export_package2_off() async { +- try { +- UriContributor.suggestFilePaths =3D false; +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('export "package:foo/baz/^" import'); +- await computeSuggestions(); +- assertNotSuggested('package:foo/baz/too.dart'); +- } finally { +- UriContributor.suggestFilePaths =3D true; +- } +- } +- +- test_import() async { +- addTestSource('import "^"'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import2() async { +- addTestSource('import "^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import3() async { +- addTestSource('import "^ import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 7); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_dart() async { +- addTestSource('import "d^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('dart:core', +- csKind: CompletionSuggestionKind.IMPORT, relevance: DART_RELEVANC= E_LOW); +- assertNotSuggested('dart:_internal'); +- assertSuggest('dart:async', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('dart:math', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_dart2() async { +- addTestSource('import "dart:async"; import "d^"'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('dart:core', +- csKind: CompletionSuggestionKind.IMPORT, relevance: DART_RELEVANC= E_LOW); +- assertNotSuggested('dart:_internal'); +- assertSuggest('dart:async', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('dart:math', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_file() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('import "^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file2() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('import "..^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 2); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file2_off() async { +- try { +- UriContributor.suggestFilePaths =3D false; +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('import "..^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 2); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } finally { +- UriContributor.suggestFilePaths =3D true; +- } +- } +- +- test_import_file_child() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('import "foo/^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 4); +- expect(replacementLength, 4); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertSuggest('foo/bar.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file_outside_lib() async { +- testFile =3D '/proj/lib/completion.dart'; +- addSource('/proj/lib/other.dart', 'library other;'); +- addSource('/proj/lib/foo/bar.dart', 'library bar;'); +- addSource('/proj/blat.dart', 'library blat;'); +- addSource('/proj/bin/boo.dart', 'library boo;'); +- addTestSource('import "../^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../bin'); +- assertNotSuggested('../bin/'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file_parent() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addSource('/proj2/boo.dart', 'library boo;'); +- addTestSource('import "../^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertSuggest('../blat.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- assertSuggest('../proj2/', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_file_parent2() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('import "../b^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 4); +- expect(replacementLength, 4); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertSuggest('../blat.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- } +- +- test_import_package() async { +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('import "p^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:foo/', csKind: CompletionSuggestionKind.IMPORT= ); +- assertSuggest('package:foo/foo.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:foo/baz/', csKind: CompletionSuggestionKind.IM= PORT); +- assertNotSuggested('package:foo/baz/too.dart'); +- assertSuggest('package:bar/', csKind: CompletionSuggestionKind.IMPORT= ); +- assertSuggest('package:bar/bar.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_package2() async { +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('import "package:foo/baz/^" import'); +- await computeSuggestions(); +- assertSuggest('package:foo/baz/too.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_package2_off() async { +- try { +- UriContributor.suggestFilePaths =3D false; +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('import "package:foo/baz/^" import'); +- await computeSuggestions(); +- assertNotSuggested('package:foo/baz/too.dart'); +- } finally { +- UriContributor.suggestFilePaths =3D true; +- } +- } +- +- test_import_package2_raw() async { +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('import r"package:foo/baz/^" import'); +- await computeSuggestions(); +- assertSuggest('package:foo/baz/too.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_package2_with_trailing() async { +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('import "package:foo/baz/^.dart" import'); +- await computeSuggestions(); +- assertSuggest('package:foo/baz/too.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- expect(replacementOffset, completionOffset - 16); +- expect(replacementLength, 5 + 16); +- } +- +- test_import_package_missing_lib() async { +- var pkgSrc =3D addPackageSource('bar', 'bar.dart', 'library bar;'); +- provider.deleteFolder(dirname(pkgSrc.fullName)); +- addTestSource('import "p^" class'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:bar/', csKind: CompletionSuggestionKind.IMPORT= ); +- assertNotSuggested('package:bar/bar.dart'); +- } +- +- test_import_package_raw() async { +- addPackageSource('foo', 'foo.dart', 'library foo;'); +- addPackageSource('foo', 'baz/too.dart', 'library too;'); +- addPackageSource('bar', 'bar.dart', 'library bar;'); +- addTestSource('import r"p^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:foo/', csKind: CompletionSuggestionKind.IMPORT= ); +- assertSuggest('package:foo/foo.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:foo/baz/', csKind: CompletionSuggestionKind.IM= PORT); +- assertNotSuggested('package:foo/baz/too.dart'); +- assertSuggest('package:bar/', csKind: CompletionSuggestionKind.IMPORT= ); +- assertSuggest('package:bar/bar.dart', +- csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_raw() async { +- addTestSource('import r"^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_without_any_quotes() async { +- addTestSource('import ^ import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_import_without_any_quotes_eof() async { +- addTestSource('import ^'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNoSuggestions(); +- } +- +- test_import_without_closing_quote_eof() async { +- addTestSource('import "^'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_without_closing_quote_eof2() async { +- addTestSource('import "^d'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 1); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_without_closing_quote_eof3() async { +- addTestSource('import "d^'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_import_without_closing_quote_eof4() async { +- addTestSource('import "d^"'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 1); +- expect(replacementLength, 1); +- assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT); +- assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT); +- } +- +- test_outside_import() async { +- addTestSource('import ^"d" import'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_outside_import2() async { +- addTestSource('import "d"^ import'); +- await computeSuggestions(); +- assertNoSuggestions(); +- } +- +- test_part_file() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('library x; part "^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_part_file2() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('library x; part "..^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 2); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_part_file_child() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('library x; part "foo/^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 4); +- expect(replacementLength, 4); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertSuggest('foo/bar.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- assertNotSuggested('../blat.dart'); +- } +- +- test_part_file_parent() async { +- testFile =3D '/proj/completion.dart'; +- addSource('/proj/other.dart', 'library other;'); +- addSource('/proj/foo/bar.dart', 'library bar;'); +- addSource('/blat.dart', 'library blat;'); +- addTestSource('library x; part "../^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertSuggest('../blat.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- } +-} +- +-@reflectiveTest +-class UriContributorWindowsTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new UriContributor(); +- } +- +- @override +- void setupResourceProvider() { +- provider =3D new _TestWinResourceProvider(); +- } +- +- test_import_file() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('import "^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file2() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('import "..^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 2); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file_child() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('import "foo/^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 4); +- expect(replacementLength, 4); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertSuggest('foo/bar.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- assertNotSuggested('../blat.dart'); +- } +- +- test_import_file_parent() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('import "../^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertSuggest('../blat.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- } +- +- test_import_file_parent2() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('import "../b^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 4); +- expect(replacementLength, 4); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertSuggest('../blat.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- } +- +- test_part_file() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('library x; part "^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_part_file2() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('library x; part "..^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 2); +- expect(replacementLength, 2); +- assertNotSuggested('completion.dart'); +- assertSuggest('other.dart', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo'); +- assertSuggest('foo/', csKind: CompletionSuggestionKind.IMPORT); +- assertNotSuggested('foo/bar.dart'); +- assertNotSuggested('../blat.dart'); +- } +- +- test_part_file_child() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('library x; part "foo/^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 4); +- expect(replacementLength, 4); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertSuggest('foo/bar.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- assertNotSuggested('../blat.dart'); +- } +- +- test_part_file_parent() async { +- testFile =3D '\\proj\\completion.dart'; +- addSource('\\proj\\other.dart', 'library other;'); +- addSource('\\proj\\foo\\bar.dart', 'library bar;'); +- addSource('\\blat.dart', 'library blat;'); +- addTestSource('library x; part "../^" import'); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertNotSuggested('completion.dart'); +- assertNotSuggested('other.dart'); +- assertNotSuggested('foo'); +- assertNotSuggested('foo/'); +- assertNotSuggested('foo/bar.dart'); +- assertSuggest('../blat.dart', csKind: CompletionSuggestionKind.IMPORT= ); +- } +-} +- +-class _TestWinResourceProvider extends MemoryResourceProvider { +- @override +- Context get pathContext =3D> windows; +-} +diff --git a/pkg/analysis_server/test/services/completion/dart/variable_na= me_contributor_test.dart b/pkg/analysis_server/test/services/completion/dar= t/variable_name_contributor_test.dart +deleted file mode 100644 +index f1f2c23828e..00000000000 +--- a/pkg/analysis_server/test/services/completion/dart/variable_name_cont= ributor_test.dart ++++ /dev/null +@@ -1,244 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/provisional/completion/dart/completio= n_dart.dart'; +-import 'package:analysis_server/src/services/completion/dart/variable_nam= e_contributor.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion_contributor_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(VariableNameContributorTest); +- }); +-} +- +-@reflectiveTest +-class VariableNameContributorTest extends DartCompletionContributorTest { +- @override +- DartCompletionContributor createContributor() { +- return new VariableNameContributor(); +- } +- +- test_ExpressionStatement_dont_suggest_type() async { +- addTestSource(''' +- f() { a ^ } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- } +- +- test_ExpressionStatement_dont_suggest_type_semicolon() async { +- addTestSource(''' +- f() { a ^; } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- } +- +- test_ExpressionStatement_long() async { +- addTestSource(''' +- f() { AbstractCrazyNonsenseClassName ^ } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_ExpressionStatement_long_semicolon() async { +- addTestSource(''' +- f() { AbstractCrazyNonsenseClassName ^; } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_ExpressionStatement_prefixed() async { +- addTestSource(''' +- f() { prefix.AbstractCrazyNonsenseClassName ^ } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_ExpressionStatement_prefixed_semicolon() async { +- addTestSource(''' +- f() { prefix.AbstractCrazyNonsenseClassName ^; } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_ExpressionStatement_short() async { +- addTestSource(''' +- f() { A ^ } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('a'); +- } +- +- test_ExpressionStatement_short_semicolon() async { +- addTestSource(''' +- f() { A ^; } +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('a'); +- } +- +- test_TopLevelVariableDeclaration_dont_suggest_type() async { +- addTestSource(''' +- a ^ +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- } +- +- test_TopLevelVariableDeclaration_dont_suggest_type_semicolon() async { +- addTestSource(''' +- a ^; +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertNotSuggested('a'); +- } +- +- test_TopLevelVariableDeclaration_long() async { +- addTestSource(''' +- AbstractCrazyNonsenseClassName ^ +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_TopLevelVariableDeclaration_long_semicolon() async { +- addTestSource(''' +- AbstractCrazyNonsenseClassName ^; +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_TopLevelVariableDeclaration_partial() async { +- addTestSource(''' +- AbstractCrazyNonsenseClassName abs^ +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_TopLevelVariableDeclaration_partial_semicolon() async { +- addTestSource(''' +- AbstractCrazyNonsenseClassName abs^ +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset - 3); +- expect(replacementLength, 3); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_TopLevelVariableDeclaration_prefixed() async { +- addTestSource(''' +- prefix.AbstractCrazyNonsenseClassName ^ +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_TopLevelVariableDeclaration_prefixed_semicolon() async { +- addTestSource(''' +- prefix.AbstractCrazyNonsenseClassName ^; +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('abstractCrazyNonsenseClassName'); +- assertSuggestName('crazyNonsenseClassName'); +- assertSuggestName('nonsenseClassName'); +- assertSuggestName('className'); +- assertSuggestName('name'); +- } +- +- test_TopLevelVariableDeclaration_short() async { +- addTestSource(''' +- A ^ +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('a'); +- } +- +- test_TopLevelVariableDeclaration_short_semicolon() async { +- addTestSource(''' +- A ^; +- '''); +- await computeSuggestions(); +- expect(replacementOffset, completionOffset); +- expect(replacementLength, 0); +- assertSuggestName('a'); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/postfix/postfix_= completion_test.dart b/pkg/analysis_server/test/services/completion/postfix= /postfix_completion_test.dart +deleted file mode 100644 +index 244b2b270e5..00000000000 +--- a/pkg/analysis_server/test/services/completion/postfix/postfix_complet= ion_test.dart ++++ /dev/null +@@ -1,709 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/services/completion/postfix/postfix_c= ompletion.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(_AssertTest); +- defineReflectiveTests(_ForTest); +- defineReflectiveTests(_NegateTest); +- defineReflectiveTests(_IfTest); +- defineReflectiveTests(_NotNullTest); +- defineReflectiveTests(_ParenTest); +- defineReflectiveTests(_ReturnTest); +- defineReflectiveTests(_SwitchTest); +- defineReflectiveTests(_TryTest); +- defineReflectiveTests(_WhileTest); +- }); +-} +- +-class PostfixCompletionTest extends AbstractSingleUnitTest { +- SourceChange change; +- +- void _assertHasChange(String message, String expectedCode, [Function cm= p]) { +- if (change.message =3D=3D message) { +- if (!change.edits.isEmpty) { +- String resultCode =3D +- SourceEdit.applySequence(testCode, change.edits[0].edits); +- expect(resultCode, expectedCode.replaceAll('/*caret*/', '')); +- if (cmp !=3D null) { +- int offset =3D cmp(resultCode); +- expect(change.selection.offset, offset); +- } +- } else { +- if (cmp !=3D null) { +- int offset =3D cmp(testCode); +- expect(change.selection.offset, offset); +- } +- } +- return; +- } +- fail("Expected to find |$message| but got: " + change.message); +- } +- +- _computeCompletion(int offset, String key) async { +- driver.changeFile(testFile); +- AnalysisResult result =3D await driver.getResult(testFile); +- PostfixCompletionContext context =3D new PostfixCompletionContext( +- testFile, +- result.lineInfo, +- offset, +- key, +- result.driver, +- testUnit, +- testUnitElement, +- result.errors); +- PostfixCompletionProcessor processor =3D +- new PostfixCompletionProcessor(context); +- bool isApplicable =3D await processor.isApplicable(); +- if (!isApplicable) { +- fail("Postfix completion not applicable at given location"); +- } +- PostfixCompletion completion =3D await processor.compute(); +- change =3D completion.change; +- } +- +- _prepareCompletion(String key, String sourceCode) async { +- testCode =3D sourceCode.replaceAll('////', ''); +- int offset =3D findOffset(key); +- testCode =3D testCode.replaceFirst(key, '', offset); +- await _prepareCompletionAt(offset, key, testCode); +- } +- +- _prepareCompletionAt(int offset, String key, String sourceCode) async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(sourceCode); +- await _computeCompletion(offset, key); +- } +-} +- +-@reflectiveTest +-class _AssertTest extends PostfixCompletionTest { +- test_assert() async { +- await _prepareCompletion('.assert', ''' +-f(bool expr) { +- expr.assert +-} +-'''); +- _assertHasChange('Expand .assert', ''' +-f(bool expr) { +- assert(expr); +-} +-'''); +- } +- +- test_assertFunc() async { +- await _prepareCompletion('.assert', ''' +-f() { +- () =3D> true.assert +-} +-'''); +- _assertHasChange('Expand .assert', ''' +-f() { +- assert(() =3D> true); +-} +-'''); +- } +- +- @failingTest +- test_assertFunc_invalid() async { +- await _prepareCompletion('.assert', ''' +-f() { +- () =3D> null.assert +-} +-'''); +- } +- +- test_assertFuncCmp() async { +- await _prepareCompletion('.assert', ''' +-f(int x, int y) { +- () =3D> x + 3 > y + 4.assert +-} +-'''); +- _assertHasChange('Expand .assert', ''' +-f(int x, int y) { +- assert(() =3D> x + 3 > y + 4); +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _ForTest extends PostfixCompletionTest { +- @failingTest +- test_for_invalid() async { +- await _prepareCompletion('.for', ''' +-f() { +- {}.for +-} +-'''); +- } +- +- test_forEmptyDynamic() async { +- await _prepareCompletion('.for', ''' +-f() { +- [].for +-} +-'''); +- _assertHasChange('Expand .for', ''' +-f() { +- for (var value in []) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_forEmptyString() async { +- await _prepareCompletion('.for', ''' +-f() { +- [].for +-} +-'''); +- _assertHasChange('Expand .for', ''' +-f() { +- for (var value in []) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_fori() async { +- await _prepareCompletion('.fori', ''' +-f() { +- 100.fori +-} +-'''); +- _assertHasChange('Expand .fori', ''' +-f() { +- for (int i =3D 0; i < 100; i++) { +- /*caret*/ +- } +-} +-'''); +- } +- +- @failingTest +- test_fori_invalid() async { +- await _prepareCompletion('.fori', ''' +-f() { +- [].fori +-} +-'''); +- } +- +- test_forIntList() async { +- await _prepareCompletion('.for', ''' +-f() { +- [1,2,3].for +-} +-'''); +- _assertHasChange('Expand .for', ''' +-f() { +- for (var value in [1,2,3]) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_foriVar() async { +- await _prepareCompletion('.fori', ''' +-f() { +- var n =3D 100; +- n.fori +-} +-'''); +- _assertHasChange('Expand .fori', ''' +-f() { +- var n =3D 100; +- for (int i =3D 0; i < n; i++) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_iterList() async { +- await _prepareCompletion('.iter', ''' +-f() { +- [1,2,3].iter +-} +-'''); +- _assertHasChange('Expand .iter', ''' +-f() { +- for (var value in [1,2,3]) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_iterName() async { +- await _prepareCompletion('.iter', ''' +-f() { +- var value =3D [1,2,3]; +- value.iter +-} +-'''); +- _assertHasChange('Expand .iter', ''' +-f() { +- var value =3D [1,2,3]; +- for (var value1 in value) { +- /*caret*/ +- } +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _IfTest extends PostfixCompletionTest { +- test_Else() async { +- await _prepareCompletion('.else', ''' +-f(bool val) { +- val.else +-} +-'''); +- _assertHasChange('Expand .else', ''' +-f(bool val) { +- if (!val) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_if() async { +- await _prepareCompletion('.if', ''' +-f() { +- 3 < 4.if +-} +-'''); +- _assertHasChange('Expand .if', ''' +-f() { +- if (3 < 4) { +- /*caret*/ +- } +-} +-'''); +- } +- +- @failingTest +- test_if_invalid() async { +- await _prepareCompletion('.if', ''' +-f(List expr) { +- expr.if +-} +-'''); +- } +- +- test_ifDynamic() async { +- await _prepareCompletion('.if', ''' +-f(expr) { +- expr.if +-} +-'''); +- _assertHasChange('Expand .if', ''' +-f(expr) { +- if (expr) { +- /*caret*/ +- } +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _NegateTest extends PostfixCompletionTest { +- test_negate() async { +- await _prepareCompletion('.not', ''' +-f(expr) { +- if (expr.not) +-} +-'''); +- _assertHasChange('Expand .not', ''' +-f(expr) { +- if (!expr) +-} +-'''); +- } +- +- @failingTest +- test_negate_invalid() async { +- await _prepareCompletion('.not', ''' +-f(int expr) { +- if (expr.not) +-} +-'''); +- } +- +- test_negateCascade() async { +- await _prepareCompletion('.not', ''' +-f(expr) { +- if (expr..a..b..c.not) +-} +-'''); +- _assertHasChange('Expand .not', ''' +-f(expr) { +- if (!expr..a..b..c) +-} +-'''); +- } +- +- test_negateExpr() async { +- await _prepareCompletion('.not', ''' +-f(int i, int j) { +- if (i + 3 < j - 4.not) +-} +-'''); +- _assertHasChange('Expand .not', ''' +-f(int i, int j) { +- if (i + 3 >=3D j - 4) +-} +-'''); +- } +- +- test_negateProperty() async { +- await _prepareCompletion('.not', ''' +-f(expr) { +- if (expr.a.b.c.not) +-} +-'''); +- _assertHasChange('Expand .not', ''' +-f(expr) { +- if (!expr.a.b.c) +-} +-'''); +- } +- +- test_notFalse() async { +- await _prepareCompletion('!', ''' +-f() { +- if (false!) +-} +-'''); +- _assertHasChange('Expand !', ''' +-f() { +- if (true) +-} +-'''); +- } +- +- test_notFunc() async { +- await _prepareCompletion('.not', ''' +-bool f() { +- if (f().not) +-} +-'''); +- _assertHasChange('Expand .not', ''' +-bool f() { +- if (!f()) +-} +-'''); +- } +- +- test_notTrue() async { +- await _prepareCompletion('.not', ''' +-f() { +- if (true.not) +-} +-'''); +- _assertHasChange('Expand .not', ''' +-f() { +- if (false) +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _NotNullTest extends PostfixCompletionTest { +- test_nn() async { +- await _prepareCompletion('.nn', ''' +-f(expr) { +- var list =3D [1,2,3]; +- list.nn +-} +-'''); +- _assertHasChange('Expand .nn', ''' +-f(expr) { +- var list =3D [1,2,3]; +- if (list !=3D null) { +- /*caret*/ +- } +-} +-'''); +- } +- +- @failingTest +- test_nn_invalid() async { +- await _prepareCompletion('.nn', ''' +-f(expr) { +- var list =3D [1,2,3]; +-}.nn +-'''); +- } +- +- test_nnDynamic() async { +- await _prepareCompletion('.nn', ''' +-f(expr) { +- expr.nn +-} +-'''); +- _assertHasChange('Expand .nn', ''' +-f(expr) { +- if (expr !=3D null) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_notnull() async { +- await _prepareCompletion('.notnull', ''' +-f(expr) { +- var list =3D [1,2,3]; +- list.notnull +-} +-'''); +- _assertHasChange('Expand .notnull', ''' +-f(expr) { +- var list =3D [1,2,3]; +- if (list !=3D null) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_null() async { +- await _prepareCompletion('.null', ''' +-f(expr) { +- var list =3D [1,2,3]; +- list.null +-} +-'''); +- _assertHasChange('Expand .null', ''' +-f(expr) { +- var list =3D [1,2,3]; +- if (list =3D=3D null) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_nullnn() async { +- await _prepareCompletion('.nn', ''' +-f() { +- null.nn +-} +-'''); +- _assertHasChange('Expand .nn', ''' +-f() { +- if (false) { +- /*caret*/ +- } +-} +-'''); +- } +- +- test_nullnull() async { +- await _prepareCompletion('.null', ''' +-f() { +- null.null +-} +-'''); +- _assertHasChange('Expand .null', ''' +-f() { +- if (true) { +- /*caret*/ +- } +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _ParenTest extends PostfixCompletionTest { +- test_paren() async { +- await _prepareCompletion('.par', ''' +-f(expr) { +- expr.par +-} +-'''); +- _assertHasChange('Expand .par', ''' +-f(expr) { +- (expr) +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _ReturnTest extends PostfixCompletionTest { +- test_return() async { +- await _prepareCompletion('.return', ''' +-f(expr) { +- expr.return +-} +-'''); +- _assertHasChange('Expand .return', ''' +-f(expr) { +- return expr; +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _SwitchTest extends PostfixCompletionTest { +- test_return() async { +- await _prepareCompletion('.switch', ''' +-f(expr) { +- expr.switch +-} +-'''); +- _assertHasChange('Expand .switch', ''' +-f(expr) { +- switch (expr) { +- /*caret*/ +- } +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _TryTest extends PostfixCompletionTest { +- test_try() async { +- await _prepareCompletion('.try', ''' +-f() { +- var x =3D 1.try +-} +-'''); +- _assertHasChange('Expand .try', ''' +-f() { +- try { +- var x =3D 1/*caret*/ +- } catch (e, s) { +- print(s); +- } +-} +-'''); +- } +- +- @failingTest +- test_try_invalid() async { +- // The semicolon is fine; this fails because of the do-statement. +- await _prepareCompletion('.try', ''' +-f() { +- do {} while (true);.try +-} +-'''); +- } +- +- test_tryMultiline() async { +- await _prepareCompletion('.try', ''' +-f(arg) { +- arg +- ..first +- ..second +- ..third +- ..fourth.try +-} +-'''); +- _assertHasChange('Expand .try', ''' +-f(arg) { +- try { +- arg +- ..first +- ..second +- ..third +- ..fourth/*caret*/ +- } catch (e, s) { +- print(s); +- } +-} +-'''); +- } +- +- test_tryon() async { +- await _prepareCompletion('.tryon', ''' +-f() { +- var x =3D 1.tryon +-} +-'''); +- _assertHasChange('Expand .tryon', ''' +-f() { +- try { +- var x =3D 1/*caret*/ +- } on Exception catch (e, s) { +- print(s); +- } +-} +-'''); +- } +- +- test_tryonThrowStatement() async { +- await _prepareCompletion('.tryon', ''' +-f() { +- throw 'error';.tryon +-} +-'''); +- _assertHasChange('Expand .tryon', ''' +-f() { +- try { +- throw 'error';/*caret*/ +- } on String catch (e, s) { +- print(s); +- } +-} +-'''); +- } +- +- test_tryonThrowString() async { +- await _prepareCompletion('.tryon', ''' +-f() { +- throw 'error'.tryon +-} +-'''); +- _assertHasChange('Expand .tryon', ''' +-f() { +- try { +- throw 'error'/*caret*/ +- } on String catch (e, s) { +- print(s); +- } +-} +-'''); +- } +-} +- +-@reflectiveTest +-class _WhileTest extends PostfixCompletionTest { +- test_while() async { +- await _prepareCompletion('.while', ''' +-f(expr) { +- expr.while +-} +-'''); +- _assertHasChange('Expand .while', ''' +-f(expr) { +- while (expr) { +- /*caret*/ +- } +-} +-'''); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/postfix/test_all= .dart b/pkg/analysis_server/test/services/completion/postfix/test_all.dart +deleted file mode 100644 +index a2a43c5fecd..00000000000 +--- a/pkg/analysis_server/test/services/completion/postfix/test_all.dart ++++ /dev/null +@@ -1,13 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'postfix_completion_test.dart' as postfix_completion_test; +- +-main() { +- defineReflectiveSuite(() { +- postfix_completion_test.main(); +- }, name: 'postfix'); +-} +diff --git a/pkg/analysis_server/test/services/completion/statement/statem= ent_completion_test.dart b/pkg/analysis_server/test/services/completion/sta= tement/statement_completion_test.dart +deleted file mode 100644 +index c3ddced2138..00000000000 +--- a/pkg/analysis_server/test/services/completion/statement/statement_com= pletion_test.dart ++++ /dev/null +@@ -1,1912 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analysis_server/src/services/completion/statement/stateme= nt_completion.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(_DeclarationCompletionTest); +- defineReflectiveTests(_ControlFlowCompletionTest); +- defineReflectiveTests(_DoCompletionTest); +- defineReflectiveTests(_ExpressionCompletionTest); +- defineReflectiveTests(_ForCompletionTest); +- defineReflectiveTests(_ForEachCompletionTest); +- defineReflectiveTests(_IfCompletionTest); +- defineReflectiveTests(_SimpleCompletionTest); +- defineReflectiveTests(_SwitchCompletionTest); +- defineReflectiveTests(_TryCompletionTest); +- defineReflectiveTests(_WhileCompletionTest); +- }); +-} +- +-class StatementCompletionTest extends AbstractSingleUnitTest { +- SourceChange change; +- +- int _after(String source, String match) =3D> +- source.indexOf(match) + match.length; +- +- int _afterLast(String source, String match) =3D> +- source.lastIndexOf(match) + match.length; +- +- void _assertHasChange(String message, String expectedCode, [Function cm= p]) { +- if (change.message =3D=3D message) { +- if (!change.edits.isEmpty) { +- String resultCode =3D +- SourceEdit.applySequence(testCode, change.edits[0].edits); +- expect(resultCode, expectedCode.replaceAll('////', '')); +- if (cmp !=3D null) { +- int offset =3D cmp(resultCode); +- expect(change.selection.offset, offset); +- } +- } else { +- expect(testCode, expectedCode.replaceAll('////', '')); +- if (cmp !=3D null) { +- int offset =3D cmp(testCode); +- expect(change.selection.offset, offset); +- } +- } +- return; +- } +- fail("Expected to find |$message| but got: " + change.message); +- } +- +- _computeCompletion(int offset) async { +- driver.changeFile(testFile); +- AnalysisResult result =3D await driver.getResult(testFile); +- StatementCompletionContext context =3D new StatementCompletionContext( +- testFile, +- result.lineInfo, +- offset, +- testUnit, +- testUnitElement, +- result.errors); +- StatementCompletionProcessor processor =3D +- new StatementCompletionProcessor(context); +- StatementCompletion completion =3D await processor.compute(); +- change =3D completion.change; +- } +- +- _prepareCompletion(String search, String sourceCode, +- {bool atStart: false, bool atEnd: false, int delta: 0}) async { +- testCode =3D sourceCode.replaceAll('////', ''); +- int offset =3D findOffset(search); +- if (atStart) { +- delta =3D 0; +- } else if (atEnd) { +- delta =3D search.length; +- } +- await _prepareCompletionAt(offset + delta, testCode); +- } +- +- _prepareCompletionAt(int offset, String sourceCode) async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(sourceCode); +- await _computeCompletion(offset); +- } +-} +- +-@reflectiveTest +-class _ControlFlowCompletionTest extends StatementCompletionTest { +- test_doReturnExprLineComment() async { +- await _prepareCompletion( +- 'return 3', +- ''' +-ex(e) { +- do { +- return 3// +- } while (true); +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- do { +- return 3;// +- } while (true); +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_doReturnUnterminated() async { +- await _prepareCompletion( +- 'return', +- ''' +-ex(e) { +- do { +- return +- } while (true); +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- do { +- return; +- } while (true); +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_forEachReturn() async { +- await _prepareCompletion( +- 'return;', +- ''' +-ex(e) { +- for (var x in e) { +- return; +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- for (var x in e) { +- return; +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_forThrowUnterminated() async { +- await _prepareCompletion( +- 'throw e', +- ''' +-ex(e) { +- for (int i =3D 0; i < 3; i++) { +- throw e +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- for (int i =3D 0; i < 3; i++) { +- throw e; +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_ifNoBlock() async { +- await _prepareCompletion( +- 'return', +- ''' +-ex(e) { +- if (true) return 0 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-ex(e) { +- if (true) return 0; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_ifThrow() async { +- await _prepareCompletion( +- 'throw e;', +- ''' +-ex(e) { +- if (true) { +- throw e; +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- if (true) { +- throw e; +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_ifThrowUnterminated() async { +- await _prepareCompletion( +- 'throw e', +- ''' +-ex(e) { +- if (true) { +- throw e +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- if (true) { +- throw e; +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_whileReturnExpr() async { +- await _prepareCompletion( +- '+ 4', +- ''' +-ex(e) { +- while (true) { +- return 3 + 4 +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-ex(e) { +- while (true) { +- return 3 + 4; +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _DeclarationCompletionTest extends StatementCompletionTest { +- test_classNameNoBody() async { +- await _prepareCompletion( +- 'Sample', +- ''' +-class Sample +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete class declaration', +- ''' +-class Sample { +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_extendsNoBody() async { +- await _prepareCompletion( +- 'Sample', +- ''' +-class Sample extends Object +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete class declaration', +- ''' +-class Sample extends Object { +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_functionDeclNoBody() async { +- await _prepareCompletion( +- 'source()', +- ''' +-String source() +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete function declaration', +- ''' +-String source() { +- //// +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_functionDeclNoParen() async { +- await _prepareCompletion( +- 'source(', +- ''' +-String source( +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete function declaration', +- ''' +-String source() { +- //// +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_implementsNoBody() async { +- await _prepareCompletion( +- 'Sample', +- ''' +-class Interface {} +-class Sample implements Interface +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete class declaration', +- ''' +-class Interface {} +-class Sample implements Interface { +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_methodDeclNoBody() async { +- await _prepareCompletion( +- 'source()', +- ''' +-class Sample { +- String source() +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete function declaration', +- ''' +-class Sample { +- String source() { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_methodDeclNoParen() async { +- await _prepareCompletion( +- 'source(', +- ''' +-class Sample { +- String source( +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete function declaration', +- ''' +-class Sample { +- String source() { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_variableDeclNoBody() async { +- await _prepareCompletion( +- 'source', +- ''' +-String source +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete variable declaration', +- ''' +-String source; +-//// +-''', +- (s) =3D> _after(s, ';\n')); +- } +- +- test_withNoBody() async { +- await _prepareCompletion( +- 'Sample', +- ''' +-class M {} +-class Sample extends Object with M +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete class declaration', +- ''' +-class M {} +-class Sample extends Object with M { +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _DoCompletionTest extends StatementCompletionTest { +- test_emptyCondition() async { +- await _prepareCompletion( +- 'while ()', +- ''' +-main() { +- do { +- } while () +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete do-statement', +- ''' +-main() { +- do { +- } while (); +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +- +- test_keywordOnly() async { +- await _prepareCompletion( +- 'do', +- ''' +-main() { +- do //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete do-statement', +- ''' +-main() { +- do { +- //// +- } while (); +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +- +- test_keywordStatement() async { +- await _prepareCompletion( +- 'do', +- ''' +-main() { +- do //// +- return; +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete do-statement', +- ''' +-main() { +- do { +- //// +- } while (); +- return; +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +- +- test_noBody() async { +- await _prepareCompletion( +- 'do', +- ''' +-main() { +- do; +- while +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete do-statement', +- ''' +-main() { +- do { +- //// +- } while (); +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +- +- test_noCondition() async { +- await _prepareCompletion( +- 'while', +- ''' +-main() { +- do { +- } while +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete do-statement', +- ''' +-main() { +- do { +- } while (); +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +- +- test_noWhile() async { +- await _prepareCompletion( +- '}', +- ''' +-main() { +- do { +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete do-statement', +- ''' +-main() { +- do { +- } while (); +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +-} +- +-@reflectiveTest +-class _ExpressionCompletionTest extends StatementCompletionTest { +- test_listAssign() async { +- await _prepareCompletion( +- '=3D ', +- ''' +-main() { +- var x =3D [1, 2, 3 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- var x =3D [1, 2, 3]; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_listAssignMultiLine() async { +- // The indent of the final line is incorrect. +- await _prepareCompletion( +- '3', +- ''' +-main() { +- var x =3D [ +- 1, +- 2, +- 3 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- var x =3D [ +- 1, +- 2, +- 3, +- ]; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- @failingTest +- test_mapAssign() async { +- await _prepareCompletion( +- '3: 3', +- ''' +-main() { +- var x =3D {1: 1, 2: 2, 3: 3 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- var x =3D {1: 1, 2: 2, 3: 3}; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- @failingTest +- test_mapAssignMissingColon() async { +- await _prepareCompletion( +- '3', +- ''' +-main() { +- var x =3D {1: 1, 2: 2, 3 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- var x =3D {1: 1, 2: 2, 3: }; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_returnString() async { +- await _prepareCompletion( +- 'text', +- ''' +-main() { +- if (done()) { +- return 'text +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete control flow block', +- ''' +-main() { +- if (done()) { +- return 'text'; +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_stringAssign() async { +- await _prepareCompletion( +- '=3D ', +- ''' +-main() { +- var x =3D ' +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- var x =3D ''; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_stringSingle() async { +- await _prepareCompletion( +- 'text', +- ''' +-main() { +- print("text +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- print("text"); +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_stringSingleRaw() async { +- await _prepareCompletion( +- 'text', +- ''' +-main() { +- print(r"text +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- print(r"text"); +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_stringTriple() async { +- await _prepareCompletion( +- 'text', +- ''' +-main() { +- print(\'\'\'text +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- print(\'\'\'text\'\'\'); +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_stringTripleRaw() async { +- await _prepareCompletion( +- 'text', +- r""" +-main() { +- print(r'''text +-} +-""", +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- r""" +-main() { +- print(r'''text'''); +- //// +-} +-""", +- (s) =3D> _afterLast(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _ForCompletionTest extends StatementCompletionTest { +- test_emptyCondition() async { +- await _prepareCompletion( +- '0;', +- ''' +-main() { +- for (int i =3D 0;) /**/ //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (int i =3D 0; ; ) /**/ { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_emptyConditionWithBody() async { +- await _prepareCompletion( +- '0;', +- ''' +-main() { +- for (int i =3D 0;) { +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (int i =3D 0; ; ) { +- } +-} +-''', +- (s) =3D> _after(s, '0; ')); +- } +- +- test_emptyInitializers() async { +- // This does nothing, same as for Java. +- await _prepareCompletion( +- 'r (', +- ''' +-main() { +- for () { +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for () { +- } +-} +-''', +- (s) =3D> _after(s, 'r (')); +- } +- +- test_emptyInitializersAfterBody() async { +- await _prepareCompletion( +- '}', +- ''' +-main() { +- for () { +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- for () { +- } +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_emptyInitializersEmptyCondition() async { +- await _prepareCompletion( +- '/**/', +- ''' +-main() { +- for (;/**/) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (; /**/; ) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_emptyParts() async { +- await _prepareCompletion( +- ';)', +- ''' +-main() { +- for (;;) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (;;) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_emptyUpdaters() async { +- await _prepareCompletion( +- '/**/', +- ''' +-main() { +- for (int i =3D 0; i < 10 /**/) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (int i =3D 0; i < 10 /**/; ) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_emptyUpdatersWithBody() async { +- await _prepareCompletion( +- '/**/', +- ''' +-main() { +- for (int i =3D 0; i < 10 /**/) { +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (int i =3D 0; i < 10 /**/; ) { +- } +-} +-''', +- (s) =3D> _after(s, '*/; ')); +- } +- +- test_keywordOnly() async { +- await _prepareCompletion( +- 'for', +- ''' +-main() { +- for +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'for (')); +- } +- +- test_missingLeftSeparator() async { +- await _prepareCompletion( +- '=3D 0', +- ''' +-main() { +- for (int i =3D 0) { +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (int i =3D 0; ; ) { +- } +-} +-''', +- (s) =3D> _after(s, '0; ')); +- } +- +- test_noError() async { +- await _prepareCompletion( +- ';)', +- ''' +-main() { +- for (;;) +- return; +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-statement', +- ''' +-main() { +- for (;;) { +- //// +- } +- return; +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _ForEachCompletionTest extends StatementCompletionTest { +- test_emptyIdentifier() async { +- await _prepareCompletion( +- 'in xs)', +- ''' +-main() { +- for (in xs) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-each-statement', +- ''' +-main() { +- for ( in xs) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'for (')); +- } +- +- test_emptyIdentifierAndIterable() async { +- await _prepareCompletion( +- 'in)', +- ''' +-main() { +- for (in) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-each-statement', +- ''' +-main() { +- for ( in ) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'for (')); +- } +- +- test_emptyIterable() async { +- await _prepareCompletion( +- 'in)', +- ''' +-main() { +- for (var x in) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-each-statement', +- ''' +-main() { +- for (var x in ) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'in ')); +- } +- +- test_noError() async { +- await _prepareCompletion( +- '])', +- ''' +-main() { +- for (var x in [1,2]) +- return; +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete for-each-statement', +- ''' +-main() { +- for (var x in [1,2]) { +- //// +- } +- return; +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _IfCompletionTest extends StatementCompletionTest { +- test_afterCondition() async { +- await _prepareCompletion( +- 'if (true) ', // Trigger completion after space. +- ''' +-main() { +- if (true) //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if (true) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_emptyCondition() async { +- await _prepareCompletion( +- 'if ()', +- ''' +-main() { +- if () +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'if (')); +- } +- +- test_keywordOnly() async { +- await _prepareCompletion( +- 'if', +- ''' +-main() { +- if //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'if (')); +- } +- +- test_noError() async { +- await _prepareCompletion( +- 'if (true)', +- ''' +-main() { +- if (true) +- return; +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if (true) { +- //// +- } +- return; +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_withCondition() async { +- await _prepareCompletion( +- 'if (tr', // Trigger completion from within expression. +- ''' +-main() { +- if (true) +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if (true) { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_withElse() async { +- await _prepareCompletion( +- 'else', +- ''' +-main() { +- if () { +- } else +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if () { +- } else { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_withElse_BAD() async { +- await _prepareCompletion( +- 'if ()', +- ''' +-main() { +- if () +- else +-} +-''', +- atEnd: true); +- _assertHasChange( +- // Note: if-statement completion should not trigger. +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- if () +- else +-} +-''', +- (s) =3D> _after(s, 'if ()')); +- } +- +- test_withElseNoThen() async { +- await _prepareCompletion( +- 'else', +- ''' +-main() { +- if () +- else +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if () +- else { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_withinEmptyCondition() async { +- await _prepareCompletion( +- 'if (', +- ''' +-main() { +- if () +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete if-statement', +- ''' +-main() { +- if () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'if (')); +- } +-} +- +-@reflectiveTest +-class _SimpleCompletionTest extends StatementCompletionTest { +- test_enter() async { +- await _prepareCompletion( +- 'v =3D 1;', +- ''' +-main() { +- int v =3D 1; +-} +-''', +- atEnd: true); +- _assertHasChange('Insert a newline at the end of the current line', '= '' +-main() { +- int v =3D 1; +- //// +-} +-'''); +- } +- +- test_noCloseParen() async { +- await _prepareCompletion( +- 'ing(3', +- ''' +-main() { +- var s =3D 'sample'.substring(3 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- var s =3D 'sample'.substring(3); +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_noCloseParenWithSemicolon() async { +- String before =3D ''' +-main() { +- var s =3D 'sample'.substring(3; +-} +-'''; +- String after =3D ''' +-main() { +- var s =3D 'sample'.substring(3); +- //// +-} +-'''; +- // Check completion both before and after the semicolon. +- await _prepareCompletion('ing(3', before, atEnd: true); +- _assertHasChange('Insert a newline at the end of the current line', a= fter, +- (s) =3D> _afterLast(s, ' ')); +- await _prepareCompletion('ing(3;', before, atEnd: true); +- _assertHasChange('Insert a newline at the end of the current line', a= fter, +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_semicolonFn() async { +- await _prepareCompletion( +- '=3D> 3', +- ''' +-main() { +- int f() =3D> 3 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- int f() =3D> 3; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_semicolonFnBody() async { +- // It would be reasonable to add braces in this case. Unfortunately, +- // the incomplete line parses as two statements ['int;', 'f();'], not= one. +- await _prepareCompletion( +- 'f()', +- ''' +-main() { +- int f() +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Insert a newline at the end of the current line', +- ''' +-main() { +- int f() +-} +-''', +- (s) =3D> _afterLast(s, '()')); +- } +- +- test_semicolonFnBodyWithDef() async { +- // This ought to be the same as test_semicolonFnBody() but the defini= tion +- // of f() removes an error and it appears to be a different case. +- // Suggestions for unifying the two are welcome. +- await _prepareCompletion( +- 'f()', +- ''' +-main() { +- int f() +-} +-f() {} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- int f(); +- //// +-} +-f() {} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +- +- test_semicolonFnExpr() async { +- await _prepareCompletion( +- '=3D>', +- ''' +-main() { +- int f() =3D> +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- int f() =3D> ; +- //// +-} +-''', +- (s) =3D> _afterLast(s, '=3D> ')); +- } +- +- test_semicolonFnSpaceExpr() async { +- await _prepareCompletion( +- '=3D>', +- ''' +-main() { +- int f() =3D> //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- int f() =3D> ; +- //// +-} +-''', +- (s) =3D> _afterLast(s, '=3D> ')); +- } +- +- test_semicolonVar() async { +- await _prepareCompletion( +- 'v =3D 1', +- ''' +-main() { +- int v =3D 1 +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Add a semicolon and newline', +- ''' +-main() { +- int v =3D 1; +- //// +-} +-''', +- (s) =3D> _afterLast(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _SwitchCompletionTest extends StatementCompletionTest { +- test_caseNoColon() async { +- await _prepareCompletion( +- 'label', +- ''' +-main(x) { +- switch (x) { +- case label +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete switch-statement', +- ''' +-main(x) { +- switch (x) { +- case label: //// +- } +-} +-''', +- (s) =3D> _after(s, 'label: ')); +- } +- +- test_defaultNoColon() async { +- await _prepareCompletion( +- 'default', +- ''' +-main(x) { +- switch (x) { +- default +- } +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete switch-statement', +- ''' +-main(x) { +- switch (x) { +- default: //// +- } +-} +-''', +- (s) =3D> _after(s, 'default: ')); +- } +- +- test_emptyCondition() async { +- await _prepareCompletion( +- 'switch', +- ''' +-main() { +- switch () +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete switch-statement', +- ''' +-main() { +- switch () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'switch (')); +- } +- +- test_keywordOnly() async { +- await _prepareCompletion( +- 'switch', +- ''' +-main() { +- switch//// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete switch-statement', +- ''' +-main() { +- switch () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'switch (')); +- } +- +- test_keywordSpace() async { +- await _prepareCompletion( +- 'switch', +- ''' +-main() { +- switch //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete switch-statement', +- ''' +-main() { +- switch () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'switch (')); +- } +-} +- +-@reflectiveTest +-class _TryCompletionTest extends StatementCompletionTest { +- test_catchOnly() async { +- await _prepareCompletion( +- '{} catch', +- ''' +-main() { +- try { +- } catch(e){} catch //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } catch(e){} catch () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'catch (')); +- } +- +- test_catchSecond() async { +- await _prepareCompletion( +- '} catch ', +- ''' +-main() { +- try { +- } catch() { +- } catch(e){} catch //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } catch() { +- } catch(e){} catch () { +- //// +- } +-} +-''', +- (s) =3D> _afterLast(s, 'catch (')); +- } +- +- test_finallyOnly() async { +- await _prepareCompletion( +- 'finally', +- ''' +-main() { +- try { +- } finally +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } finally { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_keywordOnly() async { +- await _prepareCompletion( +- 'try', +- ''' +-main() { +- try//// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_keywordSpace() async { +- await _prepareCompletion( +- 'try', +- ''' +-main() { +- try //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +- +- test_onCatch() async { +- await _prepareCompletion( +- 'on', +- ''' +-main() { +- try { +- } on catch +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } on catch () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'catch (')); +- } +- +- test_onCatchComment() async { +- await _prepareCompletion( +- 'on', +- ''' +-main() { +- try { +- } on catch +- // +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } on catch () { +- //// +- } +- // +-} +-''', +- (s) =3D> _after(s, 'catch (')); +- } +- +- test_onOnly() async { +- await _prepareCompletion( +- 'on', +- ''' +-main() { +- try { +- } on +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } on { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' on ')); +- } +- +- test_onSpace() async { +- await _prepareCompletion( +- 'on', +- ''' +-main() { +- try { +- } on //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } on { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' on ')); +- } +- +- test_onSpaces() async { +- await _prepareCompletion( +- 'on', +- ''' +-main() { +- try { +- } on //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } on { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' on ')); +- } +- +- test_onType() async { +- await _prepareCompletion( +- 'on', +- ''' +-main() { +- try { +- } on Exception +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete try-statement', +- ''' +-main() { +- try { +- } on Exception { +- //// +- } +-} +-''', +- (s) =3D> _after(s, ' ')); +- } +-} +- +-@reflectiveTest +-class _WhileCompletionTest extends StatementCompletionTest { +- /* +- The implementation of completion for while-statements is shared with +- if-statements. Here we check that the wrapper for while-statements +- functions as expected. The individual test cases are covered by the +- _IfCompletionTest tests. If the implementation changes then the same +- set of tests defined for if-statements should be duplicated here. +- */ +- test_keywordOnly() async { +- await _prepareCompletion( +- 'while', +- ''' +-main() { +- while //// +-} +-''', +- atEnd: true); +- _assertHasChange( +- 'Complete while-statement', +- ''' +-main() { +- while () { +- //// +- } +-} +-''', +- (s) =3D> _after(s, 'while (')); +- } +-} +diff --git a/pkg/analysis_server/test/services/completion/statement/test_a= ll.dart b/pkg/analysis_server/test/services/completion/statement/test_all.d= art +deleted file mode 100644 +index f88ea5a079a..00000000000 +--- a/pkg/analysis_server/test/services/completion/statement/test_all.dart ++++ /dev/null +@@ -1,13 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'statement_completion_test.dart' as statement_completion_test; +- +-main() { +- defineReflectiveSuite(() { +- statement_completion_test.main(); +- }, name: 'statement'); +-} +diff --git a/pkg/analysis_server/test/services/completion/test_all.dart b/= pkg/analysis_server/test/services/completion/test_all.dart +deleted file mode 100644 +index e89a4e8bd5a..00000000000 +--- a/pkg/analysis_server/test/services/completion/test_all.dart ++++ /dev/null +@@ -1,17 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'dart/test_all.dart' as dart_all; +-import 'postfix/test_all.dart' as postfix_all; +-import 'statement/test_all.dart' as statement_all; +- +-main() { +- defineReflectiveSuite(() { +- dart_all.main(); +- postfix_all.main(); +- statement_all.main(); +- }, name: 'completion'); +-} +diff --git a/pkg/analysis_server/test/services/correction/assist_test.dart= b/pkg/analysis_server/test/services/correction/assist_test.dart +deleted file mode 100644 +index 350a11de67b..00000000000 +--- a/pkg/analysis_server/test/services/correction/assist_test.dart ++++ /dev/null +@@ -1,4443 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/plugin/edit/assist/assist_core.dart'; +-import 'package:analysis_server/plugin/edit/assist/assist_dart.dart'; +-import 'package:analysis_server/src/services/correction/assist.dart'; +-import 'package:analysis_server/src/services/correction/assist_internal.d= art'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/utilities/assist/assist.dart'; +-import 'package:plugin/manager.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +-import '../../src/utilities/flutter_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AssistProcessorTest); +- }); +-} +- +-@reflectiveTest +-class AssistProcessorTest extends AbstractSingleUnitTest { +- int offset; +- int length; +- +- Assist assist; +- SourceChange change; +- String resultCode; +- LinkedEditGroup linkedPositionGroup; +- +- /** +- * Asserts that there is an [Assist] of the given [kind] at [offset] wh= ich +- * produces the [expected] code when applied to [testCode]. +- */ +- assertHasAssist(AssistKind kind, String expected) async { +- assist =3D await _assertHasAssist(kind); +- change =3D assist.change; +- // apply to "file" +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- resultCode =3D SourceEdit.applySequence(testCode, change.edits[0].edi= ts); +- // verify +- expect(resultCode, expected); +- } +- +- /** +- * Calls [assertHasAssist] at the offset of [offsetSearch] in [testCode= ]. +- */ +- assertHasAssistAt( +- String offsetSearch, AssistKind kind, String expected) async { +- offset =3D findOffset(offsetSearch); +- await assertHasAssist(kind, expected); +- } +- +- /** +- * Asserts that there is no [Assist] of the given [kind] at [offset]. +- */ +- assertNoAssist(AssistKind kind) async { +- List assists =3D await _computeAssists(); +- for (Assist assist in assists) { +- if (assist.kind =3D=3D kind) { +- throw fail('Unexpected assist $kind in\n${assists.join('\n')}'); +- } +- } +- } +- +- /** +- * Calls [assertNoAssist] at the offset of [offsetSearch] in [testCode]. +- */ +- assertNoAssistAt(String offsetSearch, AssistKind kind) async { +- offset =3D findOffset(offsetSearch); +- await assertNoAssist(kind); +- } +- +- Position expectedPosition(String search) { +- int offset =3D resultCode.indexOf(search); +- return new Position(testFile, offset); +- } +- +- List expectedPositions(List patterns) { +- List positions =3D []; +- patterns.forEach((String search) { +- positions.add(expectedPosition(search)); +- }); +- return positions; +- } +- +- List expectedSuggestions( +- LinkedEditSuggestionKind kind, List values) { +- return values.map((value) { +- return new LinkedEditSuggestion(value, kind); +- }).toList(); +- } +- +- void processRequiredPlugins() { +- ExtensionManager manager =3D new ExtensionManager(); +- manager.processPlugins(AnalysisEngine.instance.requiredPlugins); +- } +- +- void setUp() { +- super.setUp(); +- offset =3D 0; +- length =3D 0; +- } +- +- test_addTypeAnnotation_BAD_privateType_closureParameter() async { +- addSource('/my_lib.dart', ''' +-library my_lib; +-class A {} +-class _B extends A {} +-foo(f(_B p)) {} +-'''); +- await resolveTestUnit(''' +-import 'my_lib.dart'; +-main() { +- foo((test) {}); +-} +- '''); +- await assertNoAssistAt('test)', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_BAD_privateType_declaredIdentifier() async { +- addSource('/my_lib.dart', ''' +-library my_lib; +-class A {} +-class _B extends A {} +-List<_B> getValues() =3D> []; +-'''); +- await resolveTestUnit(''' +-import 'my_lib.dart'; +-class A { +- main() { +- for (var item in getValues()) { +- } +- } +-} +-'''); +- await assertNoAssistAt('var item', DartAssistKind.ADD_TYPE_ANNOTATION= ); +- } +- +- test_addTypeAnnotation_BAD_privateType_list() async { +- // This is now failing because we're suggesting "List" rather than no= thing. +- // Is it really better to produce nothing? +- addSource('/my_lib.dart', ''' +-library my_lib; +-class A {} +-class _B extends A {} +-List<_B> getValues() =3D> []; +-'''); +- await resolveTestUnit(''' +-import 'my_lib.dart'; +-main() { +- var v =3D getValues(); +-} +-'''); +- await assertHasAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION, '= '' +-import 'my_lib.dart'; +-main() { +- List v =3D getValues(); +-} +-'''); +- } +- +- test_addTypeAnnotation_BAD_privateType_variable() async { +- addSource('/my_lib.dart', ''' +-library my_lib; +-class A {} +-class _B extends A {} +-_B getValue() =3D> new _B(); +-'''); +- await resolveTestUnit(''' +-import 'my_lib.dart'; +-main() { +- var v =3D getValue(); +-} +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_classField_OK_final() async { +- await resolveTestUnit(''' +-class A { +- final f =3D 0; +-} +-'''); +- await assertHasAssistAt('final ', DartAssistKind.ADD_TYPE_ANNOTATION,= ''' +-class A { +- final int f =3D 0; +-} +-'''); +- } +- +- test_addTypeAnnotation_classField_OK_int() async { +- await resolveTestUnit(''' +-class A { +- var f =3D 0; +-} +-'''); +- await await assertHasAssistAt( +- 'var ', DartAssistKind.ADD_TYPE_ANNOTATION, ''' +-class A { +- int f =3D 0; +-} +-'''); +- } +- +- test_addTypeAnnotation_declaredIdentifier_BAD_hasTypeAnnotation() async= { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- } +-} +-'''); +- await assertNoAssistAt('item in', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_declaredIdentifier_BAD_inForEachBody() async { +- await resolveTestUnit(''' +-main(List items) { +- for (var item in items) { +- 42; +- } +-} +-'''); +- await assertNoAssistAt('42;', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_declaredIdentifier_BAD_unknownType() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main() { +- for (var item in unknownList) { +- } +-} +-'''); +- await assertNoAssistAt('item in', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_declaredIdentifier_generic_OK() async { +- await resolveTestUnit(''' +-class A { +- main(List> items) { +- for (var item in items) { +- } +- } +-} +-'''); +- await assertHasAssistAt('item in', DartAssistKind.ADD_TYPE_ANNOTATION= , ''' +-class A { +- main(List> items) { +- for (List item in items) { +- } +- } +-} +-'''); +- } +- +- test_addTypeAnnotation_declaredIdentifier_OK() async { +- await resolveTestUnit(''' +-main(List items) { +- for (var item in items) { +- } +-} +-'''); +- // on identifier +- await assertHasAssistAt('item in', DartAssistKind.ADD_TYPE_ANNOTATION= , ''' +-main(List items) { +- for (String item in items) { +- } +-} +-'''); +- // on "for" +- await assertHasAssistAt('for (', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-main(List items) { +- for (String item in items) { +- } +-} +-'''); +- } +- +- test_addTypeAnnotation_declaredIdentifier_OK_addImport_dartUri() async { +- addSource('/my_lib.dart', r''' +-import 'dart:async'; +-List> getFutures() =3D> null; +-'''); +- await resolveTestUnit(''' +-import 'my_lib.dart'; +-main() { +- for (var future in getFutures()) { +- } +-} +-'''); +- await assertHasAssistAt('future in', DartAssistKind.ADD_TYPE_ANNOTATI= ON, ''' +-import 'dart:async'; +- +-import 'my_lib.dart'; +-main() { +- for (Future future in getFutures()) { +- } +-} +-'''); +- } +- +- test_addTypeAnnotation_declaredIdentifier_OK_final() async { +- await resolveTestUnit(''' +-main(List items) { +- for (final item in items) { +- } +-} +-'''); +- await assertHasAssistAt('item in', DartAssistKind.ADD_TYPE_ANNOTATION= , ''' +-main(List items) { +- for (final String item in items) { +- } +-} +-'''); +- } +- +- test_addTypeAnnotation_local_BAD_bottom() async { +- await resolveTestUnit(''' +-main() { +- var v =3D throw 42; +-} +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_BAD_hasTypeAnnotation() async { +- await resolveTestUnit(''' +-main() { +- int v =3D 42; +-} +-'''); +- await assertNoAssistAt(' =3D 42', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_BAD_multiple() async { +- await resolveTestUnit(''' +-main() { +- var a =3D 1, b =3D ''; +-} +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_BAD_noValue() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main() { +- var v; +-} +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_BAD_null() async { +- await resolveTestUnit(''' +-main() { +- var v =3D null; +-} +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_BAD_onInitializer() async { +- await resolveTestUnit(''' +-main() { +- var abc =3D 0; +-} +-'''); +- await assertNoAssistAt('0;', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_BAD_unknown() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main() { +- var v =3D unknownVar; +-} +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_local_generic_OK_literal() async { +- await resolveTestUnit(''' +-class A { +- main(List items) { +- var v =3D items; +- } +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-class A { +- main(List items) { +- List v =3D items; +- } +-} +-'''); +- } +- +- test_addTypeAnnotation_local_generic_OK_local() async { +- await resolveTestUnit(''' +-class A { +- main(List items) { +- var v =3D items; +- } +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-class A { +- main(List items) { +- List v =3D items; +- } +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_addImport_dartUri() async { +- addSource('/my_lib.dart', r''' +-import 'dart:async'; +-Future getFutureInt() =3D> null; +-'''); +- await resolveTestUnit(''' +-import 'my_lib.dart'; +-main() { +- var v =3D getFutureInt(); +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-import 'dart:async'; +- +-import 'my_lib.dart'; +-main() { +- Future v =3D getFutureInt(); +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_addImport_notLibraryUnit() async { +- // prepare library +- addSource('/my_lib.dart', r''' +-import 'dart:async'; +-Future getFutureInt() =3D> null; +-'''); +- // prepare code +- String appCode =3D r''' +-library my_app; +-import 'my_lib.dart'; +-part 'test.dart'; +-'''; +- testCode =3D r''' +-part of my_app; +-main() { +- var v =3D getFutureInt(); +-} +-'''; +- // add sources +- addSource('/app.dart', appCode); +- testSource =3D addSource('/test.dart', testCode); +- // resolve +- await resolveTestUnit(testCode); +- // prepare the assist +- offset =3D findOffset('v =3D '); +- assist =3D await _assertHasAssist(DartAssistKind.ADD_TYPE_ANNOTATION); +- change =3D assist.change; +- // verify +- { +- var testFileEdit =3D change.getFileEdit('/app.dart'); +- var resultCode =3D SourceEdit.applySequence(appCode, testFileEdit.e= dits); +- expect(resultCode, ''' +-library my_app; +-import 'dart:async'; +- +-import 'my_lib.dart'; +-part 'test.dart'; +-'''); +- } +- { +- var testFileEdit =3D change.getFileEdit('/test.dart'); +- var resultCode =3D SourceEdit.applySequence(testCode, testFileEdit.= edits); +- expect(resultCode, ''' +-part of my_app; +-main() { +- Future v =3D getFutureInt(); +-} +-'''); +- } +- } +- +- test_addTypeAnnotation_local_OK_addImport_relUri() async { +- addSource('/aa/bbb/lib_a.dart', r''' +-class MyClass {} +-'''); +- addSource('/ccc/lib_b.dart', r''' +-import '../aa/bbb/lib_a.dart'; +-MyClass newMyClass() =3D> null; +-'''); +- await resolveTestUnit(''' +-import 'ccc/lib_b.dart'; +-main() { +- var v =3D newMyClass(); +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-import 'aa/bbb/lib_a.dart'; +-import 'ccc/lib_b.dart'; +-main() { +- MyClass v =3D newMyClass(); +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_Function() async { +- await resolveTestUnit(''' +-main() { +- var v =3D () =3D> 1; +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-main() { +- Function v =3D () =3D> 1; +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_int() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 0; +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-main() { +- int v =3D 0; +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_List() async { +- await resolveTestUnit(''' +-main() { +- var v =3D []; +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-main() { +- List v =3D []; +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_localType() async { +- await resolveTestUnit(''' +-class C {} +-C f() =3D> null; +-main() { +- var x =3D f(); +-} +-'''); +- await assertHasAssistAt('x =3D', DartAssistKind.ADD_TYPE_ANNOTATION, = ''' +-class C {} +-C f() =3D> null; +-main() { +- C x =3D f(); +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_onName() async { +- await resolveTestUnit(''' +-main() { +- var abc =3D 0; +-} +-'''); +- await assertHasAssistAt('bc', DartAssistKind.ADD_TYPE_ANNOTATION, ''' +-main() { +- int abc =3D 0; +-} +-'''); +- } +- +- test_addTypeAnnotation_local_OK_onVar() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 0; +-} +-'''); +- await assertHasAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION, '= '' +-main() { +- int v =3D 0; +-} +-'''); +- } +- +- test_addTypeAnnotation_OK_privateType_sameLibrary() async { +- await resolveTestUnit(''' +-class _A {} +-_A getValue() =3D> new _A(); +-main() { +- var v =3D getValue(); +-} +-'''); +- await assertHasAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION, '= '' +-class _A {} +-_A getValue() =3D> new _A(); +-main() { +- _A v =3D getValue(); +-} +-'''); +- } +- +- test_addTypeAnnotation_parameter_BAD_hasExplicitType() async { +- await resolveTestUnit(''' +-foo(f(int p)) {} +-main() { +- foo((num test) {}); +-} +-'''); +- await assertNoAssistAt('test', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_parameter_BAD_noPropagatedType() async { +- await resolveTestUnit(''' +-foo(f(p)) {} +-main() { +- foo((test) {}); +-} +-'''); +- await assertNoAssistAt('test', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_parameter_OK() async { +- await resolveTestUnit(''' +-foo(f(int p)) {} +-main() { +- foo((test) {}); +-} +-'''); +- await assertHasAssistAt('test', DartAssistKind.ADD_TYPE_ANNOTATION, '= '' +-foo(f(int p)) {} +-main() { +- foo((int test) {}); +-} +-'''); +- } +- +- test_addTypeAnnotation_topLevelField_BAD_multiple() async { +- await resolveTestUnit(''' +-var A =3D 1, V =3D ''; +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_topLevelField_BAD_noValue() async { +- await resolveTestUnit(''' +-var V; +-'''); +- await assertNoAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION); +- } +- +- test_addTypeAnnotation_topLevelField_OK_int() async { +- await resolveTestUnit(''' +-var V =3D 0; +-'''); +- await assertHasAssistAt('var ', DartAssistKind.ADD_TYPE_ANNOTATION, '= '' +-int V =3D 0; +-'''); +- } +- +- test_assignToLocalVariable() async { +- await resolveTestUnit(''' +-main() { +- List bytes; +- readBytes(); +-} +-List readBytes() =3D> []; +-'''); +- await assertHasAssistAt( +- 'readBytes();', DartAssistKind.ASSIGN_TO_LOCAL_VARIABLE, ''' +-main() { +- List bytes; +- var readBytes =3D readBytes(); +-} +-List readBytes() =3D> []; +-'''); +- _assertLinkedGroup( +- change.linkedEditGroups[0], +- ['readBytes =3D '], +- expectedSuggestions(LinkedEditSuggestionKind.VARIABLE, +- ['list', 'bytes2', 'readBytes'])); +- } +- +- test_assignToLocalVariable_alreadyAssignment() async { +- await resolveTestUnit(''' +-main() { +- var vvv; +- vvv =3D 42; +-} +-'''); +- await assertNoAssistAt('vvv =3D', DartAssistKind.ASSIGN_TO_LOCAL_VARI= ABLE); +- } +- +- test_assignToLocalVariable_inClosure() async { +- await resolveTestUnit(r''' +-main() { +- print(() { +- 12345; +- }); +-} +-'''); +- await assertHasAssistAt('345', DartAssistKind.ASSIGN_TO_LOCAL_VARIABL= E, ''' +-main() { +- print(() { +- var i =3D 12345; +- }); +-} +-'''); +- } +- +- test_assignToLocalVariable_invocationArgument() async { +- await resolveTestUnit(r''' +-main() { +- f(12345); +-} +-void f(p) {} +-'''); +- await assertNoAssistAt('345', DartAssistKind.ASSIGN_TO_LOCAL_VARIABLE= ); +- } +- +- test_assignToLocalVariable_throw() async { +- await resolveTestUnit(''' +-main() { +- throw 42; +-} +-'''); +- await assertNoAssistAt('throw ', DartAssistKind.ASSIGN_TO_LOCAL_VARIA= BLE); +- } +- +- test_assignToLocalVariable_void() async { +- await resolveTestUnit(''' +-main() { +- f(); +-} +-void f() {} +-'''); +- await assertNoAssistAt('f();', DartAssistKind.ASSIGN_TO_LOCAL_VARIABL= E); +- } +- +- test_convertDocumentationIntoBlock_BAD_alreadyBlock() async { +- await resolveTestUnit(''' +-/** +- * AAAAAAA +- */ +-class A {} +-'''); +- await assertNoAssistAt( +- 'AAA', DartAssistKind.CONVERT_DOCUMENTATION_INTO_BLOCK); +- } +- +- test_convertDocumentationIntoBlock_BAD_notDocumentation() async { +- await resolveTestUnit(''' +-// AAAA +-class A {} +-'''); +- await assertNoAssistAt( +- 'AAA', DartAssistKind.CONVERT_DOCUMENTATION_INTO_BLOCK); +- } +- +- test_convertDocumentationIntoBlock_OK_noSpaceBeforeText() async { +- await resolveTestUnit(''' +-class A { +- /// AAAAA +- ///BBBBB +- /// +- /// CCCCC +- mmm() {} +-} +-'''); +- await assertHasAssistAt( +- 'AAAAA', DartAssistKind.CONVERT_DOCUMENTATION_INTO_BLOCK, ''' +-class A { +- /** +- * AAAAA +- *BBBBB +- * +- * CCCCC +- */ +- mmm() {} +-} +-'''); +- } +- +- test_convertDocumentationIntoBlock_OK_onReference() async { +- await resolveTestUnit(''' +-/// AAAAAAA [int] AAAAAAA +-class A {} +-'''); +- await assertHasAssistAt( +- 'nt]', DartAssistKind.CONVERT_DOCUMENTATION_INTO_BLOCK, ''' +-/** +- * AAAAAAA [int] AAAAAAA +- */ +-class A {} +-'''); +- } +- +- test_convertDocumentationIntoBlock_OK_onText() async { +- await resolveTestUnit(''' +-class A { +- /// AAAAAAA [int] AAAAAAA +- /// BBBBBBBB BBBB BBBB +- /// CCC [A] CCCCCCCCCCC +- mmm() {} +-} +-'''); +- await assertHasAssistAt( +- 'AAA [', DartAssistKind.CONVERT_DOCUMENTATION_INTO_BLOCK, ''' +-class A { +- /** +- * AAAAAAA [int] AAAAAAA +- * BBBBBBBB BBBB BBBB +- * CCC [A] CCCCCCCCCCC +- */ +- mmm() {} +-} +-'''); +- } +- +- test_convertDocumentationIntoLine_BAD_alreadyLine() async { +- await resolveTestUnit(''' +-/// AAAAAAA +-class A {} +-'''); +- await assertNoAssistAt( +- 'AAA', DartAssistKind.CONVERT_DOCUMENTATION_INTO_LINE); +- } +- +- test_convertDocumentationIntoLine_BAD_notDocumentation() async { +- await resolveTestUnit(''' +-/* AAAA */ +-class A {} +-'''); +- await assertNoAssistAt( +- 'AAA', DartAssistKind.CONVERT_DOCUMENTATION_INTO_LINE); +- } +- +- test_convertDocumentationIntoLine_OK_onReference() async { +- await resolveTestUnit(''' +-/** +- * AAAAAAA [int] AAAAAAA +- */ +-class A {} +-'''); +- await assertHasAssistAt( +- 'nt]', DartAssistKind.CONVERT_DOCUMENTATION_INTO_LINE, ''' +-/// AAAAAAA [int] AAAAAAA +-class A {} +-'''); +- } +- +- test_convertDocumentationIntoLine_OK_onText() async { +- await resolveTestUnit(''' +-class A { +- /** +- * AAAAAAA [int] AAAAAAA +- * BBBBBBBB BBBB BBBB +- * CCC [A] CCCCCCCCCCC +- */ +- mmm() {} +-} +-'''); +- await assertHasAssistAt( +- 'AAA [', DartAssistKind.CONVERT_DOCUMENTATION_INTO_LINE, ''' +-class A { +- /// AAAAAAA [int] AAAAAAA +- /// BBBBBBBB BBBB BBBB +- /// CCC [A] CCCCCCCCCCC +- mmm() {} +-} +-'''); +- } +- +- test_convertDocumentationIntoLine_OK_onText_hasFirstLine() async { +- await resolveTestUnit(''' +-class A { +- /** AAAAAAA [int] AAAAAAA +- * BBBBBBBB BBBB BBBB +- * CCC [A] CCCCCCCCCCC +- */ +- mmm() {} +-} +-'''); +- await assertHasAssistAt( +- 'AAA [', DartAssistKind.CONVERT_DOCUMENTATION_INTO_LINE, ''' +-class A { +- /// AAAAAAA [int] AAAAAAA +- /// BBBBBBBB BBBB BBBB +- /// CCC [A] CCCCCCCCCCC +- mmm() {} +-} +-'''); +- } +- +- test_convertFlutterChild_OK_multiLine() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- /*caret*/child: new Container( +- width: 200.0, +- height: 300.0, +- ), +- key: null, +- ), +-// end +- ); +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.CONVERT_FLUTTER_CHILD, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- /*caret*/children: [ +- new Container( +- width: 200.0, +- height: 300.0, +- ), +- ], +- key: null, +- ), +-// end +- ); +-} +-'''); +- } +- +- test_convertFlutterChild_OK_newlineChild() async { +- // This case could occur with deeply nested constructors, common in F= lutter. +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- /*caret*/child: +- new Container( +- width: 200.0, +- height: 300.0, +- ), +- key: null, +- ), +-// end +- ); +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.CONVERT_FLUTTER_CHILD, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- /*caret*/children: [ +- new Container( +- width: 200.0, +- height: 300.0, +- ), +- ], +- key: null, +- ), +-// end +- ); +-} +-'''); +- } +- +- test_convertFlutterChild_OK_singleLine() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- /*caret*/child: new GestureDetector(), +- key: null, +- ), +-// end +- ); +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.CONVERT_FLUTTER_CHILD, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- /*caret*/children: [new GestureDetector()], +- key: null, +- ), +-// end +- ); +-} +-'''); +- } +- +- test_convertPartOfToUri_file_nonSibling() async { +- addSource('/pkg/lib/foo.dart', ''' +-library foo; +-part 'src/bar.dart'; +-'''); +- testFile =3D provider.convertPath('/pkg/lib/src/bar.dart'); +- await resolveTestUnit(''' +-part of foo; +-'''); +- await assertHasAssistAt('foo', DartAssistKind.CONVERT_PART_OF_TO_URI,= ''' +-part of '../foo.dart'; +-'''); +- } +- +- test_convertPartOfToUri_file_sibling() async { +- addSource('/pkg/foo.dart', ''' +-library foo; +-part 'bar.dart'; +-'''); +- testFile =3D provider.convertPath('/pkg/bar.dart'); +- await resolveTestUnit(''' +-part of foo; +-'''); +- await assertHasAssistAt('foo', DartAssistKind.CONVERT_PART_OF_TO_URI,= ''' +-part of 'foo.dart'; +-'''); +- } +- +- test_convertToBlockBody_BAD_inExpression() async { +- await resolveTestUnit(''' +-main() =3D> 123; +-'''); +- await assertNoAssistAt('123;', DartAssistKind.CONVERT_INTO_BLOCK_BODY= ); +- } +- +- test_convertToBlockBody_BAD_noEnclosingFunction() async { +- await resolveTestUnit(''' +-var v =3D 123; +-'''); +- await assertNoAssistAt('v =3D', DartAssistKind.CONVERT_INTO_BLOCK_BOD= Y); +- } +- +- test_convertToBlockBody_BAD_notExpressionBlock() async { +- await resolveTestUnit(''' +-fff() { +- return 123; +-} +-'''); +- await assertNoAssistAt('fff() {', DartAssistKind.CONVERT_INTO_BLOCK_B= ODY); +- } +- +- test_convertToBlockBody_OK_async() async { +- await resolveTestUnit(''' +-class A { +- mmm() async =3D> 123; +-} +-'''); +- await assertHasAssistAt('mmm()', DartAssistKind.CONVERT_INTO_BLOCK_BO= DY, ''' +-class A { +- mmm() async { +- return 123; +- } +-} +-'''); +- } +- +- test_convertToBlockBody_OK_closure() async { +- await resolveTestUnit(''' +-setup(x) {} +-main() { +- setup(() =3D> 42); +-} +-'''); +- await assertHasAssistAt( +- '() =3D> 42', DartAssistKind.CONVERT_INTO_BLOCK_BODY, ''' +-setup(x) {} +-main() { +- setup(() { +- return 42; +- }); +-} +-'''); +- { +- Position exitPos =3D change.selection; +- expect(exitPos, isNotNull); +- expect(exitPos.file, testFile); +- expect(exitPos.offset - 3, resultCode.indexOf('42;')); +- } +- } +- +- test_convertToBlockBody_OK_closure_voidExpression() async { +- await resolveTestUnit(''' +-setup(x) {} +-main() { +- setup(() =3D> print('done')); +-} +-'''); +- await assertHasAssistAt( +- '() =3D> print', DartAssistKind.CONVERT_INTO_BLOCK_BODY, ''' +-setup(x) {} +-main() { +- setup(() { +- print('done'); +- }); +-} +-'''); +- { +- Position exitPos =3D change.selection; +- expect(exitPos, isNotNull); +- expect(exitPos.file, testFile); +- expect(exitPos.offset - 3, resultCode.indexOf("');")); +- } +- } +- +- test_convertToBlockBody_OK_constructor() async { +- await resolveTestUnit(''' +-class A { +- factory A() =3D> null; +-} +-'''); +- await assertHasAssistAt('A()', DartAssistKind.CONVERT_INTO_BLOCK_BODY= , ''' +-class A { +- factory A() { +- return null; +- } +-} +-'''); +- } +- +- test_convertToBlockBody_OK_method() async { +- await resolveTestUnit(''' +-class A { +- mmm() =3D> 123; +-} +-'''); +- await assertHasAssistAt('mmm()', DartAssistKind.CONVERT_INTO_BLOCK_BO= DY, ''' +-class A { +- mmm() { +- return 123; +- } +-} +-'''); +- } +- +- test_convertToBlockBody_OK_onArrow() async { +- await resolveTestUnit(''' +-fff() =3D> 123; +-'''); +- await assertHasAssistAt('=3D>', DartAssistKind.CONVERT_INTO_BLOCK_BOD= Y, ''' +-fff() { +- return 123; +-} +-'''); +- } +- +- test_convertToBlockBody_OK_onName() async { +- await resolveTestUnit(''' +-fff() =3D> 123; +-'''); +- await assertHasAssistAt('fff()', DartAssistKind.CONVERT_INTO_BLOCK_BO= DY, ''' +-fff() { +- return 123; +-} +-'''); +- } +- +- test_convertToExpressionBody_BAD_already() async { +- await resolveTestUnit(''' +-fff() =3D> 42; +-'''); +- await assertNoAssistAt( +- 'fff()', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY); +- } +- +- test_convertToExpressionBody_BAD_inExpression() async { +- await resolveTestUnit(''' +-main() { +- return 42; +-} +-'''); +- await assertNoAssistAt('42;', DartAssistKind.CONVERT_INTO_EXPRESSION_= BODY); +- } +- +- test_convertToExpressionBody_BAD_moreThanOneStatement() async { +- await resolveTestUnit(''' +-fff() { +- var v =3D 42; +- return v; +-} +-'''); +- await assertNoAssistAt( +- 'fff()', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY); +- } +- +- test_convertToExpressionBody_BAD_noEnclosingFunction() async { +- await resolveTestUnit(''' +-var V =3D 42; +-'''); +- await assertNoAssistAt('V =3D ', DartAssistKind.CONVERT_INTO_EXPRESSI= ON_BODY); +- } +- +- test_convertToExpressionBody_BAD_noReturn() async { +- await resolveTestUnit(''' +-fff() { +- var v =3D 42; +-} +-'''); +- await assertNoAssistAt( +- 'fff()', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY); +- } +- +- test_convertToExpressionBody_BAD_noReturnValue() async { +- await resolveTestUnit(''' +-fff() { +- return; +-} +-'''); +- await assertNoAssistAt( +- 'fff()', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY); +- } +- +- test_convertToExpressionBody_OK_async() async { +- await resolveTestUnit(''' +-class A { +- mmm() async { +- return 42; +- } +-} +-'''); +- await assertHasAssistAt( +- 'mmm', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-class A { +- mmm() async =3D> 42; +-} +-'''); +- } +- +- test_convertToExpressionBody_OK_closure() async { +- await resolveTestUnit(''' +-setup(x) {} +-main() { +- setup(() { +- return 42; +- }); +-} +-'''); +- await assertHasAssistAt( +- 'return', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-setup(x) {} +-main() { +- setup(() =3D> 42); +-} +-'''); +- } +- +- test_convertToExpressionBody_OK_closure_voidExpression() async { +- await resolveTestUnit(''' +-setup(x) {} +-main() { +- setup((_) { +- print('test'); +- }); +-} +-'''); +- await assertHasAssistAt( +- '(_) {', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-setup(x) {} +-main() { +- setup((_) =3D> print('test')); +-} +-'''); +- } +- +- test_convertToExpressionBody_OK_constructor() async { +- await resolveTestUnit(''' +-class A { +- factory A() { +- return null; +- } +-} +-'''); +- await assertHasAssistAt( +- 'A()', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-class A { +- factory A() =3D> null; +-} +-'''); +- } +- +- test_convertToExpressionBody_OK_function_onBlock() async { +- await resolveTestUnit(''' +-fff() { +- return 42; +-} +-'''); +- await assertHasAssistAt( +- '{', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-fff() =3D> 42; +-'''); +- } +- +- test_convertToExpressionBody_OK_function_onName() async { +- await resolveTestUnit(''' +-fff() { +- return 42; +-} +-'''); +- await assertHasAssistAt( +- 'ff()', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-fff() =3D> 42; +-'''); +- } +- +- test_convertToExpressionBody_OK_method_onBlock() async { +- await resolveTestUnit(''' +-class A { +- m() { // marker +- return 42; +- } +-} +-'''); +- await assertHasAssistAt( +- '{ // marker', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-class A { +- m() =3D> 42; +-} +-'''); +- } +- +- test_convertToExpressionBody_OK_topFunction_onReturnStatement() async { +- await resolveTestUnit(''' +-fff() { +- return 42; +-} +-'''); +- await assertHasAssistAt( +- 'return', DartAssistKind.CONVERT_INTO_EXPRESSION_BODY, ''' +-fff() =3D> 42; +-'''); +- } +- +- test_convertToFieldParameter_BAD_additionalUse() async { +- await resolveTestUnit(''' +-class A { +- int aaa2; +- int bbb2; +- A(int aaa) : aaa2 =3D aaa, bbb2 =3D aaa; +-} +-'''); +- await assertNoAssistAt('aaa)', DartAssistKind.CONVERT_TO_FIELD_PARAME= TER); +- } +- +- test_convertToFieldParameter_BAD_notPureAssignment() async { +- await resolveTestUnit(''' +-class A { +- int aaa2; +- A(int aaa) : aaa2 =3D aaa * 2; +-} +-'''); +- await assertNoAssistAt('aaa)', DartAssistKind.CONVERT_TO_FIELD_PARAME= TER); +- } +- +- test_convertToFieldParameter_OK_firstInitializer() async { +- await resolveTestUnit(''' +-class A { +- int aaa2; +- int bbb2; +- A(int aaa, int bbb) : aaa2 =3D aaa, bbb2 =3D bbb; +-} +-'''); +- await assertHasAssistAt( +- 'aaa, ', DartAssistKind.CONVERT_TO_FIELD_PARAMETER, ''' +-class A { +- int aaa2; +- int bbb2; +- A(this.aaa2, int bbb) : bbb2 =3D bbb; +-} +-'''); +- } +- +- test_convertToFieldParameter_OK_onParameterName_inInitializer() async { +- await resolveTestUnit(''' +-class A { +- int test2; +- A(int test) : test2 =3D test { +- } +-} +-'''); +- await assertHasAssistAt( +- 'test {', DartAssistKind.CONVERT_TO_FIELD_PARAMETER, ''' +-class A { +- int test2; +- A(this.test2) { +- } +-} +-'''); +- } +- +- test_convertToFieldParameter_OK_onParameterName_inParameters() async { +- await resolveTestUnit(''' +-class A { +- int test; +- A(int test) : test =3D test { +- } +-} +-'''); +- await assertHasAssistAt( +- 'test)', DartAssistKind.CONVERT_TO_FIELD_PARAMETER, ''' +-class A { +- int test; +- A(this.test) { +- } +-} +-'''); +- } +- +- test_convertToFieldParameter_OK_secondInitializer() async { +- await resolveTestUnit(''' +-class A { +- int aaa2; +- int bbb2; +- A(int aaa, int bbb) : aaa2 =3D aaa, bbb2 =3D bbb; +-} +-'''); +- await assertHasAssistAt( +- 'bbb)', DartAssistKind.CONVERT_TO_FIELD_PARAMETER, ''' +-class A { +- int aaa2; +- int bbb2; +- A(int aaa, this.bbb2) : aaa2 =3D aaa; +-} +-'''); +- } +- +- test_convertToFinalField_BAD_hasSetter_inThisClass() async { +- await resolveTestUnit(''' +-class A { +- int get foo =3D> null; +- void set foo(_) {} +-} +-'''); +- await assertNoAssistAt('get foo', DartAssistKind.CONVERT_INTO_FINAL_F= IELD); +- } +- +- test_convertToFinalField_BAD_notExpressionBody() async { +- await resolveTestUnit(''' +-class A { +- int get foo { +- int v =3D 1 + 2; +- return v + 3; +- } +-} +-'''); +- await assertNoAssistAt('get foo', DartAssistKind.CONVERT_INTO_FINAL_F= IELD); +- } +- +- test_convertToFinalField_BAD_notGetter() async { +- await resolveTestUnit(''' +-class A { +- int foo() =3D> 42; +-} +-'''); +- await assertNoAssistAt('foo', DartAssistKind.CONVERT_INTO_FINAL_FIELD= ); +- } +- +- test_convertToFinalField_OK_blockBody_onlyReturnStatement() async { +- await resolveTestUnit(''' +-class A { +- int get foo { +- return 1 + 2; +- } +-} +-'''); +- await assertHasAssistAt( +- 'get foo', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-class A { +- final int foo =3D 1 + 2; +-} +-'''); +- } +- +- test_convertToFinalField_OK_hasOverride() async { +- await resolveTestUnit(''' +-const myAnnotation =3D const Object(); +-class A { +- @myAnnotation +- int get foo =3D> 42; +-} +-'''); +- await assertHasAssistAt( +- 'get foo', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-const myAnnotation =3D const Object(); +-class A { +- @myAnnotation +- final int foo =3D 42; +-} +-'''); +- } +- +- test_convertToFinalField_OK_hasSetter_inSuper() async { +- await resolveTestUnit(''' +-class A { +- void set foo(_) {} +-} +-class B extends A { +- int get foo =3D> null; +-} +-'''); +- await assertHasAssistAt( +- 'get foo', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-class A { +- void set foo(_) {} +-} +-class B extends A { +- final int foo; +-} +-'''); +- } +- +- test_convertToFinalField_OK_notNull() async { +- await resolveTestUnit(''' +-class A { +- int get foo =3D> 1 + 2; +-} +-'''); +- await assertHasAssistAt( +- 'get foo', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-class A { +- final int foo =3D 1 + 2; +-} +-'''); +- } +- +- test_convertToFinalField_OK_null() async { +- await resolveTestUnit(''' +-class A { +- int get foo =3D> null; +-} +-'''); +- await assertHasAssistAt( +- 'get foo', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-class A { +- final int foo; +-} +-'''); +- } +- +- test_convertToFinalField_OK_onName() async { +- await resolveTestUnit(''' +-class A { +- int get foo =3D> 42; +-} +-'''); +- await assertHasAssistAt('foo', DartAssistKind.CONVERT_INTO_FINAL_FIEL= D, ''' +-class A { +- final int foo =3D 42; +-} +-'''); +- } +- +- test_convertToFinalField_OK_onReturnType_parameterized() async { +- await resolveTestUnit(''' +-class A { +- List get foo =3D> null; +-} +-'''); +- await assertHasAssistAt( +- 'nt> get', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-class A { +- final List foo; +-} +-'''); +- } +- +- test_convertToFinalField_OK_onReturnType_simple() async { +- await resolveTestUnit(''' +-class A { +- int get foo =3D> 42; +-} +-'''); +- await assertHasAssistAt( +- 'int get', DartAssistKind.CONVERT_INTO_FINAL_FIELD, ''' +-class A { +- final int foo =3D 42; +-} +-'''); +- } +- +- test_convertToForIndex_BAD_bodyNotBlock() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) print(item); +-} +-'''); +- await assertNoAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX); +- } +- +- test_convertToForIndex_BAD_doesNotDeclareVariable() async { +- await resolveTestUnit(''' +-main(List items) { +- String item; +- for (item in items) { +- print(item); +- } +-} +-'''); +- await assertNoAssistAt('for (item', DartAssistKind.CONVERT_INTO_FOR_I= NDEX); +- } +- +- test_convertToForIndex_BAD_iterableIsNotVariable() async { +- await resolveTestUnit(''' +-main() { +- for (String item in ['a', 'b', 'c']) { +- print(item); +- } +-} +-'''); +- await assertNoAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX); +- } +- +- test_convertToForIndex_BAD_iterableNotList() async { +- await resolveTestUnit(''' +-main(Iterable items) { +- for (String item in items) { +- print(item); +- } +-} +-'''); +- await assertNoAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX); +- } +- +- test_convertToForIndex_BAD_usesIJK() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- print(item); +- int i, j, k; +- } +-} +-'''); +- await assertNoAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX); +- } +- +- test_convertToForIndex_OK_onDeclaredIdentifier_name() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- print(item); +- } +-} +-'''); +- await assertHasAssistAt( +- 'item in', DartAssistKind.CONVERT_INTO_FOR_INDEX, ''' +-main(List items) { +- for (int i =3D 0; i < items.length; i++) { +- String item =3D items[i]; +- print(item); +- } +-} +-'''); +- } +- +- test_convertToForIndex_OK_onDeclaredIdentifier_type() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- print(item); +- } +-} +-'''); +- await assertHasAssistAt( +- 'tring item', DartAssistKind.CONVERT_INTO_FOR_INDEX, ''' +-main(List items) { +- for (int i =3D 0; i < items.length; i++) { +- String item =3D items[i]; +- print(item); +- } +-} +-'''); +- } +- +- test_convertToForIndex_OK_onFor() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- print(item); +- } +-} +-'''); +- await assertHasAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX, ''' +-main(List items) { +- for (int i =3D 0; i < items.length; i++) { +- String item =3D items[i]; +- print(item); +- } +-} +-'''); +- } +- +- test_convertToForIndex_OK_usesI() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- int i =3D 0; +- } +-} +-'''); +- await assertHasAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX, ''' +-main(List items) { +- for (int j =3D 0; j < items.length; j++) { +- String item =3D items[j]; +- int i =3D 0; +- } +-} +-'''); +- } +- +- test_convertToForIndex_OK_usesIJ() async { +- await resolveTestUnit(''' +-main(List items) { +- for (String item in items) { +- print(item); +- int i =3D 0, j =3D 1; +- } +-} +-'''); +- await assertHasAssistAt( +- 'for (String', DartAssistKind.CONVERT_INTO_FOR_INDEX, ''' +-main(List items) { +- for (int k =3D 0; k < items.length; k++) { +- String item =3D items[k]; +- print(item); +- int i =3D 0, j =3D 1; +- } +-} +-'''); +- } +- +- test_convertToGetter_BAD_noInitializer() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-class A { +- final int foo; +-} +-'''); +- await assertNoAssistAt('foo', DartAssistKind.CONVERT_INTO_GETTER); +- } +- +- test_convertToGetter_BAD_notFinal() async { +- await resolveTestUnit(''' +-class A { +- int foo =3D 1; +-} +-'''); +- await assertNoAssistAt('foo', DartAssistKind.CONVERT_INTO_GETTER); +- } +- +- test_convertToGetter_BAD_notSingleField() async { +- await resolveTestUnit(''' +-class A { +- final int foo =3D 1, bar =3D 2; +-} +-'''); +- await assertNoAssistAt('foo', DartAssistKind.CONVERT_INTO_GETTER); +- } +- +- test_convertToGetter_OK() async { +- await resolveTestUnit(''' +-const myAnnotation =3D const Object(); +-class A { +- @myAnnotation +- final int foo =3D 1 + 2; +-} +-'''); +- await assertHasAssistAt('foo =3D', DartAssistKind.CONVERT_INTO_GETTER= , ''' +-const myAnnotation =3D const Object(); +-class A { +- @myAnnotation +- int get foo =3D> 1 + 2; +-} +-'''); +- } +- +- test_convertToGetter_OK_noType() async { +- await resolveTestUnit(''' +-class A { +- final foo =3D 42; +-} +-'''); +- await assertHasAssistAt('foo =3D', DartAssistKind.CONVERT_INTO_GETTER= , ''' +-class A { +- get foo =3D> 42; +-} +-'''); +- } +- +- test_convertToIsNot_BAD_is_alreadyIsNot() async { +- await resolveTestUnit(''' +-main(p) { +- p is! String; +-} +-'''); +- await assertNoAssistAt('is!', DartAssistKind.CONVERT_INTO_IS_NOT); +- } +- +- test_convertToIsNot_BAD_is_noEnclosingParenthesis() async { +- await resolveTestUnit(''' +-main(p) { +- p is String; +-} +-'''); +- await assertNoAssistAt('is String', DartAssistKind.CONVERT_INTO_IS_NO= T); +- } +- +- test_convertToIsNot_BAD_is_noPrefix() async { +- await resolveTestUnit(''' +-main(p) { +- (p is String); +-} +-'''); +- await assertNoAssistAt('is String', DartAssistKind.CONVERT_INTO_IS_NO= T); +- } +- +- test_convertToIsNot_BAD_is_notIsExpression() async { +- await resolveTestUnit(''' +-main(p) { +- 123 + 456; +-} +-'''); +- await assertNoAssistAt('123 +', DartAssistKind.CONVERT_INTO_IS_NOT); +- } +- +- test_convertToIsNot_BAD_is_notTheNotOperator() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main(p) { +- ++(p is String); +-} +-'''); +- await assertNoAssistAt('is String', DartAssistKind.CONVERT_INTO_IS_NO= T); +- } +- +- test_convertToIsNot_BAD_not_alreadyIsNot() async { +- await resolveTestUnit(''' +-main(p) { +- !(p is! String); +-} +-'''); +- await assertNoAssistAt('!(p', DartAssistKind.CONVERT_INTO_IS_NOT); +- } +- +- test_convertToIsNot_BAD_not_noEnclosingParenthesis() async { +- await resolveTestUnit(''' +-main(p) { +- !p; +-} +-'''); +- await assertNoAssistAt('!p', DartAssistKind.CONVERT_INTO_IS_NOT); +- } +- +- test_convertToIsNot_BAD_not_notIsExpression() async { +- await resolveTestUnit(''' +-main(p) { +- !(p =3D=3D null); +-} +-'''); +- await assertNoAssistAt('!(p', DartAssistKind.CONVERT_INTO_IS_NOT); +- } +- +- test_convertToIsNot_BAD_not_notTheNotOperator() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main(p) { +- ++(p is String); +-} +-'''); +- await assertNoAssistAt('++(', DartAssistKind.CONVERT_INTO_IS_NOT); +- } +- +- test_convertToIsNot_OK_childOfIs_left() async { +- await resolveTestUnit(''' +-main(p) { +- !(p is String); +-} +-'''); +- await assertHasAssistAt('p is', DartAssistKind.CONVERT_INTO_IS_NOT, '= '' +-main(p) { +- p is! String; +-} +-'''); +- } +- +- test_convertToIsNot_OK_childOfIs_right() async { +- await resolveTestUnit(''' +-main(p) { +- !(p is String); +-} +-'''); +- await assertHasAssistAt('String)', DartAssistKind.CONVERT_INTO_IS_NOT= , ''' +-main(p) { +- p is! String; +-} +-'''); +- } +- +- test_convertToIsNot_OK_is() async { +- await resolveTestUnit(''' +-main(p) { +- !(p is String); +-} +-'''); +- await assertHasAssistAt('is String', DartAssistKind.CONVERT_INTO_IS_N= OT, ''' +-main(p) { +- p is! String; +-} +-'''); +- } +- +- test_convertToIsNot_OK_is_higherPrecedencePrefix() async { +- await resolveTestUnit(''' +-main(p) { +- !!(p is String); +-} +-'''); +- await assertHasAssistAt('is String', DartAssistKind.CONVERT_INTO_IS_N= OT, ''' +-main(p) { +- !(p is! String); +-} +-'''); +- } +- +- test_convertToIsNot_OK_is_not_higherPrecedencePrefix() async { +- await resolveTestUnit(''' +-main(p) { +- !!(p is String); +-} +-'''); +- await assertHasAssistAt('!(p', DartAssistKind.CONVERT_INTO_IS_NOT, ''' +-main(p) { +- !(p is! String); +-} +-'''); +- } +- +- test_convertToIsNot_OK_not() async { +- await resolveTestUnit(''' +-main(p) { +- !(p is String); +-} +-'''); +- await assertHasAssistAt('!(p', DartAssistKind.CONVERT_INTO_IS_NOT, ''' +-main(p) { +- p is! String; +-} +-'''); +- } +- +- test_convertToIsNot_OK_parentheses() async { +- await resolveTestUnit(''' +-main(p) { +- !(p is String); +-} +-'''); +- await assertHasAssistAt('(p is', DartAssistKind.CONVERT_INTO_IS_NOT, = ''' +-main(p) { +- p is! String; +-} +-'''); +- } +- +- test_convertToIsNotEmpty_BAD_noBang() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main(String str) { +- ~str.isEmpty; +-} +-'''); +- await assertNoAssistAt( +- 'isEmpty;', DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY); +- } +- +- test_convertToIsNotEmpty_BAD_noIsNotEmpty() async { +- await resolveTestUnit(''' +-class A { +- bool get isEmpty =3D> false; +-} +-main(A a) { +- !a.isEmpty; +-} +-'''); +- await assertNoAssistAt( +- 'isEmpty;', DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY); +- } +- +- test_convertToIsNotEmpty_BAD_notInPrefixExpression() async { +- await resolveTestUnit(''' +-main(String str) { +- str.isEmpty; +-} +-'''); +- await assertNoAssistAt( +- 'isEmpty;', DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY); +- } +- +- test_convertToIsNotEmpty_BAD_notIsEmpty() async { +- await resolveTestUnit(''' +-main(int p) { +- !p.isEven; +-} +-'''); +- await assertNoAssistAt('isEven;', DartAssistKind.CONVERT_INTO_IS_NOT_= EMPTY); +- } +- +- test_convertToIsNotEmpty_OK_on_isEmpty() async { +- await resolveTestUnit(''' +-main(String str) { +- !str.isEmpty; +-} +-'''); +- await assertHasAssistAt( +- 'isEmpty', DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY, ''' +-main(String str) { +- str.isNotEmpty; +-} +-'''); +- } +- +- test_convertToIsNotEmpty_OK_on_str() async { +- await resolveTestUnit(''' +-main(String str) { +- !str.isEmpty; +-} +-'''); +- await assertHasAssistAt( +- 'str.', DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY, ''' +-main(String str) { +- str.isNotEmpty; +-} +-'''); +- } +- +- test_convertToIsNotEmpty_OK_propertyAccess() async { +- await resolveTestUnit(''' +-main(String str) { +- !'text'.isEmpty; +-} +-'''); +- await assertHasAssistAt( +- 'isEmpty', DartAssistKind.CONVERT_INTO_IS_NOT_EMPTY, ''' +-main(String str) { +- 'text'.isNotEmpty; +-} +-'''); +- } +- +- test_convertToNormalParameter_OK_dynamic() async { +- await resolveTestUnit(''' +-class A { +- var test; +- A(this.test) { +- } +-} +-'''); +- await assertHasAssistAt( +- 'test)', DartAssistKind.CONVERT_TO_NORMAL_PARAMETER, ''' +-class A { +- var test; +- A(test) : test =3D test { +- } +-} +-'''); +- } +- +- test_convertToNormalParameter_OK_firstInitializer() async { +- await resolveTestUnit(''' +-class A { +- int test; +- A(this.test) { +- } +-} +-'''); +- await assertHasAssistAt( +- 'test)', DartAssistKind.CONVERT_TO_NORMAL_PARAMETER, ''' +-class A { +- int test; +- A(int test) : test =3D test { +- } +-} +-'''); +- } +- +- test_convertToNormalParameter_OK_secondInitializer() async { +- await resolveTestUnit(''' +-class A { +- double aaa; +- int bbb; +- A(this.bbb) : aaa =3D 1.0; +-} +-'''); +- await assertHasAssistAt( +- 'bbb)', DartAssistKind.CONVERT_TO_NORMAL_PARAMETER, ''' +-class A { +- double aaa; +- int bbb; +- A(int bbb) : aaa =3D 1.0, bbb =3D bbb; +-} +-'''); +- } +- +- test_encapsulateField_BAD_alreadyPrivate() async { +- await resolveTestUnit(''' +-class A { +- int _test =3D 42; +-} +-main(A a) { +- print(a._test); +-} +-'''); +- await assertNoAssistAt('_test =3D', DartAssistKind.ENCAPSULATE_FIELD); +- } +- +- test_encapsulateField_BAD_final() async { +- await resolveTestUnit(''' +-class A { +- final int test =3D 42; +-} +-'''); +- await assertNoAssistAt('test =3D', DartAssistKind.ENCAPSULATE_FIELD); +- } +- +- test_encapsulateField_BAD_multipleFields() async { +- await resolveTestUnit(''' +-class A { +- int aaa, bbb, ccc; +-} +-main(A a) { +- print(a.bbb); +-} +-'''); +- await assertNoAssistAt('bbb, ', DartAssistKind.ENCAPSULATE_FIELD); +- } +- +- test_encapsulateField_BAD_notOnName() async { +- await resolveTestUnit(''' +-class A { +- int test =3D 1 + 2 + 3; +-} +-'''); +- await assertNoAssistAt('+ 2', DartAssistKind.ENCAPSULATE_FIELD); +- } +- +- test_encapsulateField_BAD_parseError() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-class A { +- int; // marker +-} +-main(A a) { +- print(a.test); +-} +-'''); +- await assertNoAssistAt('; // marker', DartAssistKind.ENCAPSULATE_FIEL= D); +- } +- +- test_encapsulateField_BAD_static() async { +- await resolveTestUnit(''' +-class A { +- static int test =3D 42; +-} +-'''); +- await assertNoAssistAt('test =3D', DartAssistKind.ENCAPSULATE_FIELD); +- } +- +- test_encapsulateField_OK_hasType() async { +- await resolveTestUnit(''' +-class A { +- int test =3D 42; +- A(this.test); +-} +-main(A a) { +- print(a.test); +-} +-'''); +- await assertHasAssistAt('test =3D 42', DartAssistKind.ENCAPSULATE_FIE= LD, ''' +-class A { +- int _test =3D 42; +- +- int get test =3D> _test; +- +- void set test(int test) { +- _test =3D test; +- } +- A(this._test); +-} +-main(A a) { +- print(a.test); +-} +-'''); +- } +- +- test_encapsulateField_OK_noType() async { +- await resolveTestUnit(''' +-class A { +- var test =3D 42; +-} +-main(A a) { +- print(a.test); +-} +-'''); +- await assertHasAssistAt('test =3D 42', DartAssistKind.ENCAPSULATE_FIE= LD, ''' +-class A { +- var _test =3D 42; +- +- get test =3D> _test; +- +- void set test(test) { +- _test =3D test; +- } +-} +-main(A a) { +- print(a.test); +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_BAD_extraLength() async { +- await resolveTestUnit(''' +-main() { +- 111 + 222; +-} +-'''); +- length =3D 3; +- await assertNoAssistAt('+ 222', DartAssistKind.EXCHANGE_OPERANDS); +- } +- +- test_exchangeBinaryExpressionArguments_BAD_onOperand() async { +- await resolveTestUnit(''' +-main() { +- 111 + 222; +-} +-'''); +- length =3D 3; +- await assertNoAssistAt('11 +', DartAssistKind.EXCHANGE_OPERANDS); +- } +- +- test_exchangeBinaryExpressionArguments_BAD_selectionWithBinary() async { +- await resolveTestUnit(''' +-main() { +- 1 + 2 + 3; +-} +-'''); +- length =3D '1 + 2 + 3'.length; +- await assertNoAssistAt('1 + 2 + 3', DartAssistKind.EXCHANGE_OPERANDS); +- } +- +- test_exchangeBinaryExpressionArguments_OK_compare() async { +- const initialOperators =3D const ['<', '<=3D', '>', '>=3D']; +- const resultOperators =3D const ['>', '>=3D', '<', '<=3D']; +- for (int i =3D 0; i <=3D 0; i++) { +- String initialOperator =3D initialOperators[i]; +- String resultOperator =3D resultOperators[i]; +- await resolveTestUnit(''' +-bool main(int a, int b) { +- return a $initialOperator b; +-} +-'''); +- await assertHasAssistAt( +- initialOperator, DartAssistKind.EXCHANGE_OPERANDS, ''' +-bool main(int a, int b) { +- return b $resultOperator a; +-} +-'''); +- } +- } +- +- test_exchangeBinaryExpressionArguments_OK_extended_mixOperator_1() asyn= c { +- await resolveTestUnit(''' +-main() { +- 1 * 2 * 3 + 4; +-} +-'''); +- await assertHasAssistAt('* 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 * 3 * 1 + 4; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_extended_mixOperator_2() asyn= c { +- await resolveTestUnit(''' +-main() { +- 1 + 2 - 3 + 4; +-} +-'''); +- await assertHasAssistAt('+ 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 + 1 - 3 + 4; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_extended_sameOperator_afterFi= rst() async { +- await resolveTestUnit(''' +-main() { +- 1 + 2 + 3; +-} +-'''); +- await assertHasAssistAt('+ 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 + 3 + 1; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_extended_sameOperator_afterSe= cond() async { +- await resolveTestUnit(''' +-main() { +- 1 + 2 + 3; +-} +-'''); +- await assertHasAssistAt('+ 3', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 3 + 1 + 2; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_simple_afterOperator() async { +- await resolveTestUnit(''' +-main() { +- 1 + 2; +-} +-'''); +- await assertHasAssistAt(' 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 + 1; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_simple_beforeOperator() async= { +- await resolveTestUnit(''' +-main() { +- 1 + 2; +-} +-'''); +- await assertHasAssistAt('+ 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 + 1; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_simple_fullSelection() async { +- await resolveTestUnit(''' +-main() { +- 1 + 2; +-} +-'''); +- length =3D '1 + 2'.length; +- await assertHasAssistAt('1 + 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 + 1; +-} +-'''); +- } +- +- test_exchangeBinaryExpressionArguments_OK_simple_withLength() async { +- await resolveTestUnit(''' +-main() { +- 1 + 2; +-} +-'''); +- length =3D 2; +- await assertHasAssistAt('+ 2', DartAssistKind.EXCHANGE_OPERANDS, ''' +-main() { +- 2 + 1; +-} +-'''); +- } +- +- test_importAddShow_BAD_hasShow() async { +- await resolveTestUnit(''' +-import 'dart:math' show PI; +-main() { +- PI; +-} +-'''); +- await assertNoAssistAt('import ', DartAssistKind.IMPORT_ADD_SHOW); +- } +- +- test_importAddShow_BAD_unresolvedUri() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-import '/no/such/lib.dart'; +-'''); +- await assertNoAssistAt('import ', DartAssistKind.IMPORT_ADD_SHOW); +- } +- +- test_importAddShow_BAD_unused() async { +- await resolveTestUnit(''' +-import 'dart:math'; +-'''); +- await assertNoAssistAt('import ', DartAssistKind.IMPORT_ADD_SHOW); +- } +- +- test_importAddShow_OK_hasUnresolvedIdentifier() async { +- await resolveTestUnit(''' +-import 'dart:math'; +-main(x) { +- PI; +- return x.foo(); +-} +-'''); +- await assertHasAssistAt('import ', DartAssistKind.IMPORT_ADD_SHOW, ''' +-import 'dart:math' show PI; +-main(x) { +- PI; +- return x.foo(); +-} +-'''); +- } +- +- test_importAddShow_OK_onDirective() async { +- await resolveTestUnit(''' +-import 'dart:math'; +-main() { +- PI; +- E; +- max(1, 2); +-} +-'''); +- await assertHasAssistAt('import ', DartAssistKind.IMPORT_ADD_SHOW, ''' +-import 'dart:math' show E, PI, max; +-main() { +- PI; +- E; +- max(1, 2); +-} +-'''); +- } +- +- test_importAddShow_OK_onUri() async { +- await resolveTestUnit(''' +-import 'dart:math'; +-main() { +- PI; +- E; +- max(1, 2); +-} +-'''); +- await assertHasAssistAt('art:math', DartAssistKind.IMPORT_ADD_SHOW, '= '' +-import 'dart:math' show E, PI, max; +-main() { +- PI; +- E; +- max(1, 2); +-} +-'''); +- } +- +- test_introduceLocalTestedType_BAD_notBlock() async { +- await resolveTestUnit(''' +-main(p) { +- if (p is String) +- print('not a block'); +-} +-'''); +- await assertNoAssistAt('if (p', DartAssistKind.INTRODUCE_LOCAL_CAST_T= YPE); +- } +- +- test_introduceLocalTestedType_BAD_notIsExpression() async { +- await resolveTestUnit(''' +-main(p) { +- if (p =3D=3D null) { +- } +-} +-'''); +- await assertNoAssistAt('if (p', DartAssistKind.INTRODUCE_LOCAL_CAST_T= YPE); +- } +- +- test_introduceLocalTestedType_BAD_notStatement() async { +- await resolveTestUnit(''' +-class C { +- bool b; +- C(v) : b =3D v is int; +-}'''); +- await assertNoAssistAt('is int', DartAssistKind.INTRODUCE_LOCAL_CAST_= TYPE); +- } +- +- test_introduceLocalTestedType_OK_if_is() async { +- await resolveTestUnit(''' +-class MyTypeName {} +-main(p) { +- if (p is MyTypeName) { +- } +- p =3D null; +-} +-'''); +- String expected =3D ''' +-class MyTypeName {} +-main(p) { +- if (p is MyTypeName) { +- MyTypeName myTypeName =3D p; +- } +- p =3D null; +-} +-'''; +- await assertHasAssistAt( +- 'is MyType', DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE, expected); +- _assertLinkedGroup( +- change.linkedEditGroups[0], +- ['myTypeName =3D '], +- expectedSuggestions(LinkedEditSuggestionKind.VARIABLE, +- ['myTypeName', 'typeName', 'name'])); +- // another good location +- await assertHasAssistAt( +- 'if (p', DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE, expected); +- } +- +- test_introduceLocalTestedType_OK_if_isNot() async { +- await resolveTestUnit(''' +-class MyTypeName {} +-main(p) { +- if (p is! MyTypeName) { +- return; +- } +-} +-'''); +- String expected =3D ''' +-class MyTypeName {} +-main(p) { +- if (p is! MyTypeName) { +- return; +- } +- MyTypeName myTypeName =3D p; +-} +-'''; +- await assertHasAssistAt( +- 'is! MyType', DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE, expected); +- _assertLinkedGroup( +- change.linkedEditGroups[0], +- ['myTypeName =3D '], +- expectedSuggestions(LinkedEditSuggestionKind.VARIABLE, +- ['myTypeName', 'typeName', 'name'])); +- // another good location +- await assertHasAssistAt( +- 'if (p', DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE, expected); +- } +- +- test_introduceLocalTestedType_OK_while() async { +- await resolveTestUnit(''' +-main(p) { +- while (p is String) { +- } +- p =3D null; +-} +-'''); +- String expected =3D ''' +-main(p) { +- while (p is String) { +- String s =3D p; +- } +- p =3D null; +-} +-'''; +- await assertHasAssistAt( +- 'is String', DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE, expected); +- await assertHasAssistAt( +- 'while (p', DartAssistKind.INTRODUCE_LOCAL_CAST_TYPE, expected); +- } +- +- test_invalidSelection() async { +- await resolveTestUnit(''); +- offset =3D -1; +- length =3D 0; +- List assists =3D await _computeAssists(); +- expect(assists, isEmpty); +- } +- +- test_invertIfStatement_blocks() async { +- await resolveTestUnit(''' +-main() { +- if (true) { +- 0; +- } else { +- 1; +- } +-} +-'''); +- await assertHasAssistAt('if (', DartAssistKind.INVERT_IF_STATEMENT, '= '' +-main() { +- if (false) { +- 1; +- } else { +- 0; +- } +-} +-'''); +- } +- +- test_invertIfStatement_statements() async { +- await resolveTestUnit(''' +-main() { +- if (true) +- 0; +- else +- 1; +-} +-'''); +- await assertHasAssistAt('if (', DartAssistKind.INVERT_IF_STATEMENT, '= '' +-main() { +- if (false) +- 1; +- else +- 0; +-} +-'''); +- } +- +- test_joinIfStatementInner_BAD_innerNotIf() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- print(0); +- } +-} +-'''); +- await assertNoAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_IN= NER); +- } +- +- test_joinIfStatementInner_BAD_innerWithElse() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } else { +- print(1); +- } +- } +-} +-'''); +- await assertNoAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_IN= NER); +- } +- +- test_joinIfStatementInner_BAD_statementAfterInner() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(2); +- } +- print(1); +- } +-} +-'''); +- await assertNoAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_IN= NER); +- } +- +- test_joinIfStatementInner_BAD_statementBeforeInner() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- print(1); +- if (2 =3D=3D 2) { +- print(2); +- } +- } +-} +-'''); +- await assertNoAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_IN= NER); +- } +- +- test_joinIfStatementInner_BAD_targetNotIf() async { +- await resolveTestUnit(''' +-main() { +- print(0); +-} +-'''); +- await assertNoAssistAt('print', DartAssistKind.JOIN_IF_WITH_INNER); +- } +- +- test_joinIfStatementInner_BAD_targetWithElse() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } else { +- print(1); +- } +-} +-'''); +- await assertNoAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_IN= NER); +- } +- +- test_joinIfStatementInner_OK_conditionAndOr() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2 || 3 =3D=3D 3) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_I= NNER, ''' +-main() { +- if (1 =3D=3D 1 && (2 =3D=3D 2 || 3 =3D=3D 3)) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementInner_OK_conditionInvocation() async { +- await resolveTestUnit(''' +-main() { +- if (isCheck()) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } +-} +-bool isCheck() =3D> false; +-'''); +- await assertHasAssistAt( +- 'if (isCheck', DartAssistKind.JOIN_IF_WITH_INNER, ''' +-main() { +- if (isCheck() && 2 =3D=3D 2) { +- print(0); +- } +-} +-bool isCheck() =3D> false; +-'''); +- } +- +- test_joinIfStatementInner_OK_conditionOrAnd() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1 || 2 =3D=3D 2) { +- if (3 =3D=3D 3) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_I= NNER, ''' +-main() { +- if ((1 =3D=3D 1 || 2 =3D=3D 2) && 3 =3D=3D 3) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementInner_OK_onCondition() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('1 =3D=3D', DartAssistKind.JOIN_IF_WITH_INNER= , ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementInner_OK_simpleConditions_block_block() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_I= NNER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementInner_OK_simpleConditions_block_single() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) +- print(0); +- } +-} +-'''); +- await assertHasAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_I= NNER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementInner_OK_simpleConditions_single_blockMulti() async= { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(1); +- print(2); +- print(3); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_I= NNER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(1); +- print(2); +- print(3); +- } +-} +-'''); +- } +- +- test_joinIfStatementInner_OK_simpleConditions_single_blockOne() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) +- if (2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- await assertHasAssistAt('if (1 =3D=3D', DartAssistKind.JOIN_IF_WITH_I= NNER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_BAD_outerNotIf() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- print(0); +- } +-} +-'''); +- await assertNoAssistAt('if (1 =3D=3D 1', DartAssistKind.JOIN_IF_WITH_= OUTER); +- } +- +- test_joinIfStatementOuter_BAD_outerWithElse() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } else { +- print(1); +- } +-} +-'''); +- await assertNoAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH_= OUTER); +- } +- +- test_joinIfStatementOuter_BAD_statementAfterInner() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(2); +- } +- print(1); +- } +-} +-'''); +- await assertNoAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH_= OUTER); +- } +- +- test_joinIfStatementOuter_BAD_statementBeforeInner() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- print(1); +- if (2 =3D=3D 2) { +- print(2); +- } +- } +-} +-'''); +- await assertNoAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH_= OUTER); +- } +- +- test_joinIfStatementOuter_BAD_targetNotIf() async { +- await resolveTestUnit(''' +-main() { +- print(0); +-} +-'''); +- await assertNoAssistAt('print', DartAssistKind.JOIN_IF_WITH_OUTER); +- } +- +- test_joinIfStatementOuter_BAD_targetWithElse() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } else { +- print(1); +- } +- } +-} +-'''); +- await assertNoAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH_= OUTER); +- } +- +- test_joinIfStatementOuter_OK_conditionAndOr() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2 || 3 =3D=3D 3) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (2 =3D=3D', DartAssistKind.JOIN_IF_WITH_O= UTER, ''' +-main() { +- if (1 =3D=3D 1 && (2 =3D=3D 2 || 3 =3D=3D 3)) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_OK_conditionInvocation() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (isCheck()) { +- print(0); +- } +- } +-} +-bool isCheck() =3D> false; +-'''); +- await assertHasAssistAt( +- 'if (isCheck', DartAssistKind.JOIN_IF_WITH_OUTER, ''' +-main() { +- if (1 =3D=3D 1 && isCheck()) { +- print(0); +- } +-} +-bool isCheck() =3D> false; +-'''); +- } +- +- test_joinIfStatementOuter_OK_conditionOrAnd() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1 || 2 =3D=3D 2) { +- if (3 =3D=3D 3) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (3 =3D=3D 3', DartAssistKind.JOIN_IF_WITH= _OUTER, ''' +-main() { +- if ((1 =3D=3D 1 || 2 =3D=3D 2) && 3 =3D=3D 3) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_OK_onCondition() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH= _OUTER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_OK_simpleConditions_block_block() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(0); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH= _OUTER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_OK_simpleConditions_block_single() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) +- print(0); +- } +-} +-'''); +- await assertHasAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH= _OUTER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_OK_simpleConditions_single_blockMulti() async= { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2) { +- print(1); +- print(2); +- print(3); +- } +- } +-} +-'''); +- await assertHasAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH= _OUTER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(1); +- print(2); +- print(3); +- } +-} +-'''); +- } +- +- test_joinIfStatementOuter_OK_simpleConditions_single_blockOne() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1) +- if (2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- await assertHasAssistAt('if (2 =3D=3D 2', DartAssistKind.JOIN_IF_WITH= _OUTER, ''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_hasInitializer() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 1; +- v =3D 2; +-} +-'''); +- await assertNoAssistAt('v =3D 2', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notAdjacent() async { +- await resolveTestUnit(''' +-main() { +- var v; +- var bar; +- v =3D 1; +-} +-'''); +- await assertNoAssistAt('v =3D 1', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notAssignment() async { +- await resolveTestUnit(''' +-main() { +- var v; +- v +=3D 1; +-} +-'''); +- await assertNoAssistAt('v +=3D 1', DartAssistKind.JOIN_VARIABLE_DECLA= RATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notDeclaration() async { +- await resolveTestUnit(''' +-main(var v) { +- v =3D 1; +-} +-'''); +- await assertNoAssistAt('v =3D 1', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notLeftArgument() async { +- await resolveTestUnit(''' +-main() { +- var v; +- 1 + v; // marker +-} +-'''); +- await assertNoAssistAt( +- 'v; // marker', DartAssistKind.JOIN_VARIABLE_DECLARATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notOneVariable() async { +- await resolveTestUnit(''' +-main() { +- var v, v2; +- v =3D 1; +-} +-'''); +- await assertNoAssistAt('v =3D 1', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notResolved() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-main() { +- var v; +- x =3D 1; +-} +-'''); +- await assertNoAssistAt('x =3D 1', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onAssignment_BAD_notSameBlock() async { +- await resolveTestUnit(''' +-main() { +- var v; +- { +- v =3D 1; +- } +-} +-'''); +- await assertNoAssistAt('v =3D 1', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onAssignment_OK() async { +- await resolveTestUnit(''' +-main() { +- var v; +- v =3D 1; +-} +-'''); +- await assertHasAssistAt('v =3D', DartAssistKind.JOIN_VARIABLE_DECLARA= TION, ''' +-main() { +- var v =3D 1; +-} +-'''); +- } +- +- test_joinVariableDeclaration_onDeclaration_BAD_hasInitializer() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 1; +- v =3D 2; +-} +-'''); +- await assertNoAssistAt('v =3D 1', DartAssistKind.JOIN_VARIABLE_DECLAR= ATION); +- } +- +- test_joinVariableDeclaration_onDeclaration_BAD_lastStatement() async { +- await resolveTestUnit(''' +-main() { +- if (true) +- var v; +-} +-'''); +- await assertNoAssistAt('v;', DartAssistKind.JOIN_VARIABLE_DECLARATION= ); +- } +- +- test_joinVariableDeclaration_onDeclaration_BAD_nextNotAssignmentExpress= ion() async { +- await resolveTestUnit(''' +-main() { +- var v; +- 42; +-} +-'''); +- await assertNoAssistAt('v;', DartAssistKind.JOIN_VARIABLE_DECLARATION= ); +- } +- +- test_joinVariableDeclaration_onDeclaration_BAD_nextNotExpressionStateme= nt() async { +- await resolveTestUnit(''' +-main() { +- var v; +- if (true) return; +-} +-'''); +- await assertNoAssistAt('v;', DartAssistKind.JOIN_VARIABLE_DECLARATION= ); +- } +- +- test_joinVariableDeclaration_onDeclaration_BAD_nextNotPureAssignment() = async { +- await resolveTestUnit(''' +-main() { +- var v; +- v +=3D 1; +-} +-'''); +- await assertNoAssistAt('v;', DartAssistKind.JOIN_VARIABLE_DECLARATION= ); +- } +- +- test_joinVariableDeclaration_onDeclaration_BAD_notOneVariable() async { +- await resolveTestUnit(''' +-main() { +- var v, v2; +- v =3D 1; +-} +-'''); +- await assertNoAssistAt('v, ', DartAssistKind.JOIN_VARIABLE_DECLARATIO= N); +- } +- +- test_joinVariableDeclaration_onDeclaration_OK_onName() async { +- await resolveTestUnit(''' +-main() { +- var v; +- v =3D 1; +-} +-'''); +- await assertHasAssistAt('v;', DartAssistKind.JOIN_VARIABLE_DECLARATIO= N, ''' +-main() { +- var v =3D 1; +-} +-'''); +- } +- +- test_joinVariableDeclaration_onDeclaration_OK_onType() async { +- await resolveTestUnit(''' +-main() { +- int v; +- v =3D 1; +-} +-'''); +- await assertHasAssistAt( +- 'int v', DartAssistKind.JOIN_VARIABLE_DECLARATION, ''' +-main() { +- int v =3D 1; +-} +-'''); +- } +- +- test_joinVariableDeclaration_onDeclaration_OK_onVar() async { +- await resolveTestUnit(''' +-main() { +- var v; +- v =3D 1; +-} +-'''); +- await assertHasAssistAt( +- 'var v', DartAssistKind.JOIN_VARIABLE_DECLARATION, ''' +-main() { +- var v =3D 1; +-} +-'''); +- } +- +- test_moveFlutterWidgetDown_OK() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new /*caret*/GestureDetector( +- onTap: () =3D> startResize(), +- child: new Center( +- child: new Container( +- width: 200.0, +- height: 300.0, +- ), +- key: null, +- ), +- ), +-// end +- ); +-} +-startResize() {} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.MOVE_FLUTTER_WIDGET_DOWN, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- child: new /*caret*/GestureDetector( +- onTap: () =3D> startResize(), +- child: new Container( +- width: 200.0, +- height: 300.0, +- ), +- ), +- key: null, +- ), +-// end +- ); +-} +-startResize() {} +-'''); +- } +- +- test_moveFlutterWidgetUp_OK() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new Center( +- child: new /*caret*/GestureDetector( +- onTap: () =3D> startResize(), +- child: new Container( +- width: 200.0, +- height: 300.0, +- ), +- ), +- key: null, +- ), +-// end +- ); +-} +-startResize() {} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.MOVE_FLUTTER_WIDGET_UP, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +-// start +- body: new /*caret*/GestureDetector( +- onTap: () =3D> startResize(), +- child: new Center( +- child: new Container( +- width: 200.0, +- height: 300.0, +- ), +- key: null, +- ), +- ), +-// end +- ); +-} +-startResize() {} +-'''); +- } +- +- test_removeTypeAnnotation_classField_OK() async { +- await resolveTestUnit(''' +-class A { +- int v =3D 1; +-} +-'''); +- await assertHasAssistAt('v =3D ', DartAssistKind.REMOVE_TYPE_ANNOTATI= ON, ''' +-class A { +- var v =3D 1; +-} +-'''); +- } +- +- test_removeTypeAnnotation_classField_OK_final() async { +- await resolveTestUnit(''' +-class A { +- final int v =3D 1; +-} +-'''); +- await assertHasAssistAt('v =3D ', DartAssistKind.REMOVE_TYPE_ANNOTATI= ON, ''' +-class A { +- final v =3D 1; +-} +-'''); +- } +- +- test_removeTypeAnnotation_field_BAD_noInitializer() async { +- await resolveTestUnit(''' +-class A { +- int v; +-} +-'''); +- await assertNoAssistAt('v;', DartAssistKind.REMOVE_TYPE_ANNOTATION); +- } +- +- test_removeTypeAnnotation_localVariable_BAD_noInitializer() async { +- await resolveTestUnit(''' +-main() { +- int v; +-} +-'''); +- await assertNoAssistAt('v;', DartAssistKind.REMOVE_TYPE_ANNOTATION); +- } +- +- test_removeTypeAnnotation_localVariable_BAD_onInitializer() async { +- await resolveTestUnit(''' +-main() { +- final int v =3D 1; +-} +-'''); +- await assertNoAssistAt('1;', DartAssistKind.REMOVE_TYPE_ANNOTATION); +- } +- +- test_removeTypeAnnotation_localVariable_OK() async { +- await resolveTestUnit(''' +-main() { +- int a =3D 1, b =3D 2; +-} +-'''); +- await assertHasAssistAt('int ', DartAssistKind.REMOVE_TYPE_ANNOTATION= , ''' +-main() { +- var a =3D 1, b =3D 2; +-} +-'''); +- } +- +- test_removeTypeAnnotation_localVariable_OK_const() async { +- await resolveTestUnit(''' +-main() { +- const int v =3D 1; +-} +-'''); +- await assertHasAssistAt('int ', DartAssistKind.REMOVE_TYPE_ANNOTATION= , ''' +-main() { +- const v =3D 1; +-} +-'''); +- } +- +- test_removeTypeAnnotation_localVariable_OK_final() async { +- await resolveTestUnit(''' +-main() { +- final int v =3D 1; +-} +-'''); +- await assertHasAssistAt('int ', DartAssistKind.REMOVE_TYPE_ANNOTATION= , ''' +-main() { +- final v =3D 1; +-} +-'''); +- } +- +- test_removeTypeAnnotation_topLevelVariable_BAD_noInitializer() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-int v; +-'''); +- await assertNoAssistAt('v;', DartAssistKind.REMOVE_TYPE_ANNOTATION); +- } +- +- test_removeTypeAnnotation_topLevelVariable_BAD_syntheticName() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-MyType +-'''); +- await assertNoAssistAt('MyType', DartAssistKind.REMOVE_TYPE_ANNOTATIO= N); +- } +- +- test_removeTypeAnnotation_topLevelVariable_OK() async { +- await resolveTestUnit(''' +-int V =3D 1; +-'''); +- await assertHasAssistAt('int ', DartAssistKind.REMOVE_TYPE_ANNOTATION= , ''' +-var V =3D 1; +-'''); +- } +- +- test_removeTypeAnnotation_topLevelVariable_OK_final() async { +- await resolveTestUnit(''' +-final int V =3D 1; +-'''); +- await assertHasAssistAt('int ', DartAssistKind.REMOVE_TYPE_ANNOTATION= , ''' +-final V =3D 1; +-'''); +- } +- +- test_reparentFlutterList_BAD_multiLine() async { +- verifyNoTestUnitErrors =3D false; +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +- children: [/*caret*/ +-// start +- new Transform(), +- new Object(), +- new AspectRatio(), +-// end +- ], +- ), +- ); +-} +-'''); +- _setCaretLocation(); +- await assertNoAssist(DartAssistKind.REPARENT_FLUTTER_LIST); +- } +- +- test_reparentFlutterList_BAD_singleLine() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +- var obj; +-// start +- return new Row(children: [/*caret*/ new Transform()]); +-// end +- } +-} +-'''); +- _setCaretLocation(); +- await assertNoAssist(DartAssistKind.REPARENT_FLUTTER_LIST); +- } +- +- test_reparentFlutterList_OK_multiLine() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +-// start +- children: [/*caret*/ +- new Transform(), +- new Transform(), +- new AspectRatio(), +- ], +-// end +- ), +- ); +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.REPARENT_FLUTTER_LIST, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +-// start +- children: [ +- new widget( +- children: [/*caret*/ +- new Transform(), +- new Transform(), +- new AspectRatio(), +- ], +- ), +- ], +-// end +- ), +- ); +-} +-'''); +- } +- +- test_reparentFlutterWidget_BAD_minimal() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-/*caret*/x(){} +-'''); +- _setCaretLocation(); +- await assertNoAssist(DartAssistKind.REPARENT_FLUTTER_WIDGET); +- } +- +- test_reparentFlutterWidget_BAD_singleLine() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +- var obj; +-// start +- return new Container(child: obj.xyz./*caret*/abc); +-// end +- } +-} +-'''); +- _setCaretLocation(); +- await assertNoAssist(DartAssistKind.REPARENT_FLUTTER_WIDGET); +- } +- +- test_reparentFlutterWidget_OK_multiLines() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +- return new Container( +-// start +- child: new /*caret*/DefaultTextStyle( +- child: new Row( +- children: [ +- new Container( +- ), +- ], +- ), +- ), +-// end +- ); +- } +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.REPARENT_FLUTTER_WIDGET, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +- return new Container( +-// start +- child: new widget( +- child: new /*caret*/DefaultTextStyle( +- child: new Row( +- children: [ +- new Container( +- ), +- ], +- ), +- ), +- ), +-// end +- ); +- } +-} +-'''); +- } +- +- test_reparentFlutterWidget_OK_multiLines_eol2() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart';\r +-class FakeFlutter {\r +- main() {\r +- return new Container(\r +-// start\r +- child: new /*caret*/DefaultTextStyle(\r +- child: new Row(\r +- children: [\r +- new Container(\r +- ),\r +- ],\r +- ),\r +- ),\r +-// end\r +- );\r +- }\r +-}\r +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.REPARENT_FLUTTER_WIDGET, ''' +-import 'package:flutter/src/widgets/framework.dart';\r +-class FakeFlutter {\r +- main() {\r +- return new Container(\r +-// start\r +- child: new widget(\r +- child: new /*caret*/DefaultTextStyle(\r +- child: new Row(\r +- children: [\r +- new Container(\r +- ),\r +- ],\r +- ),\r +- ),\r +- ),\r +-// end\r +- );\r +- }\r +-}\r +-'''); +- } +- +- test_reparentFlutterWidget_OK_singleLine1() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +-// start +- return /*caret*/new Container(); +-// end +- } +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.REPARENT_FLUTTER_WIDGET, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +-// start +- return /*caret*/new widget(child: new Container()); +-// end +- } +-} +-'''); +- } +- +- test_reparentFlutterWidget_OK_singleLine2() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +-// start +- return new ClipRect./*caret*/rect(); +-// end +- } +-} +-'''); +- _setCaretLocation(); +- await assertHasAssist(DartAssistKind.REPARENT_FLUTTER_WIDGET, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-class FakeFlutter { +- main() { +-// start +- return new widget(child: new ClipRect./*caret*/rect()); +-// end +- } +-} +-'''); +- } +- +- test_replaceConditionalWithIfElse_BAD_noEnclosingStatement() async { +- await resolveTestUnit(''' +-var v =3D true ? 111 : 222; +-'''); +- await assertNoAssistAt( +- '? 111', DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE); +- } +- +- test_replaceConditionalWithIfElse_BAD_notConditional() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 42; +-} +-'''); +- await assertNoAssistAt( +- 'v =3D 42', DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE); +- } +- +- test_replaceConditionalWithIfElse_OK_assignment() async { +- await resolveTestUnit(''' +-main() { +- var v; +- v =3D true ? 111 : 222; +-} +-'''); +- // on conditional +- await assertHasAssistAt( +- '11 :', DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE, ''' +-main() { +- var v; +- if (true) { +- v =3D 111; +- } else { +- v =3D 222; +- } +-} +-'''); +- // on variable +- await assertHasAssistAt( +- 'v =3D', DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE, ''' +-main() { +- var v; +- if (true) { +- v =3D 111; +- } else { +- v =3D 222; +- } +-} +-'''); +- } +- +- test_replaceConditionalWithIfElse_OK_return() async { +- await resolveTestUnit(''' +-main() { +- return true ? 111 : 222; +-} +-'''); +- await assertHasAssistAt( +- 'return ', DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE, ''' +-main() { +- if (true) { +- return 111; +- } else { +- return 222; +- } +-} +-'''); +- } +- +- test_replaceConditionalWithIfElse_OK_variableDeclaration() async { +- await resolveTestUnit(''' +-main() { +- int a =3D 1, vvv =3D true ? 111 : 222, b =3D 2; +-} +-'''); +- await assertHasAssistAt( +- '11 :', DartAssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE, ''' +-main() { +- int a =3D 1, vvv, b =3D 2; +- if (true) { +- vvv =3D 111; +- } else { +- vvv =3D 222; +- } +-} +-'''); +- } +- +- test_replaceIfElseWithConditional_BAD_expressionVsReturn() async { +- await resolveTestUnit(''' +-main() { +- if (true) { +- print(42); +- } else { +- return; +- } +-} +-'''); +- await assertNoAssistAt( +- 'else', DartAssistKind.REPLACE_IF_ELSE_WITH_CONDITIONAL); +- } +- +- test_replaceIfElseWithConditional_BAD_notIfStatement() async { +- await resolveTestUnit(''' +-main() { +- print(0); +-} +-'''); +- await assertNoAssistAt( +- 'print', DartAssistKind.REPLACE_IF_ELSE_WITH_CONDITIONAL); +- } +- +- test_replaceIfElseWithConditional_BAD_notSingleStatement() async { +- await resolveTestUnit(''' +-main() { +- int vvv; +- if (true) { +- print(0); +- vvv =3D 111; +- } else { +- print(0); +- vvv =3D 222; +- } +-} +-'''); +- await assertNoAssistAt( +- 'if (true)', DartAssistKind.REPLACE_IF_ELSE_WITH_CONDITIONAL); +- } +- +- test_replaceIfElseWithConditional_OK_assignment() async { +- await resolveTestUnit(''' +-main() { +- int vvv; +- if (true) { +- vvv =3D 111; +- } else { +- vvv =3D 222; +- } +-} +-'''); +- await assertHasAssistAt( +- 'if (true)', DartAssistKind.REPLACE_IF_ELSE_WITH_CONDITIONAL, ''' +-main() { +- int vvv; +- vvv =3D true ? 111 : 222; +-} +-'''); +- } +- +- test_replaceIfElseWithConditional_OK_return() async { +- await resolveTestUnit(''' +-main() { +- if (true) { +- return 111; +- } else { +- return 222; +- } +-} +-'''); +- await assertHasAssistAt( +- 'if (true)', DartAssistKind.REPLACE_IF_ELSE_WITH_CONDITIONAL, ''' +-main() { +- return true ? 111 : 222; +-} +-'''); +- } +- +- test_splitAndCondition_BAD_hasElse() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(1); +- } else { +- print(2); +- } +-} +-'''); +- await assertNoAssistAt('&& 2', DartAssistKind.SPLIT_AND_CONDITION); +- } +- +- test_splitAndCondition_BAD_notAnd() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1 || 2 =3D=3D 2) { +- print(0); +- } +-} +-'''); +- await assertNoAssistAt('|| 2', DartAssistKind.SPLIT_AND_CONDITION); +- } +- +- test_splitAndCondition_BAD_notPartOfIf() async { +- await resolveTestUnit(''' +-main() { +- print(1 =3D=3D 1 && 2 =3D=3D 2); +-} +-'''); +- await assertNoAssistAt('&& 2', DartAssistKind.SPLIT_AND_CONDITION); +- } +- +- test_splitAndCondition_BAD_notTopLevelAnd() async { +- await resolveTestUnit(''' +-main() { +- if (true || (1 =3D=3D 1 && 2 =3D=3D 2)) { +- print(0); +- } +- if (true && (3 =3D=3D 3 && 4 =3D=3D 4)) { +- print(0); +- } +-} +-'''); +- await assertNoAssistAt('&& 2', DartAssistKind.SPLIT_AND_CONDITION); +- await assertNoAssistAt('&& 4', DartAssistKind.SPLIT_AND_CONDITION); +- } +- +- test_splitAndCondition_OK_innerAndExpression() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2 && 3 =3D=3D 3) { +- print(0); +- } +-} +-'''); +- await assertHasAssistAt('&& 2 =3D=3D 2', DartAssistKind.SPLIT_AND_CON= DITION, ''' +-main() { +- if (1 =3D=3D 1) { +- if (2 =3D=3D 2 && 3 =3D=3D 3) { +- print(0); +- } +- } +-} +-'''); +- } +- +- test_splitAndCondition_OK_thenBlock() async { +- await resolveTestUnit(''' +-main() { +- if (true && false) { +- print(0); +- if (3 =3D=3D 3) { +- print(1); +- } +- } +-} +-'''); +- await assertHasAssistAt('&& false', DartAssistKind.SPLIT_AND_CONDITIO= N, ''' +-main() { +- if (true) { +- if (false) { +- print(0); +- if (3 =3D=3D 3) { +- print(1); +- } +- } +- } +-} +-'''); +- } +- +- test_splitAndCondition_OK_thenStatement() async { +- await resolveTestUnit(''' +-main() { +- if (true && false) +- print(0); +-} +-'''); +- await assertHasAssistAt('&& false', DartAssistKind.SPLIT_AND_CONDITIO= N, ''' +-main() { +- if (true) +- if (false) +- print(0); +-} +-'''); +- } +- +- test_splitAndCondition_wrong() async { +- await resolveTestUnit(''' +-main() { +- if (1 =3D=3D 1 && 2 =3D=3D 2) { +- print(0); +- } +- print(3 =3D=3D 3 && 4 =3D=3D 4); +-} +-'''); +- // not binary expression +- await assertNoAssistAt('main() {', DartAssistKind.SPLIT_AND_CONDITION= ); +- // selection is not empty and includes more than just operator +- { +- length =3D 5; +- await assertNoAssistAt('&& 2 =3D=3D 2', DartAssistKind.SPLIT_AND_CO= NDITION); +- } +- } +- +- test_splitVariableDeclaration_BAD_notOneVariable() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 1, v2; +-} +-'''); +- await assertNoAssistAt('v =3D 1', DartAssistKind.SPLIT_VARIABLE_DECLA= RATION); +- } +- +- test_splitVariableDeclaration_OK_onName() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 1; +-} +-'''); +- await assertHasAssistAt( +- 'v =3D', DartAssistKind.SPLIT_VARIABLE_DECLARATION, ''' +-main() { +- var v; +- v =3D 1; +-} +-'''); +- } +- +- test_splitVariableDeclaration_OK_onType() async { +- await resolveTestUnit(''' +-main() { +- int v =3D 1; +-} +-'''); +- await assertHasAssistAt( +- 'int ', DartAssistKind.SPLIT_VARIABLE_DECLARATION, ''' +-main() { +- int v; +- v =3D 1; +-} +-'''); +- } +- +- test_splitVariableDeclaration_OK_onVar() async { +- await resolveTestUnit(''' +-main() { +- var v =3D 1; +-} +-'''); +- await assertHasAssistAt( +- 'var ', DartAssistKind.SPLIT_VARIABLE_DECLARATION, ''' +-main() { +- var v; +- v =3D 1; +-} +-'''); +- } +- +- test_surroundWith_block() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_BLOCK, ''' +-main() { +-// start +- { +- print(0); +- print(1); +- } +-// end +-} +-'''); +- } +- +- test_surroundWith_doWhile() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_DO_WHILE, ''' +-main() { +-// start +- do { +- print(0); +- print(1); +- } while (condition); +-// end +-} +-'''); +- } +- +- test_surroundWith_for() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_FOR, ''' +-main() { +-// start +- for (var v =3D init; condition; increment) { +- print(0); +- print(1); +- } +-// end +-} +-'''); +- } +- +- test_surroundWith_forIn() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_FOR_IN, ''' +-main() { +-// start +- for (var item in iterable) { +- print(0); +- print(1); +- } +-// end +-} +-'''); +- } +- +- test_surroundWith_if() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_IF, ''' +-main() { +-// start +- if (condition) { +- print(0); +- print(1); +- } +-// end +-} +-'''); +- } +- +- test_surroundWith_tryCatch() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_TRY_CATCH, ''' +-main() { +-// start +- try { +- print(0); +- print(1); +- } on Exception catch (e) { +- // TODO +- } +-// end +-} +-'''); +- } +- +- test_surroundWith_tryFinally() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_TRY_FINALLY, ''' +-main() { +-// start +- try { +- print(0); +- print(1); +- } finally { +- // TODO +- } +-// end +-} +-'''); +- } +- +- test_surroundWith_while() async { +- await resolveTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _setStartEndSelection(); +- await assertHasAssist(DartAssistKind.SURROUND_WITH_WHILE, ''' +-main() { +-// start +- while (condition) { +- print(0); +- print(1); +- } +-// end +-} +-'''); +- } +- +- /** +- * Computes assists and verifies that there is an assist of the given k= ind. +- */ +- Future _assertHasAssist(AssistKind kind) async { +- List assists =3D await _computeAssists(); +- for (Assist assist in assists) { +- if (assist.kind =3D=3D kind) { +- return assist; +- } +- } +- throw fail('Expected to find assist $kind in\n${assists.join('\n')}'); +- } +- +- void _assertLinkedGroup(LinkedEditGroup group, List expectedStr= ings, +- [List expectedSuggestions]) { +- List expectedPositions =3D _findResultPositions(expectedStr= ings); +- expect(group.positions, unorderedEquals(expectedPositions)); +- if (expectedSuggestions !=3D null) { +- expect(group.suggestions, unorderedEquals(expectedSuggestions)); +- } +- } +- +- Future> _computeAssists() async { +- CompilationUnitElement testUnitElement =3D +- resolutionMap.elementDeclaredByCompilationUnit(testUnit); +- DartAssistContext assistContext; +- assistContext =3D new _DartAssistContextForValues(testUnitElement.sou= rce, +- offset, length, driver, new AstProviderForDriver(driver), testUni= t); +- AssistProcessor processor =3D new AssistProcessor(assistContext); +- return await processor.compute(); +- } +- +- /** +- * Configures the [SourceFactory] to have the `flutter` package in +- * `/packages/flutter/lib` folder. +- */ +- void _configureFlutterPkg(Map pathToCode) { +- pathToCode.forEach((path, code) { +- provider.newFile('$flutterPkgLibPath/$path', code); +- }); +- // configure SourceFactory +- Folder myPkgFolder =3D provider.getResource(flutterPkgLibPath); +- UriResolver pkgResolver =3D new PackageMapUriResolver(provider, { +- 'flutter': [myPkgFolder] +- }); +- SourceFactory sourceFactory =3D new SourceFactory( +- [new DartUriResolver(sdk), pkgResolver, resourceResolver]); +- driver.configure(sourceFactory: sourceFactory); +- // force 'flutter' resolution +- addSource( +- '/tmp/other.dart', +- pathToCode.keys +- .map((path) =3D> "import 'package:flutter/$path';") +- .join('\n')); +- } +- +- List _findResultPositions(List searchStrings) { +- List positions =3D []; +- for (String search in searchStrings) { +- int offset =3D resultCode.indexOf(search); +- positions.add(new Position(testFile, offset)); +- } +- return positions; +- } +- +- void _setCaretLocation() { +- offset =3D findOffset('/*caret*/') + '/*caret*/'.length; +- length =3D 0; +- } +- +- void _setStartEndSelection() { +- offset =3D findOffset('// start\n') + '// start\n'.length; +- length =3D findOffset('// end') - offset; +- } +-} +- +-class _DartAssistContextForValues implements DartAssistContext { +- @override +- final Source source; +- +- @override +- final int selectionOffset; +- +- @override +- final int selectionLength; +- +- @override +- final AnalysisDriver analysisDriver; +- +- @override +- final AstProvider astProvider; +- +- @override +- final CompilationUnit unit; +- +- _DartAssistContextForValues(this.source, this.selectionOffset, +- this.selectionLength, this.analysisDriver, this.astProvider, this.u= nit); +-} +diff --git a/pkg/analysis_server/test/services/correction/change_test.dart= b/pkg/analysis_server/test/services/correction/change_test.dart +deleted file mode 100644 +index 0dc019bb658..00000000000 +--- a/pkg/analysis_server/test/services/correction/change_test.dart ++++ /dev/null +@@ -1,296 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/constants.dart'; +-import 'package:analysis_server/src/protocol_server.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ChangeTest); +- defineReflectiveTests(EditTest); +- defineReflectiveTests(FileEditTest); +- defineReflectiveTests(LinkedEditGroupTest); +- defineReflectiveTests(LinkedEditSuggestionTest); +- defineReflectiveTests(PositionTest); +- }); +-} +- +-@reflectiveTest +-class ChangeTest { +- void test_addEdit() { +- SourceChange change =3D new SourceChange('msg'); +- SourceEdit edit1 =3D new SourceEdit(1, 2, 'a'); +- SourceEdit edit2 =3D new SourceEdit(1, 2, 'b'); +- expect(change.edits, hasLength(0)); +- change.addEdit('/a.dart', 0, edit1); +- expect(change.edits, hasLength(1)); +- change.addEdit('/a.dart', 0, edit2); +- expect(change.edits, hasLength(1)); +- { +- SourceFileEdit fileEdit =3D change.getFileEdit('/a.dart'); +- expect(fileEdit, isNotNull); +- expect(fileEdit.edits, unorderedEquals([edit1, edit2])); +- } +- } +- +- void test_getFileEdit() { +- SourceChange change =3D new SourceChange('msg'); +- SourceFileEdit fileEdit =3D new SourceFileEdit('/a.dart', 0); +- change.addFileEdit(fileEdit); +- expect(change.getFileEdit('/a.dart'), fileEdit); +- } +- +- void test_getFileEdit_empty() { +- SourceChange change =3D new SourceChange('msg'); +- expect(change.getFileEdit('/some.dart'), isNull); +- } +- +- void test_toJson() { +- SourceChange change =3D new SourceChange('msg'); +- change.addFileEdit(new SourceFileEdit('/a.dart', 1) +- ..add(new SourceEdit(1, 2, 'aaa')) +- ..add(new SourceEdit(10, 20, 'bbb'))); +- change.addFileEdit(new SourceFileEdit('/b.dart', 2) +- ..add(new SourceEdit(21, 22, 'xxx')) +- ..add(new SourceEdit(210, 220, 'yyy'))); +- { +- var group =3D new LinkedEditGroup.empty(); +- change.addLinkedEditGroup(group +- ..addPosition(new Position('/ga.dart', 1), 2) +- ..addPosition(new Position('/ga.dart', 10), 2)); +- group.addSuggestion( +- new LinkedEditSuggestion('AA', LinkedEditSuggestionKind.TYPE)); +- group.addSuggestion( +- new LinkedEditSuggestion('BB', LinkedEditSuggestionKind.TYPE)); +- } +- change.addLinkedEditGroup(new LinkedEditGroup.empty() +- ..addPosition(new Position('/gb.dart', 10), 5) +- ..addPosition(new Position('/gb.dart', 100), 5)); +- change.selection =3D new Position('/selection.dart', 42); +- var expectedJson =3D { +- 'message': 'msg', +- 'edits': [ +- { +- 'file': '/a.dart', +- 'fileStamp': 1, +- 'edits': [ +- {'offset': 10, 'length': 20, 'replacement': 'bbb'}, +- {'offset': 1, 'length': 2, 'replacement': 'aaa'} +- ] +- }, +- { +- 'file': '/b.dart', +- 'fileStamp': 2, +- 'edits': [ +- {'offset': 210, 'length': 220, 'replacement': 'yyy'}, +- {'offset': 21, 'length': 22, 'replacement': 'xxx'} +- ] +- } +- ], +- 'linkedEditGroups': [ +- { +- 'length': 2, +- 'positions': [ +- {'file': '/ga.dart', 'offset': 1}, +- {'file': '/ga.dart', 'offset': 10} +- ], +- 'suggestions': [ +- {'kind': 'TYPE', 'value': 'AA'}, +- {'kind': 'TYPE', 'value': 'BB'} +- ] +- }, +- { +- 'length': 5, +- 'positions': [ +- {'file': '/gb.dart', 'offset': 10}, +- {'file': '/gb.dart', 'offset': 100} +- ], +- 'suggestions': [] +- } +- ], +- 'selection': {'file': '/selection.dart', 'offset': 42} +- }; +- expect(change.toJson(), expectedJson); +- // some toString() +- change.toString(); +- } +-} +- +-@reflectiveTest +-class EditTest { +- void test_applySequence() { +- SourceEdit edit1 =3D new SourceEdit(5, 2, 'abc'); +- SourceEdit edit2 =3D new SourceEdit(1, 0, '!'); +- expect( +- SourceEdit.applySequence('0123456789', [edit1, edit2]), '0!1234ab= c789'); +- } +- +- void test_editFromRange() { +- SourceRange range =3D new SourceRange(1, 2); +- SourceEdit edit =3D newSourceEdit_range(range, 'foo'); +- expect(edit.offset, 1); +- expect(edit.length, 2); +- expect(edit.replacement, 'foo'); +- } +- +- void test_eqEq() { +- SourceEdit a =3D new SourceEdit(1, 2, 'aaa'); +- expect(a =3D=3D a, isTrue); +- expect(a =3D=3D new SourceEdit(1, 2, 'aaa'), isTrue); +- expect(a =3D=3D this, isFalse); +- expect(a =3D=3D new SourceEdit(1, 2, 'bbb'), isFalse); +- expect(a =3D=3D new SourceEdit(10, 2, 'aaa'), isFalse); +- } +- +- void test_new() { +- SourceEdit edit =3D new SourceEdit(1, 2, 'foo', id: 'my-id'); +- expect(edit.offset, 1); +- expect(edit.length, 2); +- expect(edit.replacement, 'foo'); +- expect(edit.toJson(), +- {'offset': 1, 'length': 2, 'replacement': 'foo', 'id': 'my-id'}); +- } +- +- void test_toJson() { +- SourceEdit edit =3D new SourceEdit(1, 2, 'foo'); +- var expectedJson =3D {OFFSET: 1, LENGTH: 2, REPLACEMENT: 'foo'}; +- expect(edit.toJson(), expectedJson); +- } +-} +- +-@reflectiveTest +-class FileEditTest { +- void test_add_sorts() { +- SourceEdit edit1a =3D new SourceEdit(1, 0, 'a1'); +- SourceEdit edit1b =3D new SourceEdit(1, 0, 'a2'); +- SourceEdit edit10 =3D new SourceEdit(10, 1, 'b'); +- SourceEdit edit100 =3D new SourceEdit(100, 2, 'c'); +- SourceFileEdit fileEdit =3D new SourceFileEdit('/test.dart', 0); +- fileEdit.add(edit100); +- fileEdit.add(edit1a); +- fileEdit.add(edit1b); +- fileEdit.add(edit10); +- expect(fileEdit.edits, [edit100, edit10, edit1b, edit1a]); +- } +- +- void test_addAll() { +- SourceEdit edit1a =3D new SourceEdit(1, 0, 'a1'); +- SourceEdit edit1b =3D new SourceEdit(1, 0, 'a2'); +- SourceEdit edit10 =3D new SourceEdit(10, 1, 'b'); +- SourceEdit edit100 =3D new SourceEdit(100, 2, 'c'); +- SourceFileEdit fileEdit =3D new SourceFileEdit('/test.dart', 0); +- fileEdit.addAll([edit100, edit1a, edit10, edit1b]); +- expect(fileEdit.edits, [edit100, edit10, edit1b, edit1a]); +- } +- +- void test_new() { +- SourceFileEdit fileEdit =3D new SourceFileEdit('/test.dart', 100); +- fileEdit.add(new SourceEdit(1, 2, 'aaa')); +- fileEdit.add(new SourceEdit(10, 20, 'bbb')); +- expect( +- fileEdit.toString(), +- '{"file":"/test.dart","fileStamp":100,"edits":[' +- '{"offset":10,"length":20,"replacement":"bbb"},' +- '{"offset":1,"length":2,"replacement":"aaa"}]}'); +- } +- +- void test_toJson() { +- SourceFileEdit fileEdit =3D new SourceFileEdit('/test.dart', 100); +- fileEdit.add(new SourceEdit(1, 2, 'aaa')); +- fileEdit.add(new SourceEdit(10, 20, 'bbb')); +- var expectedJson =3D { +- FILE: '/test.dart', +- FILE_STAMP: 100, +- EDITS: [ +- {OFFSET: 10, LENGTH: 20, REPLACEMENT: 'bbb'}, +- {OFFSET: 1, LENGTH: 2, REPLACEMENT: 'aaa'}, +- ] +- }; +- expect(fileEdit.toJson(), expectedJson); +- } +-} +- +-@reflectiveTest +-class LinkedEditGroupTest { +- void test_new() { +- LinkedEditGroup group =3D new LinkedEditGroup.empty(); +- group.addPosition(new Position('/a.dart', 1), 2); +- group.addPosition(new Position('/b.dart', 10), 2); +- expect( +- group.toString(), +- '{"positions":[' +- '{"file":"/a.dart","offset":1},' +- '{"file":"/b.dart","offset":10}],"length":2,"suggestions":[]}'); +- } +- +- void test_toJson() { +- LinkedEditGroup group =3D new LinkedEditGroup.empty(); +- group.addPosition(new Position('/a.dart', 1), 2); +- group.addPosition(new Position('/b.dart', 10), 2); +- group.addSuggestion( +- new LinkedEditSuggestion('AA', LinkedEditSuggestionKind.TYPE)); +- group.addSuggestion( +- new LinkedEditSuggestion('BB', LinkedEditSuggestionKind.TYPE)); +- expect(group.toJson(), { +- 'length': 2, +- 'positions': [ +- {'file': '/a.dart', 'offset': 1}, +- {'file': '/b.dart', 'offset': 10} +- ], +- 'suggestions': [ +- {'kind': 'TYPE', 'value': 'AA'}, +- {'kind': 'TYPE', 'value': 'BB'} +- ] +- }); +- } +-} +- +-@reflectiveTest +-class LinkedEditSuggestionTest { +- void test_eqEq() { +- var a =3D new LinkedEditSuggestion('a', LinkedEditSuggestionKind.METH= OD); +- var a2 =3D new LinkedEditSuggestion('a', LinkedEditSuggestionKind.MET= HOD); +- var b =3D new LinkedEditSuggestion('a', LinkedEditSuggestionKind.TYPE= ); +- var c =3D new LinkedEditSuggestion('c', LinkedEditSuggestionKind.METH= OD); +- expect(a =3D=3D a, isTrue); +- expect(a =3D=3D a2, isTrue); +- expect(a =3D=3D this, isFalse); +- expect(a =3D=3D b, isFalse); +- expect(a =3D=3D c, isFalse); +- } +-} +- +-@reflectiveTest +-class PositionTest { +- void test_eqEq() { +- Position a =3D new Position('/a.dart', 1); +- Position a2 =3D new Position('/a.dart', 1); +- Position b =3D new Position('/b.dart', 1); +- expect(a =3D=3D a, isTrue); +- expect(a =3D=3D a2, isTrue); +- expect(a =3D=3D b, isFalse); +- expect(a =3D=3D this, isFalse); +- } +- +- void test_hashCode() { +- Position position =3D new Position('/test.dart', 1); +- position.hashCode; +- } +- +- void test_new() { +- Position position =3D new Position('/test.dart', 1); +- expect(position.file, '/test.dart'); +- expect(position.offset, 1); +- expect(position.toString(), '{"file":"/test.dart","offset":1}'); +- } +- +- void test_toJson() { +- Position position =3D new Position('/test.dart', 1); +- var expectedJson =3D {FILE: '/test.dart', OFFSET: 1}; +- expect(position.toJson(), expectedJson); +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/fix_test.dart b/= pkg/analysis_server/test/services/correction/fix_test.dart +deleted file mode 100644 +index b4c7c4ded55..00000000000 +--- a/pkg/analysis_server/test/services/correction/fix_test.dart ++++ /dev/null +@@ -1,6753 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/plugin/edit/fix/fix_core.dart'; +-import 'package:analysis_server/plugin/edit/fix/fix_dart.dart'; +-import 'package:analysis_server/src/services/correction/fix.dart'; +-import 'package:analysis_server/src/services/correction/fix_internal.dart= '; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/ast/standard_resolution_map.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/error/codes.dart'; +-import 'package:analyzer/src/generated/parser.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- hide AnalysisError; +-import 'package:analyzer_plugin/utilities/fixes/fixes.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +-import '../../src/utilities/flutter_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FixProcessorTest); +- defineReflectiveTests(LintFixTest); +- }); +-} +- +-typedef bool AnalysisErrorFilter(AnalysisError error); +- +-/** +- * Base class for fix processor tests. +- */ +-class BaseFixProcessorTest extends AbstractSingleUnitTest { +- AnalysisErrorFilter errorFilter =3D (AnalysisError error) { +- return error.errorCode !=3D HintCode.UNUSED_CATCH_CLAUSE && +- error.errorCode !=3D HintCode.UNUSED_CATCH_STACK && +- error.errorCode !=3D HintCode.UNUSED_ELEMENT && +- error.errorCode !=3D HintCode.UNUSED_FIELD && +- error.errorCode !=3D HintCode.UNUSED_LOCAL_VARIABLE; +- }; +- +- String myPkgLibPath =3D '/packages/my_pkg/lib'; +- +- String flutterPkgLibPath =3D '/packages/flutter/lib'; +- +- Fix fix; +- +- SourceChange change; +- String resultCode; +- +- assert_undefinedFunction_create_returnType_bool(String lineWithTest) as= ync { +- await resolveTestUnit(''' +-main() { +- bool b =3D true; +- $lineWithTest +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- bool b =3D true; +- $lineWithTest +-} +- +-bool test() { +-} +-'''); +- } +- +- assertHasFix(FixKind kind, String expected, {String target}) async { +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(kind, error); +- change =3D fix.change; +- +- // apply to "file" +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- +- String fileContent =3D testCode; +- if (target !=3D null) { +- expect(target, fileEdits.first.file); +- fileContent =3D provider.getFile(target).readAsStringSync(); +- } +- +- resultCode =3D SourceEdit.applySequence(fileContent, change.edits[0].= edits); +- // verify +- expect(resultCode, expected); +- } +- +- assertNoFix(FixKind kind) async { +- AnalysisError error =3D await _findErrorToFix(); +- List fixes =3D await _computeFixes(error); +- for (Fix fix in fixes) { +- if (fix.kind =3D=3D kind) { +- throw fail('Unexpected fix $kind in\n${fixes.join('\n')}'); +- } +- } +- } +- +- Position expectedPosition(String search) { +- int offset =3D resultCode.indexOf(search); +- return new Position(testFile, offset); +- } +- +- List expectedPositions(List patterns) { +- List positions =3D []; +- patterns.forEach((String search) { +- positions.add(expectedPosition(search)); +- }); +- return positions; +- } +- +- List expectedSuggestions( +- LinkedEditSuggestionKind kind, List values) { +- return values.map((value) { +- return new LinkedEditSuggestion(value, kind); +- }).toList(); +- } +- +- void setUp() { +- super.setUp(); +- verifyNoTestUnitErrors =3D false; +- } +- +- /** +- * Computes fixes and verifies that there is a fix of the given kind. +- */ +- Future _assertHasFix(FixKind kind, AnalysisError error) async { +- List fixes =3D await _computeFixes(error); +- for (Fix fix in fixes) { +- if (fix.kind =3D=3D kind) { +- return fix; +- } +- } +- throw fail('Expected to find fix $kind in\n${fixes.join('\n')}'); +- } +- +- void _assertLinkedGroup(LinkedEditGroup group, List expectedStr= ings, +- [List expectedSuggestions]) { +- List expectedPositions =3D _findResultPositions(expectedStr= ings); +- expect(group.positions, unorderedEquals(expectedPositions)); +- if (expectedSuggestions !=3D null) { +- expect(group.suggestions, unorderedEquals(expectedSuggestions)); +- } +- } +- +- Future> _computeErrors() async { +- return (await driver.getResult(testFile)).errors; +- } +- +- /** +- * Computes fixes for the given [error] in [testUnit]. +- */ +- Future> _computeFixes(AnalysisError error) async { +- DartFixContext fixContext =3D new _DartFixContextImpl( +- provider, driver, new AstProviderForDriver(driver), testUnit, err= or); +- return await new DefaultFixContributor().internalComputeFixes(fixCont= ext); +- } +- +- /** +- * Configures the [SourceFactory] to have the `my_pkg` package in +- * `/packages/my_pkg/lib` folder. +- */ +- void _configureMyPkg(Map pathToCode) { +- pathToCode.forEach((path, code) { +- provider.newFile('$myPkgLibPath/$path', code); +- }); +- // configure SourceFactory +- Folder myPkgFolder =3D provider.getResource(myPkgLibPath); +- UriResolver pkgResolver =3D new PackageMapUriResolver(provider, { +- 'my_pkg': [myPkgFolder] +- }); +- SourceFactory sourceFactory =3D new SourceFactory( +- [new DartUriResolver(sdk), pkgResolver, resourceResolver]); +- driver.configure(sourceFactory: sourceFactory); +- // force 'my_pkg' resolution +- addSource( +- '/tmp/other.dart', +- pathToCode.keys +- .map((path) =3D> "import 'package:my_pkg/$path';") +- .join('\n')); +- } +- +- Future _findErrorToFix() async { +- List errors =3D await _computeErrors(); +- if (errorFilter !=3D null) { +- errors =3D errors.where(errorFilter).toList(); +- } +- expect(errors, hasLength(1)); +- return errors[0]; +- } +- +- List _findResultPositions(List searchStrings) { +- List positions =3D []; +- for (String search in searchStrings) { +- int offset =3D resultCode.indexOf(search); +- positions.add(new Position(testFile, offset)); +- } +- return positions; +- } +-} +- +-@reflectiveTest +-class FixProcessorTest extends BaseFixProcessorTest { +- test_addFieldFormalParameters_hasRequiredParameter() async { +- await resolveTestUnit(''' +-class Test { +- final int a; +- final int b; +- final int c; +- Test(this.a); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_FIELD_FORMAL_PARAMETERS, ''' +-class Test { +- final int a; +- final int b; +- final int c; +- Test(this.a, this.b, this.c); +-} +-'''); +- } +- +- test_addFieldFormalParameters_noParameters() async { +- await resolveTestUnit(''' +-class Test { +- final int a; +- final int b; +- final int c; +- Test(); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_FIELD_FORMAL_PARAMETERS, ''' +-class Test { +- final int a; +- final int b; +- final int c; +- Test(this.a, this.b, this.c); +-} +-'''); +- } +- +- test_addFieldFormalParameters_noRequiredParameter() async { +- await resolveTestUnit(''' +-class Test { +- final int a; +- final int b; +- final int c; +- Test([this.c]); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_FIELD_FORMAL_PARAMETERS, ''' +-class Test { +- final int a; +- final int b; +- final int c; +- Test(this.a, this.b, [this.c]); +-} +-'''); +- } +- +- test_addFieldFormalParameters_notAllFinal() async { +- await resolveTestUnit(''' +-class Test { +- final int a; +- int b; +- final int c; +- Test(); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_FIELD_FORMAL_PARAMETERS, ''' +-class Test { +- final int a; +- int b; +- final int c; +- Test(this.a, this.c); +-} +-'''); +- } +- +- test_addMissingParameter_function_positional_hasNamed() async { +- await resolveTestUnit(''' +-test({int a}) {} +-main() { +- test(1); +-} +-'''); +- await assertNoFix(DartFixKind.ADD_MISSING_PARAMETER_POSITIONAL); +- } +- +- test_addMissingParameter_function_positional_hasZero() async { +- await resolveTestUnit(''' +-test() {} +-main() { +- test(1); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_POSITIONAL, ''' +-test([int i]) {} +-main() { +- test(1); +-} +-'''); +- } +- +- test_addMissingParameter_function_required_hasNamed() async { +- await resolveTestUnit(''' +-test({int a}) {} +-main() { +- test(1); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_REQUIRED, ''' +-test(int i, {int a}) {} +-main() { +- test(1); +-} +-'''); +- } +- +- test_addMissingParameter_function_required_hasOne() async { +- await resolveTestUnit(''' +-test(int a) {} +-main() { +- test(1, 2.0); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_REQUIRED, ''' +-test(int a, double d) {} +-main() { +- test(1, 2.0); +-} +-'''); +- } +- +- test_addMissingParameter_function_required_hasZero() async { +- await resolveTestUnit(''' +-test() {} +-main() { +- test(1); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_REQUIRED, ''' +-test(int i) {} +-main() { +- test(1); +-} +-'''); +- } +- +- test_addMissingParameter_method_positional_hasOne() async { +- await resolveTestUnit(''' +-class A { +- test(int a) {} +- main() { +- test(1, 2.0); +- } +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_POSITIONAL, ''' +-class A { +- test(int a, [double d]) {} +- main() { +- test(1, 2.0); +- } +-} +-'''); +- } +- +- test_addMissingParameter_method_required_hasOne() async { +- await resolveTestUnit(''' +-class A { +- test(int a) {} +- main() { +- test(1, 2.0); +- } +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_REQUIRED, ''' +-class A { +- test(int a, double d) {} +- main() { +- test(1, 2.0); +- } +-} +-'''); +- } +- +- test_addMissingParameter_method_required_hasZero() async { +- await resolveTestUnit(''' +-class A { +- test() {} +- main() { +- test(1); +- } +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_PARAMETER_REQUIRED, ''' +-class A { +- test(int i) {} +- main() { +- test(1); +- } +-} +-'''); +- } +- +- test_addMissingRequiredArg_cons_flutter_children() async { +- addPackageSource( +- 'flutter', 'src/widgets/framework.dart', flutter_framework_code); +- +- _addMetaPackageSource(); +- +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-import 'package:meta/meta.dart'; +- +-class MyWidget extends Widget { +- MyWidget({@required List children}); +-} +- +-build() { +- return new MyWidget(); +-} +-'''); +- +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'package:flutter/src/widgets/framework.dart'; +-import 'package:meta/meta.dart'; +- +-class MyWidget extends Widget { +- MyWidget({@required List children}); +-} +- +-build() { +- return new MyWidget(children: [],); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_cons_single() async { +- _addMetaPackageSource(); +- addSource('/libA.dart', r''' +-library libA; +-import 'package:meta/meta.dart'; +- +-class A { +- A({@required int a}) {} +-} +-'''); +- +- await resolveTestUnit(''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(); +-} +-'''); +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(a: null); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_cons_single_closure() async { +- _addMetaPackageSource(); +- +- addSource('/libA.dart', r''' +-library libA; +-import 'package:meta/meta.dart'; +- +-typedef void VoidCallback(); +- +-class A { +- A({@required VoidCallback onPressed}) {} +-} +-'''); +- +- await resolveTestUnit(''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(); +-} +-'''); +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(onPressed: () {}); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_cons_single_closure_2() async { +- _addMetaPackageSource(); +- +- addSource('/libA.dart', r''' +-library libA; +-import 'package:meta/meta.dart'; +- +-typedef void Callback(e); +- +-class A { +- A({@required Callback callback}) {} +-} +-'''); +- +- await resolveTestUnit(''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(); +-} +-'''); +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(callback: (e) {}); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_cons_single_closure_3() async { +- _addMetaPackageSource(); +- +- addSource('/libA.dart', r''' +-library libA; +-import 'package:meta/meta.dart'; +- +-typedef void Callback(a,b,c); +- +-class A { +- A({@required Callback callback}) {} +-} +-'''); +- +- await resolveTestUnit(''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(); +-} +-'''); +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(callback: (a, b, c) {}); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_cons_single_closure_4() async { +- _addMetaPackageSource(); +- +- addSource('/libA.dart', r''' +-library libA; +-import 'package:meta/meta.dart'; +- +-typedef int Callback(int a, String b,c); +- +-class A { +- A({@required Callback callback}) {} +-} +-'''); +- +- await resolveTestUnit(''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(); +-} +-'''); +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(callback: (int a, String b, c) {}); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_cons_single_list() async { +- _addMetaPackageSource(); +- +- addSource('/libA.dart', r''' +-library libA; +-import 'package:meta/meta.dart'; +- +-class A { +- A({@required List names}) {} +-} +-'''); +- +- await resolveTestUnit(''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(); +-} +-'''); +- await assertHasFix( +- DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, +- ''' +-import 'libA.dart'; +- +-main() { +- A a =3D new A(names: []); +-} +-''', +- target: '/test.dart'); +- } +- +- test_addMissingRequiredArg_multiple() async { +- _addMetaPackageSource(); +- +- await resolveTestUnit(''' +-import 'package:meta/meta.dart'; +- +-test({@required int a, @required int bcd}) {} +-main() { +- test(a: 3); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, ''' +-import 'package:meta/meta.dart'; +- +-test({@required int a, @required int bcd}) {} +-main() { +- test(a: 3, bcd: null); +-} +-'''); +- } +- +- test_addMissingRequiredArg_multiple_2() async { +- _addMetaPackageSource(); +- +- await resolveTestUnit(''' +-import 'package:meta/meta.dart'; +- +-test({@required int a, @required int bcd}) {} +-main() { +- test(); +-} +-'''); +- +- // For now we expect one error per missing arg (dartbug.com/28830). +- List errors =3D await _computeErrors(); +- expect(errors, hasLength(2)); +- +- List filteredErrors =3D errors +- .where((e) =3D> e.message =3D=3D "The parameter 'a' is required.") +- .toList(); +- expect(filteredErrors, hasLength(1)); +- +- List fixes =3D await _computeFixes(filteredErrors.first); +- +- List filteredFixes =3D fixes +- .where((fix) =3D> fix.change.message =3D=3D "Add required argumen= t 'a'") +- .toList(); +- expect(filteredFixes, hasLength(1)); +- change =3D filteredFixes.first.change; +- resultCode =3D SourceEdit.applySequence(testCode, change.edits[0].edi= ts); +- // verify +- expect(resultCode, ''' +-import 'package:meta/meta.dart'; +- +-test({@required int a, @required int bcd}) {} +-main() { +- test(a: null); +-} +-'''); +- } +- +- test_addMissingRequiredArg_single() async { +- _addMetaPackageSource(); +- +- await resolveTestUnit(''' +-import 'package:meta/meta.dart'; +- +-test({@required int abc}) {} +-main() { +- test(); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, ''' +-import 'package:meta/meta.dart'; +- +-test({@required int abc}) {} +-main() { +- test(abc: null); +-} +-'''); +- } +- +- test_addMissingRequiredArg_single_normal() async { +- _addMetaPackageSource(); +- +- await resolveTestUnit(''' +-import 'package:meta/meta.dart'; +- +-test(String x, {@required int abc}) {} +-main() { +- test("foo"); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, ''' +-import 'package:meta/meta.dart'; +- +-test(String x, {@required int abc}) {} +-main() { +- test("foo", abc: null); +-} +-'''); +- } +- +- test_addMissingRequiredArg_single_with_details() async { +- _addMetaPackageSource(); +- +- await resolveTestUnit(''' +-import 'package:meta/meta.dart'; +- +-test({@Required("Really who doesn't need an abc?") int abc}) {} +-main() { +- test(); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_MISSING_REQUIRED_ARGUMENT, ''' +-import 'package:meta/meta.dart'; +- +-test({@Required("Really who doesn't need an abc?") int abc}) {} +-main() { +- test(abc: null); +-} +-'''); +- } +- +- test_addSync_asyncFor() async { +- await resolveTestUnit(''' +-import 'dart:async'; +-void main(Stream names) { +- await for (String name in names) { +- print(name); +- } +-} +-'''); +- await assertHasFix(DartFixKind.ADD_ASYNC, ''' +-import 'dart:async'; +-Future main(Stream names) async { +- await for (String name in names) { +- print(name); +- } +-} +-'''); +- } +- +- test_addSync_BAD_nullFunctionBody() async { +- await resolveTestUnit(''' +-var F =3D await; +-'''); +- await assertNoFix(DartFixKind.ADD_ASYNC); +- } +- +- test_addSync_blockFunctionBody() async { +- await resolveTestUnit(''' +-foo() {} +-main() { +- await foo(); +-} +-'''); +- List errors =3D await _computeErrors(); +- expect(errors, hasLength(2)); +- errors.sort((a, b) =3D> a.message.compareTo(b.message)); +- // No fix for ";". +- { +- AnalysisError error =3D errors[0]; +- expect(error.message, "Expected to find ';'."); +- List fixes =3D await _computeFixes(error); +- expect(fixes, isEmpty); +- } +- // Has fix for "await". +- { +- AnalysisError error =3D errors[1]; +- expect(error.message, startsWith("Undefined name 'await' in functio= n")); +- List fixes =3D await _computeFixes(error); +- // has exactly one fix +- expect(fixes, hasLength(1)); +- Fix fix =3D fixes[0]; +- expect(fix.kind, DartFixKind.ADD_ASYNC); +- // apply to "file" +- List fileEdits =3D fix.change.edits; +- expect(fileEdits, hasLength(1)); +- resultCode =3D SourceEdit.applySequence(testCode, fileEdits[0].edit= s); +- // verify +- expect(resultCode, ''' +-foo() {} +-main() async { +- await foo(); +-} +-'''); +- } +- } +- +- test_addSync_expressionFunctionBody() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R_AWAIT; +- }; +- await resolveTestUnit(''' +-foo() {} +-main() =3D> await foo(); +-'''); +- await assertHasFix(DartFixKind.ADD_ASYNC, ''' +-foo() {} +-main() async =3D> await foo(); +-'''); +- } +- +- test_addSync_returnFuture() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R_AWAIT; +- }; +- await resolveTestUnit(''' +-foo() {} +-int main() { +- await foo(); +- return 42; +-} +-'''); +- await assertHasFix(DartFixKind.ADD_ASYNC, ''' +-import 'dart:async'; +- +-foo() {} +-Future main() async { +- await foo(); +- return 42; +-} +-'''); +- } +- +- test_addSync_returnFuture_alreadyFuture() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R_AWAIT; +- }; +- await resolveTestUnit(''' +-import 'dart:async'; +-foo() {} +-Future main() { +- await foo(); +- return 42; +-} +-'''); +- await assertHasFix(DartFixKind.ADD_ASYNC, ''' +-import 'dart:async'; +-foo() {} +-Future main() async { +- await foo(); +- return 42; +-} +-'''); +- } +- +- test_addSync_returnFuture_dynamic() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R_AWAIT; +- }; +- await resolveTestUnit(''' +-foo() {} +-dynamic main() { +- await foo(); +- return 42; +-} +-'''); +- await assertHasFix(DartFixKind.ADD_ASYNC, ''' +-foo() {} +-dynamic main() async { +- await foo(); +- return 42; +-} +-'''); +- } +- +- test_addSync_returnFuture_noType() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R_AWAIT; +- }; +- await resolveTestUnit(''' +-foo() {} +-main() { +- await foo(); +- return 42; +-} +-'''); +- await assertHasFix(DartFixKind.ADD_ASYNC, ''' +-foo() {} +-main() async { +- await foo(); +- return 42; +-} +-'''); +- } +- +- test_boolean() async { +- await resolveTestUnit(''' +-main() { +- boolean v; +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_BOOLEAN_WITH_BOOL, ''' +-main() { +- bool v; +-} +-'''); +- } +- +- test_canBeNullAfterNullAware_chain() async { +- await resolveTestUnit(''' +-main(x) { +- x?.a.b.c; +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_WITH_NULL_AWARE, ''' +-main(x) { +- x?.a?.b?.c; +-} +-'''); +- } +- +- test_canBeNullAfterNullAware_methodInvocation() async { +- await resolveTestUnit(''' +-main(x) { +- x?.a.b(); +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_WITH_NULL_AWARE, ''' +-main(x) { +- x?.a?.b(); +-} +-'''); +- } +- +- test_canBeNullAfterNullAware_propertyAccess() async { +- await resolveTestUnit(''' +-main(x) { +- x?.a().b; +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_WITH_NULL_AWARE, ''' +-main(x) { +- x?.a()?.b; +-} +-'''); +- } +- +- test_changeToStaticAccess_method() async { +- await resolveTestUnit(''' +-class A { +- static foo() {} +-} +-main(A a) { +- a.foo(); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO_STATIC_ACCESS, ''' +-class A { +- static foo() {} +-} +-main(A a) { +- A.foo(); +-} +-'''); +- } +- +- test_changeToStaticAccess_method_importType() async { +- addSource('/libA.dart', r''' +-library libA; +-class A { +- static foo() {} +-} +-'''); +- addSource('/libB.dart', r''' +-library libB; +-import 'libA.dart'; +-class B extends A {} +-'''); +- await resolveTestUnit(''' +-import 'libB.dart'; +-main(B b) { +- b.foo(); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO_STATIC_ACCESS, ''' +-import 'libA.dart'; +-import 'libB.dart'; +-main(B b) { +- A.foo(); +-} +-'''); +- } +- +- test_changeToStaticAccess_method_prefixLibrary() async { +- await resolveTestUnit(''' +-import 'dart:async' as pref; +-main(pref.Future f) { +- f.wait([]); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO_STATIC_ACCESS, ''' +-import 'dart:async' as pref; +-main(pref.Future f) { +- pref.Future.wait([]); +-} +-'''); +- } +- +- test_changeToStaticAccess_property() async { +- await resolveTestUnit(''' +-class A { +- static get foo =3D> 42; +-} +-main(A a) { +- a.foo; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO_STATIC_ACCESS, ''' +-class A { +- static get foo =3D> 42; +-} +-main(A a) { +- A.foo; +-} +-'''); +- } +- +- test_changeToStaticAccess_property_importType() async { +- addSource('/libA.dart', r''' +-library libA; +-class A { +- static get foo =3D> null; +-} +-'''); +- addSource('/libB.dart', r''' +-library libB; +-import 'libA.dart'; +-class B extends A {} +-'''); +- await resolveTestUnit(''' +-import 'libB.dart'; +-main(B b) { +- b.foo; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO_STATIC_ACCESS, ''' +-import 'libA.dart'; +-import 'libB.dart'; +-main(B b) { +- A.foo; +-} +-'''); +- } +- +- test_changeTypeAnnotation_BAD_multipleVariables() async { +- await resolveTestUnit(''' +-main() { +- String a, b =3D 42; +-} +-'''); +- await assertNoFix(DartFixKind.CHANGE_TYPE_ANNOTATION); +- } +- +- test_changeTypeAnnotation_BAD_notVariableDeclaration() async { +- await resolveTestUnit(''' +-main() { +- String v; +- v =3D 42; +-} +-'''); +- await assertNoFix(DartFixKind.CHANGE_TYPE_ANNOTATION); +- } +- +- test_changeTypeAnnotation_OK_generic() async { +- await resolveTestUnit(''' +-main() { +- String v =3D []; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TYPE_ANNOTATION, ''' +-main() { +- List v =3D []; +-} +-'''); +- } +- +- test_changeTypeAnnotation_OK_simple() async { +- await resolveTestUnit(''' +-main() { +- String v =3D 'abc'.length; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TYPE_ANNOTATION, ''' +-main() { +- int v =3D 'abc'.length; +-} +-'''); +- } +- +- test_createClass() async { +- await resolveTestUnit(''' +-main() { +- Test v =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CLASS, ''' +-main() { +- Test v =3D null; +-} +- +-class Test { +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['Test v =3D', 'Test {= ']); +- } +- +- test_createClass_BAD_hasUnresolvedPrefix() async { +- await resolveTestUnit(''' +-main() { +- prefix.Test v =3D null; +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_CLASS); +- } +- +- test_createClass_inLibraryOfPrefix() async { +- String libCode =3D r''' +-library my.lib; +- +-class A {} +-'''; +- addSource('/lib.dart', libCode); +- await resolveTestUnit(''' +-import 'lib.dart' as lib; +- +-main() { +- lib.A a =3D null; +- lib.Test t =3D null; +-} +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_CLASS, error); +- change =3D fix.change; +- // apply to "lib.dart" +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/lib.dart'); +- expect(SourceEdit.applySequence(libCode, fileEdit.edits), r''' +-library my.lib; +- +-class A {} +- +-class Test { +-} +-'''); +- expect(change.linkedEditGroups, hasLength(1)); +- } +- +- test_createClass_innerLocalFunction() async { +- await resolveTestUnit(''' +-f() { +- g() { +- Test v =3D null; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CLASS, ''' +-f() { +- g() { +- Test v =3D null; +- } +-} +- +-class Test { +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['Test v =3D', 'Test {= ']); +- } +- +- test_createClass_itemOfList() async { +- await resolveTestUnit(''' +-main() { +- var a =3D [Test]; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CLASS, ''' +-main() { +- var a =3D [Test]; +-} +- +-class Test { +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['Test];', 'Test {']); +- } +- +- test_createClass_itemOfList_inAnnotation() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R; +- }; +- await resolveTestUnit(''' +-class MyAnnotation { +- const MyAnnotation(a, b); +-} +-@MyAnnotation(int, const [Test]) +-main() {} +-'''); +- await assertHasFix(DartFixKind.CREATE_CLASS, ''' +-class MyAnnotation { +- const MyAnnotation(a, b); +-} +-@MyAnnotation(int, const [Test]) +-main() {} +- +-class Test { +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['Test])', 'Test {']); +- } +- +- test_createConstructor_forFinalFields() async { +- errorFilter =3D (AnalysisError error) { +- return error.message.contains("'a'"); +- }; +- await resolveTestUnit(''' +-class Test { +- final int a; +- final int b =3D 2; +- final int c; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR_FOR_FINAL_FIELDS, '= '' +-class Test { +- final int a; +- final int b =3D 2; +- final int c; +- +- Test(this.a, this.c); +-} +-'''); +- } +- +- test_createConstructor_insteadOfSyntheticDefault() async { +- await resolveTestUnit(''' +-class A { +- int field; +- +- method() {} +-} +-main() { +- new A(1, 2.0); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR, ''' +-class A { +- int field; +- +- A(int i, double d); +- +- method() {} +-} +-main() { +- new A(1, 2.0); +-} +-'''); +- } +- +- test_createConstructor_named() async { +- await resolveTestUnit(''' +-class A { +- method() {} +-} +-main() { +- new A.named(1, 2.0); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR, ''' +-class A { +- A.named(int i, double d); +- +- method() {} +-} +-main() { +- new A.named(1, 2.0); +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['named(int ', 'named(= 1']); +- } +- +- test_createConstructor_named_emptyClassBody() async { +- await resolveTestUnit(''' +-class A {} +-main() { +- new A.named(1); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR, ''' +-class A { +- A.named(int i); +-} +-main() { +- new A.named(1); +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['named(int ', 'named(= 1']); +- } +- +- test_createConstructorForFinalFields_inTopLevelMethod() async { +- await resolveTestUnit(''' +-main() { +- final int v; +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_CONSTRUCTOR_FOR_FINAL_FIELDS); +- } +- +- test_createConstructorForFinalFields_topLevelField() async { +- await resolveTestUnit(''' +-final int v; +-'''); +- await assertNoFix(DartFixKind.CREATE_CONSTRUCTOR_FOR_FINAL_FIELDS); +- } +- +- test_createConstructorSuperExplicit() async { +- await resolveTestUnit(''' +-class A { +- A(bool p1, int p2, double p3, String p4, {p5}); +-} +-class B extends A { +- B() {} +-} +-'''); +- await assertHasFix(DartFixKind.ADD_SUPER_CONSTRUCTOR_INVOCATION, ''' +-class A { +- A(bool p1, int p2, double p3, String p4, {p5}); +-} +-class B extends A { +- B() : super(false, 0, 0.0, '') {} +-} +-'''); +- } +- +- test_createConstructorSuperExplicit_hasInitializers() async { +- await resolveTestUnit(''' +-class A { +- A(int p); +-} +-class B extends A { +- int field; +- B() : field =3D 42 {} +-} +-'''); +- await assertHasFix(DartFixKind.ADD_SUPER_CONSTRUCTOR_INVOCATION, ''' +-class A { +- A(int p); +-} +-class B extends A { +- int field; +- B() : field =3D 42, super(0) {} +-} +-'''); +- } +- +- test_createConstructorSuperExplicit_named() async { +- await resolveTestUnit(''' +-class A { +- A.named(int p); +-} +-class B extends A { +- B() {} +-} +-'''); +- await assertHasFix(DartFixKind.ADD_SUPER_CONSTRUCTOR_INVOCATION, ''' +-class A { +- A.named(int p); +-} +-class B extends A { +- B() : super.named(0) {} +-} +-'''); +- } +- +- test_createConstructorSuperExplicit_named_private() async { +- await resolveTestUnit(''' +-class A { +- A._named(int p); +-} +-class B extends A { +- B() {} +-} +-'''); +- await assertNoFix(DartFixKind.ADD_SUPER_CONSTRUCTOR_INVOCATION); +- } +- +- test_createConstructorSuperExplicit_typeArgument() async { +- await resolveTestUnit(''' +-class A { +- A(T p); +-} +-class B extends A { +- B(); +-} +-'''); +- await assertHasFix(DartFixKind.ADD_SUPER_CONSTRUCTOR_INVOCATION, ''' +-class A { +- A(T p); +-} +-class B extends A { +- B() : super(0); +-} +-'''); +- } +- +- test_createConstructorSuperImplicit() async { +- await resolveTestUnit(''' +-class A { +- A(p1, int p2, List p3, [int p4]); +-} +-class B extends A { +- int existingField; +- +- void existingMethod() {} +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR_SUPER, ''' +-class A { +- A(p1, int p2, List p3, [int p4]); +-} +-class B extends A { +- int existingField; +- +- B(p1, int p2, List p3) : super(p1, p2, p3); +- +- void existingMethod() {} +-} +-'''); +- } +- +- test_createConstructorSuperImplicit_fieldInitializer() async { +- await resolveTestUnit(''' +-class A { +- int _field; +- A(this._field); +-} +-class B extends A { +- int existingField; +- +- void existingMethod() {} +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR_SUPER, ''' +-class A { +- int _field; +- A(this._field); +-} +-class B extends A { +- int existingField; +- +- B(int field) : super(field); +- +- void existingMethod() {} +-} +-'''); +- } +- +- test_createConstructorSuperImplicit_importType() async { +- addSource('/libA.dart', r''' +-library libA; +-class A {} +-'''); +- addSource('/libB.dart', r''' +-library libB; +-import 'libA.dart'; +-class B { +- B(A a); +-} +-'''); +- await resolveTestUnit(''' +-import 'libB.dart'; +-class C extends B { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR_SUPER, ''' +-import 'libA.dart'; +-import 'libB.dart'; +-class C extends B { +- C(A a) : super(a); +-} +-'''); +- } +- +- test_createConstructorSuperImplicit_named() async { +- await resolveTestUnit(''' +-class A { +- A.named(p1, int p2); +-} +-class B extends A { +- int existingField; +- +- void existingMethod() {} +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR_SUPER, ''' +-class A { +- A.named(p1, int p2); +-} +-class B extends A { +- int existingField; +- +- B.named(p1, int p2) : super.named(p1, p2); +- +- void existingMethod() {} +-} +-'''); +- } +- +- test_createConstructorSuperImplicit_private() async { +- await resolveTestUnit(''' +-class A { +- A._named(p); +-} +-class B extends A { +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_CONSTRUCTOR_SUPER); +- } +- +- test_createConstructorSuperImplicit_typeArgument() async { +- await resolveTestUnit(''' +-class C { +- final T x; +- C(this.x); +-} +-class D extends C { +-}'''); +- await assertHasFix(DartFixKind.CREATE_CONSTRUCTOR_SUPER, ''' +-class C { +- final T x; +- C(this.x); +-} +-class D extends C { +- D(int x) : super(x); +-}'''); +- } +- +- test_createField_BAD_inEnum() async { +- await resolveTestUnit(''' +-enum MyEnum { +- AAA, BBB +-} +-main() { +- MyEnum.foo; +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_FIELD); +- } +- +- test_createField_BAD_inSDK() async { +- await resolveTestUnit(''' +-main(List p) { +- p.foo =3D 1; +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_FIELD); +- } +- +- test_createField_getter_multiLevel() async { +- await resolveTestUnit(''' +-class A { +-} +-class B { +- A a; +-} +-class C { +- B b; +-} +-main(C c) { +- int v =3D c.b.a.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +-} +-class B { +- A a; +-} +-class C { +- B b; +-} +-main(C c) { +- int v =3D c.b.a.test; +-} +-'''); +- } +- +- test_createField_getter_qualified_instance() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- int v =3D a.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +-} +-main(A a) { +- int v =3D a.test; +-} +-'''); +- } +- +- test_createField_getter_qualified_instance_differentLibrary() async { +- addSource('/other.dart', ''' +-/** +- * A comment to push the offset of the braces for the following class +- * declaration past the end of the content of the test file. Used to catc= h an +- * index out of bounds exception that occurs when using the test source i= nstead +- * of the target source to compute the location at which to insert the fi= eld. +- */ +-class A { +-} +-'''); +- await resolveTestUnit(''' +-import 'other.dart'; +-main(A a) { +- int v =3D a.test; +-} +-'''); +- await assertHasFix( +- DartFixKind.CREATE_FIELD, +- ''' +-/** +- * A comment to push the offset of the braces for the following class +- * declaration past the end of the content of the test file. Used to catc= h an +- * index out of bounds exception that occurs when using the test source i= nstead +- * of the target source to compute the location at which to insert the fi= eld. +- */ +-class A { +- int test; +-} +-''', +- target: '/other.dart'); +- } +- +- test_createField_getter_qualified_instance_dynamicType() async { +- await resolveTestUnit(''' +-class A { +- B b; +- void f(Object p) { +- p =3D=3D b.test; +- } +-} +-class B { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- B b; +- void f(Object p) { +- p =3D=3D b.test; +- } +-} +-class B { +- var test; +-} +-'''); +- } +- +- test_createField_getter_qualified_propagatedType() async { +- await resolveTestUnit(''' +-class A { +- A get self =3D> this; +-} +-main() { +- var a =3D new A(); +- int v =3D a.self.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +- +- A get self =3D> this; +-} +-main() { +- var a =3D new A(); +- int v =3D a.self.test; +-} +-'''); +- } +- +- test_createField_getter_unqualified_instance_asInvocationArgument() asy= nc { +- await resolveTestUnit(''' +-class A { +- main() { +- f(test); +- } +-} +-f(String s) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- String test; +- +- main() { +- f(test); +- } +-} +-f(String s) {} +-'''); +- } +- +- test_createField_getter_unqualified_instance_assignmentRhs() async { +- await resolveTestUnit(''' +-class A { +- main() { +- int v =3D test; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +- +- main() { +- int v =3D test; +- } +-} +-'''); +- } +- +- test_createField_getter_unqualified_instance_asStatement() async { +- await resolveTestUnit(''' +-class A { +- main() { +- test; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- var test; +- +- main() { +- test; +- } +-} +-'''); +- } +- +- test_createField_hint() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- var x =3D a; +- int v =3D x.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +-} +-main(A a) { +- var x =3D a; +- int v =3D x.test; +-} +-'''); +- } +- +- test_createField_hint_setter() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- var x =3D a; +- x.test =3D 0; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +-} +-main(A a) { +- var x =3D a; +- x.test =3D 0; +-} +-'''); +- } +- +- test_createField_importType() async { +- addSource('/libA.dart', r''' +-library libA; +-class A {} +-'''); +- addSource('/libB.dart', r''' +-library libB; +-import 'libA.dart'; +-A getA() =3D> null; +-'''); +- await resolveTestUnit(''' +-import 'libB.dart'; +-class C { +-} +-main(C c) { +- c.test =3D getA(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-import 'libA.dart'; +-import 'libB.dart'; +-class C { +- A test; +-} +-main(C c) { +- c.test =3D getA(); +-} +-'''); +- } +- +- test_createField_invalidInitializer_withoutType() async { +- await resolveTestUnit(''' +-class C { +- C(this.text); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class C { +- var text; +- +- C(this.text); +-} +-'''); +- } +- +- test_createField_invalidInitializer_withType() async { +- await resolveTestUnit(''' +-class C { +- C(String this.text); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class C { +- String text; +- +- C(String this.text); +-} +-'''); +- } +- +- test_createField_setter_generic_BAD() async { +- await resolveTestUnit(''' +-class A { +-} +-class B { +- List items; +- main(A a) { +- a.test =3D items; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- List test; +-} +-class B { +- List items; +- main(A a) { +- a.test =3D items; +- } +-} +-'''); +- } +- +- test_createField_setter_generic_OK_local() async { +- await resolveTestUnit(''' +-class A { +- List items; +- +- main(A a) { +- test =3D items; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- List items; +- +- List test; +- +- main(A a) { +- test =3D items; +- } +-} +-'''); +- } +- +- test_createField_setter_qualified_instance_hasField() async { +- await resolveTestUnit(''' +-class A { +- int aaa; +- int zzz; +- +- existingMethod() {} +-} +-main(A a) { +- a.test =3D 5; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int aaa; +- int zzz; +- +- int test; +- +- existingMethod() {} +-} +-main(A a) { +- a.test =3D 5; +-} +-'''); +- } +- +- test_createField_setter_qualified_instance_hasMethod() async { +- await resolveTestUnit(''' +-class A { +- existingMethod() {} +-} +-main(A a) { +- a.test =3D 5; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +- +- existingMethod() {} +-} +-main(A a) { +- a.test =3D 5; +-} +-'''); +- } +- +- test_createField_setter_qualified_static() async { +- await resolveTestUnit(''' +-class A { +-} +-main() { +- A.test =3D 5; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- static int test; +-} +-main() { +- A.test =3D 5; +-} +-'''); +- } +- +- test_createField_setter_unqualified_instance() async { +- await resolveTestUnit(''' +-class A { +- main() { +- test =3D 5; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- int test; +- +- main() { +- test =3D 5; +- } +-} +-'''); +- } +- +- test_createField_setter_unqualified_static() async { +- await resolveTestUnit(''' +-class A { +- static main() { +- test =3D 5; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FIELD, ''' +-class A { +- static int test; +- +- static main() { +- test =3D 5; +- } +-} +-'''); +- } +- +- test_createFile_forImport() async { +- testFile =3D '/my/project/bin/test.dart'; +- await resolveTestUnit(''' +-import 'my_file.dart'; +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_FILE, error); +- change =3D fix.change; +- // validate change +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/my/project/bin/my_file.dart'); +- expect(fileEdit.fileStamp, -1); +- expect(fileEdit.edits, hasLength(1)); +- expect(fileEdit.edits[0].replacement, contains('library my_file;')); +- } +- +- test_createFile_forImport_BAD_inPackage_lib_justLib() async { +- provider.newFile('/projects/my_package/pubspec.yaml', 'name: my_packa= ge'); +- testFile =3D '/projects/my_package/test.dart'; +- await resolveTestUnit(''' +-import 'lib'; +-'''); +- await assertNoFix(DartFixKind.CREATE_FILE); +- } +- +- test_createFile_forImport_BAD_notDart() async { +- testFile =3D '/my/project/bin/test.dart'; +- await resolveTestUnit(''' +-import 'my_file.txt'; +-'''); +- await assertNoFix(DartFixKind.CREATE_FILE); +- } +- +- test_createFile_forImport_inPackage_lib() async { +- provider.newFile('/projects/my_package/pubspec.yaml', 'name: my_packa= ge'); +- testFile =3D '/projects/my_package/lib/test.dart'; +- provider.newFolder('/projects/my_package/lib'); +- await resolveTestUnit(''' +-import 'a/bb/c_cc/my_lib.dart'; +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_FILE, error); +- change =3D fix.change; +- // validate change +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/projects/my_package/lib/a/bb/c_cc/my_lib.dart= '); +- expect(fileEdit.fileStamp, -1); +- expect(fileEdit.edits, hasLength(1)); +- expect(fileEdit.edits[0].replacement, +- contains('library my_package.a.bb.c_cc.my_lib;')); +- } +- +- test_createFile_forImport_inPackage_test() async { +- provider.newFile('/projects/my_package/pubspec.yaml', 'name: my_packa= ge'); +- testFile =3D '/projects/my_package/test/misc/test_all.dart'; +- await resolveTestUnit(''' +-import 'a/bb/my_lib.dart'; +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_FILE, error); +- change =3D fix.change; +- // validate change +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/projects/my_package/test/misc/a/bb/my_lib.dar= t'); +- expect(fileEdit.fileStamp, -1); +- expect(fileEdit.edits, hasLength(1)); +- expect(fileEdit.edits[0].replacement, +- contains('library my_package.test.misc.a.bb.my_lib;')); +- } +- +- test_createFile_forPart() async { +- testFile =3D '/my/project/bin/test.dart'; +- await resolveTestUnit(''' +-library my.lib; +-part 'my_part.dart'; +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_FILE, error); +- change =3D fix.change; +- // validate change +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/my/project/bin/my_part.dart'); +- expect(fileEdit.fileStamp, -1); +- expect(fileEdit.edits, hasLength(1)); +- expect(fileEdit.edits[0].replacement, contains('part of my.lib;')); +- } +- +- test_createFile_forPart_inPackageLib() async { +- provider.newFile('/my/pubspec.yaml', r''' +-name: my_test +-'''); +- testFile =3D '/my/lib/test.dart'; +- addTestSource(''' +-library my.lib; +-part 'my_part.dart'; +-''', Uri.parse('package:my/test.dart')); +- // configure SourceFactory +- UriResolver pkgResolver =3D new PackageMapUriResolver(provider, { +- 'my': [provider.getResource('/my/lib')], +- }); +- SourceFactory sourceFactory =3D new SourceFactory( +- [new DartUriResolver(sdk), pkgResolver, resourceResolver]); +- driver.configure(sourceFactory: sourceFactory); +- testUnit =3D (await driver.getResult(testFile)).unit; +- // prepare fix +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_FILE, error); +- change =3D fix.change; +- // validate change +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/my/lib/my_part.dart'); +- expect(fileEdit.fileStamp, -1); +- expect(fileEdit.edits, hasLength(1)); +- expect(fileEdit.edits[0].replacement, contains('part of my.lib;')); +- } +- +- test_createGetter_BAD_inSDK() async { +- await resolveTestUnit(''' +-main(List p) { +- int v =3D p.foo; +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_GETTER); +- } +- +- test_createGetter_hint_getter() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- var x =3D a; +- int v =3D x.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- int get test =3D> null; +-} +-main(A a) { +- var x =3D a; +- int v =3D x.test; +-} +-'''); +- } +- +- test_createGetter_location_afterLastGetter() async { +- await resolveTestUnit(''' +-class A { +- int existingField; +- +- int get existingGetter =3D> null; +- +- existingMethod() {} +-} +-main(A a) { +- int v =3D a.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- int existingField; +- +- int get existingGetter =3D> null; +- +- int get test =3D> null; +- +- existingMethod() {} +-} +-main(A a) { +- int v =3D a.test; +-} +-'''); +- } +- +- test_createGetter_multiLevel() async { +- await resolveTestUnit(''' +-class A { +-} +-class B { +- A a; +-} +-class C { +- B b; +-} +-main(C c) { +- int v =3D c.b.a.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- int get test =3D> null; +-} +-class B { +- A a; +-} +-class C { +- B b; +-} +-main(C c) { +- int v =3D c.b.a.test; +-} +-'''); +- } +- +- test_createGetter_qualified_instance() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- int v =3D a.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- int get test =3D> null; +-} +-main(A a) { +- int v =3D a.test; +-} +-'''); +- } +- +- test_createGetter_qualified_instance_differentLibrary() async { +- addSource('/other.dart', ''' +-/** +- * A comment to push the offset of the braces for the following class +- * declaration past the end of the content of the test file. Used to catc= h an +- * index out of bounds exception that occurs when using the test source i= nstead +- * of the target source to compute the location at which to insert the fi= eld. +- */ +-class A { +-} +-'''); +- await resolveTestUnit(''' +-import 'other.dart'; +-main(A a) { +- int v =3D a.test; +-} +-'''); +- await assertHasFix( +- DartFixKind.CREATE_GETTER, +- ''' +-/** +- * A comment to push the offset of the braces for the following class +- * declaration past the end of the content of the test file. Used to catc= h an +- * index out of bounds exception that occurs when using the test source i= nstead +- * of the target source to compute the location at which to insert the fi= eld. +- */ +-class A { +- int get test =3D> null; +-} +-''', +- target: '/other.dart'); +- } +- +- test_createGetter_qualified_instance_dynamicType() async { +- await resolveTestUnit(''' +-class A { +- B b; +- void f(Object p) { +- p =3D=3D b.test; +- } +-} +-class B { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- B b; +- void f(Object p) { +- p =3D=3D b.test; +- } +-} +-class B { +- get test =3D> null; +-} +-'''); +- } +- +- test_createGetter_qualified_propagatedType() async { +- await resolveTestUnit(''' +-class A { +- A get self =3D> this; +-} +-main() { +- var a =3D new A(); +- int v =3D a.self.test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- A get self =3D> this; +- +- int get test =3D> null; +-} +-main() { +- var a =3D new A(); +- int v =3D a.self.test; +-} +-'''); +- } +- +- test_createGetter_setterContext() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- a.test =3D 42; +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_GETTER); +- } +- +- test_createGetter_unqualified_instance_asInvocationArgument() async { +- await resolveTestUnit(''' +-class A { +- main() { +- f(test); +- } +-} +-f(String s) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- String get test =3D> null; +- +- main() { +- f(test); +- } +-} +-f(String s) {} +-'''); +- } +- +- test_createGetter_unqualified_instance_assignmentLhs() async { +- await resolveTestUnit(''' +-class A { +- main() { +- test =3D 42; +- } +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_GETTER); +- } +- +- test_createGetter_unqualified_instance_assignmentRhs() async { +- await resolveTestUnit(''' +-class A { +- main() { +- int v =3D test; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- int get test =3D> null; +- +- main() { +- int v =3D test; +- } +-} +-'''); +- } +- +- test_createGetter_unqualified_instance_asStatement() async { +- await resolveTestUnit(''' +-class A { +- main() { +- test; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_GETTER, ''' +-class A { +- get test =3D> null; +- +- main() { +- test; +- } +-} +-'''); +- } +- +- test_createLocalVariable_functionType_named() async { +- await resolveTestUnit(''' +-typedef MY_FUNCTION(int p); +-foo(MY_FUNCTION f) {} +-main() { +- foo(bar); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-typedef MY_FUNCTION(int p); +-foo(MY_FUNCTION f) {} +-main() { +- MY_FUNCTION bar; +- foo(bar); +-} +-'''); +- } +- +- test_createLocalVariable_functionType_named_generic() async { +- await resolveTestUnit(''' +-typedef MY_FUNCTION(T p); +-foo(MY_FUNCTION f) {} +-main() { +- foo(bar); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-typedef MY_FUNCTION(T p); +-foo(MY_FUNCTION f) {} +-main() { +- MY_FUNCTION bar; +- foo(bar); +-} +-'''); +- } +- +- @failingTest +- test_createLocalVariable_functionType_synthetic() async { +- await resolveTestUnit(''' +-foo(f(int p)) {} +-main() { +- foo(bar); +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_LOCAL_VARIABLE); +- } +- +- test_createLocalVariable_read_typeAssignment() async { +- await resolveTestUnit(''' +-main() { +- int a =3D test; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-main() { +- int test; +- int a =3D test; +-} +-'''); +- } +- +- test_createLocalVariable_read_typeCondition() async { +- await resolveTestUnit(''' +-main() { +- if (!test) { +- print(42); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-main() { +- bool test; +- if (!test) { +- print(42); +- } +-} +-'''); +- } +- +- test_createLocalVariable_read_typeInvocationArgument() async { +- await resolveTestUnit(''' +-main() { +- f(test); +-} +-f(String p) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-main() { +- String test; +- f(test); +-} +-f(String p) {} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['String test;']); +- _assertLinkedGroup(change.linkedEditGroups[1], ['test;', 'test);']); +- } +- +- test_createLocalVariable_read_typeInvocationTarget() async { +- await resolveTestUnit(''' +-main() { +- test.add('hello'); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-main() { +- var test; +- test.add('hello'); +-} +-'''); +- _assertLinkedGroup(change.linkedEditGroups[0], ['test;', 'test.add(']= ); +- } +- +- test_createLocalVariable_withImport() async { +- addPackageSource('pkg', 'a/a.dart', ''' +-class A {} +-'''); +- addPackageSource('pkg', 'b/b.dart', ''' +-class B {} +-'''); +- addPackageSource('pkg', 'c/c.dart', ''' +-import 'package:pkg/a/a.dart'; +-import 'package:pkg/b/b.dart'; +- +-class C { +- C(A a, B b); +-} +-'''); +- +- await resolveTestUnit(''' +-import 'package:pkg/a/a.dart'; +-import 'package:pkg/c/c.dart'; +- +-main() { +- A a; +- new C(a, b); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-import 'package:pkg/a/a.dart'; +-import 'package:pkg/b/b.dart'; +-import 'package:pkg/c/c.dart'; +- +-main() { +- A a; +- B b; +- new C(a, b); +-} +-'''); +- +- List groups =3D change.linkedEditGroups; +- expect(groups, hasLength(2)); +- LinkedEditGroup typeGroup =3D groups[0]; +- List typePositions =3D typeGroup.positions; +- expect(typePositions, hasLength(1)); +- expect(typePositions[0].offset, 112); +- LinkedEditGroup nameGroup =3D groups[1]; +- List groupPositions =3D nameGroup.positions; +- expect(groupPositions, hasLength(2)); +- expect(groupPositions[0].offset, 114); +- expect(groupPositions[1].offset, 128); +- } +- +- test_createLocalVariable_write_assignment() async { +- await resolveTestUnit(''' +-main() { +- test =3D 42; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-main() { +- var test =3D 42; +-} +-'''); +- } +- +- test_createLocalVariable_write_assignment_compound() async { +- await resolveTestUnit(''' +-main() { +- test +=3D 42; +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_LOCAL_VARIABLE, ''' +-main() { +- int test; +- test +=3D 42; +-} +-'''); +- } +- +- test_createMissingMethodCall() async { +- await resolveTestUnit(''' +-class C implements Function { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_METHOD_CALL, ''' +-class C implements Function { +- call() { +- // TODO: implement call +- } +-} +-'''); +- } +- +- test_createMissingOverrides_field_untyped() async { +- await resolveTestUnit(''' +-class A { +- var f; +-} +- +-class B implements A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-class A { +- var f; +-} +- +-class B implements A { +- @override +- var f; +-} +-'''); +- } +- +- test_createMissingOverrides_functionTypeAlias() async { +- await resolveTestUnit(''' +-typedef int Binary(int left, int right); +- +-abstract class Emulator { +- void performBinary(Binary binary); +-} +- +-class MyEmulator extends Emulator { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-typedef int Binary(int left, int right); +- +-abstract class Emulator { +- void performBinary(Binary binary); +-} +- +-class MyEmulator extends Emulator { +- @override +- void performBinary(Binary binary) { +- // TODO: implement performBinary +- } +-} +-'''); +- } +- +- @failingTest +- test_createMissingOverrides_functionTypedParameter() async { +- await resolveTestUnit(''' +-abstract class A { +- forEach(int f(double p1, String p2)); +-} +- +-class B extends A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class A { +- forEach(int f(double p1, String p2)); +-} +- +-class B extends A { +- @override +- forEach(int f(double p1, String p2)) { +- // TODO: implement forEach +- } +-} +-'''); +- } +- +- test_createMissingOverrides_generics_typeArguments() async { +- await resolveTestUnit(''' +-class Iterator { +-} +- +-abstract class IterableMixin { +- Iterator get iterator; +-} +- +-class Test extends IterableMixin { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-class Iterator { +-} +- +-abstract class IterableMixin { +- Iterator get iterator; +-} +- +-class Test extends IterableMixin { +- // TODO: implement iterator +- @override +- Iterator get iterator =3D> null; +-} +-'''); +- } +- +- test_createMissingOverrides_generics_typeParameters() async { +- await resolveTestUnit(''' +-abstract class ItemProvider { +- List getItems(); +-} +- +-class Test extends ItemProvider { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class ItemProvider { +- List getItems(); +-} +- +-class Test extends ItemProvider { +- @override +- List getItems() { +- // TODO: implement getItems +- } +-} +-'''); +- } +- +- test_createMissingOverrides_getter() async { +- await resolveTestUnit(''' +-abstract class A { +- get g1; +- int get g2; +-} +- +-class B extends A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class A { +- get g1; +- int get g2; +-} +- +-class B extends A { +- // TODO: implement g1 +- @override +- get g1 =3D> null; +- +- // TODO: implement g2 +- @override +- int get g2 =3D> null; +-} +-'''); +- } +- +- test_createMissingOverrides_importPrefix() async { +- await resolveTestUnit(''' +-import 'dart:async' as aaa; +-abstract class A { +- Map> g(aaa.Future p); +-} +- +-class B extends A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-import 'dart:async' as aaa; +-abstract class A { +- Map> g(aaa.Future p); +-} +- +-class B extends A { +- @override +- Map> g(aaa.Future p) { +- // TODO: implement g +- } +-} +-'''); +- } +- +- test_createMissingOverrides_mergeToField_getterSetter() async { +- await resolveTestUnit(''' +-class A { +- int ma; +- void mb() {} +- double mc; +-} +- +-class B implements A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-class A { +- int ma; +- void mb() {} +- double mc; +-} +- +-class B implements A { +- @override +- int ma; +- +- @override +- double mc; +- +- @override +- void mb() { +- // TODO: implement mb +- } +-} +-'''); +- } +- +- test_createMissingOverrides_method() async { +- await resolveTestUnit(''' +-abstract class A { +- m1(); +- int m2(); +- String m3(int p1, double p2, Map> p3); +- String m4(p1, p2); +- String m5(p1, [int p2 =3D 2, int p3, p4 =3D 4]); +- String m6(p1, {int p2: 2, int p3, p4: 4}); +-} +- +-class B extends A { +-} +-'''); +- String expectedCode =3D ''' +-abstract class A { +- m1(); +- int m2(); +- String m3(int p1, double p2, Map> p3); +- String m4(p1, p2); +- String m5(p1, [int p2 =3D 2, int p3, p4 =3D 4]); +- String m6(p1, {int p2: 2, int p3, p4: 4}); +-} +- +-class B extends A { +- @override +- m1() { +- // TODO: implement m1 +- } +- +- @override +- int m2() { +- // TODO: implement m2 +- } +- +- @override +- String m3(int p1, double p2, Map> p3) { +- // TODO: implement m3 +- } +- +- @override +- String m4(p1, p2) { +- // TODO: implement m4 +- } +- +- @override +- String m5(p1, [int p2 =3D 2, int p3, p4 =3D 4]) { +- // TODO: implement m5 +- } +- +- @override +- String m6(p1, {int p2: 2, int p3, p4: 4}) { +- // TODO: implement m6 +- } +-} +-'''; +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, expectedCode= ); +- // end position should be on "m1", not on "m2", "m3", etc +- { +- Position endPosition =3D change.selection; +- expect(endPosition, isNotNull); +- expect(endPosition.file, testFile); +- int endOffset =3D endPosition.offset; +- String endString =3D expectedCode.substring(endOffset, endOffset + = 25); +- expect(endString, contains('m1')); +- expect(endString, isNot(contains('m2'))); +- expect(endString, isNot(contains('m3'))); +- expect(endString, isNot(contains('m4'))); +- expect(endString, isNot(contains('m5'))); +- expect(endString, isNot(contains('m6'))); +- } +- } +- +- test_createMissingOverrides_method_emptyClassBody() async { +- await resolveTestUnit(''' +-abstract class A { +- void foo(); +-} +- +-class B extends A {} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class A { +- void foo(); +-} +- +-class B extends A { +- @override +- void foo() { +- // TODO: implement foo +- } +-} +-'''); +- } +- +- test_createMissingOverrides_method_generic() async { +- await resolveTestUnit(''' +-class C {} +-class V {} +- +-abstract class A { +- E1 foo>(V v); +-} +- +-class B implements A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-class C {} +-class V {} +- +-abstract class A { +- E1 foo>(V v); +-} +- +-class B implements A { +- @override +- E1 foo>(V v) { +- // TODO: implement foo +- } +-} +-'''); +- } +- +- test_createMissingOverrides_method_notEmptyClassBody() async { +- await resolveTestUnit(''' +-abstract class A { +- void foo(); +-} +- +-class B extends A { +- void bar() {} +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class A { +- void foo(); +-} +- +-class B extends A { +- void bar() {} +- +- @override +- void foo() { +- // TODO: implement foo +- } +-} +-'''); +- } +- +- test_createMissingOverrides_operator() async { +- await resolveTestUnit(''' +-abstract class A { +- int operator [](int index); +- void operator []=3D(int index, String value); +-} +- +-class B extends A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class A { +- int operator [](int index); +- void operator []=3D(int index, String value); +-} +- +-class B extends A { +- @override +- int operator [](int index) { +- // TODO: implement [] +- } +- +- @override +- void operator []=3D(int index, String value) { +- // TODO: implement []=3D +- } +-} +-'''); +- } +- +- test_createMissingOverrides_setter() async { +- await resolveTestUnit(''' +-abstract class A { +- set s1(x); +- set s2(int x); +- void set s3(String x); +-} +- +-class B extends A { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_MISSING_OVERRIDES, ''' +-abstract class A { +- set s1(x); +- set s2(int x); +- void set s3(String x); +-} +- +-class B extends A { +- @override +- set s1(x) { +- // TODO: implement s1 +- } +- +- @override +- set s2(int x) { +- // TODO: implement s2 +- } +- +- @override +- set s3(String x) { +- // TODO: implement s3 +- } +-} +-'''); +- } +- +- test_createNoSuchMethod() async { +- await resolveTestUnit(''' +-abstract class A { +- m1(); +- int m2(); +-} +- +-class B extends A { +- existing() {} +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_NO_SUCH_METHOD, ''' +-abstract class A { +- m1(); +- int m2(); +-} +- +-class B extends A { +- existing() {} +- +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_cascadeSecond() async { +- await resolveTestUnit(''' +-class A { +- B ma() =3D> null; +-} +-class B { +- useFunction(int g(double a, String b)) {} +-} +- +-main() { +- A a =3D new A(); +- a..ma().useFunction(test); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-class A { +- B ma() =3D> null; +-} +-class B { +- useFunction(int g(double a, String b)) {} +-} +- +-main() { +- A a =3D new A(); +- a..ma().useFunction(test); +-} +- +-int test(double a, String b) { +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_coreFunction() async { +- await resolveTestUnit(''' +-main() { +- useFunction(g: test); +-} +-useFunction({Function g}) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- useFunction(g: test); +-} +-useFunction({Function g}) {} +- +-test() { +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_dynamicArgument() async { +- await resolveTestUnit(''' +-main() { +- useFunction(test); +-} +-useFunction(int g(a, b)) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- useFunction(test); +-} +-useFunction(int g(a, b)) {} +- +-int test(a, b) { +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_function() async { +- await resolveTestUnit(''' +-main() { +- useFunction(test); +-} +-useFunction(int g(double a, String b)) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- useFunction(test); +-} +-useFunction(int g(double a, String b)) {} +- +-int test(double a, String b) { +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_function_namedArgument() async { +- await resolveTestUnit(''' +-main() { +- useFunction(g: test); +-} +-useFunction({int g(double a, String b)}) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- useFunction(g: test); +-} +-useFunction({int g(double a, String b)}) {} +- +-int test(double a, String b) { +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_importType() async { +- addSource('/libA.dart', r''' +-library libA; +-class A {} +-'''); +- addSource('/libB.dart', r''' +-library libB; +-import 'libA.dart'; +-useFunction(int g(A a)) {} +-'''); +- await resolveTestUnit(''' +-import 'libB.dart'; +-main() { +- useFunction(test); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-import 'libA.dart'; +-import 'libB.dart'; +-main() { +- useFunction(test); +-} +- +-int test(A a) { +-} +-'''); +- } +- +- test_creationFunction_forFunctionType_method_enclosingClass_static() as= ync { +- await resolveTestUnit(''' +-class A { +- static foo() { +- useFunction(test); +- } +-} +-useFunction(int g(double a, String b)) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- static foo() { +- useFunction(test); +- } +- +- static int test(double a, String b) { +- } +-} +-useFunction(int g(double a, String b)) {} +-'''); +- } +- +- test_creationFunction_forFunctionType_method_enclosingClass_static2() a= sync { +- await resolveTestUnit(''' +-class A { +- var f; +- A() : f =3D useFunction(test); +-} +-useFunction(int g(double a, String b)) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- var f; +- A() : f =3D useFunction(test); +- +- static int test(double a, String b) { +- } +-} +-useFunction(int g(double a, String b)) {} +-'''); +- } +- +- test_creationFunction_forFunctionType_method_targetClass() async { +- await resolveTestUnit(''' +-main(A a) { +- useFunction(a.test); +-} +-class A { +-} +-useFunction(int g(double a, String b)) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-main(A a) { +- useFunction(a.test); +-} +-class A { +- int test(double a, String b) { +- } +-} +-useFunction(int g(double a, String b)) {} +-'''); +- } +- +- test_creationFunction_forFunctionType_method_targetClass_hasOtherMember= () async { +- await resolveTestUnit(''' +-main(A a) { +- useFunction(a.test); +-} +-class A { +- m() {} +-} +-useFunction(int g(double a, String b)) {} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-main(A a) { +- useFunction(a.test); +-} +-class A { +- m() {} +- +- int test(double a, String b) { +- } +-} +-useFunction(int g(double a, String b)) {} +-'''); +- } +- +- test_creationFunction_forFunctionType_notFunctionType() async { +- await resolveTestUnit(''' +-main(A a) { +- useFunction(a.test); +-} +-typedef A(); +-useFunction(g) {} +-'''); +- await assertNoFix(DartFixKind.CREATE_METHOD); +- await assertNoFix(DartFixKind.CREATE_FUNCTION); +- } +- +- test_creationFunction_forFunctionType_unknownTarget() async { +- await resolveTestUnit(''' +-main(A a) { +- useFunction(a.test); +-} +-class A { +-} +-useFunction(g) {} +-'''); +- await assertNoFix(DartFixKind.CREATE_METHOD); +- } +- +- test_expectedToken_semicolon() async { +- await resolveTestUnit(''' +-main() { +- print(0) +-} +-'''); +- await assertHasFix(DartFixKind.INSERT_SEMICOLON, ''' +-main() { +- print(0); +-} +-'''); +- } +- +- test_illegalAsyncReturnType_adjacentNodes() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_R= ETURN_TYPE; +- }; +- await resolveTestUnit(''' +-import 'dart:async'; +-var v;int main() async =3D> 0; +-'''); +- await assertHasFix(DartFixKind.REPLACE_RETURN_TYPE_FUTURE, ''' +-import 'dart:async'; +-var v;Future main() async =3D> 0; +-'''); +- } +- +- test_illegalAsyncReturnType_asyncLibrary_import() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_R= ETURN_TYPE; +- }; +- await resolveTestUnit(''' +-library main; +-int main() async { +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_RETURN_TYPE_FUTURE, ''' +-library main; +- +-import 'dart:async'; +- +-Future main() async { +-} +-'''); +- } +- +- test_illegalAsyncReturnType_asyncLibrary_usePrefix() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_R= ETURN_TYPE; +- }; +- await resolveTestUnit(''' +-import 'dart:async' as al; +-int main() async { +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_RETURN_TYPE_FUTURE, ''' +-import 'dart:async' as al; +-al.Future main() async { +-} +-'''); +- } +- +- test_illegalAsyncReturnType_complexTypeName() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_R= ETURN_TYPE; +- }; +- await resolveTestUnit(''' +-import 'dart:async'; +-List main() async { +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_RETURN_TYPE_FUTURE, ''' +-import 'dart:async'; +-Future> main() async { +-} +-'''); +- } +- +- test_illegalAsyncReturnType_void() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticTypeWarningCode.ILLEGAL_ASYNC_R= ETURN_TYPE; +- }; +- await resolveTestUnit(''' +-import 'dart:async'; +-void main() async { +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_RETURN_TYPE_FUTURE, ''' +-import 'dart:async'; +-Future main() async { +-} +-'''); +- } +- +- test_importLibraryPackage_preferDirectOverExport() async { +- _configureMyPkg({'b.dart': 'class Test {}', 'a.dart': "export 'b.dart= ';"}); +- await resolveTestUnit(''' +-main() { +- Test test =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'package:my_pkg/b.dart'; +- +-main() { +- Test test =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT2, ''' +-import 'package:my_pkg/a.dart'; +- +-main() { +- Test test =3D null; +-} +-'''); +- } +- +- test_importLibraryPackage_preferDirectOverExport_src() async { +- myPkgLibPath =3D '/my/src/packages/my_pkg/lib'; +- _configureMyPkg({'b.dart': 'class Test {}', 'a.dart': "export 'b.dart= ';"}); +- await resolveTestUnit(''' +-main() { +- Test test =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'package:my_pkg/b.dart'; +- +-main() { +- Test test =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT2, ''' +-import 'package:my_pkg/a.dart'; +- +-main() { +- Test test =3D null; +-} +-'''); +- } +- +- test_importLibraryPackage_preferPublicOverPrivate() async { +- _configureMyPkg( +- {'src/a.dart': 'class Test {}', 'b.dart': "export 'src/a.dart';"}= ); +- await resolveTestUnit(''' +-main() { +- Test test =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT2, ''' +-import 'package:my_pkg/b.dart'; +- +-main() { +- Test test =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT3, ''' +-import 'package:my_pkg/src/a.dart'; +- +-main() { +- Test test =3D null; +-} +-'''); +- } +- +- test_importLibraryProject_BAD_notInLib_BUILD() async { +- testFile =3D '/aaa/bin/test.dart'; +- provider.newFile('/aaa/BUILD', ''); +- provider.newFile('/bbb/BUILD', ''); +- addSource('/bbb/test/lib.dart', 'class Test {}'); +- await resolveTestUnit(''' +-main() { +- Test t; +-} +-'''); +- await assertNoFix(DartFixKind.IMPORT_LIBRARY_PROJECT1); +- } +- +- test_importLibraryProject_BAD_notInLib_pubspec() async { +- testFile =3D '/aaa/bin/test.dart'; +- provider.newFile('/aaa/pubspec.yaml', 'name: aaa'); +- provider.newFile('/bbb/pubspec.yaml', 'name: bbb'); +- addSource('/bbb/test/lib.dart', 'class Test {}'); +- await resolveTestUnit(''' +-main() { +- Test t; +-} +-'''); +- await assertNoFix(DartFixKind.IMPORT_LIBRARY_PROJECT1); +- } +- +- test_importLibraryProject_withClass_annotation() async { +- addSource('/lib.dart', ''' +-library lib; +-class Test { +- const Test(int p); +-} +-'''); +- await resolveTestUnit(''' +-@Test(0) +-main() { +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-@Test(0) +-main() { +-} +-'''); +- } +- +- test_importLibraryProject_withClass_constInstanceCreation() async { +- addSource('/lib.dart', ''' +-class Test { +- const Test(); +-} +-'''); +- await resolveTestUnit(''' +-main() { +- const Test(); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-main() { +- const Test(); +-} +-'''); +- } +- +- test_importLibraryProject_withClass_hasOtherLibraryWithPrefix() async { +- testFile =3D '/project/bin/test.dart'; +- addSource('/project/bin/a.dart', ''' +-library a; +-class One {} +-'''); +- addSource('/project/bin/b.dart', ''' +-library b; +-class One {} +-class Two {} +-'''); +- await resolveTestUnit(''' +-import 'b.dart' show Two; +-main () { +- new Two(); +- new One(); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'a.dart'; +-import 'b.dart' show Two; +-main () { +- new Two(); +- new One(); +-} +-'''); +- } +- +- test_importLibraryProject_withClass_inParentFolder() async { +- testFile =3D '/project/bin/test.dart'; +- addSource('/project/lib.dart', ''' +-library lib; +-class Test {} +-'''); +- await resolveTestUnit(''' +-main() { +- Test t =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import '../lib.dart'; +- +-main() { +- Test t =3D null; +-} +-'''); +- } +- +- test_importLibraryProject_withClass_inRelativeFolder() async { +- testFile =3D '/project/bin/test.dart'; +- addSource('/project/lib/sub/folder/lib.dart', ''' +-library lib; +-class Test {} +-'''); +- await resolveTestUnit(''' +-main() { +- Test t =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import '../lib/sub/folder/lib.dart'; +- +-main() { +- Test t =3D null; +-} +-'''); +- } +- +- test_importLibraryProject_withClass_inSameFolder() async { +- testFile =3D '/project/bin/test.dart'; +- addSource('/project/bin/lib.dart', ''' +-library lib; +-class Test {} +-'''); +- await resolveTestUnit(''' +-main() { +- Test t =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-main() { +- Test t =3D null; +-} +-'''); +- } +- +- test_importLibraryProject_withFunction() async { +- addSource('/lib.dart', ''' +-library lib; +-myFunction() {} +-'''); +- await resolveTestUnit(''' +-main() { +- myFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-main() { +- myFunction(); +-} +-'''); +- } +- +- test_importLibraryProject_withFunction_unresolvedMethod() async { +- addSource('/lib.dart', ''' +-library lib; +-myFunction() {} +-'''); +- await resolveTestUnit(''' +-class A { +- main() { +- myFunction(); +- } +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-class A { +- main() { +- myFunction(); +- } +-} +-'''); +- } +- +- test_importLibraryProject_withFunctionTypeAlias() async { +- testFile =3D '/project/bin/test.dart'; +- addSource('/project/bin/lib.dart', ''' +-library lib; +-typedef MyFunction(); +-'''); +- await resolveTestUnit(''' +-main() { +- MyFunction t =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-main() { +- MyFunction t =3D null; +-} +-'''); +- } +- +- test_importLibraryProject_withTopLevelVariable() async { +- addSource('/lib.dart', ''' +-library lib; +-int MY_VAR =3D 42; +-'''); +- await resolveTestUnit(''' +-main() { +- print(MY_VAR); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PROJECT1, ''' +-import 'lib.dart'; +- +-main() { +- print(MY_VAR); +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_AsExpression() async { +- await resolveTestUnit(''' +-main(p) { +- p as Future; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main(p) { +- p as Future; +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_invocationTarget() async { +- await resolveTestUnit(''' +-main() { +- Future.wait(null); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main() { +- Future.wait(null); +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_IsExpression() async { +- await resolveTestUnit(''' +-main(p) { +- p is Future; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main(p) { +- p is Future; +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_itemOfList() async { +- await resolveTestUnit(''' +-main() { +- var a =3D [Future]; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main() { +- var a =3D [Future]; +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_itemOfList_inAnnotation() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D StaticWarningCode.UNDEFINED_IDENTIFIE= R; +- }; +- await resolveTestUnit(''' +-class MyAnnotation { +- const MyAnnotation(a, b); +-} +-@MyAnnotation(int, const [Future]) +-main() {} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-class MyAnnotation { +- const MyAnnotation(a, b); +-} +-@MyAnnotation(int, const [Future]) +-main() {} +-'''); +- } +- +- test_importLibrarySdk_withClass_typeAnnotation() async { +- await resolveTestUnit(''' +-main() { +- Future f =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main() { +- Future f =3D null; +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_typeAnnotation_PrefixedIdentifier() asy= nc { +- await resolveTestUnit(''' +-main() { +- Future.wait; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main() { +- Future.wait; +-} +-'''); +- } +- +- test_importLibrarySdk_withClass_typeArgument() async { +- await resolveTestUnit(''' +-main() { +- List futures =3D []; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:async'; +- +-main() { +- List futures =3D []; +-} +-'''); +- } +- +- test_importLibrarySdk_withTopLevelVariable() async { +- await resolveTestUnit(''' +-main() { +- print(PI); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:math'; +- +-main() { +- print(PI); +-} +-'''); +- } +- +- test_importLibrarySdk_withTopLevelVariable_annotation() async { +- await resolveTestUnit(''' +-@PI +-main() { +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SDK, ''' +-import 'dart:math'; +- +-@PI +-main() { +-} +-'''); +- } +- +- test_importLibraryShow_project() async { +- testFile =3D '/project/bin/test.dart'; +- addSource('/project/bin/lib.dart', ''' +-class A {} +-class B {} +-'''); +- await resolveTestUnit(''' +-import 'lib.dart' show A; +-main() { +- A a; +- B b; +-} +-'''); +- await assertNoFix(DartFixKind.IMPORT_LIBRARY_PROJECT1); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SHOW, ''' +-import 'lib.dart' show A, B; +-main() { +- A a; +- B b; +-} +-'''); +- } +- +- test_importLibraryShow_sdk() async { +- await resolveTestUnit(''' +-import 'dart:async' show Stream; +-main() { +- Stream s =3D null; +- Future f =3D null; +-} +-'''); +- await assertNoFix(DartFixKind.IMPORT_LIBRARY_SDK); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_SHOW, ''' +-import 'dart:async' show Future, Stream; +-main() { +- Stream s =3D null; +- Future f =3D null; +-} +-'''); +- } +- +- test_invokeConstructorUsingNew() async { +- await resolveTestUnit(''' +-class C { +- C.c(); +-} +-main() { +- C c =3D C.c(); +-} +-'''); +- await assertHasFix(DartFixKind.INVOKE_CONSTRUCTOR_USING_NEW, ''' +-class C { +- C.c(); +-} +-main() { +- C c =3D new C.c(); +-} +-'''); +- } +- +- test_isNotNull() async { +- await resolveTestUnit(''' +-main(p) { +- p is! Null; +-} +-'''); +- await assertHasFix(DartFixKind.USE_NOT_EQ_NULL, ''' +-main(p) { +- p !=3D null; +-} +-'''); +- } +- +- test_isNull() async { +- await resolveTestUnit(''' +-main(p) { +- p is Null; +-} +-'''); +- await assertHasFix(DartFixKind.USE_EQ_EQ_NULL, ''' +-main(p) { +- p =3D=3D null; +-} +-'''); +- } +- +- test_makeEnclosingClassAbstract_declaresAbstractMethod() async { +- await resolveTestUnit(''' +-class A { +- m(); +-} +-'''); +- await assertHasFix(DartFixKind.MAKE_CLASS_ABSTRACT, ''' +-abstract class A { +- m(); +-} +-'''); +- } +- +- test_makeEnclosingClassAbstract_inheritsAbstractMethod() async { +- await resolveTestUnit(''' +-abstract class A { +- m(); +-} +-class B extends A { +-} +-'''); +- await assertHasFix(DartFixKind.MAKE_CLASS_ABSTRACT, ''' +-abstract class A { +- m(); +-} +-abstract class B extends A { +-} +-'''); +- } +- +- test_makeFieldNotFinal_hasType() async { +- await resolveTestUnit(''' +-class A { +- final int fff =3D 1; +- main() { +- fff =3D 2; +- } +-} +-'''); +- await assertHasFix(DartFixKind.MAKE_FIELD_NOT_FINAL, ''' +-class A { +- int fff =3D 1; +- main() { +- fff =3D 2; +- } +-} +-'''); +- } +- +- test_makeFieldNotFinal_noType() async { +- await resolveTestUnit(''' +-class A { +- final fff =3D 1; +- main() { +- fff =3D 2; +- } +-} +-'''); +- await assertHasFix(DartFixKind.MAKE_FIELD_NOT_FINAL, ''' +-class A { +- var fff =3D 1; +- main() { +- fff =3D 2; +- } +-} +-'''); +- } +- +- test_noException_1() async { +- await resolveTestUnit(''' +-main(p) { +- p i s Null; +-}'''); +- List errors =3D await _computeErrors(); +- for (var error in errors) { +- await _computeFixes(error); +- } +- } +- +- test_nonBoolCondition_addNotNull() async { +- await resolveTestUnit(''' +-main(String p) { +- if (p) { +- print(p); +- } +-} +-'''); +- await assertHasFix(DartFixKind.ADD_NE_NULL, ''' +-main(String p) { +- if (p !=3D null) { +- print(p); +- } +-} +-'''); +- } +- +- test_removeDeadCode_condition() async { +- await resolveTestUnit(''' +-main(int p) { +- if (true || p > 5) { +- print(1); +- } +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_DEAD_CODE, ''' +-main(int p) { +- if (true) { +- print(1); +- } +-} +-'''); +- } +- +- test_removeDeadCode_statements_one() async { +- await resolveTestUnit(''' +-int main() { +- print(0); +- return 42; +- print(1); +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_DEAD_CODE, ''' +-int main() { +- print(0); +- return 42; +-} +-'''); +- } +- +- test_removeDeadCode_statements_two() async { +- await resolveTestUnit(''' +-int main() { +- print(0); +- return 42; +- print(1); +- print(2); +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_DEAD_CODE, ''' +-int main() { +- print(0); +- return 42; +-} +-'''); +- } +- +- test_removeParentheses_inGetterDeclaration() async { +- await resolveTestUnit(''' +-class A { +- int get foo() =3D> 0; +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_PARAMETERS_IN_GETTER_DECLARATIO= N, ''' +-class A { +- int get foo =3D> 0; +-} +-'''); +- } +- +- test_removeParentheses_inGetterInvocation() async { +- await resolveTestUnit(''' +-class A { +- int get foo =3D> 0; +-} +-main(A a) { +- a.foo(); +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_PARENTHESIS_IN_GETTER_INVOCATIO= N, ''' +-class A { +- int get foo =3D> 0; +-} +-main(A a) { +- a.foo; +-} +-'''); +- } +- +- test_removeUnnecessaryCast_assignment() async { +- await resolveTestUnit(''' +-main(Object p) { +- if (p is String) { +- String v =3D ((p as String)); +- } +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_UNNECESSARY_CAST, ''' +-main(Object p) { +- if (p is String) { +- String v =3D p; +- } +-} +-'''); +- } +- +- test_removeUnusedCatchClause() async { +- errorFilter =3D (AnalysisError error) =3D> true; +- await resolveTestUnit(''' +-main() { +- try { +- throw 42; +- } on int catch (e) { +- } +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_UNUSED_CATCH_CLAUSE, ''' +-main() { +- try { +- throw 42; +- } on int { +- } +-} +-'''); +- } +- +- test_removeUnusedCatchStack() async { +- errorFilter =3D (AnalysisError error) =3D> true; +- await resolveTestUnit(''' +-main() { +- try { +- throw 42; +- } catch (e, stack) { +- } +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_UNUSED_CATCH_STACK, ''' +-main() { +- try { +- throw 42; +- } catch (e) { +- } +-} +-'''); +- } +- +- test_removeUnusedImport() async { +- await resolveTestUnit(''' +-import 'dart:math'; +-main() { +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_UNUSED_IMPORT, ''' +-main() { +-} +-'''); +- } +- +- test_removeUnusedImport_anotherImportOnLine() async { +- await resolveTestUnit(''' +-import 'dart:math'; import 'dart:async'; +- +-main() { +- Future f; +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_UNUSED_IMPORT, ''' +-import 'dart:async'; +- +-main() { +- Future f; +-} +-'''); +- } +- +- test_removeUnusedImport_severalLines() async { +- await resolveTestUnit(''' +-import +- 'dart:math'; +-main() { +-} +-'''); +- await assertHasFix(DartFixKind.REMOVE_UNUSED_IMPORT, ''' +-main() { +-} +-'''); +- } +- +- test_replaceVarWithDynamic() async { +- errorFilter =3D (AnalysisError error) { +- return error.errorCode =3D=3D ParserErrorCode.VAR_AS_TYPE_NAME; +- }; +- await resolveTestUnit(''' +-class A { +- Map m; +-} +-'''); +- await assertHasFix(DartFixKind.REPLACE_VAR_WITH_DYNAMIC, ''' +-class A { +- Map m; +-} +-'''); +- } +- +- test_replaceWithConstInstanceCreation() async { +- await resolveTestUnit(''' +-class A { +- const A(); +-} +-const a =3D new A(); +-'''); +- await assertHasFix(DartFixKind.USE_CONST, ''' +-class A { +- const A(); +-} +-const a =3D const A(); +-'''); +- } +- +- test_undefinedClass_useSimilar_BAD_prefixed() async { +- await resolveTestUnit(''' +-import 'dart:async' as c; +-main() { +- c.Fture v =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-import 'dart:async' as c; +-main() { +- c.Future v =3D null; +-} +-'''); +- } +- +- test_undefinedClass_useSimilar_fromImport() async { +- await resolveTestUnit(''' +-main() { +- Stirng s =3D 'abc'; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-main() { +- String s =3D 'abc'; +-} +-'''); +- } +- +- test_undefinedClass_useSimilar_fromThisLibrary() async { +- await resolveTestUnit(''' +-class MyClass {} +-main() { +- MyCalss v =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class MyClass {} +-main() { +- MyClass v =3D null; +-} +-'''); +- } +- +- test_undefinedFunction_create_bottomArgument() async { +- await resolveTestUnit(''' +-main() { +- test(throw 42); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- test(throw 42); +-} +- +-void test(param0) { +-} +-'''); +- } +- +- test_undefinedFunction_create_duplicateArgumentNames() async { +- await resolveTestUnit(''' +-class C { +- int x; +-} +- +-foo(C c1, C c2) { +- bar(c1.x, c2.x); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-class C { +- int x; +-} +- +-foo(C c1, C c2) { +- bar(c1.x, c2.x); +-} +- +-void bar(int x, int x2) { +-} +-'''); +- } +- +- test_undefinedFunction_create_dynamicArgument() async { +- await resolveTestUnit(''' +-main() { +- dynamic v; +- test(v); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- dynamic v; +- test(v); +-} +- +-void test(v) { +-} +-'''); +- } +- +- test_undefinedFunction_create_dynamicReturnType() async { +- await resolveTestUnit(''' +-main() { +- dynamic v =3D test(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- dynamic v =3D test(); +-} +- +-test() { +-} +-'''); +- } +- +- test_undefinedFunction_create_fromFunction() async { +- await resolveTestUnit(''' +-main() { +- int v =3D myUndefinedFunction(1, 2.0, '3'); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- int v =3D myUndefinedFunction(1, 2.0, '3'); +-} +- +-int myUndefinedFunction(int i, double d, String s) { +-} +-'''); +- } +- +- test_undefinedFunction_create_fromMethod() async { +- await resolveTestUnit(''' +-class A { +- main() { +- int v =3D myUndefinedFunction(1, 2.0, '3'); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-class A { +- main() { +- int v =3D myUndefinedFunction(1, 2.0, '3'); +- } +-} +- +-int myUndefinedFunction(int i, double d, String s) { +-} +-'''); +- } +- +- test_undefinedFunction_create_generic_BAD() async { +- await resolveTestUnit(''' +-class A { +- Map items; +- main() { +- process(items); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-class A { +- Map items; +- main() { +- process(items); +- } +-} +- +-void process(Map items) { +-} +-'''); +- } +- +- test_undefinedFunction_create_generic_OK() async { +- await resolveTestUnit(''' +-class A { +- List items; +- main() { +- process(items); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-class A { +- List items; +- main() { +- process(items); +- } +-} +- +-void process(List items) { +-} +-'''); +- _assertLinkedGroup( +- change.linkedEditGroups[2], +- ['List items) {'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['List', 'Iterable', 'Object'])); +- } +- +- test_undefinedFunction_create_importType() async { +- addSource('/lib.dart', r''' +-library lib; +-import 'dart:async'; +-Future getFuture() =3D> null; +-'''); +- await resolveTestUnit(''' +-import 'lib.dart'; +-main() { +- test(getFuture()); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-import 'dart:async'; +- +-import 'lib.dart'; +-main() { +- test(getFuture()); +-} +- +-void test(Future future) { +-} +-'''); +- } +- +- test_undefinedFunction_create_nullArgument() async { +- await resolveTestUnit(''' +-main() { +- test(null); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- test(null); +-} +- +-void test(param0) { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_bool_expressions() async { +- await assert_undefinedFunction_create_returnType_bool("!test();"); +- await assert_undefinedFunction_create_returnType_bool("b && test();"); +- await assert_undefinedFunction_create_returnType_bool("test() && b;"); +- await assert_undefinedFunction_create_returnType_bool("b || test();"); +- await assert_undefinedFunction_create_returnType_bool("test() || b;"); +- } +- +- test_undefinedFunction_create_returnType_bool_statements() async { +- await assert_undefinedFunction_create_returnType_bool("assert ( test(= ) );"); +- await assert_undefinedFunction_create_returnType_bool("if ( test() ) = {}"); +- await assert_undefinedFunction_create_returnType_bool( +- "while ( test() ) {}"); +- await assert_undefinedFunction_create_returnType_bool( +- "do {} while ( test() );"); +- } +- +- test_undefinedFunction_create_returnType_fromAssignment_eq() async { +- await resolveTestUnit(''' +-main() { +- int v; +- v =3D myUndefinedFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- int v; +- v =3D myUndefinedFunction(); +-} +- +-int myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_fromAssignment_plusEq() async { +- await resolveTestUnit(''' +-main() { +- int v; +- v +=3D myUndefinedFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- int v; +- v +=3D myUndefinedFunction(); +-} +- +-num myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_fromBinary_right() async { +- await resolveTestUnit(''' +-main() { +- 0 + myUndefinedFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- 0 + myUndefinedFunction(); +-} +- +-num myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_fromInitializer() async { +- await resolveTestUnit(''' +-main() { +- int v =3D myUndefinedFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- int v =3D myUndefinedFunction(); +-} +- +-int myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_fromInvocationArgument() async= { +- await resolveTestUnit(''' +-foo(int p) {} +-main() { +- foo( myUndefinedFunction() ); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-foo(int p) {} +-main() { +- foo( myUndefinedFunction() ); +-} +- +-int myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_fromReturn() async { +- await resolveTestUnit(''' +-int main() { +- return myUndefinedFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-int main() { +- return myUndefinedFunction(); +-} +- +-int myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_create_returnType_void() async { +- await resolveTestUnit(''' +-main() { +- myUndefinedFunction(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_FUNCTION, ''' +-main() { +- myUndefinedFunction(); +-} +- +-void myUndefinedFunction() { +-} +-'''); +- } +- +- test_undefinedFunction_useSimilar_fromImport() async { +- await resolveTestUnit(''' +-main() { +- pritn(0); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-main() { +- print(0); +-} +-'''); +- } +- +- test_undefinedFunction_useSimilar_prefixed_fromImport() async { +- await resolveTestUnit(''' +-import 'dart:core' as c; +-main() { +- c.prnt(42); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-import 'dart:core' as c; +-main() { +- c.print(42); +-} +-'''); +- } +- +- test_undefinedFunction_useSimilar_prefixed_ignoreLocal() async { +- await resolveTestUnit(''' +-import 'dart:async' as c; +-main() { +- c.main(); +-} +-'''); +- await assertNoFix(DartFixKind.CHANGE_TO); +- } +- +- test_undefinedFunction_useSimilar_thisLibrary() async { +- await resolveTestUnit(''' +-myFunction() {} +-main() { +- myFuntcion(); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-myFunction() {} +-main() { +- myFunction(); +-} +-'''); +- } +- +- test_undefinedGetter_useSimilar_hint() async { +- await resolveTestUnit(''' +-class A { +- int myField; +-} +-main(A a) { +- var x =3D a; +- print(x.myFild); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- int myField; +-} +-main(A a) { +- var x =3D a; +- print(x.myField); +-} +-'''); +- } +- +- test_undefinedGetter_useSimilar_qualified() async { +- await resolveTestUnit(''' +-class A { +- int myField; +-} +-main(A a) { +- print(a.myFild); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- int myField; +-} +-main(A a) { +- print(a.myField); +-} +-'''); +- } +- +- test_undefinedGetter_useSimilar_qualified_static() async { +- await resolveTestUnit(''' +-class A { +- static int MY_NAME =3D 1; +-} +-main() { +- A.MY_NAM; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- static int MY_NAME =3D 1; +-} +-main() { +- A.MY_NAME; +-} +-'''); +- } +- +- test_undefinedGetter_useSimilar_unqualified() async { +- await resolveTestUnit(''' +-class A { +- int myField; +- main() { +- print(myFild); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- int myField; +- main() { +- print(myField); +- } +-} +-'''); +- } +- +- test_undefinedMethod_create_BAD_inSDK() async { +- await resolveTestUnit(''' +-main() { +- List.foo(); +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_METHOD); +- } +- +- test_undefinedMethod_create_BAD_targetIsEnum() async { +- await resolveTestUnit(''' +-enum MyEnum {A, B} +-main() { +- MyEnum.foo(); +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_METHOD); +- } +- +- test_undefinedMethod_create_generic_BAD_argumentType() async { +- await resolveTestUnit(''' +-class A { +- B b; +- Map items; +- main() { +- b.process(items); +- } +-} +- +-class B { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- B b; +- Map items; +- main() { +- b.process(items); +- } +-} +- +-class B { +- void process(Map items) {} +-} +-'''); +- } +- +- test_undefinedMethod_create_generic_BAD_returnType() async { +- await resolveTestUnit(''' +-class A { +- main() { +- T t =3D new B().compute(); +- } +-} +- +-class B { +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- main() { +- T t =3D new B().compute(); +- } +-} +- +-class B { +- compute() {} +-} +-'''); +- } +- +- test_undefinedMethod_create_generic_OK_literal() async { +- await resolveTestUnit(''' +-class A { +- B b; +- List items; +- main() { +- b.process(items); +- } +-} +- +-class B {} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- B b; +- List items; +- main() { +- b.process(items); +- } +-} +- +-class B { +- void process(List items) {} +-} +-'''); +- } +- +- test_undefinedMethod_create_generic_OK_local() async { +- await resolveTestUnit(''' +-class A { +- List items; +- main() { +- process(items); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- List items; +- main() { +- process(items); +- } +- +- void process(List items) {} +-} +-'''); +- } +- +- test_undefinedMethod_createQualified_emptyClassBody() async { +- await resolveTestUnit(''' +-class A {} +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- static void myUndefinedMethod() {} +-} +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- } +- +- test_undefinedMethod_createQualified_fromClass() async { +- await resolveTestUnit(''' +-class A { +-} +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- static void myUndefinedMethod() {} +-} +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- } +- +- test_undefinedMethod_createQualified_fromClass_hasOtherMember() async { +- await resolveTestUnit(''' +-class A { +- foo() {} +-} +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- foo() {} +- +- static void myUndefinedMethod() {} +-} +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- } +- +- test_undefinedMethod_createQualified_fromInstance() async { +- await resolveTestUnit(''' +-class A { +-} +-main(A a) { +- a.myUndefinedMethod(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- void myUndefinedMethod() {} +-} +-main(A a) { +- a.myUndefinedMethod(); +-} +-'''); +- } +- +- test_undefinedMethod_createQualified_targetIsFunctionType() async { +- await resolveTestUnit(''' +-typedef A(); +-main() { +- A.myUndefinedMethod(); +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_METHOD); +- } +- +- test_undefinedMethod_createQualified_targetIsUnresolved() async { +- await resolveTestUnit(''' +-main() { +- NoSuchClass.myUndefinedMethod(); +-} +-'''); +- await assertNoFix(DartFixKind.CREATE_METHOD); +- } +- +- test_undefinedMethod_createUnqualified_duplicateArgumentNames() async { +- await resolveTestUnit(''' +-class C { +- int x; +-} +- +-class D { +- foo(C c1, C c2) { +- bar(c1.x, c2.x); +- } +-}'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class C { +- int x; +-} +- +-class D { +- foo(C c1, C c2) { +- bar(c1.x, c2.x); +- } +- +- void bar(int x, int x2) {} +-}'''); +- } +- +- test_undefinedMethod_createUnqualified_parameters() async { +- await resolveTestUnit(''' +-class A { +- main() { +- myUndefinedMethod(0, 1.0, '3'); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- main() { +- myUndefinedMethod(0, 1.0, '3'); +- } +- +- void myUndefinedMethod(int i, double d, String s) {} +-} +-'''); +- // linked positions +- int index =3D 0; +- _assertLinkedGroup( +- change.linkedEditGroups[index++], ['void myUndefinedMethod(']); +- _assertLinkedGroup(change.linkedEditGroups[index++], +- ['myUndefinedMethod(0', 'myUndefinedMethod(int']); +- _assertLinkedGroup( +- change.linkedEditGroups[index++], +- ['int i'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['int', 'num', 'Object', 'Comparable'])); +- _assertLinkedGroup(change.linkedEditGroups[index++], ['i,']); +- _assertLinkedGroup( +- change.linkedEditGroups[index++], +- ['double d'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['double', 'num', 'Object', 'Comparable'])); +- _assertLinkedGroup(change.linkedEditGroups[index++], ['d,']); +- _assertLinkedGroup( +- change.linkedEditGroups[index++], +- ['String s'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['String', 'Object', 'Comparable'])); +- _assertLinkedGroup(change.linkedEditGroups[index++], ['s)']); +- } +- +- test_undefinedMethod_createUnqualified_parameters_named() async { +- await resolveTestUnit(''' +-class A { +- main() { +- myUndefinedMethod(0, bbb: 1.0, ccc: '2'); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- main() { +- myUndefinedMethod(0, bbb: 1.0, ccc: '2'); +- } +- +- void myUndefinedMethod(int i, {double bbb, String ccc}) {} +-} +-'''); +- // linked positions +- int index =3D 0; +- _assertLinkedGroup( +- change.linkedEditGroups[index++], ['void myUndefinedMethod(']); +- _assertLinkedGroup(change.linkedEditGroups[index++], +- ['myUndefinedMethod(0', 'myUndefinedMethod(int']); +- _assertLinkedGroup( +- change.linkedEditGroups[index++], +- ['int i'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['int', 'num', 'Object', 'Comparable'])); +- _assertLinkedGroup(change.linkedEditGroups[index++], ['i,']); +- _assertLinkedGroup( +- change.linkedEditGroups[index++], +- ['double bbb'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['double', 'num', 'Object', 'Comparable'])); +- _assertLinkedGroup( +- change.linkedEditGroups[index++], +- ['String ccc'], +- expectedSuggestions(LinkedEditSuggestionKind.TYPE, +- ['String', 'Object', 'Comparable'])); +- } +- +- test_undefinedMethod_createUnqualified_returnType() async { +- await resolveTestUnit(''' +-class A { +- main() { +- int v =3D myUndefinedMethod(); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- main() { +- int v =3D myUndefinedMethod(); +- } +- +- int myUndefinedMethod() {} +-} +-'''); +- // linked positions +- _assertLinkedGroup(change.linkedEditGroups[0], ['int myUndefinedMetho= d(']); +- _assertLinkedGroup(change.linkedEditGroups[1], +- ['myUndefinedMethod();', 'myUndefinedMethod() {']); +- } +- +- test_undefinedMethod_createUnqualified_staticFromField() async { +- await resolveTestUnit(''' +-class A { +- static var f =3D myUndefinedMethod(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- static var f =3D myUndefinedMethod(); +- +- static myUndefinedMethod() {} +-} +-'''); +- } +- +- test_undefinedMethod_createUnqualified_staticFromMethod() async { +- await resolveTestUnit(''' +-class A { +- static main() { +- myUndefinedMethod(); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- static main() { +- myUndefinedMethod(); +- } +- +- static void myUndefinedMethod() {} +-} +-'''); +- } +- +- test_undefinedMethod_hint_createQualified_fromInstance() async { +- await resolveTestUnit(''' +-class A { +-} +-main() { +- var a =3D new A(); +- a.myUndefinedMethod(); +-} +-'''); +- await assertHasFix(DartFixKind.CREATE_METHOD, ''' +-class A { +- void myUndefinedMethod() {} +-} +-main() { +- var a =3D new A(); +- a.myUndefinedMethod(); +-} +-'''); +- } +- +- test_undefinedMethod_parameterType_differentPrefixInTargetUnit() async { +- String code2 =3D r''' +-library test2; +-import 'test3.dart' as bbb; +-export 'test3.dart'; +-class D { +-} +-'''; +- addSource('/test2.dart', code2); +- addSource('/test3.dart', r''' +-library test3; +-class E {} +-'''); +- await resolveTestUnit(''' +-library test; +-import 'test2.dart' as aaa; +-main(aaa.D d, aaa.E e) { +- d.foo(e); +-} +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_METHOD, error); +- change =3D fix.change; +- // apply to "test2.dart" +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/test2.dart'); +- expect(SourceEdit.applySequence(code2, fileEdit.edits), r''' +-library test2; +-import 'test3.dart' as bbb; +-export 'test3.dart'; +-class D { +- void foo(bbb.E e) {} +-} +-'''); +- } +- +- test_undefinedMethod_parameterType_inTargetUnit() async { +- String code2 =3D r''' +-library test2; +-class D { +-} +-class E {} +-'''; +- addSource('/test2.dart', code2); +- await resolveTestUnit(''' +-library test; +-import 'test2.dart' as test2; +-main(test2.D d, test2.E e) { +- d.foo(e); +-} +-'''); +- AnalysisError error =3D await _findErrorToFix(); +- fix =3D await _assertHasFix(DartFixKind.CREATE_METHOD, error); +- change =3D fix.change; +- // apply to "test2.dart" +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- SourceFileEdit fileEdit =3D change.edits[0]; +- expect(fileEdit.file, '/test2.dart'); +- expect(SourceEdit.applySequence(code2, fileEdit.edits), r''' +-library test2; +-class D { +- void foo(E e) {} +-} +-class E {} +-'''); +- } +- +- test_undefinedMethod_useSimilar_ignoreOperators() async { +- await resolveTestUnit(''' +-main(Object object) { +- object.then(); +-} +-'''); +- await assertNoFix(DartFixKind.CHANGE_TO); +- } +- +- test_undefinedMethod_useSimilar_qualified() async { +- await resolveTestUnit(''' +-class A { +- myMethod() {} +-} +-main() { +- A a =3D new A(); +- a.myMehtod(); +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- myMethod() {} +-} +-main() { +- A a =3D new A(); +- a.myMethod(); +-} +-'''); +- } +- +- test_undefinedMethod_useSimilar_unqualified_superClass() async { +- await resolveTestUnit(''' +-class A { +- myMethod() {} +-} +-class B extends A { +- main() { +- myMehtod(); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- myMethod() {} +-} +-class B extends A { +- main() { +- myMethod(); +- } +-} +-'''); +- } +- +- test_undefinedMethod_useSimilar_unqualified_thisClass() async { +- await resolveTestUnit(''' +-class A { +- myMethod() {} +- main() { +- myMehtod(); +- } +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- myMethod() {} +- main() { +- myMethod(); +- } +-} +-'''); +- } +- +- test_undefinedParameter_convertFlutterChild_invalidList() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +- child: [ +- new Transform(), +- null, +- new AspectRatio(), +- ], +- ), +- ); +-} +-'''); +- await assertNoFix(DartFixKind.CONVERT_FLUTTER_CHILD); +- } +- +- test_undefinedParameter_convertFlutterChild_OK_hasList() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +- child: [ +- new Transform(), +- new ClipRect.rect(), +- new AspectRatio(), +- ], +- ), +- ); +-} +-'''); +- await assertHasFix(DartFixKind.CONVERT_FLUTTER_CHILD, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +- children: [ +- new Transform(), +- new ClipRect.rect(), +- new AspectRatio(), +- ], +- ), +- ); +-} +-'''); +- } +- +- test_undefinedParameter_convertFlutterChild_OK_hasTypedList() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +- child: [ +- new Transform(), +- new ClipRect.rect(), +- new AspectRatio(), +- ], +- ), +- ); +-} +-'''); +- await assertHasFix(DartFixKind.CONVERT_FLUTTER_CHILD, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Container( +- child: new Row( +- children: [ +- new Transform(), +- new ClipRect.rect(), +- new AspectRatio(), +- ], +- ), +- ); +-} +-'''); +- } +- +- test_undefinedParameter_convertFlutterChild_OK_multiLine() async { +- _configureFlutterPkg({ +- 'src/widgets/framework.dart': flutter_framework_code, +- }); +- await resolveTestUnit(''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +- body: new Row( +- child: new Container( +- width: 200.0, +- height: 300.0, +- ), +- ), +- ); +-} +-'''); +- await assertHasFix(DartFixKind.CONVERT_FLUTTER_CHILD, ''' +-import 'package:flutter/src/widgets/framework.dart'; +-build() { +- return new Scaffold( +- body: new Row( +- children: [ +- new Container( +- width: 200.0, +- height: 300.0, +- ), +- ], +- ), +- ); +-} +-'''); +- } +- +- test_undefinedSetter_useSimilar_hint() async { +- await resolveTestUnit(''' +-class A { +- int myField; +-} +-main(A a) { +- var x =3D a; +- x.myFild =3D 42; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- int myField; +-} +-main(A a) { +- var x =3D a; +- x.myField =3D 42; +-} +-'''); +- } +- +- test_undefinedSetter_useSimilar_qualified() async { +- await resolveTestUnit(''' +-class A { +- int myField; +-} +-main(A a) { +- a.myFild =3D 42; +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- int myField; +-} +-main(A a) { +- a.myField =3D 42; +-} +-'''); +- } +- +- test_undefinedSetter_useSimilar_unqualified() async { +- await resolveTestUnit(''' +-class A { +- int myField; +- main() { +- myFild =3D 42; +- } +-} +-'''); +- await assertHasFix(DartFixKind.CHANGE_TO, ''' +-class A { +- int myField; +- main() { +- myField =3D 42; +- } +-} +-'''); +- } +- +- test_useEffectiveIntegerDivision() async { +- await resolveTestUnit(''' +-main() { +- var a =3D 5; +- var b =3D 2; +- print((a / b).toInt()); +-} +-'''); +- await assertHasFix(DartFixKind.USE_EFFECTIVE_INTEGER_DIVISION, ''' +-main() { +- var a =3D 5; +- var b =3D 2; +- print(a ~/ b); +-} +-'''); +- } +- +- test_useImportPrefix_withClass() async { +- await resolveTestUnit(''' +-import 'dart:async' as pref; +-main() { +- pref.Stream s =3D null; +- Future f =3D null; +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PREFIX, ''' +-import 'dart:async' as pref; +-main() { +- pref.Stream s =3D null; +- pref.Future f =3D null; +-} +-'''); +- } +- +- test_useImportPrefix_withTopLevelVariable() async { +- await resolveTestUnit(''' +-import 'dart:math' as pref; +-main() { +- print(pref.E); +- print(PI); +-} +-'''); +- await assertHasFix(DartFixKind.IMPORT_LIBRARY_PREFIX, ''' +-import 'dart:math' as pref; +-main() { +- print(pref.E); +- print(pref.PI); +-} +-'''); +- } +- +- void _addMetaPackageSource() { +- addPackageSource('meta', 'meta.dart', r''' +-library meta; +- +-const Required required =3D const Required(); +- +-class Required { +- final String reason; +- const Required([this.reason]); +-} +-'''); +- } +- +- /** +- * Configures the [SourceFactory] to have the `flutter` package in +- * `/packages/flutter/lib` folder. +- */ +- void _configureFlutterPkg(Map pathToCode) { +- pathToCode.forEach((path, code) { +- provider.newFile('$flutterPkgLibPath/$path', code); +- }); +- // configure SourceFactory +- Folder myPkgFolder =3D provider.getResource(flutterPkgLibPath); +- UriResolver pkgResolver =3D new PackageMapUriResolver(provider, { +- 'flutter': [myPkgFolder] +- }); +- SourceFactory sourceFactory =3D new SourceFactory( +- [new DartUriResolver(sdk), pkgResolver, resourceResolver]); +- driver.configure(sourceFactory: sourceFactory); +- // force 'flutter' resolution +- addSource( +- '/tmp/other.dart', +- pathToCode.keys +- .map((path) =3D> "import 'package:flutter/$path';") +- .join('\n')); +- } +-} +- +-@reflectiveTest +-class LintFixTest extends BaseFixProcessorTest { +- AnalysisError error; +- +- Future applyFix(FixKind kind) async { +- fix =3D await _assertHasFix(kind, error); +- change =3D fix.change; +- // apply to "file" +- List fileEdits =3D change.edits; +- expect(fileEdits, hasLength(1)); +- resultCode =3D SourceEdit.applySequence(testCode, change.edits[0].edi= ts); +- } +- +- Future findLint(String src, String lintCode, {int length: 1}) asy= nc { +- int errorOffset =3D src.indexOf('/*LINT*/'); +- await resolveTestUnit(src.replaceAll('/*LINT*/', '')); +- error =3D new AnalysisError( +- resolutionMap.elementDeclaredByCompilationUnit(testUnit).source, +- errorOffset, +- length, +- new LintCode(lintCode, '')); +- } +- +- test_addRequiredAnnotation() async { +- String src =3D ''' +-void function({String /*LINT*/param}) { +- assert(param !=3D null); +-} +-'''; +- await findLint(src, LintNames.always_require_non_null_named_parameter= s); +- await applyFix(DartFixKind.LINT_ADD_REQUIRED); +- verifyResult(''' +-void function({@required String param}) { +- assert(param !=3D null); +-} +-'''); +- } +- +- test_isNotEmpty() async { +- String src =3D ''' +-f(c) { +- if (/*LINT*/!c.isEmpty) {} +-} +-'''; +- await findLint(src, LintNames.prefer_is_not_empty); +- +- await applyFix(DartFixKind.USE_IS_NOT_EMPTY); +- +- verifyResult(''' +-f(c) { +- if (c.isNotEmpty) {} +-} +-'''); +- } +- +- test_lint_addMissingOverride_field() async { +- String src =3D ''' +-class abstract Test { +- int get t; +-} +-class Sub extends Test { +- int /*LINT*/t =3D 42; +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class abstract Test { +- int get t; +-} +-class Sub extends Test { +- @override +- int t =3D 42; +-} +-'''); +- } +- +- test_lint_addMissingOverride_getter() async { +- String src =3D ''' +-class Test { +- int get t =3D> null; +-} +-class Sub extends Test { +- int get /*LINT*/t =3D> null; +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class Test { +- int get t =3D> null; +-} +-class Sub extends Test { +- @override +- int get t =3D> null; +-} +-'''); +- } +- +- test_lint_addMissingOverride_method() async { +- String src =3D ''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- void /*LINT*/t() { } +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- @override +- void t() { } +-} +-'''); +- } +- +- test_lint_addMissingOverride_method_with_doc_comment() async { +- String src =3D ''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- /// Doc comment. +- void /*LINT*/t() { } +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- /// Doc comment. +- @override +- void t() { } +-} +-'''); +- } +- +- test_lint_addMissingOverride_method_with_doc_comment_2() async { +- String src =3D ''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- /** +- * Doc comment. +- */ +- void /*LINT*/t() { } +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- /** +- * Doc comment. +- */ +- @override +- void t() { } +-} +-'''); +- } +- +- test_lint_addMissingOverride_method_with_doc_comment_and_metadata() asy= nc { +- String src =3D ''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- /// Doc comment. +- @foo +- void /*LINT*/t() { } +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- /// Doc comment. +- @override +- @foo +- void t() { } +-} +-'''); +- } +- +- test_lint_addMissingOverride_method_with_non_doc_comment() async { +- String src =3D ''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- // Non-doc comment. +- void /*LINT*/t() { } +-} +-'''; +- await findLint(src, LintNames.annotate_overrides); +- +- await applyFix(DartFixKind.LINT_ADD_OVERRIDE); +- +- verifyResult(''' +-class Test { +- void t() { } +-} +-class Sub extends Test { +- // Non-doc comment. +- @override +- void t() { } +-} +-'''); +- } +- +- test_lint_removeInterpolationBraces() async { +- String src =3D r''' +-main() { +- var v =3D 42; +- print('v: /*LINT*/${ v}'); +-} +-'''; +- await findLint(src, LintNames.unnecessary_brace_in_string_interp, +- length: 4); +- await applyFix(DartFixKind.LINT_REMOVE_INTERPOLATION_BRACES); +- verifyResult(r''' +-main() { +- var v =3D 42; +- print('v: $v'); +-} +-'''); +- } +- +- test_removeAwait_intLiteral() async { +- String src =3D ''' +-bad() async { +- print(/*LINT*/await 23); +-} +-'''; +- await findLint(src, LintNames.await_only_futures); +- +- await applyFix(DartFixKind.REMOVE_AWAIT); +- +- verifyResult(''' +-bad() async { +- print(23); +-} +-'''); +- } +- +- test_removeAwait_StringLiteral() async { +- String src =3D ''' +-bad() async { +- print(/*LINT*/await 'hola'); +-} +-'''; +- await findLint(src, LintNames.await_only_futures); +- +- await applyFix(DartFixKind.REMOVE_AWAIT); +- +- verifyResult(''' +-bad() async { +- print('hola'); +-} +-'''); +- } +- +- test_removeEmptyCatch_newLine() async { +- String src =3D ''' +-void foo() { +- try {} +- catch (e) {/*LINT*/} +- finally {} +-} +-'''; +- await findLint(src, LintNames.empty_catches); +- +- await applyFix(DartFixKind.REMOVE_EMPTY_CATCH); +- +- verifyResult(''' +-void foo() { +- try {} +- finally {} +-} +-'''); +- } +- +- test_removeEmptyCatch_sameLine() async { +- String src =3D ''' +-void foo() { +- try {} catch (e) {/*LINT*/} finally {} +-} +-'''; +- await findLint(src, LintNames.empty_catches); +- +- await applyFix(DartFixKind.REMOVE_EMPTY_CATCH); +- +- verifyResult(''' +-void foo() { +- try {} finally {} +-} +-'''); +- } +- +- test_removeEmptyConstructorBody() async { +- String src =3D ''' +-class C { +- C() {/*LINT*/} +-} +-'''; +- await findLint(src, LintNames.empty_constructor_bodies); +- +- await applyFix(DartFixKind.REMOVE_EMPTY_CONSTRUCTOR_BODY); +- +- verifyResult(''' +-class C { +- C(); +-} +-'''); +- } +- +- test_removeEmptyElse_newLine() async { +- String src =3D ''' +-void foo(bool cond) { +- if (cond) { +- // +- } +- else /*LINT*/; +-} +-'''; +- await findLint(src, LintNames.avoid_empty_else); +- +- await applyFix(DartFixKind.REMOVE_EMPTY_ELSE); +- +- verifyResult(''' +-void foo(bool cond) { +- if (cond) { +- // +- } +-} +-'''); +- } +- +- test_removeEmptyElse_sameLine() async { +- String src =3D ''' +-void foo(bool cond) { +- if (cond) { +- // +- } else /*LINT*/; +-} +-'''; +- await findLint(src, LintNames.avoid_empty_else); +- +- await applyFix(DartFixKind.REMOVE_EMPTY_ELSE); +- +- verifyResult(''' +-void foo(bool cond) { +- if (cond) { +- // +- } +-} +-'''); +- } +- +- test_removeEmptyStatement_insideBlock() async { +- String src =3D ''' +-void foo() { +- while(true) { +- /*LINT*/; +- } +-} +-'''; +- await findLint(src, LintNames.empty_statements); +- +- await applyFix(DartFixKind.REMOVE_EMPTY_STATEMENT); +- +- verifyResult(''' +-void foo() { +- while(true) { +- } +-} +-'''); +- } +- +- test_removeEmptyStatement_outOfBlock_otherLine() async { +- String src =3D ''' +-void foo() { +- while(true) +- /*LINT*/; +- print('hi'); +-} +-'''; +- await findLint(src, LintNames.empty_statements); +- +- await applyFix(DartFixKind.REPLACE_WITH_BRACKETS); +- +- verifyResult(''' +-void foo() { +- while(true) {} +- print('hi'); +-} +-'''); +- } +- +- test_removeEmptyStatement_outOfBlock_sameLine() async { +- String src =3D ''' +-void foo() { +- while(true)/*LINT*/; +- print('hi'); +-} +-'''; +- await findLint(src, LintNames.empty_statements); +- +- await applyFix(DartFixKind.REPLACE_WITH_BRACKETS); +- +- verifyResult(''' +-void foo() { +- while(true) {} +- print('hi'); +-} +-'''); +- } +- +- test_removeInitializer_field() async { +- String src =3D ''' +-class Test { +- int /*LINT*/x =3D null; +-} +-'''; +- await findLint(src, LintNames.avoid_init_to_null); +- +- await applyFix(DartFixKind.REMOVE_INITIALIZER); +- +- verifyResult(''' +-class Test { +- int x; +-} +-'''); +- } +- +- test_removeInitializer_listOfVariableDeclarations() async { +- String src =3D ''' +-String a =3D 'a', /*LINT*/b =3D null, c =3D 'c'; +-'''; +- await findLint(src, LintNames.avoid_init_to_null); +- +- await applyFix(DartFixKind.REMOVE_INITIALIZER); +- +- verifyResult(''' +-String a =3D 'a', b, c =3D 'c'; +-'''); +- } +- +- test_removeInitializer_topLevel() async { +- String src =3D ''' +-var /*LINT*/x =3D null; +-'''; +- await findLint(src, LintNames.avoid_init_to_null); +- +- await applyFix(DartFixKind.REMOVE_INITIALIZER); +- +- verifyResult(''' +-var x; +-'''); +- } +- +- test_removeMethodDeclaration_getter() async { +- String src =3D ''' +-class A { +- int x; +-} +-class B extends A { +- @override +- int get /*LINT*/x =3D> super.x; +-} +-'''; +- await findLint(src, LintNames.unnecessary_override); +- +- await applyFix(DartFixKind.REMOVE_METHOD_DECLARATION); +- +- verifyResult(''' +-class A { +- int x; +-} +-class B extends A { +-} +-'''); +- } +- +- test_removeMethodDeclaration_method() async { +- String src =3D ''' +-class A { +- @override +- String /*LINT*/toString() =3D> super.toString(); +-} +-'''; +- await findLint(src, LintNames.unnecessary_override); +- +- await applyFix(DartFixKind.REMOVE_METHOD_DECLARATION); +- +- verifyResult(''' +-class A { +-} +-'''); +- } +- +- test_removeMethodDeclaration_setter() async { +- String src =3D ''' +-class A { +- int x; +-} +-class B extends A { +- @override +- set /*LINT*/x(int other) { +- this.x =3D other; +- } +-} +-'''; +- await findLint(src, LintNames.unnecessary_override); +- +- await applyFix(DartFixKind.REMOVE_METHOD_DECLARATION); +- +- verifyResult(''' +-class A { +- int x; +-} +-class B extends A { +-} +-'''); +- } +- +- test_removeThisExpression_methodInvocation_oneCharacterOperator() async= { +- String src =3D ''' +-class A { +- void foo() { +- /*LINT*/this.foo(); +- } +-} +-'''; +- await findLint(src, LintNames.unnecessary_this); +- +- await applyFix(DartFixKind.REMOVE_THIS_EXPRESSION); +- +- verifyResult(''' +-class A { +- void foo() { +- foo(); +- } +-} +-'''); +- } +- +- test_removeThisExpression_methodInvocation_twoCharactersOperator() asyn= c { +- String src =3D ''' +-class A { +- void foo() { +- /*LINT*/this?.foo(); +- } +-} +-'''; +- await findLint(src, LintNames.unnecessary_this); +- +- await applyFix(DartFixKind.REMOVE_THIS_EXPRESSION); +- +- verifyResult(''' +-class A { +- void foo() { +- foo(); +- } +-} +-'''); +- } +- +- test_removeThisExpression_propertyAccess_oneCharacterOperator() async { +- String src =3D ''' +-class A { +- int x; +- void foo() { +- /*LINT*/this.x =3D 2; +- } +-} +-'''; +- await findLint(src, LintNames.unnecessary_this); +- +- await applyFix(DartFixKind.REMOVE_THIS_EXPRESSION); +- +- verifyResult(''' +-class A { +- int x; +- void foo() { +- x =3D 2; +- } +-} +-'''); +- } +- +- test_removeThisExpression_propertyAccess_twoCharactersOperator() async { +- String src =3D ''' +-class A { +- int x; +- void foo() { +- /*LINT*/this?.x =3D 2; +- } +-} +-'''; +- await findLint(src, LintNames.unnecessary_this); +- +- await applyFix(DartFixKind.REMOVE_THIS_EXPRESSION); +- +- verifyResult(''' +-class A { +- int x; +- void foo() { +- x =3D 2; +- } +-} +-'''); +- } +- +- test_removeTypeAnnotation_avoidAnnotatingWithDynamic_InsideFunctionType= dFormalParameter() async { +- String src =3D ''' +-bad(void foo(/*LINT*/dynamic x)) { +- return null; +-} +-'''; +- await findLint(src, LintNames.avoid_annotating_with_dynamic); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-bad(void foo(x)) { +- return null; +-} +-'''); +- } +- +- test_removeTypeAnnotation_avoidAnnotatingWithDynamic_NamedParameter() a= sync { +- String src =3D ''' +-bad({/*LINT*/dynamic defaultValue}) { +- return null; +-} +-'''; +- await findLint(src, LintNames.avoid_annotating_with_dynamic); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-bad({defaultValue}) { +- return null; +-} +-'''); +- } +- +- test_removeTypeAnnotation_avoidAnnotatingWithDynamic_NormalParameter() = async { +- String src =3D ''' +-bad(/*LINT*/dynamic defaultValue) { +- return null; +-} +-'''; +- await findLint(src, LintNames.avoid_annotating_with_dynamic); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-bad(defaultValue) { +- return null; +-} +-'''); +- } +- +- test_removeTypeAnnotation_avoidAnnotatingWithDynamic_OptionalParameter(= ) async { +- String src =3D ''' +-bad([/*LINT*/dynamic defaultValue]) { +- return null; +-} +-'''; +- await findLint(src, LintNames.avoid_annotating_with_dynamic); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-bad([defaultValue]) { +- return null; +-} +-'''); +- } +- +- test_removeTypeAnnotation_avoidReturnTypesOnSetters_void() async { +- String src =3D ''' +-/*LINT*/void set speed2(int ms) {} +-'''; +- await findLint(src, LintNames.avoid_return_types_on_setters); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-set speed2(int ms) {} +-'''); +- } +- +- test_removeTypeAnnotation_avoidTypesOnClosureParameters_FunctionTypedFo= rmalParameter() async { +- String src =3D ''' +-var functionWithFunction =3D (/*LINT*/int f(int x)) =3D> f(0); +-'''; +- await findLint(src, LintNames.avoid_types_on_closure_parameters); +- +- await applyFix(DartFixKind.REPLACE_WITH_IDENTIFIER); +- +- verifyResult(''' +-var functionWithFunction =3D (f) =3D> f(0); +-'''); +- } +- +- test_removeTypeAnnotation_avoidTypesOnClosureParameters_NamedParameter(= ) async { +- String src =3D ''' +-var x =3D ({/*LINT*/Future defaultValue}) { +- return null; +-}; +-'''; +- await findLint(src, LintNames.avoid_types_on_closure_parameters); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-var x =3D ({defaultValue}) { +- return null; +-}; +-'''); +- } +- +- test_removeTypeAnnotation_avoidTypesOnClosureParameters_NormalParameter= () async { +- String src =3D ''' +-var x =3D (/*LINT*/Future defaultValue) { +- return null; +-}; +-'''; +- await findLint(src, LintNames.avoid_types_on_closure_parameters); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-var x =3D (defaultValue) { +- return null; +-}; +-'''); +- } +- +- test_removeTypeAnnotation_avoidTypesOnClosureParameters_OptionalParamet= er() async { +- String src =3D ''' +-var x =3D ([/*LINT*/Future defaultValue]) { +- return null; +-}; +-'''; +- await findLint(src, LintNames.avoid_types_on_closure_parameters); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-var x =3D ([defaultValue]) { +- return null; +-}; +-'''); +- } +- +- test_removeTypeAnnotation_typeInitFormals_void() async { +- String src =3D ''' +-class C { +- int f; +- C(/*LINT*/int this.f); +-} +-'''; +- await findLint(src, LintNames.type_init_formals); +- +- await applyFix(DartFixKind.REMOVE_TYPE_NAME); +- +- verifyResult(''' +-class C { +- int f; +- C(this.f); +-} +-'''); +- } +- +- test_replaceWithConditionalAssignment_withCodeBeforeAndAfter() async { +- String src =3D ''' +-class Person { +- String _fullName; +- void foo() { +- print('hi'); +- /*LINT*/if (_fullName =3D=3D null) { +- _fullName =3D getFullUserName(this); +- } +- print('hi'); +- } +-} +-'''; +- await findLint(src, LintNames.prefer_conditional_assignment); +- +- await applyFix(DartFixKind.REPLACE_WITH_CONDITIONAL_ASSIGNMENT); +- +- verifyResult(''' +-class Person { +- String _fullName; +- void foo() { +- print('hi'); +- _fullName ??=3D getFullUserName(this); +- print('hi'); +- } +-} +-'''); +- } +- +- test_replaceWithConditionalAssignment_withOneBlock() async { +- String src =3D ''' +-class Person { +- String _fullName; +- void foo() { +- /*LINT*/if (_fullName =3D=3D null) { +- _fullName =3D getFullUserName(this); +- } +- } +-} +-'''; +- await findLint(src, LintNames.prefer_conditional_assignment); +- +- await applyFix(DartFixKind.REPLACE_WITH_CONDITIONAL_ASSIGNMENT); +- +- verifyResult(''' +-class Person { +- String _fullName; +- void foo() { +- _fullName ??=3D getFullUserName(this); +- } +-} +-'''); +- } +- +- test_replaceWithConditionalAssignment_withoutBlock() async { +- String src =3D ''' +-class Person { +- String _fullName; +- void foo() { +- /*LINT*/if (_fullName =3D=3D null) +- _fullName =3D getFullUserName(this); +- } +-} +-'''; +- await findLint(src, LintNames.prefer_conditional_assignment); +- +- await applyFix(DartFixKind.REPLACE_WITH_CONDITIONAL_ASSIGNMENT); +- +- verifyResult(''' +-class Person { +- String _fullName; +- void foo() { +- _fullName ??=3D getFullUserName(this); +- } +-} +-'''); +- } +- +- test_replaceWithConditionalAssignment_withTwoBlock() async { +- String src =3D ''' +-class Person { +- String _fullName; +- void foo() { +- /*LINT*/if (_fullName =3D=3D null) {{ +- _fullName =3D getFullUserName(this); +- }} +- } +-} +-'''; +- await findLint(src, LintNames.prefer_conditional_assignment); +- +- await applyFix(DartFixKind.REPLACE_WITH_CONDITIONAL_ASSIGNMENT); +- +- verifyResult(''' +-class Person { +- String _fullName; +- void foo() { +- _fullName ??=3D getFullUserName(this); +- } +-} +-'''); +- } +- +- test_replaceWithLiteral_linkedHashMap_withCommentsInGeneric() async { +- String src =3D ''' +-import 'dart:collection'; +- +-final a =3D /*LINT*/new LinkedHashMap(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-import 'dart:collection'; +- +-final a =3D {}; +-'''); +- } +- +- test_replaceWithLiteral_linkedHashMap_withDynamicGenerics() async { +- String src =3D ''' +-import 'dart:collection'; +- +-final a =3D /*LINT*/new LinkedHashMap(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-import 'dart:collection'; +- +-final a =3D {}; +-'''); +- } +- +- test_replaceWithLiteral_linkedHashMap_withGeneric() async { +- String src =3D ''' +-import 'dart:collection'; +- +-final a =3D /*LINT*/new LinkedHashMap(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-import 'dart:collection'; +- +-final a =3D {}; +-'''); +- } +- +- test_replaceWithLiteral_linkedHashMap_withoutGeneric() async { +- String src =3D ''' +-import 'dart:collection'; +- +-final a =3D /*LINT*/new LinkedHashMap(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-import 'dart:collection'; +- +-final a =3D {}; +-'''); +- } +- +- test_replaceWithLiteral_list_withGeneric() async { +- String src =3D ''' +-final a =3D /*LINT*/new List(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-final a =3D []; +-'''); +- } +- +- test_replaceWithLiteral_list_withoutGeneric() async { +- String src =3D ''' +-final a =3D /*LINT*/new List(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-final a =3D []; +-'''); +- } +- +- test_replaceWithLiteral_map_withGeneric() async { +- String src =3D ''' +-final a =3D /*LINT*/new Map(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-final a =3D {}; +-'''); +- } +- +- test_replaceWithLiteral_map_withoutGeneric() async { +- String src =3D ''' +-final a =3D /*LINT*/new Map(); +-'''; +- await findLint(src, LintNames.prefer_collection_literals); +- +- await applyFix(DartFixKind.REPLACE_WITH_LITERAL); +- +- verifyResult(''' +-final a =3D {}; +-'''); +- } +- +- test_replaceWithTearOff_function_oneParameter() async { +- String src =3D ''' +-final x =3D /*LINT*/(name) { +- print(name); +-}; +-'''; +- await findLint(src, LintNames.unnecessary_lambdas); +- +- await applyFix(DartFixKind.REPLACE_WITH_TEAR_OFF); +- +- verifyResult(''' +-final x =3D print; +-'''); +- } +- +- test_replaceWithTearOff_function_zeroParameters() async { +- String src =3D ''' +-void foo(){} +-Function finalVar() { +- return /*LINT*/() { +- foo(); +- }; +-} +-'''; +- await findLint(src, LintNames.unnecessary_lambdas); +- +- await applyFix(DartFixKind.REPLACE_WITH_TEAR_OFF); +- +- verifyResult(''' +-void foo(){} +-Function finalVar() { +- return foo; +-} +-'''); +- } +- +- test_replaceWithTearOff_lambda_asArgument() async { +- String src =3D ''' +-void foo() { +- bool isPair(int a) =3D> a % 2 =3D=3D 0; +- final finalList =3D []; +- finalList.where(/*LINT*/(number) =3D> +- isPair(number)); +-} +-'''; +- await findLint(src, LintNames.unnecessary_lambdas); +- +- await applyFix(DartFixKind.REPLACE_WITH_TEAR_OFF); +- +- verifyResult(''' +-void foo() { +- bool isPair(int a) =3D> a % 2 =3D=3D 0; +- final finalList =3D []; +- finalList.where(isPair); +-} +-'''); +- } +- +- test_replaceWithTearOff_method_oneParameter() async { +- String src =3D ''' +-var a =3D /*LINT*/(x) =3D> finalList.remove(x); +-'''; +- await findLint(src, LintNames.unnecessary_lambdas); +- +- await applyFix(DartFixKind.REPLACE_WITH_TEAR_OFF); +- +- verifyResult(''' +-var a =3D finalList.remove; +-'''); +- } +- +- test_replaceWithTearOff_method_zeroParameter() async { +- String src =3D ''' +-final Object a; +-Function finalVar() { +- return /*LINT*/() { +- return a.toString(); +- }; +-} +-'''; +- await findLint(src, LintNames.unnecessary_lambdas); +- +- await applyFix(DartFixKind.REPLACE_WITH_TEAR_OFF); +- +- verifyResult(''' +-final Object a; +-Function finalVar() { +- return a.toString; +-} +-'''); +- } +- +- void verifyResult(String expectedResult) { +- expect(resultCode, expectedResult); +- } +-} +- +-class _DartFixContextImpl implements DartFixContext { +- @override +- final ResourceProvider resourceProvider; +- +- @override +- final AnalysisDriver analysisDriver; +- +- @override +- final AstProvider astProvider; +- +- @override +- final CompilationUnit unit; +- +- @override +- final AnalysisError error; +- +- _DartFixContextImpl(this.resourceProvider, this.analysisDriver, +- this.astProvider, this.unit, this.error); +- +- @override +- GetTopLevelDeclarations get getTopLevelDeclarations =3D> +- analysisDriver.getTopLevelNameDeclarations; +-} +diff --git a/pkg/analysis_server/test/services/correction/levenshtein_test= .dart b/pkg/analysis_server/test/services/correction/levenshtein_test.dart +deleted file mode 100644 +index c344a4c06f8..00000000000 +--- a/pkg/analysis_server/test/services/correction/levenshtein_test.dart ++++ /dev/null +@@ -1,66 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/levenshtein.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LevenshteinTest); +- }); +-} +- +-@reflectiveTest +-class LevenshteinTest { +- void test_different_caseInsensitive() { +- expect(levenshtein('Saturday', 'sunday', 5, caseSensitive: false), 3); +- expect(levenshtein('SaturDay', 'sunday', 5, caseSensitive: false), 3); +- } +- +- void test_different_onThreshold() { +- expect(levenshtein('', 'abcde', 5), 5); +- expect(levenshtein('abcde', '', 5), 5); +- } +- +- void test_different_overThreshold() { +- expect(levenshtein('', 'abcde', 2), LEVENSHTEIN_MAX); +- expect(levenshtein('abcde', '', 2), LEVENSHTEIN_MAX); +- } +- +- void test_different_overThreshold_length() { +- expect(levenshtein('a', 'abcdefgh', 5), LEVENSHTEIN_MAX); +- expect(levenshtein('abcdefgh', 'a', 5), LEVENSHTEIN_MAX); +- } +- +- void test_different_underThreshold() { +- expect(levenshtein('String', 'Stirng', 5), 2); +- expect(levenshtein('kitten', 'sitting', 5), 3); +- expect(levenshtein('Saturday', 'Sunday', 5), 3); +- } +- +- void test_negativeThreshold() { +- expect(() { +- levenshtein('', '', -5); +- }, throwsArgumentError); +- } +- +- void test_null() { +- expect(() { +- levenshtein('', null, 5); +- }, throwsArgumentError); +- expect(() { +- levenshtein(null, '', 5); +- }, throwsArgumentError); +- } +- +- void test_same() { +- expect(levenshtein('', '', 5), 0); +- expect(levenshtein('test', 'test', 5), 0); +- } +- +- void test_same_caseInsensitive() { +- expect(levenshtein('test', 'Test', 5, caseSensitive: false), 0); +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/name_suggestion_= test.dart b/pkg/analysis_server/test/services/correction/name_suggestion_te= st.dart +deleted file mode 100644 +index 24f5ed80ebd..00000000000 +--- a/pkg/analysis_server/test/services/correction/name_suggestion_test.da= rt ++++ /dev/null +@@ -1,369 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/name_suggestion.d= art'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/type.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(VariableNameSuggestionTest); +- }); +-} +- +-@reflectiveTest +-class VariableNameSuggestionTest extends AbstractSingleUnitTest { +- test_forExpression_cast() async { +- await resolveTestUnit(''' +-main() { +- var sortedNodes; +- var res =3D sortedNodes as String; +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('as String', (node) =3D> node is AsExpr= ession); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- test_forExpression_expectedType() async { +- await resolveTestUnit(''' +-class TreeNode {} +-main() { +- TreeNode node =3D null; +-} +-'''); +- Set excluded =3D new Set.from([]); +- DartType expectedType =3D findLocalVariable('node').type; +- Expression assignedExpression =3D +- findNodeAtString('null;', (node) =3D> node is NullLiteral); +- List suggestions =3D getVariableNameSuggestionsForExpression( +- expectedType, assignedExpression, excluded); +- expect(suggestions, unorderedEquals(['treeNode', 'node'])); +- } +- +- test_forExpression_expectedType_double() async { +- await resolveTestUnit(''' +-main() { +- double res =3D 0.0; +-} +-'''); +- DartType expectedType =3D findLocalVariable('res').type; +- Expression assignedExpression =3D findNodeAtString('0.0;'); +- // first choice for "double" is "d" +- expect( +- getVariableNameSuggestionsForExpression( +- expectedType, assignedExpression, new Set.from([])), +- unorderedEquals(['d'])); +- // if "d" is used, try "e", "f", etc +- expect( +- getVariableNameSuggestionsForExpression( +- expectedType, assignedExpression, new Set.from(['d', 'e'])), +- unorderedEquals(['f'])); +- } +- +- test_forExpression_expectedType_int() async { +- await resolveTestUnit(''' +-main() { +- int res =3D 0; +-} +-'''); +- DartType expectedType =3D findLocalVariable('res').type; +- Expression assignedExpression =3D findNodeAtString('0;'); +- // first choice for "int" is "i" +- expect( +- getVariableNameSuggestionsForExpression( +- expectedType, assignedExpression, new Set.from([])), +- unorderedEquals(['i'])); +- // if "i" is used, try "j", "k", etc +- expect( +- getVariableNameSuggestionsForExpression( +- expectedType, assignedExpression, new Set.from(['i', 'j'])), +- unorderedEquals(['k'])); +- } +- +- test_forExpression_expectedType_String() async { +- await resolveTestUnit(''' +-main() { +- String res =3D 'abc'; +-} +-'''); +- DartType expectedType =3D findLocalVariable('res').type; +- Expression assignedExpression =3D findNodeAtString("'abc';"); +- // first choice for "String" is "s" +- expect( +- getVariableNameSuggestionsForExpression( +- expectedType, assignedExpression, new Set.from([])), +- unorderedEquals(['s'])); +- } +- +- test_forExpression_indexExpression_endsWithE() async { +- await resolveTestUnit(''' +-main() { +- var topNodes =3D [0, 1, 2]; +- print(topNodes[0]); +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('topNodes[0]').parent; +- var names =3D getVariableNameSuggestionsForExpression(null, expr, exc= luded); +- expect(names, unorderedEquals(['topNode', 'node', 'object'])); +- } +- +- test_forExpression_instanceCreation() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-import 'dart:math' as p; +-main(p) { +- new NoSuchClass(); +- new p.NoSuchClass(); +- new NoSuchClass.named(); +-} +-'''); +- var excluded =3D new Set.from([]); +- expect( +- getVariableNameSuggestionsForExpression( +- null, findNodeAtString('new NoSuchClass()'), excluded), +- unorderedEquals(['noSuchClass', 'suchClass', 'class'])); +- expect( +- getVariableNameSuggestionsForExpression( +- null, findNodeAtString('new NoSuchClass.named()'), excluded), +- unorderedEquals(['noSuchClass', 'suchClass', 'class'])); +- // TODO(scheglov) This test does not work. +- // In "p.NoSuchClass" the identifier "p" is not resolved to a PrefixE= lement. +-// expect( +-// getVariableNameSuggestionsForExpression( +-// null, +-// findNodeAtString('new p.NoSuchClass()'), +-// excluded), +-// unorderedEquals(['noSuchClass', 'suchClass', 'class'])); +- } +- +- test_forExpression_invocationArgument_named() async { +- await resolveTestUnit(''' +-foo({a, b, c}) {} +-main() { +- foo(a: 111, c: 333, b: 222); +-} +-'''); +- var excluded =3D new Set.from([]); +- { +- var expr =3D findNodeAtString('111'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['a'])); +- } +- { +- var expr =3D findNodeAtString('222'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['b'])); +- } +- { +- var expr =3D findNodeAtString('333'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['c'])); +- } +- } +- +- test_forExpression_invocationArgument_optional() async { +- await resolveTestUnit(''' +-foo(a, [b =3D 2, c =3D 3]) {} +-main() { +- foo(111, 222, 333); +-} +-'''); +- var excluded =3D new Set.from([]); +- { +- var expr =3D findNodeAtString('111'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['a'])); +- } +- { +- var expr =3D findNodeAtString('222'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['b'])); +- } +- { +- var expr =3D findNodeAtString('333'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['c'])); +- } +- } +- +- test_forExpression_invocationArgument_positional() async { +- await resolveTestUnit(''' +-foo(a, b) {} +-main() { +- foo(111, 222); +-} +-'''); +- var excluded =3D new Set.from([]); +- { +- var expr =3D findNodeAtString('111'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['a'])); +- } +- { +- var expr =3D findNodeAtString('222'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded= ), +- unorderedEquals(['b'])); +- } +- } +- +- test_forExpression_methodInvocation() async { +- await resolveTestUnit(''' +-main(p) { +- var res =3D p.getSortedNodes(); +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('p.get', (node) =3D> node is MethodInvo= cation); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- test_forExpression_inBuildMethod() async { +- await resolveTestUnit(''' +-class A { +- void build() { +- List l =3D new List(); +- } +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('new List'); +- expect( +- getVariableNameSuggestionsForExpression(null, expr, excluded, +- isMethod: false), +- unorderedEquals(['list'])); +- expect( +- getVariableNameSuggestionsForExpression(null, expr, excluded, +- isMethod: true), +- unorderedEquals(['buildList'])); +- } +- +- test_forExpression_methodInvocation_noPrefix() async { +- await resolveTestUnit(''' +-main(p) { +- var res =3D p.sortedNodes(); +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('p.sorted', (node) =3D> node is MethodI= nvocation); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- test_forExpression_name_get() async { +- await resolveTestUnit(''' +-main(p) { +- var res =3D p.get(); +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('p.get', (node) =3D> node is MethodInvo= cation); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded), +- unorderedEquals([])); +- } +- +- test_forExpression_prefixedIdentifier() async { +- await resolveTestUnit(''' +-main(p) { +- var res =3D p.sortedNodes; +-} +-'''); +- var excluded =3D new Set.from([]); +- expect( +- getVariableNameSuggestionsForExpression( +- null, +- findNodeAtString('p.sorted', (node) =3D> node is PrefixedIden= tifier), +- excluded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- test_forExpression_privateName() async { +- await resolveTestUnit(''' +-main(p) { +- p._name; +- p._computeSuffix(); +-} +-'''); +- var excluded =3D new Set.from([]); +- expect( +- getVariableNameSuggestionsForExpression( +- null, +- findNodeAtString('p._name', (node) =3D> node is PrefixedIdent= ifier), +- excluded), +- unorderedEquals(['name'])); +- expect( +- getVariableNameSuggestionsForExpression( +- null, +- findNodeAtString('p._compute', (node) =3D> node is MethodInvo= cation), +- excluded), +- unorderedEquals(['computeSuffix', 'suffix'])); +- } +- +- test_forExpression_propertyAccess() async { +- await resolveTestUnit(''' +-main(p) { +- var res =3D p.q.sortedNodes; +-} +-'''); +- var excluded =3D new Set.from([]); +- PropertyAccess expression =3D +- findNodeAtString('p.q.sorted', (node) =3D> node is PropertyAccess= ); +- expect(getVariableNameSuggestionsForExpression(null, expression, excl= uded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- test_forExpression_simpleName() async { +- await resolveTestUnit(''' +-main(p) { +- var sortedNodes =3D null; +- var res =3D sortedNodes; +-} +-'''); +- var excluded =3D new Set.from([]); +- var expr =3D findNodeAtString('sortedNodes;'); +- expect(getVariableNameSuggestionsForExpression(null, expr, excluded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- test_forExpression_unqualifiedInvocation() async { +- await resolveTestUnit(''' +-getSortedNodes() =3D> []; +-main(p) { +- var res =3D getSortedNodes(); +-} +-'''); +- var excluded =3D new Set.from([]); +- expect( +- getVariableNameSuggestionsForExpression( +- null, +- findNodeAtString( +- 'getSortedNodes();', (node) =3D> node is MethodInvocation= ), +- excluded), +- unorderedEquals(['sortedNodes', 'nodes'])); +- } +- +- void test_forText() { +- { +- Set excluded =3D new Set.from([]); +- List suggestions =3D +- getVariableNameSuggestionsForText('Goodbye, cruel world!', excl= uded); +- expect(suggestions, +- unorderedEquals(['goodbyeCruelWorld', 'cruelWorld', 'world'])); +- } +- { +- Set excluded =3D new Set.from(['world']); +- List suggestions =3D +- getVariableNameSuggestionsForText('Goodbye, cruel world!', excl= uded); +- expect(suggestions, +- unorderedEquals(['goodbyeCruelWorld', 'cruelWorld', 'world2'])); +- } +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/organize_directi= ves_test.dart b/pkg/analysis_server/test/services/correction/organize_direc= tives_test.dart +deleted file mode 100644 +index 665cad67c04..00000000000 +--- a/pkg/analysis_server/test/services/correction/organize_directives_tes= t.dart ++++ /dev/null +@@ -1,321 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/organize_directiv= es.dart'; +-import 'package:analyzer/error/error.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- hide AnalysisError; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(OrganizeDirectivesTest); +- }); +-} +- +-@reflectiveTest +-class OrganizeDirectivesTest extends AbstractSingleUnitTest { +- List testErrors; +- +- test_keep_duplicateImports_withDifferentPrefix() async { +- await _computeUnitAndErrors(r''' +-import 'dart:async' as async1; +-import 'dart:async' as async2; +- +-main() { +- async1.Future f; +- async2.Stream s; +-}'''); +- // validate change +- _assertOrganize(r''' +-import 'dart:async' as async1; +-import 'dart:async' as async2; +- +-main() { +- async1.Future f; +- async2.Stream s; +-}''', removeUnresolved: true, removeUnused: true); +- } +- +- test_remove_duplicateImports() async { +- await _computeUnitAndErrors(r''' +-import 'dart:async'; +-import 'dart:async'; +- +-main() { +- Future f; +-}'''); +- // validate change +- _assertOrganize(r''' +-import 'dart:async'; +- +-main() { +- Future f; +-}''', removeUnresolved: true, removeUnused: true); +- } +- +- test_remove_duplicateImports_differentText_uri() async { +- await _computeUnitAndErrors(r''' +-import 'dart:async' as async; +-import "dart:async" as async; +- +-main() { +- async.Future f; +-}'''); +- // validate change +- _assertOrganize(r''' +-import 'dart:async' as async; +- +-main() { +- async.Future f; +-}''', removeUnresolved: true, removeUnused: true); +- } +- +- test_remove_duplicateImports_withSamePrefix() async { +- await _computeUnitAndErrors(r''' +-import 'dart:async' as async; +-import 'dart:async' as async; +- +-main() { +- async.Future f; +-}'''); +- // validate change +- _assertOrganize(r''' +-import 'dart:async' as async; +- +-main() { +- async.Future f; +-}''', removeUnresolved: true, removeUnused: true); +- } +- +- test_remove_unresolvedDirectives() async { +- addSource('/existing_part1.dart', 'part of lib;'); +- addSource('/existing_part2.dart', 'part of lib;'); +- await _computeUnitAndErrors(r''' +-library lib; +- +-import 'dart:async'; +-import 'dart:noSuchImportSdkLibrary'; +-import 'dart:math'; +-import 'package:noSuchImportPackage/andLib.dart'; +- +-export 'dart:noSuchExportSdkLibrary'; +-export 'dart:async'; +-export 'package:noSuchExportPackage/andLib.dart'; +-export 'dart:math'; +- +-part 'existing_part1.dart'; +-part 'no_such_part.dart'; +-part 'existing_part2.dart'; +- +-main() { +-} +-'''); +- // validate change +- _assertOrganize(r''' +-library lib; +- +-import 'dart:async'; +-import 'dart:math'; +- +-export 'dart:async'; +-export 'dart:math'; +- +-part 'existing_part1.dart'; +-part 'existing_part2.dart'; +- +-main() { +-} +-''', removeUnresolved: true); +- } +- +- test_remove_unusedImports() async { +- await _computeUnitAndErrors(r''' +-library lib; +- +-import 'dart:async'; +-import 'dart:math'; +-import 'dart:convert'; +-import 'dart:collection'; +- +-main() { +- print(PI); +- new HashMap(); +-} +-'''); +- // validate change +- _assertOrganize(r''' +-library lib; +- +-import 'dart:collection'; +-import 'dart:math'; +- +-main() { +- print(PI); +- new HashMap(); +-} +-''', removeUnused: true); +- } +- +- test_remove_unusedImports2() async { +- await _computeUnitAndErrors(r''' +-import 'dart:async'; +-import 'dart:math'; +- +-class A {} +- +-main() { +- Future f; +-}'''); +- // validate change +- _assertOrganize(r''' +-import 'dart:async'; +- +-class A {} +- +-main() { +- Future f; +-}''', removeUnresolved: true, removeUnused: true); +- } +- +- test_sort() async { +- await _computeUnitAndErrors(r''' +-library lib; +- +-export 'dart:bbb'; +-import 'dart:bbb'; +-export 'package:bbb/bbb.dart'; +-export 'http://bbb.com'; +-import 'bbb/bbb.dart'; +-export 'http://aaa.com'; +-import 'http://bbb.com'; +-export 'dart:aaa'; +-export 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +-export 'aaa/aaa.dart'; +-export 'bbb/bbb.dart'; +-import 'dart:aaa'; +-import 'package:aaa/aaa.dart'; +-import 'aaa/aaa.dart'; +-import 'http://aaa.com'; +-part 'bbb/bbb.dart'; +-part 'aaa/aaa.dart'; +- +-main() { +-} +-'''); +- // validate change +- _assertOrganize(r''' +-library lib; +- +-import 'dart:aaa'; +-import 'dart:bbb'; +- +-import 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +- +-import 'http://aaa.com'; +-import 'http://bbb.com'; +- +-import 'aaa/aaa.dart'; +-import 'bbb/bbb.dart'; +- +-export 'dart:aaa'; +-export 'dart:bbb'; +- +-export 'package:aaa/aaa.dart'; +-export 'package:bbb/bbb.dart'; +- +-export 'http://aaa.com'; +-export 'http://bbb.com'; +- +-export 'aaa/aaa.dart'; +-export 'bbb/bbb.dart'; +- +-part 'aaa/aaa.dart'; +-part 'bbb/bbb.dart'; +- +-main() { +-} +-'''); +- } +- +- test_sort_hasComments() async { +- await _computeUnitAndErrors(r''' +-// header +-library lib; +- +-import 'c.dart';// c +-import 'a.dart';// aa +-import 'b.dart';// bbb +- +-/** doc */ +-main() { +-} +-'''); +- // validate change +- _assertOrganize(r''' +-// header +-library lib; +- +-import 'a.dart'; +-import 'b.dart'; +-import 'c.dart'; +-// c +-// aa +-// bbb +- +-/** doc */ +-main() { +-} +-'''); +- } +- +- test_sort_imports_packageAndPath() async { +- await _computeUnitAndErrors(r''' +-library lib; +- +-import 'package:product.ui.api.bbb/manager1.dart'; +-import 'package:product.ui.api/entity2.dart'; +-import 'package:product.ui/entity.dart'; +-import 'package:product.ui.api.aaa/manager2.dart'; +-import 'package:product.ui.api/entity1.dart'; +-import 'package:product2.client/entity.dart'; +-'''); +- // validate change +- _assertOrganize(r''' +-library lib; +- +-import 'package:product.ui/entity.dart'; +-import 'package:product.ui.api/entity1.dart'; +-import 'package:product.ui.api/entity2.dart'; +-import 'package:product.ui.api.aaa/manager2.dart'; +-import 'package:product.ui.api.bbb/manager1.dart'; +-import 'package:product2.client/entity.dart'; +-'''); +- } +- +- void _assertOrganize(String expectedCode, +- {bool removeUnresolved: false, bool removeUnused: false}) { +- DirectiveOrganizer organizer =3D new DirectiveOrganizer( +- testCode, testUnit, testErrors, +- removeUnresolved: removeUnresolved, removeUnused: removeUnused); +- List edits =3D organizer.organize(); +- String result =3D SourceEdit.applySequence(testCode, edits); +- expect(result, expectedCode); +- } +- +- Future _computeUnitAndErrors(String code) async { +- addTestSource(code); +- AnalysisResult result =3D await driver.getResult(testSource.fullName); +- testUnit =3D result.unit; +- testErrors =3D result.errors; +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/sort_members_tes= t.dart b/pkg/analysis_server/test/services/correction/sort_members_test.dart +deleted file mode 100644 +index 341cb3b315a..00000000000 +--- a/pkg/analysis_server/test/services/correction/sort_members_test.dart ++++ /dev/null +@@ -1,810 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/sort_members.dart= '; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SortMembersTest); +- }); +-} +- +-@reflectiveTest +-class SortMembersTest extends AbstractSingleUnitTest { +- test_classMembers_accessor() async { +- await _parseTestUnit(r''' +-class A { +- set c(x) {} +- set a(x) {} +- get a =3D> null; +- get b =3D> null; +- set b(x) {} +- get c =3D> null; +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- get a =3D> null; +- set a(x) {} +- get b =3D> null; +- set b(x) {} +- get c =3D> null; +- set c(x) {} +-} +-'''); +- } +- +- test_classMembers_accessor_static() async { +- await _parseTestUnit(r''' +-class A { +- get a =3D> null; +- set a(x) {} +- static get b =3D> null; +- static set b(x) {} +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- static get b =3D> null; +- static set b(x) {} +- get a =3D> null; +- set a(x) {} +-} +-'''); +- } +- +- test_classMembers_constructor() async { +- await _parseTestUnit(r''' +-class A { +- A.c() { } +- A.a() { } +- A() {} +- A.b(); +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- A() {} +- A.a() { } +- A.b(); +- A.c() { } +-} +-'''); +- } +- +- test_classMembers_external_constructorMethod() async { +- await _parseTestUnit(r''' +-class Chart { +- external Pie(); +- external Chart(); +-} +-'''); +- // validate change +- _assertSort(r''' +-class Chart { +- external Chart(); +- external Pie(); +-} +-'''); +- } +- +- test_classMembers_field() async { +- await _parseTestUnit(r''' +-class A { +- String c; +- int a; +- void toString() =3D> null; +- double b; +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- String c; +- int a; +- double b; +- void toString() =3D> null; +-} +-'''); +- } +- +- test_classMembers_field_static() async { +- await _parseTestUnit(r''' +-class A { +- int b; +- int a; +- static int d; +- static int c; +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- static int d; +- static int c; +- int b; +- int a; +-} +-'''); +- } +- +- test_classMembers_method() async { +- await _parseTestUnit(r''' +-class A { +- c() {} +- a() {} +- b() {} +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- a() {} +- b() {} +- c() {} +-} +-'''); +- } +- +- test_classMembers_method_emptyLine() async { +- await _parseTestUnit(r''' +-class A { +- b() {} +- +- a() {} +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- a() {} +- +- b() {} +-} +-'''); +- } +- +- test_classMembers_method_ignoreCase() async { +- await _parseTestUnit(r''' +-class A { +- m_C() {} +- m_a() {} +- m_B() {} +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- m_a() {} +- m_B() {} +- m_C() {} +-} +-'''); +- } +- +- test_classMembers_method_static() async { +- await _parseTestUnit(r''' +-class A { +- static a() {} +- b() {} +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- b() {} +- static a() {} +-} +-'''); +- } +- +- test_classMembers_mix() async { +- await _parseTestUnit(r''' +-class A { +- /// static field public +- static int nnn; +- /// static field private +- static int _nnn; +- /// instance getter public +- int get nnn =3D> null; +- /// instance setter public +- set nnn(x) {} +- /// instance getter private +- int get _nnn =3D> null; +- /// instance setter private +- set _nnn(x) {} +- /// instance method public +- nnn() {} +- /// instance method private +- _nnn() {} +- /// static method public +- static nnn() {} +- /// static method private +- static _nnn() {} +- /// static getter public +- static int get nnn =3D> null; +- /// static setter public +- static set nnn(x) {} +- /// static getter private +- static int get _nnn =3D> null; +- /// static setter private +- static set _nnn(x) {} +- /// instance field public +- int nnn; +- /// instance field private +- int _nnn; +- /// constructor generative unnamed +- A(); +- /// constructor factory unnamed +- factory A() =3D> null; +- /// constructor generative public +- A.nnn(); +- /// constructor factory public +- factory A.ooo() =3D> null; +- /// constructor generative private +- A._nnn(); +- /// constructor factory private +- factory A._ooo() =3D> null; +-} +-'''); +- // validate change +- _assertSort(r''' +-class A { +- /// static field public +- static int nnn; +- /// static field private +- static int _nnn; +- /// static getter public +- static int get nnn =3D> null; +- /// static setter public +- static set nnn(x) {} +- /// static getter private +- static int get _nnn =3D> null; +- /// static setter private +- static set _nnn(x) {} +- /// instance field public +- int nnn; +- /// instance field private +- int _nnn; +- /// constructor generative unnamed +- A(); +- /// constructor factory unnamed +- factory A() =3D> null; +- /// constructor generative public +- A.nnn(); +- /// constructor factory public +- factory A.ooo() =3D> null; +- /// constructor generative private +- A._nnn(); +- /// constructor factory private +- factory A._ooo() =3D> null; +- /// instance getter public +- int get nnn =3D> null; +- /// instance setter public +- set nnn(x) {} +- /// instance getter private +- int get _nnn =3D> null; +- /// instance setter private +- set _nnn(x) {} +- /// instance method public +- nnn() {} +- /// instance method private +- _nnn() {} +- /// static method public +- static nnn() {} +- /// static method private +- static _nnn() {} +-} +-'''); +- } +- +- test_directives() async { +- await _parseTestUnit(r''' +-library lib; +- +-export 'dart:bbb'; +-import 'dart:bbb'; +-export 'package:bbb/bbb.dart'; +-export 'http://bbb.com'; +-import 'bbb/bbb.dart'; +-export 'http://aaa.com'; +-import 'http://bbb.com'; +-export 'dart:aaa'; +-export 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +-export 'aaa/aaa.dart'; +-export 'bbb/bbb.dart'; +-import 'dart:aaa'; +-import 'package:aaa/aaa.dart'; +-import 'aaa/aaa.dart'; +-import 'http://aaa.com'; +-part 'bbb/bbb.dart'; +-part 'aaa/aaa.dart'; +- +-main() { +-} +-'''); +- // validate change +- _assertSort(r''' +-library lib; +- +-import 'dart:aaa'; +-import 'dart:bbb'; +- +-import 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +- +-import 'http://aaa.com'; +-import 'http://bbb.com'; +- +-import 'aaa/aaa.dart'; +-import 'bbb/bbb.dart'; +- +-export 'dart:aaa'; +-export 'dart:bbb'; +- +-export 'package:aaa/aaa.dart'; +-export 'package:bbb/bbb.dart'; +- +-export 'http://aaa.com'; +-export 'http://bbb.com'; +- +-export 'aaa/aaa.dart'; +-export 'bbb/bbb.dart'; +- +-part 'aaa/aaa.dart'; +-part 'bbb/bbb.dart'; +- +-main() { +-} +-'''); +- } +- +- test_directives_docComment_hasLibrary_lines() async { +- await _parseTestUnit(r''' +-/// Library documentation comment A. +-/// Library documentation comment B. +-library foo.bar; +- +-/// bbb1 +-/// bbb2 +-/// bbb3 +-import 'b.dart'; +-/// aaa1 +-/// aaa2 +-import 'a.dart'; +-'''); +- // validate change +- _assertSort(r''' +-/// Library documentation comment A. +-/// Library documentation comment B. +-library foo.bar; +- +-/// aaa1 +-/// aaa2 +-import 'a.dart'; +-/// bbb1 +-/// bbb2 +-/// bbb3 +-import 'b.dart'; +-'''); +- } +- +- test_directives_docComment_hasLibrary_stars() async { +- await _parseTestUnit(r''' +-/** +- * Library documentation comment A. +- * Library documentation comment B. +- */ +-library foo.bar; +- +-/** +- * bbb +- */ +-import 'b.dart'; +-/** +- * aaa +- * aaa +- */ +-import 'a.dart'; +-'''); +- // validate change +- _assertSort(r''' +-/** +- * Library documentation comment A. +- * Library documentation comment B. +- */ +-library foo.bar; +- +-/** +- * aaa +- * aaa +- */ +-import 'a.dart'; +-/** +- * bbb +- */ +-import 'b.dart'; +-'''); +- } +- +- test_directives_docComment_noLibrary_lines() async { +- await _parseTestUnit(r''' +-/// Library documentation comment A +-/// Library documentation comment B +-import 'b.dart'; +-/// aaa1 +-/// aaa2 +-import 'a.dart'; +-'''); +- // validate change +- _assertSort(r''' +-/// aaa1 +-/// aaa2 +-/// Library documentation comment A +-/// Library documentation comment B +-import 'a.dart'; +-import 'b.dart'; +-'''); +- } +- +- test_directives_docComment_noLibrary_stars() async { +- await _parseTestUnit(r''' +-/** +- * Library documentation comment A. +- * Library documentation comment B. +- */ +-import 'b.dart'; +-/** +- * aaa +- * aaa +- */ +-import 'a.dart'; +-'''); +- // validate change +- _assertSort(r''' +-/** +- * aaa +- * aaa +- */ +-/** +- * Library documentation comment A. +- * Library documentation comment B. +- */ +-import 'a.dart'; +-import 'b.dart'; +-'''); +- } +- +- test_directives_imports_packageAndPath() async { +- await _parseTestUnit(r''' +-library lib; +- +-import 'package:product.ui.api.bbb/manager1.dart'; +-import 'package:product.ui.api/entity2.dart'; +-import 'package:product.ui/entity.dart'; +-import 'package:product.ui.api.aaa/manager2.dart'; +-import 'package:product.ui.api/entity1.dart'; +-import 'package:product2.client/entity.dart'; +-'''); +- // validate change +- _assertSort(r''' +-library lib; +- +-import 'package:product.ui/entity.dart'; +-import 'package:product.ui.api/entity1.dart'; +-import 'package:product.ui.api/entity2.dart'; +-import 'package:product.ui.api.aaa/manager2.dart'; +-import 'package:product.ui.api.bbb/manager1.dart'; +-import 'package:product2.client/entity.dart'; +-'''); +- } +- +- test_unitMembers_class() async { +- await _parseTestUnit(r''' +-class C {} +-class A {} +-class B {} +-'''); +- // validate change +- _assertSort(r''' +-class A {} +-class B {} +-class C {} +-'''); +- } +- +- test_unitMembers_class_ignoreCase() async { +- await _parseTestUnit(r''' +-class C {} +-class a {} +-class B {} +-'''); +- // validate change +- _assertSort(r''' +-class a {} +-class B {} +-class C {} +-'''); +- } +- +- test_unitMembers_classTypeAlias() async { +- await _parseTestUnit(r''' +-class M {} +-class C =3D Object with M; +-class A =3D Object with M; +-class B =3D Object with M; +-'''); +- // validate change +- _assertSort(r''' +-class A =3D Object with M; +-class B =3D Object with M; +-class C =3D Object with M; +-class M {} +-'''); +- } +- +- test_unitMembers_directive_hasDirective() async { +- await _parseTestUnit(r''' +-library lib; +-class C {} +-class A {} +-class B {} +-'''); +- // validate change +- _assertSort(r''' +-library lib; +-class A {} +-class B {} +-class C {} +-'''); +- } +- +- test_unitMembers_directive_noDirective_hasComment_line() async { +- await _parseTestUnit(r''' +-// Some comment +- +-class B {} +- +-class A {} +-'''); +- // validate change +- _assertSort(r''' +-// Some comment +- +-class A {} +- +-class B {} +-'''); +- } +- +- test_unitMembers_directive_noDirective_noComment() async { +- await _parseTestUnit(r''' +- +-class B {} +- +-class A {} +-'''); +- // validate change +- _assertSort(r''' +- +-class A {} +- +-class B {} +-'''); +- } +- +- test_unitMembers_enum() async { +- await _parseTestUnit(r''' +-enum C {x, y} +-enum A {x, y} +-enum B {x, y} +-'''); +- // validate change +- _assertSort(r''' +-enum A {x, y} +-enum B {x, y} +-enum C {x, y} +-'''); +- } +- +- test_unitMembers_enumClass() async { +- await _parseTestUnit(r''' +-enum C {x, y} +-class A {} +-class D {} +-enum B {x, y} +-'''); +- // validate change +- _assertSort(r''' +-class A {} +-enum B {x, y} +-enum C {x, y} +-class D {} +-'''); +- } +- +- test_unitMembers_function() async { +- await _parseTestUnit(r''' +-fc() {} +-fa() {} +-fb() {} +-'''); +- // validate change +- _assertSort(r''' +-fa() {} +-fb() {} +-fc() {} +-'''); +- } +- +- test_unitMembers_functionTypeAlias() async { +- await _parseTestUnit(r''' +-typedef FC(); +-typedef FA(); +-typedef FB(); +-'''); +- // validate change +- _assertSort(r''' +-typedef FA(); +-typedef FB(); +-typedef FC(); +-'''); +- } +- +- test_unitMembers_importsAndDeclarations() async { +- await _parseTestUnit(r''' +-import 'dart:a'; +-import 'package:b'; +- +-foo() { +-} +- +-f() =3D> null; +-'''); +- // validate change +- _assertSort(r''' +-import 'dart:a'; +- +-import 'package:b'; +- +-f() =3D> null; +- +-foo() { +-} +-'''); +- } +- +- test_unitMembers_mainFirst() async { +- await _parseTestUnit(r''' +-class C {} +-aaa() {} +-get bbb() {} +-class A {} +-main() {} +-class B {} +-'''); +- // validate change +- _assertSort(r''' +-main() {} +-get bbb() {} +-aaa() {} +-class A {} +-class B {} +-class C {} +-'''); +- } +- +- test_unitMembers_mix() async { +- await _parseTestUnit(r''' +-_mmm() {} +-typedef nnn(); +-_nnn() {} +-typedef mmm(); +-typedef _nnn(); +-typedef _mmm(); +-class mmm {} +-get _nnn =3D> null; +-class nnn {} +-class _mmm {} +-class _nnn {} +-var mmm; +-var nnn; +-var _mmm; +-var _nnn; +-set nnn(x) {} +-get mmm =3D> null; +-set mmm(x) {} +-get nnn =3D> null; +-get _mmm =3D> null; +-set _mmm(x) {} +-set _nnn(x) {} +-mmm() {} +-nnn() {} +-'''); +- // validate change +- _assertSort(r''' +-var mmm; +-var nnn; +-var _mmm; +-var _nnn; +-get mmm =3D> null; +-set mmm(x) {} +-get nnn =3D> null; +-set nnn(x) {} +-get _mmm =3D> null; +-set _mmm(x) {} +-get _nnn =3D> null; +-set _nnn(x) {} +-mmm() {} +-nnn() {} +-_mmm() {} +-_nnn() {} +-typedef mmm(); +-typedef nnn(); +-typedef _mmm(); +-typedef _nnn(); +-class mmm {} +-class nnn {} +-class _mmm {} +-class _nnn {} +-'''); +- } +- +- test_unitMembers_topLevelVariable() async { +- await _parseTestUnit(r''' +-int c; +-int a; +-int b; +-'''); +- // validate change +- _assertSort(r''' +-int a; +-int b; +-int c; +-'''); +- } +- +- test_unitMembers_topLevelVariable_withConst() async { +- await _parseTestUnit(r''' +-int c; +-int a; +-const B =3D 2; +-int b; +-const A =3D 1; +-'''); +- // validate change +- _assertSort(r''' +-const A =3D 1; +-const B =3D 2; +-int a; +-int b; +-int c; +-'''); +- } +- +- void _assertSort(String expectedCode) { +- MemberSorter sorter =3D new MemberSorter(testCode, testUnit); +- List edits =3D sorter.sort(); +- String result =3D SourceEdit.applySequence(testCode, edits); +- expect(result, expectedCode); +- } +- +- Future _parseTestUnit(String code) async { +- addTestSource(code); +- ParseResult result =3D await driver.parseFile(testSource.fullName); +- testUnit =3D result.unit; +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/status_test.dart= b/pkg/analysis_server/test/services/correction/status_test.dart +deleted file mode 100644 +index 041ee1e1704..00000000000 +--- a/pkg/analysis_server/test/services/correction/status_test.dart ++++ /dev/null +@@ -1,235 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analysis_server/src/services/search/search_engine_interna= l.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/utilities/range_factory.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RefactoringLocationTest); +- defineReflectiveTests(RefactoringStatusTest); +- }); +-} +- +-@reflectiveTest +-class RefactoringLocationTest extends AbstractSingleUnitTest { +- test_createLocation_forElement() async { +- await resolveTestUnit('class MyClass {}'); +- Element element =3D findElement('MyClass'); +- // check +- Location location =3D newLocation_fromElement(element); +- expect(location.file, '/test.dart'); +- expect(location.offset, 6); +- expect(location.length, 7); +- expect(location.startLine, 1); +- expect(location.startColumn, 7); +- } +- +- test_createLocation_forMatch() async { +- await resolveTestUnit('class MyClass {}'); +- Element element =3D findElement('MyClass'); +- SourceRange sourceRange =3D range.elementName(element); +- SearchMatch match =3D new SearchMatchImpl( +- element.source.fullName, +- element.library.source, +- element.source, +- element.library, +- element, +- true, +- false, +- MatchKind.DECLARATION, +- sourceRange); +- // check +- Location location =3D newLocation_fromMatch(match); +- expect(location.file, '/test.dart'); +- expect(location.offset, sourceRange.offset); +- expect(location.length, sourceRange.length); +- } +- +- test_createLocation_forNode() async { +- await resolveTestUnit(''' +-main() { +-} +-'''); +- AstNode node =3D findNodeAtString('main'); +- // check +- Location location =3D newLocation_fromNode(node); +- expect(location.file, '/test.dart'); +- expect(location.offset, node.offset); +- expect(location.length, node.length); +- } +- +- test_createLocation_forUnit() async { +- await resolveTestUnit(''); +- SourceRange sourceRange =3D new SourceRange(10, 20); +- // check +- Location location =3D newLocation_fromUnit(testUnit, sourceRange); +- expect(location.file, '/test.dart'); +- expect(location.offset, sourceRange.offset); +- expect(location.length, sourceRange.length); +- } +-} +- +-@reflectiveTest +-class RefactoringStatusTest { +- void test_addError() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- // initial state +- expect(refactoringStatus.severity, null); +- // add ERROR +- refactoringStatus.addError('msg'); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.ERROR); +- expect(refactoringStatus.isOK, isFalse); +- expect(refactoringStatus.hasFatalError, isFalse); +- expect(refactoringStatus.hasError, isTrue); +- // problems +- List problems =3D refactoringStatus.problems; +- expect(problems, hasLength(1)); +- expect(problems[0].message, 'msg'); +- } +- +- void test_addFatalError_withLocation() { +- Location location =3D new Location('/test.dart', 1, 2, 3, 4); +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- // initial state +- expect(refactoringStatus.severity, null); +- // add FATAL +- refactoringStatus.addFatalError('msg', location); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.FATAL); +- expect(refactoringStatus.isOK, isFalse); +- expect(refactoringStatus.hasFatalError, isTrue); +- expect(refactoringStatus.hasError, isTrue); +- // problems +- List problems =3D refactoringStatus.problems; +- expect(problems, hasLength(1)); +- expect(problems[0].message, 'msg'); +- expect(problems[0].location.file, '/test.dart'); +- expect(problems[0].location.offset, 1); +- expect(problems[0].location.length, 2); +- // add WARNING, resulting severity is still FATAL +- refactoringStatus.addWarning("warning"); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.FATAL); +- } +- +- void test_addFatalError_withoutContext() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- // initial state +- expect(refactoringStatus.severity, null); +- // add FATAL +- refactoringStatus.addFatalError('msg'); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.FATAL); +- expect(refactoringStatus.isOK, isFalse); +- expect(refactoringStatus.hasFatalError, isTrue); +- expect(refactoringStatus.hasError, isTrue); +- // problems +- List problems =3D refactoringStatus.problems; +- expect(problems, hasLength(1)); +- expect(problems[0].message, 'msg'); +- expect(problems[0].location, isNull); +- } +- +- void test_addStatus_Error_withWarning() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- refactoringStatus.addError("err"); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.ERROR); +- // merge with OK +- { +- RefactoringStatus other =3D new RefactoringStatus(); +- other.addWarning("warn"); +- refactoringStatus.addStatus(other); +- } +- expect(refactoringStatus.severity, RefactoringProblemSeverity.ERROR); +- expect(refactoringStatus.message, 'err'); +- } +- +- void test_addStatus_Warning_null() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- refactoringStatus.addWarning("warn"); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.WARNING= ); +- // merge with "null" +- refactoringStatus.addStatus(null); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.WARNING= ); +- } +- +- void test_addStatus_Warning_withError() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- refactoringStatus.addWarning("warn"); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.WARNING= ); +- // merge with OK +- { +- RefactoringStatus other =3D new RefactoringStatus(); +- other.addError("err"); +- refactoringStatus.addStatus(other); +- } +- expect(refactoringStatus.severity, RefactoringProblemSeverity.ERROR); +- expect(refactoringStatus.message, 'err'); +- } +- +- void test_addWarning() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- // initial state +- expect(refactoringStatus.severity, null); +- // add WARNING +- refactoringStatus.addWarning('msg'); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.WARNING= ); +- expect(refactoringStatus.isOK, isFalse); +- expect(refactoringStatus.hasFatalError, isFalse); +- expect(refactoringStatus.hasError, isFalse); +- expect(refactoringStatus.hasWarning, isTrue); +- // problems +- List problems =3D refactoringStatus.problems; +- expect(problems, hasLength(1)); +- expect(problems[0].message, 'msg'); +- } +- +- void test_get_problem() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus(); +- // no entries +- expect(refactoringStatus.problem, isNull); +- expect(refactoringStatus.message, isNull); +- // add entries +- refactoringStatus.addError('msgError'); +- refactoringStatus.addWarning('msgWarning'); +- refactoringStatus.addFatalError('msgFatalError'); +- // get entry +- { +- RefactoringProblem problem =3D refactoringStatus.problem; +- expect(problem.severity, RefactoringProblemSeverity.FATAL); +- expect(problem.message, 'msgFatalError'); +- } +- // get message +- expect(refactoringStatus.problem.message, 'msgFatalError'); +- } +- +- void test_newError() { +- Location location =3D new Location('/test.dart', 1, 2, 3, 4); +- RefactoringStatus refactoringStatus =3D +- new RefactoringStatus.error('msg', location); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.ERROR); +- expect(refactoringStatus.problem.message, 'msg'); +- expect(refactoringStatus.problem.location.file, '/test.dart'); +- } +- +- void test_newFatalError() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus.fatal('= msg'); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.FATAL); +- expect(refactoringStatus.message, 'msg'); +- } +- +- void test_newWarning() { +- RefactoringStatus refactoringStatus =3D new RefactoringStatus.warning= ('msg'); +- expect(refactoringStatus.severity, RefactoringProblemSeverity.WARNING= ); +- expect(refactoringStatus.message, 'msg'); +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/strings_test.dar= t b/pkg/analysis_server/test/services/correction/strings_test.dart +deleted file mode 100644 +index abd449379e1..00000000000 +--- a/pkg/analysis_server/test/services/correction/strings_test.dart ++++ /dev/null +@@ -1,175 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/strings.dart'; +-import 'package:test/test.dart' hide isEmpty; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(StringsTest); +- }); +-} +- +-@reflectiveTest +-class StringsTest { +- void test_capitalize() { +- expect(capitalize(''), ''); +- expect(capitalize('a'), 'A'); +- expect(capitalize('abc'), 'Abc'); +- expect(capitalize('abc def'), 'Abc def'); +- expect(capitalize('ABC'), 'ABC'); +- } +- +- void test_compareStrings() { +- expect(compareStrings(null, null), 0); +- expect(compareStrings(null, 'b'), 1); +- expect(compareStrings('a', null), -1); +- expect(compareStrings('a', 'b'), -1); +- expect(compareStrings('b', 'a'), 1); +- } +- +- void test_computeSimpleDiff() { +- assertDiff(String oldStr, String newStr) { +- SimpleDiff diff =3D computeSimpleDiff(oldStr, newStr); +- expect(diff.offset, isNonNegative); +- expect(diff.length, isNonNegative); +- String applied =3D oldStr.substring(0, diff.offset) + +- diff.replacement + +- oldStr.substring(diff.offset + diff.length); +- expect(applied, newStr); +- } +- +- assertDiff('', ''); +- assertDiff('', 'a'); +- assertDiff('abc', ''); +- assertDiff('abcd', 'acd'); +- assertDiff('a', 'b'); +- assertDiff('12345xyz', '12345abcxyz'); +- assertDiff('12345xyz', '12345xyzabc'); +- assertDiff('abbc', 'abbbc'); +- assertDiff('abbbbc', 'abbbbbbc'); +- } +- +- void test_countMatches() { +- expect(countMatches(null, null), 0); +- expect(countMatches('abc', null), 0); +- expect(countMatches(null, 'abc'), 0); +- expect(countMatches('ababa', 'a'), 3); +- expect(countMatches('ababa', 'ab'), 2); +- expect(countMatches('aaabaa', 'aa'), 2); +- } +- +- void test_findCommonPrefix() { +- expect(findCommonPrefix('abc', 'xyz'), 0); +- expect(findCommonPrefix('1234abcdef', '1234xyz'), 4); +- expect(findCommonPrefix('123', '123xyz'), 3); +- } +- +- void test_findCommonSuffix() { +- expect(findCommonSuffix('abc', 'xyz'), 0); +- expect(findCommonSuffix('abcdef1234', 'xyz1234'), 4); +- expect(findCommonSuffix('123', 'xyz123'), 3); +- } +- +- void test_isBlank() { +- expect(isBlank(null), isTrue); +- expect(isBlank(''), isTrue); +- expect(isBlank(' '), isTrue); +- expect(isBlank('\t'), isTrue); +- expect(isBlank(' '), isTrue); +- expect(isBlank('X'), isFalse); +- } +- +- void test_isDigit() { +- for (int c in '0123456789'.codeUnits) { +- expect(isDigit(c), isTrue); +- } +- expect(isDigit(' '.codeUnitAt(0)), isFalse); +- expect(isDigit('A'.codeUnitAt(0)), isFalse); +- } +- +- void test_isLetter() { +- for (int c in 'abcdefghijklmnopqrstuvwxyz'.codeUnits) { +- expect(isLetter(c), isTrue); +- } +- for (int c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.codeUnits) { +- expect(isLetter(c), isTrue); +- } +- expect(isLetter(' '.codeUnitAt(0)), isFalse); +- expect(isLetter('0'.codeUnitAt(0)), isFalse); +- } +- +- void test_isLetterOrDigit() { +- for (int c in 'abcdefghijklmnopqrstuvwxyz'.codeUnits) { +- expect(isLetterOrDigit(c), isTrue); +- } +- for (int c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.codeUnits) { +- expect(isLetterOrDigit(c), isTrue); +- } +- for (int c in '0123456789'.codeUnits) { +- expect(isLetterOrDigit(c), isTrue); +- } +- expect(isLetterOrDigit(' '.codeUnitAt(0)), isFalse); +- expect(isLetterOrDigit('.'.codeUnitAt(0)), isFalse); +- } +- +- void test_isSpace() { +- expect(isSpace(' '.codeUnitAt(0)), isTrue); +- expect(isSpace('\t'.codeUnitAt(0)), isTrue); +- expect(isSpace('\r'.codeUnitAt(0)), isFalse); +- expect(isSpace('\n'.codeUnitAt(0)), isFalse); +- expect(isSpace('0'.codeUnitAt(0)), isFalse); +- expect(isSpace('A'.codeUnitAt(0)), isFalse); +- } +- +- void test_isWhitespace() { +- expect(isWhitespace(' '.codeUnitAt(0)), isTrue); +- expect(isWhitespace('\t'.codeUnitAt(0)), isTrue); +- expect(isWhitespace('\r'.codeUnitAt(0)), isTrue); +- expect(isWhitespace('\n'.codeUnitAt(0)), isTrue); +- expect(isWhitespace('0'.codeUnitAt(0)), isFalse); +- expect(isWhitespace('A'.codeUnitAt(0)), isFalse); +- } +- +- void test_remove() { +- expect(remove(null, 'x'), null); +- expect(remove('abc', null), 'abc'); +- expect(remove('abc abbc abbbc', 'b'), 'ac ac ac'); +- expect(remove('abc abbc abbbc', 'bc'), 'a ab abb'); +- } +- +- void test_removeEnd() { +- expect(removeEnd(null, 'x'), null); +- expect(removeEnd('abc', null), 'abc'); +- expect(removeEnd('www.domain.com', '.com.'), 'www.domain.com'); +- expect(removeEnd('www.domain.com', 'domain'), 'www.domain.com'); +- expect(removeEnd('www.domain.com', '.com'), 'www.domain'); +- } +- +- void test_repeat() { +- expect(repeat('x', 0), ''); +- expect(repeat('x', 5), 'xxxxx'); +- expect(repeat('abc', 3), 'abcabcabc'); +- } +- +- void test_shorten() { +- expect(shorten('', 10), ''); +- expect(shorten('0', 10), '0'); +- expect(shorten('012', 10), '012'); +- expect(shorten('0123456789', 10), '0123456789'); +- expect(shorten('0123456789abcd', 10), '0123...bcd'); +- expect(shorten('0123456789abcde', 10), '0123...cde'); +- expect(shorten('0123456789abcdef', 10), '0123...def'); +- expect(shorten('0123456789abcdef', 11), '0123...cdef'); +- expect(shorten('0123456789abcdef', 12), '01234...cdef'); +- } +- +- void test_substringAfterLast() { +- expect(substringAfterLast('', '/'), ''); +- expect(substringAfterLast('abc', ''), ''); +- expect(substringAfterLast('abc', 'd'), 'abc'); +- expect(substringAfterLast('abcbde', 'b'), 'de'); +- } +-} +diff --git a/pkg/analysis_server/test/services/correction/test_all.dart b/= pkg/analysis_server/test/services/correction/test_all.dart +deleted file mode 100644 +index 4183ef1a9d3..00000000000 +--- a/pkg/analysis_server/test/services/correction/test_all.dart ++++ /dev/null +@@ -1,32 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'assist_test.dart' as assist_test; +-import 'change_test.dart' as change_test; +-import 'fix_test.dart' as fix_test; +-import 'levenshtein_test.dart' as levenshtein_test; +-import 'name_suggestion_test.dart' as name_suggestion_test; +-import 'organize_directives_test.dart' as organize_directives_test; +-import 'sort_members_test.dart' as sort_members_test; +-import 'status_test.dart' as status_test; +-import 'strings_test.dart' as strings_test; +-import 'util_test.dart' as util_test; +- +-/// Utility for manually running all tests. +-main() { +- defineReflectiveSuite(() { +- assist_test.main(); +- change_test.main(); +- fix_test.main(); +- levenshtein_test.main(); +- name_suggestion_test.main(); +- organize_directives_test.main(); +- sort_members_test.main(); +- status_test.main(); +- strings_test.main(); +- util_test.main(); +- }, name: 'correction'); +-} +diff --git a/pkg/analysis_server/test/services/correction/util_test.dart b= /pkg/analysis_server/test/services/correction/util_test.dart +deleted file mode 100644 +index 1589df0d629..00000000000 +--- a/pkg/analysis_server/test/services/correction/util_test.dart ++++ /dev/null +@@ -1,252 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/util.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/src/utilities/string_utilities.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(UtilTest); +- }); +-} +- +-@reflectiveTest +-class UtilTest extends AbstractSingleUnitTest { +- test_addLibraryImports_dart_hasImports_between() async { +- await resolveTestUnit(''' +-import 'dart:async'; +-import 'dart:math'; +-'''); +- Source newLibrary =3D _getDartSource('dart:collection'); +- _assertAddLibraryImport([newLibrary], ''' +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:math'; +-'''); +- } +- +- test_addLibraryImports_dart_hasImports_first() async { +- await resolveTestUnit(''' +-import 'dart:collection'; +-import 'dart:math'; +-'''); +- Source newLibrary =3D _getDartSource('dart:async'); +- _assertAddLibraryImport([newLibrary], ''' +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:math'; +-'''); +- } +- +- test_addLibraryImports_dart_hasImports_last() async { +- await resolveTestUnit(''' +-import 'dart:async'; +-import 'dart:collection'; +-'''); +- Source newLibrary =3D _getDartSource('dart:math'); +- _assertAddLibraryImport([newLibrary], ''' +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:math'; +-'''); +- } +- +- test_addLibraryImports_dart_hasImports_multiple() async { +- await resolveTestUnit(''' +-import 'dart:collection'; +-import 'dart:math'; +-'''); +- Source newLibrary1 =3D _getDartSource('dart:async'); +- Source newLibrary2 =3D _getDartSource('dart:html'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:html'; +-import 'dart:math'; +-'''); +- } +- +- test_addLibraryImports_dart_hasImports_multiple_first() async { +- await resolveTestUnit(''' +-import 'dart:html'; +-import 'dart:math'; +-'''); +- Source newLibrary1 =3D _getDartSource('dart:async'); +- Source newLibrary2 =3D _getDartSource('dart:collection'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:html'; +-import 'dart:math'; +-'''); +- } +- +- test_addLibraryImports_dart_hasImports_multiple_last() async { +- await resolveTestUnit(''' +-import 'dart:async'; +-import 'dart:collection'; +-'''); +- Source newLibrary1 =3D _getDartSource('dart:html'); +- Source newLibrary2 =3D _getDartSource('dart:math'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:html'; +-import 'dart:math'; +-'''); +- } +- +- test_addLibraryImports_dart_hasLibraryDirective() async { +- await resolveTestUnit(''' +-library test; +- +-class A {} +-'''); +- Source newLibrary1 =3D _getDartSource('dart:math'); +- Source newLibrary2 =3D _getDartSource('dart:async'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-library test; +- +-import 'dart:async'; +-import 'dart:math'; +- +-class A {} +-'''); +- } +- +- test_addLibraryImports_dart_noDirectives_hasComment() async { +- await resolveTestUnit(''' +-/// Comment. +- +-class A {} +-'''); +- Source newLibrary1 =3D _getDartSource('dart:math'); +- Source newLibrary2 =3D _getDartSource('dart:async'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-/// Comment. +- +-import 'dart:async'; +-import 'dart:math'; +- +-class A {} +-'''); +- } +- +- test_addLibraryImports_dart_noDirectives_hasShebang() async { +- await resolveTestUnit(''' +-#!/bin/dart +- +-class A {} +-'''); +- Source newLibrary1 =3D _getDartSource('dart:math'); +- Source newLibrary2 =3D _getDartSource('dart:async'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-#!/bin/dart +- +-import 'dart:async'; +-import 'dart:math'; +- +-class A {} +-'''); +- } +- +- test_addLibraryImports_dart_noDirectives_noShebang() async { +- await resolveTestUnit(''' +-class A {} +-'''); +- Source newLibrary1 =3D _getDartSource('dart:math'); +- Source newLibrary2 =3D _getDartSource('dart:async'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-import 'dart:async'; +-import 'dart:math'; +- +-class A {} +-'''); +- } +- +- test_addLibraryImports_package_hasDart_hasPackages_insertAfter() async { +- addPackageSource('aaa', 'aaa.dart', ''); +- await resolveTestUnit(''' +-import 'dart:async'; +- +-import 'package:aaa/aaa.dart'; +-'''); +- Source newLibrary =3D _getSource('/lib/bbb.dart', 'package:bbb/bbb.da= rt'); +- _assertAddLibraryImport([newLibrary], ''' +-import 'dart:async'; +- +-import 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +-'''); +- } +- +- test_addLibraryImports_package_hasDart_hasPackages_insertBefore() async= { +- addPackageSource('bbb', 'bbb.dart', ''); +- await resolveTestUnit(''' +-import 'dart:async'; +- +-import 'package:bbb/bbb.dart'; +-'''); +- Source newLibrary =3D _getSource('/lib/aaa.dart', 'package:aaa/aaa.da= rt'); +- _assertAddLibraryImport([newLibrary], ''' +-import 'dart:async'; +- +-import 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +-'''); +- } +- +- test_addLibraryImports_package_hasImports_between() async { +- addPackageSource('aaa', 'aaa.dart', ''); +- addPackageSource('ddd', 'ddd.dart', ''); +- await resolveTestUnit(''' +-import 'package:aaa/aaa.dart'; +-import 'package:ddd/ddd.dart'; +-'''); +- Source newLibrary1 =3D _getSource('/lib/bbb.dart', 'package:bbb/bbb.d= art'); +- Source newLibrary2 =3D _getSource('/lib/ccc.dart', 'package:ccc/ccc.d= art'); +- _assertAddLibraryImport([newLibrary1, newLibrary2], ''' +-import 'package:aaa/aaa.dart'; +-import 'package:bbb/bbb.dart'; +-import 'package:ccc/ccc.dart'; +-import 'package:ddd/ddd.dart'; +-'''); +- } +- +- void _assertAddLibraryImport(List newLibraries, String expected= Code) { +- SourceChange change =3D new SourceChange(''); +- addLibraryImports(change, testLibraryElement, newLibraries.toSet()); +- SourceFileEdit testEdit =3D change.getFileEdit(testFile); +- expect(testEdit, isNotNull); +- String resultCode =3D SourceEdit.applySequence(testCode, testEdit.edi= ts); +- expect(resultCode, expectedCode); +- } +- +- Source _getDartSource(String uri) { +- String path =3D removeStart(uri, 'dart:'); +- return new _SourceMock('/sdk/lib/$path.dart', Uri.parse(uri)); +- } +- +- Source _getSource(String path, String uri) { +- return new _SourceMock(path, Uri.parse(uri)); +- } +-} +- +-class _SourceMock implements Source { +- @override +- final String fullName; +- +- @override +- final Uri uri; +- +- _SourceMock(this.fullName, this.uri); +- +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +-} +diff --git a/pkg/analysis_server/test/services/linter/linter_test.dart b/p= kg/analysis_server/test/services/linter/linter_test.dart +deleted file mode 100644 +index c88c48a5dec..00000000000 +--- a/pkg/analysis_server/test/services/linter/linter_test.dart ++++ /dev/null +@@ -1,79 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/analyzer.dart'; +-import 'package:analyzer/source/analysis_options_provider.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/lint/options_rule_validator.dart'; +-import 'package:linter/src/rules.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(LinterRuleOptionsValidatorTest); +- }); +-} +- +-@reflectiveTest +-class LinterRuleOptionsValidatorTest { +- final LinterRuleOptionsValidator validator =3D new LinterRuleOptionsVal= idator(); +- final AnalysisOptionsProvider optionsProvider =3D new AnalysisOptionsPr= ovider(); +- +- RecordingErrorListener recorder; +- ErrorReporter reporter; +- +- List get errors =3D> recorder.errors; +- +- setUp() { +- registerLintRules(); +- recorder =3D new RecordingErrorListener(); +- reporter =3D new ErrorReporter(recorder, new _TestSource()); +- } +- +- test_linter_defined_rules() { +- validate(''' +-linter: +- rules: +- - camel_case_types +- ''', []); +- } +- +- test_linter_no_rules() { +- validate(''' +-linter: +- rules: +- ''', []); +- } +- +- test_linter_null_rule() { +- validate(''' +-linter: +- rules: +- - +- +- ''', []); +- } +- +- test_linter_undefined_rule() { +- validate(''' +-linter: +- rules: +- - undefined +- ''', [UNDEFINED_LINT_WARNING]); +- } +- +- validate(String source, List expected) { +- var options =3D optionsProvider.getOptionsFromString(source); +- validator.validate(reporter, options); +- expect(errors.map((AnalysisError e) =3D> e.errorCode), +- unorderedEquals(expected)); +- } +-} +- +-class _TestSource implements Source { +- @override +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +-} +diff --git a/pkg/analysis_server/test/services/linter/test_all.dart b/pkg/= analysis_server/test/services/linter/test_all.dart +deleted file mode 100644 +index 270b1a41391..00000000000 +--- a/pkg/analysis_server/test/services/linter/test_all.dart ++++ /dev/null +@@ -1,13 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'linter_test.dart' as linter_test; +- +-main() { +- defineReflectiveSuite(() { +- linter_test.main(); +- }, name: 'linter'); +-} +diff --git a/pkg/analysis_server/test/services/refactoring/abstract_refact= oring.dart b/pkg/analysis_server/test/services/refactoring/abstract_refacto= ring.dart +deleted file mode 100644 +index afdd053c871..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/abstract_refactoring.d= art ++++ /dev/null +@@ -1,175 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analysis_server/src/services/search/search_engine_interna= l.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart' show Element; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/ast_provider_driver.dart'; +-import 'package:analyzer/src/dart/element/ast_provider.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show +- RefactoringProblem, +- RefactoringProblemSeverity, +- SourceChange, +- SourceEdit, +- SourceFileEdit; +-import 'package:test/test.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-int findIdentifierLength(String search) { +- int length =3D 0; +- while (length < search.length) { +- int c =3D search.codeUnitAt(length); +- if (!(c >=3D 'a'.codeUnitAt(0) && c <=3D 'z'.codeUnitAt(0) || +- c >=3D 'A'.codeUnitAt(0) && c <=3D 'Z'.codeUnitAt(0) || +- c >=3D '0'.codeUnitAt(0) && c <=3D '9'.codeUnitAt(0))) { +- break; +- } +- length++; +- } +- return length; +-} +- +-/** +- * The base class for all [Refactoring] tests. +- */ +-abstract class RefactoringTest extends AbstractSingleUnitTest { +- SearchEngine searchEngine; +- AstProvider astProvider; +- +- SourceChange refactoringChange; +- +- Refactoring get refactoring; +- +- /** +- * Asserts that [refactoringChange] contains a [FileEdit] for the file +- * with the given [path], and it results the [expectedCode]. +- */ +- void assertFileChangeResult(String path, String expectedCode) { +- // prepare FileEdit +- SourceFileEdit fileEdit =3D refactoringChange.getFileEdit(path); +- expect(fileEdit, isNotNull, reason: 'No file edit for $path'); +- // validate resulting code +- File file =3D provider.getResource(path); +- String ini =3D file.readAsStringSync(); +- String actualCode =3D SourceEdit.applySequence(ini, fileEdit.edits); +- expect(actualCode, expectedCode); +- } +- +- /** +- * Asserts that [refactoringChange] does not contain a [FileEdit] for t= he file +- * with the given [path]. +- */ +- void assertNoFileChange(String path) { +- SourceFileEdit fileEdit =3D refactoringChange.getFileEdit(path); +- expect(fileEdit, isNull); +- } +- +- /** +- * Asserts that [refactoring] initial/final conditions status is OK. +- */ +- Future assertRefactoringConditionsOK() async { +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatusOK(status); +- status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- /** +- * Asserts that [refactoring] final conditions status is OK. +- */ +- Future assertRefactoringFinalConditionsOK() async { +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- /** +- * Asserts that [status] has expected severity and message. +- */ +- void assertRefactoringStatus( +- RefactoringStatus status, RefactoringProblemSeverity expectedSeveri= ty, +- {String expectedMessage, +- SourceRange expectedContextRange, +- String expectedContextSearch}) { +- expect(status.severity, expectedSeverity, reason: status.toString()); +- if (expectedSeverity !=3D null) { +- RefactoringProblem problem =3D status.problem; +- expect(problem.severity, expectedSeverity); +- if (expectedMessage !=3D null) { +- expect(problem.message, expectedMessage); +- } +- if (expectedContextRange !=3D null) { +- expect(problem.location.offset, expectedContextRange.offset); +- expect(problem.location.length, expectedContextRange.length); +- } +- if (expectedContextSearch !=3D null) { +- int expectedOffset =3D findOffset(expectedContextSearch); +- int expectedLength =3D findIdentifierLength(expectedContextSearch= ); +- expect(problem.location.offset, expectedOffset); +- expect(problem.location.length, expectedLength); +- } +- } +- } +- +- /** +- * Asserts that [refactoring] status is OK. +- */ +- void assertRefactoringStatusOK(RefactoringStatus status) { +- assertRefactoringStatus(status, null); +- } +- +- /** +- * Checks that all conditions of [refactoring] are OK and the result of +- * applying the [Change] to [testUnit] is [expectedCode]. +- */ +- Future assertSuccessfulRefactoring(String expectedCode) async { +- await assertRefactoringConditionsOK(); +- SourceChange change =3D await refactoring.createChange(); +- this.refactoringChange =3D change; +- assertTestChangeResult(expectedCode); +- } +- +- /** +- * Asserts that [refactoringChange] contains a [FileEdit] for [testFile= ], and +- * it results the [expectedCode]. +- */ +- void assertTestChangeResult(String expectedCode) { +- // prepare FileEdit +- SourceFileEdit fileEdit =3D refactoringChange.getFileEdit(testFile); +- expect(fileEdit, isNotNull); +- // validate resulting code +- String actualCode =3D SourceEdit.applySequence(testCode, fileEdit.edi= ts); +- expect(actualCode, expectedCode); +- } +- +- /** +- * Completes with a fully resolved unit that contains the [element]. +- */ +- Future getResolvedUnitWithElement(Element element) asy= nc { +- return element.context +- .resolveCompilationUnit(element.source, element.library); +- } +- +- Future indexTestUnit(String code) async { +- await resolveTestUnit(code); +- } +- +- Future indexUnit(String file, String code) async { +- addSource(file, code); +- } +- +- void setUp() { +- super.setUp(); +- searchEngine =3D new SearchEngineImpl([driver]); +- astProvider =3D new AstProviderForDriver(driver); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/abstract_rename= .dart b/pkg/analysis_server/test/services/refactoring/abstract_rename.dart +deleted file mode 100644 +index 3d8633cf3a3..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/abstract_rename.dart ++++ /dev/null +@@ -1,75 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/namespace.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +-import 'package:test/test.dart'; +- +-import 'abstract_refactoring.dart'; +- +-/** +- * The base class for all [RenameRefactoring] tests. +- */ +-class RenameRefactoringTest extends RefactoringTest { +- RenameRefactoring refactoring; +- +- /** +- * Asserts that [refactoring] has potential edits in [testFile] at offs= et +- * of the given [searches]. +- */ +- void assertPotentialEdits(List searches) { +- Set expectedOffsets =3D new Set(); +- for (String search in searches) { +- int offset =3D findOffset(search); +- expectedOffsets.add(offset); +- } +- // remove offset marked as potential +- for (String potentialId in refactoring.potentialEditIds) { +- SourceEdit edit =3D findEditById(potentialId); +- expect(edit, isNotNull); +- expectedOffsets.remove(edit.offset); +- } +- // all potential offsets are marked as such +- expect(expectedOffsets, isEmpty); +- } +- +- /** +- * Creates a new [RenameRefactoring] in [refactoring] for the [Element]= of +- * the [SimpleIdentifier] at the given [search] pattern. +- */ +- void createRenameRefactoringAtString(String search) { +- SimpleIdentifier identifier =3D findIdentifier(search); +- Element element =3D identifier.bestElement; +- if (element is PrefixElement) { +- element =3D getImportElement(identifier); +- } +- createRenameRefactoringForElement(element); +- } +- +- /** +- * Creates a new [RenameRefactoring] in [refactoring] for [element]. +- * Fails if no [RenameRefactoring] can be created. +- */ +- void createRenameRefactoringForElement(Element element) { +- refactoring =3D new RenameRefactoring(searchEngine, astProvider, elem= ent); +- expect(refactoring, isNotNull, reason: "No refactoring for '$element'= ."); +- } +- +- /** +- * Returns the [Edit] with the given [id], maybe `null`. +- */ +- SourceEdit findEditById(String id) { +- for (SourceFileEdit fileEdit in refactoringChange.edits) { +- for (SourceEdit edit in fileEdit.edits) { +- if (edit.id =3D=3D id) { +- return edit; +- } +- } +- } +- return null; +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/convert_getter_= to_method_test.dart b/pkg/analysis_server/test/services/refactoring/convert= _getter_to_method_test.dart +deleted file mode 100644 +index 7712c7dbd6c..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/convert_getter_to_meth= od_test.dart ++++ /dev/null +@@ -1,163 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= ntKind; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ConvertGetterToMethodTest); +- }); +-} +- +-@reflectiveTest +-class ConvertGetterToMethodTest extends RefactoringTest { +- ConvertGetterToMethodRefactoring refactoring; +- +- test_change_function() async { +- await indexTestUnit(''' +-int get test =3D> 42; +-main() { +- var a =3D test; +- var b =3D test; +-} +-'''); +- _createRefactoring('test'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int test() =3D> 42; +-main() { +- var a =3D test(); +- var b =3D test(); +-} +-'''); +- } +- +- test_change_method() async { +- await indexTestUnit(''' +-class A { +- int get test =3D> 1; +-} +-class B extends A { +- int get test =3D> 2; +-} +-class C extends B { +- int get test =3D> 3; +-} +-class D extends A { +- int get test =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test; +- var vb =3D b.test; +- var vc =3D c.test; +- var vd =3D d.test; +-} +-'''); +- _createRefactoringForString('test =3D> 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- int test() =3D> 1; +-} +-class B extends A { +- int test() =3D> 2; +-} +-class C extends B { +- int test() =3D> 3; +-} +-class D extends A { +- int test() =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test(); +- var vb =3D b.test(); +- var vc =3D c.test(); +- var vd =3D d.test(); +-} +-'''); +- } +- +- test_change_multipleFiles() async { +- await indexUnit('/other.dart', r''' +-class A { +- int get test =3D> 1; +-} +-'''); +- await indexTestUnit(''' +-import 'other.dart'; +-class B extends A { +- int get test =3D> 2; +-} +-main(A a, B b) { +- a.test; +- b.test; +-} +-'''); +- _createRefactoringForString('test =3D> 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'other.dart'; +-class B extends A { +- int test() =3D> 2; +-} +-main(A a, B b) { +- a.test(); +- b.test(); +-} +-'''); +- } +- +- test_checkInitialConditions_syntheticGetter() async { +- await indexTestUnit(''' +-int test =3D 42; +-main() { +-} +-'''); +- _createRefactoring('test'); +- // check conditions +- _assertInitialConditions_fatal( +- 'Only explicit getters can be converted to methods.'); +- } +- +- Future _assertInitialConditions_fatal(String message) async { +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: message); +- } +- +- /** +- * Checks that all conditions are OK and the result of applying [refact= oring] +- * change to [testUnit] is [expectedCode]. +- */ +- Future _assertSuccessfulRefactoring(String expectedCode) async { +- await assertRefactoringConditionsOK(); +- SourceChange refactoringChange =3D await refactoring.createChange(); +- this.refactoringChange =3D refactoringChange; +- assertTestChangeResult(expectedCode); +- } +- +- void _createRefactoring(String elementName) { +- PropertyAccessorElement element =3D +- findElement(elementName, ElementKind.GETTER); +- _createRefactoringForElement(element); +- } +- +- void _createRefactoringForElement(ExecutableElement element) { +- refactoring =3D new ConvertGetterToMethodRefactoring( +- searchEngine, astProvider, element); +- } +- +- void _createRefactoringForString(String search) { +- ExecutableElement element =3D findNodeElementAtString(search); +- _createRefactoringForElement(element); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/convert_method_= to_getter_test.dart b/pkg/analysis_server/test/services/refactoring/convert= _method_to_getter_test.dart +deleted file mode 100644 +index e9cb4d892eb..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/convert_method_to_gett= er_test.dart ++++ /dev/null +@@ -1,215 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/src/generated/testing/element_search.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show RefactoringProblemSeverity, SourceChange; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ConvertMethodToGetterTest); +- }); +-} +- +-@reflectiveTest +-class ConvertMethodToGetterTest extends RefactoringTest { +- ConvertMethodToGetterRefactoring refactoring; +- +- test_change_function() async { +- await indexTestUnit(''' +-int test() =3D> 42; +-main() { +- var a =3D test(); +- var b =3D test(); +-} +-'''); +- _createRefactoring('test'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int get test =3D> 42; +-main() { +- var a =3D test; +- var b =3D test; +-} +-'''); +- } +- +- test_change_method() async { +- await indexTestUnit(''' +-class A { +- int test() =3D> 1; +-} +-class B extends A { +- int test() =3D> 2; +-} +-class C extends B { +- int test() =3D> 3; +-} +-class D extends A { +- int test() =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test(); +- var vb =3D b.test(); +- var vc =3D c.test(); +- var vd =3D d.test(); +-} +-'''); +- _createRefactoringForString('test() =3D> 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- int get test =3D> 1; +-} +-class B extends A { +- int get test =3D> 2; +-} +-class C extends B { +- int get test =3D> 3; +-} +-class D extends A { +- int get test =3D> 4; +-} +-main(A a, B b, C c, D d) { +- var va =3D a.test; +- var vb =3D b.test; +- var vc =3D c.test; +- var vd =3D d.test; +-} +-'''); +- } +- +- test_change_multipleFiles() async { +- await indexUnit('/other.dart', r''' +-class A { +- int test() =3D> 1; +-} +-'''); +- await indexTestUnit(''' +-import 'other.dart'; +-class B extends A { +- int test() =3D> 2; +-} +-main(A a, B b) { +- a.test(); +- b.test(); +-} +-'''); +- _createRefactoringForString('test() =3D> 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'other.dart'; +-class B extends A { +- int get test =3D> 2; +-} +-main(A a, B b) { +- a.test; +- b.test; +-} +-'''); +- } +- +- test_checkInitialConditions_alreadyGetter() async { +- await indexTestUnit(''' +-int get test =3D> 42; +-main() { +- var a =3D test; +- var b =3D test; +-} +-'''); +- ExecutableElement element =3D findElement('test', ElementKind.GETTER); +- _createRefactoringForElement(element); +- // check conditions +- _assertInitialConditions_fatal( +- 'Only class methods or top-level functions can be converted to ge= tters.'); +- } +- +- test_checkInitialConditions_hasParameters() async { +- await indexTestUnit(''' +-int test(x) =3D> x * 2; +-main() { +- var v =3D test(1); +-} +-'''); +- _createRefactoring('test'); +- // check conditions +- _assertInitialConditions_fatal( +- 'Only methods without parameters can be converted to getters.'); +- } +- +- test_checkInitialConditions_localFunction() async { +- await indexTestUnit(''' +-main() { +- test() {} +- var v =3D test(); +-} +-'''); +- ExecutableElement element =3D findElementsByName(testUnit, 'test').si= ngle; +- _createRefactoringForElement(element); +- // check conditions +- _assertInitialConditions_fatal( +- 'Only top-level functions can be converted to getters.'); +- } +- +- test_checkInitialConditions_notFunctionOrMethod() async { +- await indexTestUnit(''' +-class A { +- A.test(); +-} +-'''); +- _createRefactoring('test'); +- // check conditions +- _assertInitialConditions_fatal( +- 'Only class methods or top-level functions can be converted to ge= tters.'); +- } +- +- test_checkInitialConditions_returnTypeVoid() async { +- await indexTestUnit(''' +-void test() {} +-'''); +- _createRefactoring('test'); +- // check conditions +- _assertInitialConditions_fatal('Cannot convert function returning voi= d.'); +- } +- +- Future _assertInitialConditions_fatal(String message) async { +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: message); +- } +- +- /** +- * Checks that all conditions are OK and the result of applying the [Ch= ange] +- * to [testUnit] is [expectedCode]. +- */ +- Future _assertSuccessfulRefactoring(String expectedCode) async { +- await assertRefactoringConditionsOK(); +- SourceChange refactoringChange =3D await refactoring.createChange(); +- this.refactoringChange =3D refactoringChange; +- assertTestChangeResult(expectedCode); +- } +- +- void _createRefactoring(String elementName) { +- ExecutableElement element =3D findElement(elementName); +- _createRefactoringForElement(element); +- } +- +- void _createRefactoringForElement(ExecutableElement element) { +- refactoring =3D new ConvertMethodToGetterRefactoring( +- searchEngine, astProvider, element); +- } +- +- void _createRefactoringForString(String search) { +- ExecutableElement element =3D findNodeElementAtString(search); +- _createRefactoringForElement(element); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/extract_local_t= est.dart b/pkg/analysis_server/test/services/refactoring/extract_local_test= .dart +deleted file mode 100644 +index 03a65f233b3..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/extract_local_test.dart ++++ /dev/null +@@ -1,1346 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/extract_local.da= rt'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ExtractLocalTest); +- }); +-} +- +-@reflectiveTest +-class ExtractLocalTest extends RefactoringTest { +- ExtractLocalRefactoringImpl refactoring; +- +- test_checkFinalConditions_sameVariable_after() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +- var res; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // conflicting name +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "The name 'res' is already used in the scope."); +- } +- +- test_checkFinalConditions_sameVariable_before() async { +- await indexTestUnit(''' +-main() { +- var res; +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // conflicting name +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "The name 'res' is already used in the scope."); +- } +- +- test_checkInitialConditions_assignmentLeftHandSize() async { +- await indexTestUnit(''' +-main() { +- var v =3D 0; +- v =3D 1; +-} +-'''); +- _createRefactoringWithSuffix('v', ' =3D 1;'); +- // check conditions +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: 'Cannot extract the left-hand side of an assignm= ent.'); +- } +- +- test_checkInitialConditions_namePartOfDeclaration_function() async { +- await indexTestUnit(''' +-main() { +-} +-'''); +- _createRefactoringWithSuffix('main', '()'); +- // check conditions +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: 'Cannot extract the name part of a declaration.'= ); +- } +- +- test_checkInitialConditions_namePartOfDeclaration_variable() async { +- await indexTestUnit(''' +-main() { +- int vvv =3D 0; +-} +-'''); +- _createRefactoringWithSuffix('vvv', ' =3D 0;'); +- // check conditions +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: 'Cannot extract the name part of a declaration.'= ); +- } +- +- test_checkInitialConditions_noExpression() async { +- await indexTestUnit(''' +-main() { +- // abc +-} +-'''); +- _createRefactoringForString('abc'); +- // check conditions +- _assertInitialConditions_fatal_selection(); +- } +- +- test_checkInitialConditions_notPartOfFunction() async { +- await indexTestUnit(''' +-int a =3D 1 + 2; +-'''); +- _createRefactoringForString('1 + 2'); +- // check conditions +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: 'An expression inside a function must be selecte= d ' +- 'to activate this refactoring.'); +- } +- +- test_checkInitialConditions_stringSelection_leadingQuote() async { +- await indexTestUnit(''' +-main() { +- var vvv =3D 'abc'; +-} +-'''); +- _createRefactoringForString("'a"); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 'abc'; +- var vvv =3D res; +-} +-'''); +- } +- +- test_checkInitialConditions_stringSelection_trailingQuote() async { +- await indexTestUnit(''' +-main() { +- var vvv =3D 'abc'; +-} +-'''); +- _createRefactoringForString("c'"); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 'abc'; +- var vvv =3D res; +-} +-'''); +- } +- +- test_checkInitialConditions_voidExpression() async { +- await indexTestUnit(''' +-main() { +- print(42); +-} +-'''); +- _createRefactoringForString('print'); +- // check conditions +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: 'Cannot extract the void expression.'); +- } +- +- test_checkName() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- expect(refactoring.refactoringName, 'Extract Local Variable'); +- // null +- refactoring.name =3D null; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be null."); +- // empty +- refactoring.name =3D ''; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be empty."); +- // OK +- refactoring.name =3D 'res'; +- assertRefactoringStatusOK(refactoring.checkName()); +- } +- +- test_checkName_conflict_withInvokedFunction() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +- res(); +-} +- +-void res() {} +-'''); +- _createRefactoringForString('1 + 2'); +- await refactoring.checkInitialConditions(); +- refactoring.name =3D 'res'; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.ERROR, +- expectedMessage: "The name 'res' is already used in the scope."); +- } +- +- test_checkName_conflict_withOtherLocal() async { +- await indexTestUnit(''' +-main() { +- var res; +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- await refactoring.checkInitialConditions(); +- refactoring.name =3D 'res'; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.ERROR, +- expectedMessage: "The name 'res' is already used in the scope."); +- } +- +- test_checkName_conflict_withTypeName() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +- Res b =3D null; +-} +- +-class Res {} +-'''); +- _createRefactoringForString('1 + 2'); +- await refactoring.checkInitialConditions(); +- refactoring.name =3D 'Res'; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.ERROR, +- expectedMessage: "The name 'Res' is already used in the scope."); +- } +- +- test_completeStatementExpression() async { +- await indexTestUnit(''' +-main(p) { +- p.toString(); +-} +-'''); +- _createRefactoringForString('p.toString()'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(p) { +- var res =3D p.toString(); +-} +-'''); +- } +- +- test_const_argument_inConstInstanceCreation() async { +- await indexTestUnit(''' +-class A { +- const A(int a, int b); +-} +-main() { +- const A(1, 2); +-} +-'''); +- _createRefactoringForString('1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- const A(int a, int b); +-} +-main() { +- const res =3D 1; +- const A(res, 2); +-} +-'''); +- } +- +- test_const_inList() async { +- await indexTestUnit(''' +-main() { +- const [1, 2]; +-} +-'''); +- _createRefactoringForString('1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D 1; +- const [res, 2]; +-} +-'''); +- } +- +- test_const_inList_inBinaryExpression() async { +- await indexTestUnit(''' +-main() { +- const [1 + 2, 3]; +-} +-'''); +- _createRefactoringForString('1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D 1; +- const [res + 2, 3]; +-} +-'''); +- } +- +- test_const_inList_inConditionalExpression() async { +- await indexTestUnit(''' +-main() { +- const [true ? 1 : 2, 3]; +-} +-'''); +- _createRefactoringForString('1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D 1; +- const [true ? res : 2, 3]; +-} +-'''); +- } +- +- test_const_inList_inParenthesis() async { +- await indexTestUnit(''' +-main() { +- const [(1), 2]; +-} +-'''); +- _createRefactoringForString('1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D 1; +- const [(res), 2]; +-} +-'''); +- } +- +- test_const_inList_inPrefixExpression() async { +- await indexTestUnit(''' +-main() { +- const [!true, 2]; +-} +-'''); +- _createRefactoringForString('true'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D true; +- const [!res, 2]; +-} +-'''); +- } +- +- test_const_inMap_key() async { +- await indexTestUnit(''' +-main() { +- const {1: 2}; +-} +-'''); +- _createRefactoringForString('1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D 1; +- const {res: 2}; +-} +-'''); +- } +- +- test_const_inMap_value() async { +- await indexTestUnit(''' +-main() { +- const {1: 2}; +-} +-'''); +- _createRefactoringForString('2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- const res =3D 2; +- const {1: res}; +-} +-'''); +- } +- +- test_coveringExpressions() async { +- await indexTestUnit(''' +-main() { +- int aaa =3D 1; +- int bbb =3D 2; +- var c =3D aaa + bbb * 2 + 3; +-} +-'''); +- _createRefactoring(testCode.indexOf('bb * 2'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, +- ['bbb', 'bbb * 2', 'aaa + bbb * 2', 'aaa + bbb * 2 + 3']); +- } +- +- test_coveringExpressions_inArgumentList() async { +- await indexTestUnit(''' +-main() { +- foo(111 + 222); +-} +-int foo(int x) =3D> x; +-'''); +- _createRefactoring(testCode.indexOf('11 +'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['111', '111 + 222', 'foo(111 + 222)']); +- } +- +- test_coveringExpressions_inInvocationOfVoidFunction() async { +- await indexTestUnit(''' +-main() { +- foo(111 + 222); +-} +-void foo(int x) {} +-'''); +- _createRefactoring(testCode.indexOf('11 +'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['111', '111 + 222']); +- } +- +- test_coveringExpressions_namedExpression_value() async { +- await indexTestUnit(''' +-main() { +- foo(ppp: 42); +-} +-int foo({int ppp: 0}) =3D> ppp + 1; +-'''); +- _createRefactoring(testCode.indexOf('42'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['42', 'foo(ppp: 42)']); +- } +- +- test_coveringExpressions_skip_assignment() async { +- await indexTestUnit(''' +-main() { +- int v; +- foo(v =3D 111 + 222); +-} +-int foo(x) =3D> 42; +-'''); +- _createRefactoring(testCode.indexOf('11 +'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['111', '111 + 222', 'foo(v =3D 111 + 222)']); +- } +- +- test_coveringExpressions_skip_constructorName() async { +- await indexTestUnit(''' +-class AAA { +- AAA.name() {} +-} +-main() { +- var v =3D new AAA.name(); +-} +-'''); +- _createRefactoring(testCode.indexOf('AA.name();'), 5); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['new AAA.name()']); +- } +- +- test_coveringExpressions_skip_constructorName_name() async { +- await indexTestUnit(''' +-class A { +- A.name() {} +-} +-main() { +- var v =3D new A.name(); +-} +-'''); +- _createRefactoring(testCode.indexOf('ame();'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['new A.name()']); +- } +- +- test_coveringExpressions_skip_constructorName_type() async { +- await indexTestUnit(''' +-class A {} +-main() { +- var v =3D new A(); +-} +-'''); +- _createRefactoring(testCode.indexOf('A();'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['new A()']); +- } +- +- test_coveringExpressions_skip_constructorName_typeArgument() async { +- await indexTestUnit(''' +-class A {} +-main() { +- var v =3D new A(); +-} +-'''); +- _createRefactoring(testCode.indexOf('ring>'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['new A()']); +- } +- +- test_coveringExpressions_skip_namedExpression() async { +- await indexTestUnit(''' +-main() { +- foo(ppp: 42); +-} +-int foo({int ppp: 0}) =3D> ppp + 1; +-'''); +- _createRefactoring(testCode.indexOf('pp: 42'), 0); +- // check conditions +- await refactoring.checkInitialConditions(); +- List subExpressions =3D _getCoveringExpressions(); +- expect(subExpressions, ['foo(ppp: 42)']); +- } +- +- test_fragmentExpression() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString('2 + 3'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2 + 3; +- int a =3D res + 4; +-} +-'''); +- } +- +- test_fragmentExpression_leadingNotWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString('+ 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2; +- int a =3D res + 3 + 4; +-} +-'''); +- } +- +- test_fragmentExpression_leadingPartialSelection() async { +- await indexTestUnit(''' +-main() { +- int a =3D 111 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString('11 + 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 111 + 2; +- int a =3D res + 3 + 4; +-} +-'''); +- } +- +- test_fragmentExpression_leadingWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString(' 2 + 3'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2 + 3; +- int a =3D res + 4; +-} +-'''); +- } +- +- test_fragmentExpression_notAssociativeOperator() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 - 2 - 3 - 4; +-} +-'''); +- _createRefactoringForString('2 - 3'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 - 2 - 3; +- int a =3D res - 4; +-} +-'''); +- } +- +- test_fragmentExpression_trailingNotWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString('1 + 2 +'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2 + 3; +- int a =3D res + 4; +-} +-'''); +- } +- +- test_fragmentExpression_trailingPartialSelection() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 333 + 4; +-} +-'''); +- _createRefactoringForString('2 + 33'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2 + 333; +- int a =3D res + 4; +-} +-'''); +- } +- +- test_fragmentExpression_trailingWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString('2 + 3 '); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2 + 3; +- int a =3D res + 4; +-} +-'''); +- } +- +- test_guessNames_fragmentExpression() async { +- await indexTestUnit(''' +-main() { +- var a =3D 111 + 222 + 333 + 444; +-} +-'''); +- _createRefactoringForString('222 + 333'); +- // check guesses +- await refactoring.checkInitialConditions(); +- expect(refactoring.names, unorderedEquals(['i'])); +- } +- +- test_guessNames_singleExpression() async { +- await indexTestUnit(''' +-class TreeItem {} +-TreeItem getSelectedItem() =3D> null; +-process(my) {} +-main() { +- process(getSelectedItem()); // marker +-} +-'''); +- _createRefactoringWithSuffix('getSelectedItem()', '); // marker'); +- // check guesses +- await refactoring.checkInitialConditions(); +- expect(refactoring.names, +- unorderedEquals(['selectedItem', 'item', 'my', 'treeItem'])); +- } +- +- test_guessNames_stringPart() async { +- await indexTestUnit(''' +-main() { +- var s =3D 'Hello Bob... welcome to Dart!'; +-} +-'''); +- _createRefactoringForString('Hello Bob'); +- // check guesses +- await refactoring.checkInitialConditions(); +- expect(refactoring.names, unorderedEquals(['helloBob', 'bob'])); +- } +- +- test_occurrences_differentVariable() async { +- await indexTestUnit(''' +-main() { +- { +- int v =3D 1; +- print(v + 1); // marker +- print(v + 1); +- } +- { +- int v =3D 2; +- print(v + 1); +- } +-} +-'''); +- _createRefactoringWithSuffix('v + 1', '); // marker'); +- // apply refactoring +- await _assertSuccessfulRefactoring(''' +-main() { +- { +- int v =3D 1; +- var res =3D v + 1; +- print(res); // marker +- print(res); +- } +- { +- int v =3D 2; +- print(v + 1); +- } +-} +-'''); +- _assertSingleLinkedEditGroup( +- length: 3, offsets: [36, 59, 85], names: ['object', 'i']); +- } +- +- test_occurrences_disableOccurrences() async { +- await indexTestUnit(''' +-int foo() =3D> 42; +-main() { +- int a =3D 1 + foo(); +- int b =3D 2 + foo(); // marker +-} +-'''); +- _createRefactoringWithSuffix('foo()', '; // marker'); +- refactoring.extractAll =3D false; +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int foo() =3D> 42; +-main() { +- int a =3D 1 + foo(); +- var res =3D foo(); +- int b =3D 2 + res; // marker +-} +-'''); +- } +- +- test_occurrences_ignore_assignmentLeftHandSize() async { +- await indexTestUnit(''' +-main() { +- int v =3D 1; +- v =3D 2; +- print(() {v =3D 2;}); +- print(1 + (() {v =3D 2; return 3;})()); +- print(v); // marker +-} +-'''); +- _createRefactoringWithSuffix('v', '); // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v =3D 1; +- v =3D 2; +- print(() {v =3D 2;}); +- print(1 + (() {v =3D 2; return 3;})()); +- var res =3D v; +- print(res); // marker +-} +-'''); +- } +- +- test_occurrences_ignore_nameOfVariableDeclaration() async { +- await indexTestUnit(''' +-main() { +- int v =3D 1; +- print(v); // marker +-} +-'''); +- _createRefactoringWithSuffix('v', '); // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v =3D 1; +- var res =3D v; +- print(res); // marker +-} +-'''); +- } +- +- test_occurrences_singleExpression() async { +- await indexTestUnit(''' +-int foo() =3D> 42; +-main() { +- int a =3D 1 + foo(); +- int b =3D 2 + foo(); // marker +-} +-'''); +- _createRefactoringWithSuffix('foo()', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int foo() =3D> 42; +-main() { +- var res =3D foo(); +- int a =3D 1 + res; +- int b =3D 2 + res; // marker +-} +-'''); +- } +- +- test_occurrences_useDominator() async { +- await indexTestUnit(''' +-main() { +- if (true) { +- print(42); +- } else { +- print(42); +- } +-} +-'''); +- _createRefactoringForString('42'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 42; +- if (true) { +- print(res); +- } else { +- print(res); +- } +-} +-'''); +- } +- +- test_occurrences_whenComment() async { +- await indexTestUnit(''' +-int foo() =3D> 42; +-main() { +- /*int a =3D 1 + foo();*/ +- int b =3D 2 + foo(); // marker +-} +-'''); +- _createRefactoringWithSuffix('foo()', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int foo() =3D> 42; +-main() { +- /*int a =3D 1 + foo();*/ +- var res =3D foo(); +- int b =3D 2 + res; // marker +-} +-'''); +- } +- +- test_occurrences_withSpace() async { +- await indexTestUnit(''' +-int foo(String s) =3D> 42; +-main() { +- int a =3D 1 + foo('has space'); +- int b =3D 2 + foo('has space'); // marker +-} +-'''); +- _createRefactoringWithSuffix("foo('has space')", '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int foo(String s) =3D> 42; +-main() { +- var res =3D foo('has space'); +- int a =3D 1 + res; +- int b =3D 2 + res; // marker +-} +-'''); +- } +- +- test_offsets_lengths() async { +- await indexTestUnit(''' +-int foo() =3D> 42; +-main() { +- int a =3D 1 + foo(); // marker +- int b =3D 2 + foo( ); +-} +-'''); +- _createRefactoringWithSuffix('foo()', '; // marker'); +- // check offsets +- await refactoring.checkInitialConditions(); +- expect(refactoring.offsets, +- unorderedEquals([findOffset('foo();'), findOffset('foo( );')])); +- expect(refactoring.lengths, unorderedEquals([5, 6])); +- } +- +- test_singleExpression() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2; +- int a =3D res; +-} +-'''); +- } +- +- test_singleExpression_getter() async { +- await indexTestUnit(''' +-class A { +- int get foo =3D> 42; +-} +-main() { +- A a =3D new A(); +- int b =3D 1 + a.foo; // marker +-} +-'''); +- _createRefactoringWithSuffix('a.foo', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- int get foo =3D> 42; +-} +-main() { +- A a =3D new A(); +- var res =3D a.foo; +- int b =3D 1 + res; // marker +-} +-'''); +- } +- +- test_singleExpression_hasParseError_expectedSemicolon() async { +- verifyNoTestUnitErrors =3D false; +- await indexTestUnit(''' +-main(p) { +- foo +- p.bar.baz; +-} +-'''); +- _createRefactoringForString('p.bar'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(p) { +- foo +- var res =3D p.bar; +- res.baz; +-} +-'''); +- } +- +- test_singleExpression_inExpressionBody_ofClosure() async { +- await indexTestUnit(''' +-main() { +- print((x) =3D> x.y * x.y + 1); +-} +-'''); +- _createRefactoringForString('x.y'); +- // apply refactoring +- await _assertSuccessfulRefactoring(''' +-main() { +- print((x) { +- var res =3D x.y; +- return res * res + 1; +- }); +-} +-'''); +- _assertSingleLinkedEditGroup( +- length: 3, offsets: [31, 53, 59], names: ['y']); +- } +- +- test_singleExpression_inExpressionBody_ofFunction() async { +- await indexTestUnit(''' +-foo(Point p) =3D> p.x * p.x + p.y * p.y; +-class Point {int x; int y;} +-'''); +- _createRefactoringForString('p.x'); +- // apply refactoring +- await _assertSuccessfulRefactoring(''' +-foo(Point p) { +- var res =3D p.x; +- return res * res + p.y * p.y; +-} +-class Point {int x; int y;} +-'''); +- _assertSingleLinkedEditGroup( +- length: 3, offsets: [21, 41, 47], names: ['x', 'i']); +- } +- +- test_singleExpression_inExpressionBody_ofMethod() async { +- await indexTestUnit(''' +-class A { +- foo(Point p) =3D> p.x * p.x + p.y * p.y; +-} +-class Point {int x; int y;} +-'''); +- _createRefactoringForString('p.x'); +- // apply refactoring +- await _assertSuccessfulRefactoring(''' +-class A { +- foo(Point p) { +- var res =3D p.x; +- return res * res + p.y * p.y; +- } +-} +-class Point {int x; int y;} +-'''); +- _assertSingleLinkedEditGroup( +- length: 3, offsets: [35, 57, 63], names: ['x', 'i']); +- } +- +- test_singleExpression_inIfElseIf() async { +- await indexTestUnit(''' +-main(int p) { +- if (p =3D=3D 1) { +- print(1); +- } else if (p =3D=3D 2) { +- print(2); +- } +-} +-'''); +- _createRefactoringForString('2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(int p) { +- var res =3D 2; +- if (p =3D=3D 1) { +- print(1); +- } else if (p =3D=3D res) { +- print(res); +- } +-} +-'''); +- } +- +- test_singleExpression_inMethod() async { +- await indexTestUnit(''' +-class A { +- main() { +- print(1 + 2); +- } +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- main() { +- var res =3D 1 + 2; +- print(res); +- } +-} +-'''); +- } +- +- test_singleExpression_leadingNotWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 12 + 345; +-} +-'''); +- _createRefactoringForString('+ 345'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 12 + 345; +- int a =3D res; +-} +-'''); +- } +- +- test_singleExpression_leadingWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 /*abc*/ + 2 + 345; +-} +-'''); +- _createRefactoringForString('1 /*abc*/'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 /*abc*/ + 2; +- int a =3D res + 345; +-} +-'''); +- } +- +- test_singleExpression_methodName_reference() async { +- await indexTestUnit(''' +-main() { +- var v =3D foo().length; +-} +-String foo() =3D> ''; +-'''); +- _createRefactoringWithSuffix('foo', '().'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D foo(); +- var v =3D res.length; +-} +-String foo() =3D> ''; +-'''); +- } +- +- test_singleExpression_nameOfProperty_prefixedIdentifier() async { +- await indexTestUnit(''' +-main(p) { +- var v =3D p.value; // marker +-} +-'''); +- _createRefactoringWithSuffix('value', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(p) { +- var res =3D p.value; +- var v =3D res; // marker +-} +-'''); +- } +- +- test_singleExpression_nameOfProperty_propertyAccess() async { +- await indexTestUnit(''' +-main() { +- var v =3D foo().length; // marker +-} +-String foo() =3D> ''; +-'''); +- _createRefactoringWithSuffix('length', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D foo().length; +- var v =3D res; // marker +-} +-String foo() =3D> ''; +-'''); +- } +- +- /** +- * Here we use knowledge how exactly `1 + 2 + 3 + 4` is parsed. We know= that +- * `1 + 2` will be a separate and complete binary expression, so it can= be +- * handled as a single expression. +- */ +- test_singleExpression_partOfBinaryExpression() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 + 3 + 4; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2; +- int a =3D res + 3 + 4; +-} +-'''); +- } +- +- test_singleExpression_string() async { +- await indexTestUnit(''' +-void main() { +- print("1234"); +-} +-'''); +- _createRefactoringAtString('34"'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-void main() { +- var res =3D "1234"; +- print(res); +-} +-'''); +- } +- +- test_singleExpression_trailingNotWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 12 + 345; +-} +-'''); +- _createRefactoringForString('12 +'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 12 + 345; +- int a =3D res; +-} +-'''); +- } +- +- test_singleExpression_trailingWhitespace() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2 ; +-} +-'''); +- _createRefactoringForString('1 + 2 '); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 1 + 2; +- int a =3D res ; +-} +-'''); +- } +- +- test_stringLiteral_part() async { +- await indexTestUnit(''' +-main() { +- print('abcdefgh'); +-} +-'''); +- _createRefactoringForString('cde'); +- // apply refactoring +- await _assertSuccessfulRefactoring(r''' +-main() { +- var res =3D 'cde'; +- print('ab${res}fgh'); +-} +-'''); +- _assertSingleLinkedEditGroup(length: 3, offsets: [15, 41], names: ['c= de']); +- } +- +- test_stringLiteral_whole() async { +- await indexTestUnit(''' +-main() { +- print('abc'); +-} +-'''); +- _createRefactoringForString("'abc'"); +- // apply refactoring +- await _assertSuccessfulRefactoring(''' +-main() { +- var res =3D 'abc'; +- print(res); +-} +-'''); +- _assertSingleLinkedEditGroup( +- length: 3, offsets: [15, 36], names: ['object', 's']); +- } +- +- test_stringLiteralPart() async { +- await indexTestUnit(r''' +-main() { +- int x =3D 1; +- int y =3D 2; +- print('$x+$y=3D${x+y}'); +-} +-'''); +- _createRefactoringForString(r'$x+$y'); +- // apply refactoring +- await _assertSuccessfulRefactoring(r''' +-main() { +- int x =3D 1; +- int y =3D 2; +- var res =3D '$x+$y'; +- print('${res}=3D${x+y}'); +-} +-'''); +- _assertSingleLinkedEditGroup(length: 3, offsets: [41, 67], names: ['x= y']); +- } +- +- Future _assertInitialConditions_fatal_selection() async { +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- 'Expression must be selected to activate this refactoring.'); +- } +- +- void _assertSingleLinkedEditGroup( +- {int length, List offsets, List names}) { +- String positionsString =3D offsets +- .map((offset) =3D> '{"file": "$testFile", "offset": $offset}') +- .join(','); +- String suggestionsString =3D +- names.map((name) =3D> '{"value": "$name", "kind": "VARIABLE"}').j= oin(','); +- _assertSingleLinkedEditGroupJson(''' +-{ +- "length": $length, +- "positions": [$positionsString], +- "suggestions": [$suggestionsString] +-}'''); +- } +- +- void _assertSingleLinkedEditGroupJson(String expectedJsonString) { +- List editGroups =3D refactoringChange.linkedEditGrou= ps; +- expect(editGroups, hasLength(1)); +- expect(editGroups.first.toJson(), JSON.decode(expectedJsonString)); +- } +- +- /** +- * Checks that all conditions are OK and the result of applying the +- * [SourceChange] to [testUnit] is [expectedCode]. +- */ +- Future _assertSuccessfulRefactoring(String expectedCode) async { +- await assertRefactoringConditionsOK(); +- SourceChange refactoringChange =3D await refactoring.createChange(); +- this.refactoringChange =3D refactoringChange; +- assertTestChangeResult(expectedCode); +- } +- +- void _createRefactoring(int offset, int length) { +- refactoring =3D new ExtractLocalRefactoring(testUnit, offset, length); +- refactoring.name =3D 'res'; +- } +- +- /** +- * Creates a new refactoring in [refactoring] at the offset of the given +- * [search] pattern, and with the length `0`. +- */ +- void _createRefactoringAtString(String search) { +- int offset =3D findOffset(search); +- int length =3D 0; +- _createRefactoring(offset, length); +- } +- +- /** +- * Creates a new refactoring in [refactoring] for the selection range o= f the +- * given [search] pattern. +- */ +- void _createRefactoringForString(String search) { +- int offset =3D findOffset(search); +- int length =3D search.length; +- _createRefactoring(offset, length); +- } +- +- void _createRefactoringWithSuffix(String selectionSearch, String suffix= ) { +- int offset =3D findOffset(selectionSearch + suffix); +- int length =3D selectionSearch.length; +- _createRefactoring(offset, length); +- } +- +- List _getCoveringExpressions() { +- List subExpressions =3D []; +- for (int i =3D 0; i < refactoring.coveringExpressionOffsets.length; i= ++) { +- int offset =3D refactoring.coveringExpressionOffsets[i]; +- int length =3D refactoring.coveringExpressionLengths[i]; +- subExpressions.add(testCode.substring(offset, offset + length)); +- } +- return subExpressions; +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/extract_method_= test.dart b/pkg/analysis_server/test/services/refactoring/extract_method_te= st.dart +deleted file mode 100644 +index a5363ec4ec4..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/extract_method_test.da= rt ++++ /dev/null +@@ -1,2886 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/extract_method.d= art'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ExtractMethodTest); +- }); +-} +- +-@reflectiveTest +-class ExtractMethodTest extends RefactoringTest { +- ExtractMethodRefactoringImpl refactoring; +- +- test_bad_assignmentLeftHandSide() async { +- await indexTestUnit(''' +-main() { +- int aaa; +- aaa =3D 0; +-} +-'''); +- _createRefactoringForString('aaa '); +- return _assertConditionsFatal( +- 'Cannot extract the left-hand side of an assignment.'); +- } +- +- test_bad_comment_selectionEndsInside() async { +- await indexTestUnit(''' +-main() { +-// start +- print(0); +-/* +-// end +-*/ +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal('Selection ends inside a comment.'); +- } +- +- test_bad_comment_selectionStartsInside() async { +- await indexTestUnit(''' +-main() { +-/* +-// start +-*/ +- print(0); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal('Selection begins inside a comment.'); +- } +- +- test_bad_conflict_method_alreadyDeclaresMethod() async { +- await indexTestUnit(''' +-class A { +- void res() {} +- main() { +-// start +- print(0); +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsError( +- "Class 'A' already declares method with name 'res'."); +- } +- +- test_bad_conflict_method_shadowsSuperDeclaration() async { +- await indexTestUnit(''' +-class A { +- void res() {} // marker +-} +-class B extends A { +- main() { +- res(); +-// start +- print(0); +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsError("Created method will shadow method 'A.r= es'."); +- } +- +- test_bad_conflict_topLevel_alreadyDeclaresFunction() async { +- await indexTestUnit(''' +-library my.lib; +- +-void res() {} +-main() { +-// start +- print(0); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsError( +- "Library already declares function with name 'res'."); +- } +- +- test_bad_conflict_topLevel_willHideInheritedMemberUsage() async { +- await indexTestUnit(''' +-class A { +- void res() {} +-} +-class B extends A { +- foo() { +- res(); // marker +- } +-} +-main() { +-// start +- print(0); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsError( +- "Created function will shadow method 'A.res'."); +- } +- +- test_bad_constructor_initializer() async { +- await indexTestUnit(''' +-class A { +- int f; +- A() : f =3D 0 {} +-} +-'''); +- _createRefactoringForString('f =3D 0'); +- return _assertConditionsFatal( +- 'Cannot extract a constructor initializer. Select expression part= of initializer.'); +- } +- +- test_bad_constructor_redirectingConstructor() async { +- await indexTestUnit(''' +-class A { +- A() : this.named(); +- A.named() {} +-} +-'''); +- _createRefactoringForString('this.named()'); +- return _assertConditionsFatal( +- 'Cannot extract a constructor initializer. Select expression part= of initializer.'); +- } +- +- test_bad_constructor_superConstructor() async { +- await indexTestUnit(''' +-class A {} +-class B extends A { +- B() : super(); +-} +-'''); +- _createRefactoringForString('super()'); +- return _assertConditionsFatal( +- 'Cannot extract a constructor initializer. Select expression part= of initializer.'); +- } +- +- test_bad_doWhile_body() async { +- await indexTestUnit(''' +-main() { +- do +-// start +- { +- } +-// end +- while (true); +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Operation not applicable to a 'do' statement's body and expressi= on."); +- } +- +- test_bad_emptySelection() async { +- await indexTestUnit(''' +-main() { +-// start +-// end +- print(0); +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Can only extract a single expression or a set of statements."); +- } +- +- test_bad_forLoop_conditionAndUpdaters() async { +- await indexTestUnit(''' +-main() { +- for ( +- int i =3D 0; +-// start +- i < 10; +- i++ +-// end +- ) {} +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Operation not applicable to a 'for' statement's condition and up= daters."); +- } +- +- test_bad_forLoop_init() async { +- await indexTestUnit(''' +-main() { +- for ( +-// start +- int i =3D 0 +-// end +- ; i < 10; +- i++ +- ) {} +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Cannot extract initialization part of a 'for' statement."); +- } +- +- test_bad_forLoop_initAndCondition() async { +- await indexTestUnit(''' +-main() { +- for ( +-// start +- int i =3D 0; +- i < 10; +-// end +- i++ +- ) {} +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Operation not applicable to a 'for' statement's initializer and = condition."); +- } +- +- test_bad_forLoop_updaters() async { +- await indexTestUnit(''' +-main() { +- for ( +- int i =3D 0; +- i < 10; +-// start +- i++ +-// end +- ) {} +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Cannot extract increment part of a 'for' statement."); +- } +- +- test_bad_forLoop_updatersAndBody() async { +- await indexTestUnit(''' +-main() { +- for ( +- int i =3D 0; +- i < 10; +-// start +- i++ +- ) {} +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Operation not applicable to a 'for' statement's updaters and bod= y."); +- } +- +- test_bad_methodName_reference() async { +- await indexTestUnit(''' +-main() { +- main(); +-} +-'''); +- _createRefactoringWithSuffix('main', '();'); +- return _assertConditionsFatal("Cannot extract a single method name."); +- } +- +- test_bad_namePartOfDeclaration_function() async { +- await indexTestUnit(''' +-main() { +-} +-'''); +- _createRefactoringForString('main'); +- return _assertConditionsFatal( +- "Cannot extract the name part of a declaration."); +- } +- +- test_bad_namePartOfDeclaration_variable() async { +- await indexTestUnit(''' +-main() { +- int vvv =3D 0; +-} +-'''); +- _createRefactoringForString('vvv'); +- return _assertConditionsFatal( +- "Cannot extract the name part of a declaration."); +- } +- +- test_bad_namePartOfQualified() async { +- await indexTestUnit(''' +-class A { +- var fff; +-} +-main() { +- A a; +- a.fff =3D 1; +-} +-'''); +- _createRefactoringWithSuffix('fff', ' =3D 1'); +- return _assertConditionsFatal( +- "Can not extract name part of a property access."); +- } +- +- test_bad_newMethodName_notIdentifier() async { +- await indexTestUnit(''' +-main() { +-// start +- print(0); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- refactoring.name =3D 'bad-name'; +- // check conditions +- return _assertConditionsFatal("Method name must not contain '-'."); +- } +- +- test_bad_notSameParent() async { +- await indexTestUnit(''' +-main() { +- while (false) +-// start +- { +- } +- print(0); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- 'Not all selected statements are enclosed by the same parent stat= ement.'); +- } +- +- test_bad_parameterName_duplicate() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +-// start +- int a =3D v1 + v2; // marker +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // update parameters +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(2)); +- parameters[0].name =3D 'dup'; +- parameters[1].name =3D 'dup'; +- refactoring.parameters =3D parameters; +- } +- return _assertFinalConditionsError("Parameter 'dup' already exists"); +- } +- +- test_bad_parameterName_inUse_function() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +-// start +- f(v1, v2); +-// end +-} +-f(a, b) {} +-'''); +- _createRefactoringForStartEndComments(); +- // update parameters +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(2)); +- parameters[0].name =3D 'f'; +- refactoring.parameters =3D parameters; +- } +- return _assertFinalConditionsError( +- "'f' is already used as a name in the selected code"); +- } +- +- test_bad_parameterName_inUse_localVariable() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +-// start +- int a =3D v1 + v2; // marker +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // update parameters +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(2)); +- parameters[0].name =3D 'a'; +- refactoring.parameters =3D parameters; +- } +- return _assertFinalConditionsError( +- "'a' is already used as a name in the selected code"); +- } +- +- test_bad_parameterName_inUse_method() async { +- await indexTestUnit(''' +-class A { +- main() { +- int v1 =3D 1; +- int v2 =3D 2; +- // start +- m(v1, v2); +- // end +- } +- m(a, b) {} +-} +-'''); +- _createRefactoringForStartEndComments(); +- // update parameters +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(2)); +- parameters[0].name =3D 'm'; +- refactoring.parameters =3D parameters; +- } +- return _assertFinalConditionsError( +- "'m' is already used as a name in the selected code"); +- } +- +- test_bad_selectionEndsInSomeNode() async { +- await indexTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _createRefactoringForStartEndString('print(0', 'rint(1)'); +- return _assertConditionsFatal( +- "The selection does not cover a set of statements or an expressio= n. " +- "Extend selection to a valid range."); +- } +- +- test_bad_statements_exit_notAllExecutionFlows() async { +- await indexTestUnit(''' +-main(int p) { +-// start +- if (p =3D=3D 0) { +- return; +- } +-// end +- print(p); +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsError(ExtractMethodRefactoringImpl.ERROR_EXIT= S); +- } +- +- test_bad_statements_return_andAssignsVariable() async { +- await indexTestUnit(''' +-main() { +-// start +- var v =3D 0; +- return 42; +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Ambiguous return value: Selected block contains assignment(s) to= " +- "local variables and return statement."); +- } +- +- test_bad_switchCase() async { +- await indexTestUnit(''' +-main() { +- switch (1) { +-// start +- case 0: break; +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Selection must either cover whole switch statement " +- "or parts of a single case block."); +- } +- +- test_bad_tokensBetweenLastNodeAndSelectionEnd() async { +- await indexTestUnit(''' +-main() { +-// start +- print(0); +- print(1); +-} +-// end +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "The end of the selection contains characters that do not belong = to a statement."); +- } +- +- test_bad_tokensBetweenSelectionStartAndFirstNode() async { +- await indexTestUnit(''' +-main() { +-// start +- print(0); // marker +- print(1); +-// end +-} +-'''); +- _createRefactoringForStartEndString('); // marker', '// end'); +- return _assertConditionsFatal( +- "The beginning of the selection contains characters that do not b= elong to a statement."); +- } +- +- test_bad_try_catchBlock_block() async { +- await indexTestUnit(''' +-main() { +- try +- {} +- catch (e) +-// start +- {} +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Selection must either cover whole try statement or " +- "parts of try, catch, or finally block."); +- } +- +- test_bad_try_catchBlock_complete() async { +- await indexTestUnit(''' +-main() { +- try +- {} +-// start +- catch (e) +- {} +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Selection must either cover whole try statement or " +- "parts of try, catch, or finally block."); +- } +- +- test_bad_try_catchBlock_exception() async { +- await indexTestUnit(''' +-main() { +- try { +- } catch ( +-// start +- e +-// end +- ) { +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- 'Cannot extract the name part of a declaration.'); +- } +- +- test_bad_try_finallyBlock() async { +- await indexTestUnit(''' +-main() { +- try +- {} +- finally +-// start +- {} +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Selection must either cover whole try statement or " +- "parts of try, catch, or finally block."); +- } +- +- test_bad_try_tryBlock() async { +- await indexTestUnit(''' +-main() { +- try +-// start +- {} +-// end +- finally +- {} +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Selection must either cover whole try statement or " +- "parts of try, catch, or finally block."); +- } +- +- test_bad_typeReference() async { +- await indexTestUnit(''' +-main() { +- int a =3D 0; +-} +-'''); +- _createRefactoringForString("int"); +- return _assertConditionsFatal("Cannot extract a single type reference= ."); +- } +- +- test_bad_variableDeclarationFragment() async { +- await indexTestUnit(''' +-main() { +- int +-// start +- a =3D 1 +-// end +- ,b =3D 2; +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Cannot extract a variable declaration fragment. Select whole dec= laration statement."); +- } +- +- test_bad_while_conditionAndBody() async { +- await indexTestUnit(''' +-main() { +- while +-// start +- (false) +- { +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- return _assertConditionsFatal( +- "Operation not applicable to a while statement's expression and b= ody."); +- } +- +- test_canExtractGetter_false_closure() async { +- await indexTestUnit(''' +-main() { +- useFunction((_) =3D> true); +-} +-useFunction(filter(String p)) {} +-'''); +- _createRefactoringForString('(_) =3D> true'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, false); +- expect(refactoring.createGetter, false); +- } +- +- test_canExtractGetter_false_fieldAssignment() async { +- await indexTestUnit(''' +-class A { +- var f; +- main() { +-// start +- f =3D 1; +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, false); +- expect(refactoring.createGetter, false); +- } +- +- test_canExtractGetter_false_hasParameters() async { +- await indexTestUnit(''' +-main(int p) { +- int a =3D p + 1; +-} +-'''); +- _createRefactoringForString('p + 1'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, false); +- expect(refactoring.createGetter, false); +- } +- +- test_canExtractGetter_false_returnNotUsed_assignment() async { +- await indexTestUnit(''' +-var topVar =3D 0; +-f(int p) { +- topVar =3D 5; +-} +-'''); +- _createRefactoringForString('topVar =3D 5'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, false); +- expect(refactoring.createGetter, false); +- } +- +- test_canExtractGetter_false_returnNotUsed_noReturn() async { +- await indexTestUnit(''' +-var topVar =3D 0; +-main() { +-// start +- int a =3D 1; +- int b =3D 2; +- topVar =3D a + b; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, false); +- expect(refactoring.createGetter, false); +- } +- +- test_canExtractGetter_true() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, true); +- expect(refactoring.createGetter, true); +- } +- +- test_checkName() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // null +- refactoring.name =3D null; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be null."); +- // empty +- refactoring.name =3D ''; +- assertRefactoringStatus( +- refactoring.checkName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be empty."); +- // OK +- refactoring.name =3D 'res'; +- assertRefactoringStatusOK(refactoring.checkName()); +- } +- +- test_closure_asFunction_singleExpression() async { +- await indexTestUnit(''' +-process(f(x)) {} +-main() { +- process((x) =3D> x * 2); +-} +-'''); +- _createRefactoringForString('(x) =3D> x * 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-process(f(x)) {} +-main() { +- process(res); +-} +- +-res(x) =3D> x * 2; +-'''); +- } +- +- test_closure_asFunction_statements() async { +- await indexTestUnit(''' +-process(f(x)) {} +-main() { +- process((x) { +- print(x); +- return x * 2; +- }); // marker +-} +-'''); +- _createRefactoringForStartEndString('(x) {', '); // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-process(f(x)) {} +-main() { +- process(res); // marker +-} +- +-res(x) { +- print(x); +- return x * 2; +-} +-'''); +- } +- +- test_closure_asMethod_statements() async { +- await indexTestUnit(''' +-process(f(x)) {} +-class A { +- int k =3D 2; +- main() { +- process((x) { +- print(x); +- return x * k; +- }); // marker +- } +-} +-'''); +- _createRefactoringForStartEndString('(x) {', '); // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-process(f(x)) {} +-class A { +- int k =3D 2; +- main() { +- process(res); // marker +- } +- +- res(x) { +- print(x); +- return x * k; +- } +-} +-'''); +- } +- +- test_closure_atArgumentName() async { +- await indexTestUnit(''' +-void process({int fff(int x)}) {} +-class C { +- main() { +- process(fff: (int x) =3D> x * 2); +- } +-} +-'''); +- _createRefactoring(findOffset('ff: (int x)'), 0); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-void process({int fff(int x)}) {} +-class C { +- main() { +- process(fff: res); +- } +- +- int res(int x) =3D> x * 2; +-} +-'''); +- } +- +- test_closure_atParameters() async { +- await indexTestUnit(''' +-void process(num f(int x)) {} +-class C { +- main() { +- process((int x) =3D> x * 2); +- } +-} +-'''); +- _createRefactoring(findOffset('x) =3D>'), 0); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-void process(num f(int x)) {} +-class C { +- main() { +- process(res); +- } +- +- num res(int x) =3D> x * 2; +-} +-'''); +- } +- +- test_closure_bad_referencesLocalVariable() async { +- await indexTestUnit(''' +-process(f(x)) {} +-main() { +- int k =3D 2; +- process((x) =3D> x * k); +-} +-'''); +- _createRefactoringForString('(x) =3D> x * k'); +- // check +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- 'Cannot extract closure as method, it references 1 external v= ariable(s).'); +- } +- +- test_closure_bad_referencesParameter() async { +- await indexTestUnit(''' +-process(f(x)) {} +-main(int k) { +- process((x) =3D> x * k); +-} +-'''); +- _createRefactoringForString('(x) =3D> x * k'); +- // check +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- 'Cannot extract closure as method, it references 1 external v= ariable(s).'); +- } +- +- test_fromTopLevelVariableInitializerClosure() async { +- await indexTestUnit(''' +-var X =3D 1; +- +-dynamic Y =3D () { +- return 1 + X; +-}; +-'''); +- _createRefactoringForString('1 + X'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-var X =3D 1; +- +-dynamic Y =3D () { +- return res(); +-}; +- +-int res() =3D> 1 + X; +-'''); +- } +- +- test_getExtractGetter_expression_true_binaryExpression() async { +- await indexTestUnit(''' +-main() { +- print(1 + 2); +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.createGetter, true); +- } +- +- test_getExtractGetter_expression_true_literal() async { +- await indexTestUnit(''' +-main() { +- print(42); +-} +-'''); +- _createRefactoringForString('42'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.createGetter, true); +- } +- +- test_getExtractGetter_expression_true_prefixedExpression() async { +- await indexTestUnit(''' +-main() { +- print(!true); +-} +-'''); +- _createRefactoringForString('!true'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.createGetter, true); +- } +- +- test_getExtractGetter_expression_true_prefixedIdentifier() async { +- await indexTestUnit(''' +-main() { +- print(myValue.isEven); +-} +-int get myValue =3D> 42; +-'''); +- _createRefactoringForString('myValue.isEven'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.createGetter, true); +- } +- +- test_getExtractGetter_expression_true_propertyAccess() async { +- await indexTestUnit(''' +-main() { +- print(1.isEven); +-} +-'''); +- _createRefactoringForString('1.isEven'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.createGetter, true); +- } +- +- test_getExtractGetter_statements() async { +- await indexTestUnit(''' +-main() { +-// start +- int v =3D 0; +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.createGetter, false); +- } +- +- test_getRefactoringName_function() async { +- await indexTestUnit(''' +-main() { +- print(1 + 2); +-} +-'''); +- _createRefactoringForString('1 + 2'); +- expect(refactoring.refactoringName, 'Extract Function'); +- } +- +- test_getRefactoringName_method() async { +- await indexTestUnit(''' +-class A { +- main() { +- print(1 + 2); +- } +-} +-'''); +- _createRefactoringForString('1 + 2'); +- expect(refactoring.refactoringName, 'Extract Method'); +- } +- +- test_names_singleExpression() async { +- await indexTestUnit(''' +-class TreeItem {} +-TreeItem getSelectedItem() =3D> null; +-process(my) {} +-main() { +- process(getSelectedItem()); // marker +- int treeItem =3D 0; +-} +-'''); +- _createRefactoringWithSuffix('getSelectedItem()', '); // marker'); +- // check names +- await refactoring.checkInitialConditions(); +- expect(refactoring.names, +- unorderedEquals(['selectedItem', 'item', 'my', 'treeItem2'])); +- } +- +- test_offsets_lengths() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +- int b =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- await refactoring.checkInitialConditions(); +- expect(refactoring.offsets, +- unorderedEquals([findOffset('1 + 2'), findOffset('1 + 2')])); +- expect(refactoring.lengths, unorderedEquals([5, 6])); +- } +- +- test_returnType_closure() async { +- await indexTestUnit(''' +-process(f(x)) {} +-main() { +- process((x) =3D> x * 2); +-} +-'''); +- _createRefactoringForString('(x) =3D> x * 2'); +- // do check +- await refactoring.checkInitialConditions(); +- expect(refactoring.returnType, ''); +- } +- +- test_returnType_expression() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // do check +- await refactoring.checkInitialConditions(); +- expect(refactoring.returnType, 'int'); +- } +- +- test_returnType_mixInterfaceFunction() async { +- await indexTestUnit(''' +-main() { +-// start +- if (true) { +- return 1; +- } else { +- return () {}; +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // do check +- await refactoring.checkInitialConditions(); +- expect(refactoring.returnType, 'Object'); +- } +- +- test_returnType_statements() async { +- await indexTestUnit(''' +-main() { +-// start +- double v =3D 5.0; +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // do check +- await refactoring.checkInitialConditions(); +- expect(refactoring.returnType, 'double'); +- } +- +- test_returnType_statements_nullMix() async { +- await indexTestUnit(''' +-main(bool p) { +-// start +- if (p) { +- return 42; +- } +- return null; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // do check +- await refactoring.checkInitialConditions(); +- expect(refactoring.returnType, 'int'); +- } +- +- test_returnType_statements_void() async { +- await indexTestUnit(''' +-main() { +-// start +- print(42); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // do check +- await refactoring.checkInitialConditions(); +- expect(refactoring.returnType, 'void'); +- } +- +- test_setExtractGetter() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- await assertRefactoringConditionsOK(); +- expect(refactoring.canCreateGetter, true); +- expect(refactoring.createGetter, true); +- refactoringChange =3D await refactoring.createChange(); +- assertTestChangeResult(''' +-main() { +- int a =3D res; +-} +- +-int get res =3D> 1 + 2; +-'''); +- } +- +- test_singleExpression() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1 + 2; +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int a =3D res(); +-} +- +-int res() =3D> 1 + 2; +-'''); +- } +- +- test_singleExpression_cascade() async { +- await indexTestUnit(''' +-main() { +- String s =3D ''; +- var v =3D s..length; +-} +-'''); +- _createRefactoringForString('s..length'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- String s =3D ''; +- var v =3D res(s); +-} +- +-String res(String s) =3D> s..length; +-'''); +- } +- +- test_singleExpression_dynamic() async { +- await indexTestUnit(''' +-dynaFunction() {} +-main() { +- var v =3D dynaFunction(); // marker +-} +-'''); +- _createRefactoringWithSuffix('dynaFunction()', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-dynaFunction() {} +-main() { +- var v =3D res(); // marker +-} +- +-res() =3D> dynaFunction(); +-'''); +- } +- +- test_singleExpression_hasAwait() async { +- await indexTestUnit(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +- int v =3D await getValue(); +- print(v); +-} +-'''); +- _createRefactoringForString('await getValue()'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +- int v =3D await res(); +- print(v); +-} +- +-Future res() async =3D> await getValue(); +-'''); +- } +- +- test_singleExpression_ignore_assignmentLeftHandSize() async { +- await indexTestUnit(''' +-main() { +- getButton().text =3D 'txt'; +- print(getButton().text); // marker +-} +-getButton() {} +-'''); +- _createRefactoringWithSuffix('getButton().text', '); // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- getButton().text =3D 'txt'; +- print(res()); // marker +-} +- +-res() =3D> getButton().text; +-getButton() {} +-'''); +- } +- +- test_singleExpression_occurrences() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int positiveA =3D v1 + v2; // marker +- int positiveB =3D v2 + v3; +- int positiveC =3D v1 + v2; +- int positiveD =3D v1/*abc*/ + v2; +- int negA =3D 1 + 2; +- int negB =3D 1 + v2; +- int negC =3D v1 + 2; +- int negD =3D v1 * v2; +-} +-'''); +- _createRefactoringWithSuffix('v1 + v2', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int positiveA =3D res(v1, v2); // marker +- int positiveB =3D res(v2, v3); +- int positiveC =3D res(v1, v2); +- int positiveD =3D res(v1, v2); +- int negA =3D 1 + 2; +- int negB =3D 1 + v2; +- int negC =3D v1 + 2; +- int negD =3D v1 * v2; +-} +- +-int res(int v1, int v2) =3D> v1 + v2; +-'''); +- } +- +- test_singleExpression_occurrences_disabled() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D v1 + v2; // marker +- int b =3D v2 + v3; +-} +-'''); +- _createRefactoringWithSuffix('v1 + v2', '; // marker'); +- refactoring.extractAll =3D false; +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D res(v1, v2); // marker +- int b =3D v2 + v3; +-} +- +-int res(int v1, int v2) =3D> v1 + v2; +-'''); +- } +- +- test_singleExpression_occurrences_inClassOnly() async { +- await indexTestUnit(''' +-class A { +- myMethod() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D v1 + v2; // marker +- } +-} +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int negA =3D v1 + v2; +-} +-'''); +- _createRefactoringWithSuffix('v1 + v2', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- myMethod() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D res(v1, v2); // marker +- } +- +- int res(int v1, int v2) =3D> v1 + v2; +-} +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int negA =3D v1 + v2; +-} +-'''); +- } +- +- test_singleExpression_occurrences_incompatibleTypes() async { +- await indexTestUnit(''' +-main() { +- int x =3D 1; +- String y =3D 'foo'; +- print(x.toString()); +- print(y.toString()); +-} +-'''); +- _createRefactoringForString('x.toString()'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int x =3D 1; +- String y =3D 'foo'; +- print(res(x)); +- print(y.toString()); +-} +- +-String res(int x) =3D> x.toString(); +-'''); +- } +- +- test_singleExpression_occurrences_inWholeUnit() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D v1 + v2; // marker +-} +-class A { +- myMethod() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveB =3D v1 + v2; +- } +-} +-'''); +- _createRefactoringWithSuffix('v1 + v2', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D res(v1, v2); // marker +-} +- +-int res(int v1, int v2) =3D> v1 + v2; +-class A { +- myMethod() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveB =3D res(v1, v2); +- } +-} +-'''); +- } +- +- test_singleExpression_parameter_functionTypeAlias() async { +- await indexTestUnit(''' +-typedef R Foo(S s); +-void main(Foo foo, String s) { +- int a =3D foo(s); +-} +-'''); +- _createRefactoringForString('foo(s)'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-typedef R Foo(S s); +-void main(Foo foo, String s) { +- int a =3D res(foo, s); +-} +- +-int res(Foo foo, String s) =3D> foo(s); +-'''); +- } +- +- test_singleExpression_returnType_importLibrary() async { +- _addLibraryReturningAsync(); +- await indexTestUnit(''' +-import 'asyncLib.dart'; +-main() { +- var a =3D newFuture(); +-} +-'''); +- _createRefactoringForString('newFuture()'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'asyncLib.dart'; +-import 'dart:async'; +-main() { +- var a =3D res(); +-} +- +-Future res() =3D> newFuture(); +-'''); +- } +- +- test_singleExpression_returnTypeGeneric() async { +- await indexTestUnit(''' +-main() { +- var v =3D new List(); +-} +-'''); +- _createRefactoringForString('new List()'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var v =3D res(); +-} +- +-List res() =3D> new List(); +-'''); +- } +- +- test_singleExpression_returnTypePrefix() async { +- await indexTestUnit(''' +-import 'dart:math' as pref; +-main() { +- var v =3D new pref.Random(); +-} +-'''); +- _createRefactoringForString('new pref.Random()'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'dart:math' as pref; +-main() { +- var v =3D res(); +-} +- +-pref.Random res() =3D> new pref.Random(); +-'''); +- } +- +- test_singleExpression_staticContext_extractFromInitializer() async { +- await indexTestUnit(''' +-class A { +- A(int v) {} +-} +-class B extends A { +- B() : super(1 + 2) {} +-} +-'''); +- _createRefactoringForString('1 + 2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- A(int v) {} +-} +-class B extends A { +- B() : super(res()) {} +- +- static int res() =3D> 1 + 2; +-} +-'''); +- } +- +- test_singleExpression_staticContext_extractFromInstance() async { +- await indexTestUnit(''' +-class A { +- instanceMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D v1 + v2; // marker +- } +- instanceMethodB() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveB =3D v1 + v2; +- } +- static staticMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D v1 + v2; +- } +-} +-'''); +- _createRefactoringWithSuffix('v1 + v2', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- instanceMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D res(v1, v2); // marker +- } +- +- static int res(int v1, int v2) =3D> v1 + v2; +- instanceMethodB() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveB =3D res(v1, v2); +- } +- static staticMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D res(v1, v2); +- } +-} +-'''); +- } +- +- test_singleExpression_staticContext_extractFromStatic() async { +- await indexTestUnit(''' +-class A { +- static staticMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D v1 + v2; // marker +- } +- static staticMethodB() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveB =3D v1 + v2; +- } +- instanceMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D v1 + v2; +- } +-} +-'''); +- _createRefactoringWithSuffix('v1 + v2', '; // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- static staticMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D res(v1, v2); // marker +- } +- +- static int res(int v1, int v2) =3D> v1 + v2; +- static staticMethodB() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveB =3D res(v1, v2); +- } +- instanceMethodA() { +- int v1 =3D 1; +- int v2 =3D 2; +- int positiveA =3D res(v1, v2); +- } +-} +-'''); +- } +- +- test_singleExpression_staticContext_hasInInitializer() async { +- await indexTestUnit(''' +-class A { +- A(int v) {} +-} +-class B extends A { +- B() : super(1 + 2) {} +- foo() { +- print(1 + 2); // marker +- } +-} +-'''); +- _createRefactoringWithSuffix('1 + 2', '); // marker'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- A(int v) {} +-} +-class B extends A { +- B() : super(res()) {} +- foo() { +- print(res()); // marker +- } +- +- static int res() =3D> 1 + 2; +-} +-'''); +- } +- +- test_singleExpression_usesParameter() async { +- await indexTestUnit(''' +-fooA(int a1) { +- int a2 =3D 2; +- int a =3D a1 + a2; +-} +-fooB(int b1) { +- int b2 =3D 2; +- int b =3D b1 + b2; +-} +-'''); +- _createRefactoringForString('a1 + a2'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-fooA(int a1) { +- int a2 =3D 2; +- int a =3D res(a1, a2); +-} +- +-int res(int a1, int a2) =3D> a1 + a2; +-fooB(int b1) { +- int b2 =3D 2; +- int b =3D res(b1, b2); +-} +-'''); +- } +- +- test_singleExpression_withVariables() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int a =3D v1 + v2 + v1; +-} +-'''); +- _createRefactoringForString('v1 + v2 + v1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int a =3D res(v1, v2); +-} +- +-int res(int v1, int v2) =3D> v1 + v2 + v1; +-'''); +- } +- +- test_singleExpression_withVariables_doRename() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D v1 + v2 + v1; // marker +- int b =3D v2 + v3 + v2; +-} +-'''); +- _createRefactoringForString('v1 + v2 + v1'); +- // apply refactoring +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(2)); +- expect(parameters[0].name, 'v1'); +- expect(parameters[1].name, 'v2'); +- parameters[0].name =3D 'par1'; +- parameters[1].name =3D 'param2'; +- refactoring.parameters =3D parameters; +- } +- await assertRefactoringFinalConditionsOK(); +- refactoring.createGetter =3D false; +- return _assertRefactoringChange(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D res(v1, v2); // marker +- int b =3D res(v2, v3); +-} +- +-int res(int par1, int param2) =3D> par1 + param2 + par1; +-'''); +- } +- +- test_singleExpression_withVariables_doReorder() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D v1 + v2; // marker +- int b =3D v2 + v3; +-} +-'''); +- _createRefactoringForString('v1 + v2'); +- // apply refactoring +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(2)); +- expect(parameters[0].name, 'v1'); +- expect(parameters[1].name, 'v2'); +- var parameter =3D parameters.removeAt(1); +- parameters.insert(0, parameter); +- refactoring.parameters =3D parameters; +- } +- await assertRefactoringFinalConditionsOK(); +- refactoring.createGetter =3D false; +- return _assertRefactoringChange(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D res(v2, v1); // marker +- int b =3D res(v3, v2); +-} +- +-int res(int v2, int v1) =3D> v1 + v2; +-'''); +- } +- +- test_singleExpression_withVariables_namedExpression() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int a =3D process(arg: v1 + v2); +-} +-process({arg}) {} +-'''); +- _createRefactoringForString('process(arg: v1 + v2)'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int a =3D res(v1, v2); +-} +- +-res(int v1, int v2) =3D> process(arg: v1 + v2); +-process({arg}) {} +-'''); +- } +- +- test_singleExpression_withVariables_newType() async { +- await indexTestUnit(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D v1 + v2 + v3; +-} +-'''); +- _createRefactoringForString('v1 + v2 + v3'); +- // apply refactoring +- await refactoring.checkInitialConditions(); +- { +- List parameters =3D _getParametersCopy(= ); +- expect(parameters, hasLength(3)); +- expect(parameters[0].name, 'v1'); +- expect(parameters[1].name, 'v2'); +- expect(parameters[2].name, 'v3'); +- parameters[0].type =3D 'num'; +- parameters[1].type =3D 'dynamic'; +- parameters[2].type =3D ''; +- refactoring.parameters =3D parameters; +- } +- await assertRefactoringFinalConditionsOK(); +- refactoring.createGetter =3D false; +- return _assertRefactoringChange(''' +-main() { +- int v1 =3D 1; +- int v2 =3D 2; +- int v3 =3D 3; +- int a =3D res(v1, v2, v3); +-} +- +-int res(num v1, v2, v3) =3D> v1 + v2 + v3; +-'''); +- } +- +- test_singleExpression_withVariables_useBestType() async { +- await indexTestUnit(''' +-main() { +- var v1 =3D 1; +- var v2 =3D 2; +- var a =3D v1 + v2 + v1; // marker +-} +-'''); +- _createRefactoringForString('v1 + v2 + v1'); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- var v1 =3D 1; +- var v2 =3D 2; +- var a =3D res(v1, v2); // marker +-} +- +-int res(int v1, int v2) =3D> v1 + v2 + v1; +-'''); +- } +- +- test_statements_assignment() async { +- await indexTestUnit(''' +-main() { +- int v; +-// start +- v =3D 5; +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int v; +-// start +- v =3D res(v); +-// end +- print(v); +-} +- +-int res(int v) { +- v =3D 5; +- return v; +-} +-'''); +- } +- +- test_statements_changeIndentation() async { +- await indexTestUnit(''' +-main() { +- { +-// start +- if (true) { +- print(0); +- } +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- { +-// start +- res(); +-// end +- } +-} +- +-void res() { +- if (true) { +- print(0); +- } +-} +-'''); +- } +- +- test_statements_changeIndentation_multilineString() async { +- await indexTestUnit(''' +-main() { +- { +-// start +- print(""" +-first line +-second line +- """); +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- { +-// start +- res(); +-// end +- } +-} +- +-void res() { +- print(""" +-first line +-second line +- """); +-} +-'''); +- } +- +- test_statements_definesVariable_notUsedOutside() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1; +- int b =3D 1; +-// start +- int v =3D a + b; +- print(v); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int a =3D 1; +- int b =3D 1; +-// start +- res(a, b); +-// end +-} +- +-void res(int a, int b) { +- int v =3D a + b; +- print(v); +-} +-'''); +- } +- +- test_statements_definesVariable_oneUsedOutside_assignment() async { +- await indexTestUnit(''' +-myFunctionA() { +- int a =3D 1; +-// start +- a +=3D 10; +-// end +- print(a); +-} +-myFunctionB() { +- int b =3D 2; +- b +=3D 10; +- print(b); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-myFunctionA() { +- int a =3D 1; +-// start +- a =3D res(a); +-// end +- print(a); +-} +- +-int res(int a) { +- a +=3D 10; +- return a; +-} +-myFunctionB() { +- int b =3D 2; +- b =3D res(b); +- print(b); +-} +-'''); +- } +- +- test_statements_definesVariable_oneUsedOutside_declaration() async { +- await indexTestUnit(''' +-myFunctionA() { +- int a =3D 1; +- int b =3D 2; +-// start +- int v1 =3D a + b; +-// end +- print(v1); +-} +-myFunctionB() { +- int a =3D 3; +- int b =3D 4; +- int v2 =3D a + b; +- print(v2); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-myFunctionA() { +- int a =3D 1; +- int b =3D 2; +-// start +- int v1 =3D res(a, b); +-// end +- print(v1); +-} +- +-int res(int a, int b) { +- int v1 =3D a + b; +- return v1; +-} +-myFunctionB() { +- int a =3D 3; +- int b =3D 4; +- int v2 =3D res(a, b); +- print(v2); +-} +-'''); +- } +- +- test_statements_definesVariable_twoUsedOutside() async { +- await indexTestUnit(''' +-main() { +-// start +- int varA =3D 1; +- int varB =3D 2; +-// end +- int v =3D varA + varB; +-} +-'''); +- _createRefactoringForStartEndComments(); +- // check conditions +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL); +- } +- +- test_statements_duplicate_absolutelySame() async { +- await indexTestUnit(''' +-myFunctionA() { +- print(0); +- print(1); +-} +-myFunctionB() { +-// start +- print(0); +- print(1); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-myFunctionA() { +- res(); +-} +-myFunctionB() { +-// start +- res(); +-// end +-} +- +-void res() { +- print(0); +- print(1); +-} +-'''); +- } +- +- test_statements_duplicate_declaresDifferentlyNamedVariable() async { +- await indexTestUnit(''' +-myFunctionA() { +- int varA =3D 1; +- print(varA); +-} +-myFunctionB() { +-// start +- int varB =3D 1; +- print(varB); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-myFunctionA() { +- res(); +-} +-myFunctionB() { +-// start +- res(); +-// end +-} +- +-void res() { +- int varB =3D 1; +- print(varB); +-} +-'''); +- } +- +- test_statements_dynamic() async { +- await indexTestUnit(''' +-dynaFunction(p) =3D> 0; +-main() { +-// start +- var a =3D 1; +- var v =3D dynaFunction(a); +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-dynaFunction(p) =3D> 0; +-main() { +-// start +- var v =3D res(); +-// end +- print(v); +-} +- +-res() { +- var a =3D 1; +- var v =3D dynaFunction(a); +- return v; +-} +-'''); +- } +- +- /** +- * We should always add ";" when invoke method with extracted statement= s. +- */ +- test_statements_endsWithBlock() async { +- await indexTestUnit(''' +-main() { +-// start +- if (true) { +- print(0); +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +-// start +- res(); +-// end +-} +- +-void res() { +- if (true) { +- print(0); +- } +-} +-'''); +- } +- +- test_statements_exit_throws() async { +- await indexTestUnit(''' +-main(int p) { +-// start +- if (p =3D=3D 0) { +- return; +- } +- throw 'boo!'; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- await assertRefactoringConditionsOK(); +- } +- +- test_statements_hasAwait_dynamicReturnType() async { +- await indexTestUnit(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +-// start +- var v =3D await getValue(); +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +-// start +- var v =3D await res(); +-// end +- print(v); +-} +- +-Future res() async { +- var v =3D await getValue(); +- return v; +-} +-'''); +- } +- +- test_statements_hasAwait_expression() async { +- await indexTestUnit(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +-// start +- int v =3D await getValue(); +- v +=3D 2; +-// end +- print(v); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +-// start +- int v =3D await res(); +-// end +- print(v); +-} +- +-Future res() async { +- int v =3D await getValue(); +- v +=3D 2; +- return v; +-} +-'''); +- } +- +- test_statements_hasAwait_forEach() async { +- await indexTestUnit(''' +-import 'dart:async'; +-Stream getValueStream() =3D> null; +-main() async { +-// start +- int sum =3D 0; +- await for (int v in getValueStream()) { +- sum +=3D v; +- } +-// end +- print(sum); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'dart:async'; +-Stream getValueStream() =3D> null; +-main() async { +-// start +- int sum =3D await res(); +-// end +- print(sum); +-} +- +-Future res() async { +- int sum =3D 0; +- await for (int v in getValueStream()) { +- sum +=3D v; +- } +- return sum; +-} +-'''); +- } +- +- test_statements_hasAwait_voidReturnType() async { +- await indexTestUnit(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +-// start +- int v =3D await getValue(); +- print(v); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'dart:async'; +-Future getValue() async =3D> 42; +-main() async { +-// start +- await res(); +-// end +-} +- +-Future res() async { +- int v =3D await getValue(); +- print(v); +-} +-'''); +- } +- +- test_statements_inSwitchMember() async { +- await indexTestUnit(''' +-class A { +- foo(int p) { +- switch (p) { +- case 0: +-// start +- print(0); +-// end +- break; +- default: +- break; +- } +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- foo(int p) { +- switch (p) { +- case 0: +-// start +- res(); +-// end +- break; +- default: +- break; +- } +- } +- +- void res() { +- print(0); +- } +-} +-'''); +- } +- +- test_statements_method() async { +- await indexTestUnit(''' +-class A { +- foo() { +-// start +- print(0); +-// end +- } +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class A { +- foo() { +-// start +- res(); +-// end +- } +- +- void res() { +- print(0); +- } +-} +-'''); +- } +- +- test_statements_noDuplicates() async { +- await indexTestUnit(''' +-main() { +- int a =3D 1; +- int b =3D 1; +-// start +- print(a); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +- int a =3D 1; +- int b =3D 1; +-// start +- res(a); +-// end +-} +- +-void res(int a) { +- print(a); +-} +-'''); +- } +- +- test_statements_parameters_ignoreInnerPropagatedType() async { +- await indexTestUnit(''' +-main(Object x) { +-// start +- if (x is int) { +- print('int'); +- } +- if (x is bool) { +- print('bool'); +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(Object x) { +-// start +- res(x); +-// end +-} +- +-void res(Object x) { +- if (x is int) { +- print('int'); +- } +- if (x is bool) { +- print('bool'); +- } +-} +-'''); +- } +- +- test_statements_parameters_importType() async { +- _addLibraryReturningAsync(); +- await indexTestUnit(''' +-import 'asyncLib.dart'; +-main() { +- var v =3D newFuture(); +-// start +- print(v); +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-import 'asyncLib.dart'; +-import 'dart:async'; +-main() { +- var v =3D newFuture(); +-// start +- res(v); +-// end +-} +- +-void res(Future v) { +- print(v); +-} +-'''); +- } +- +- test_statements_parameters_localFunction() async { +- _addLibraryReturningAsync(); +- await indexTestUnit(''' +-class C { +- int f(int a) { +- int callback(int x, int y) =3D> x + a; +- int b =3D a + 1; +-// start +- int c =3D callback(b, 2); +-// end +- int d =3D c + 1; +- return d; +- } +-}'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-class C { +- int f(int a) { +- int callback(int x, int y) =3D> x + a; +- int b =3D a + 1; +-// start +- int c =3D res(callback, b); +-// end +- int d =3D c + 1; +- return d; +- } +- +- int res(int callback(int x, int y), int b) { +- int c =3D callback(b, 2); +- return c; +- } +-}'''); +- } +- +- test_statements_parameters_noLocalVariableConflict() async { +- await indexTestUnit(''' +-int f(int x) { +- int y =3D x + 1; +-// start +- if (y % 2 =3D=3D 0) { +- int y =3D x + 2; +- return y; +- } else { +- return y; +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- await assertRefactoringConditionsOK(); +- } +- +- test_statements_return_last() async { +- await indexTestUnit(''' +-main() { +-// start +- int v =3D 5; +- return v + 1; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +-// start +- return res(); +-// end +-} +- +-int res() { +- int v =3D 5; +- return v + 1; +-} +-'''); +- } +- +- test_statements_return_multiple_ifElse() async { +- await indexTestUnit(''' +-num main(bool b) { +-// start +- if (b) { +- return 1; +- } else { +- return 2.0; +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-num main(bool b) { +-// start +- return res(b); +-// end +-} +- +-num res(bool b) { +- if (b) { +- return 1; +- } else { +- return 2.0; +- } +-} +-'''); +- } +- +- test_statements_return_multiple_ifThen() async { +- await indexTestUnit(''' +-num main(bool b) { +-// start +- if (b) { +- return 1; +- } +- return 2.0; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-num main(bool b) { +-// start +- return res(b); +-// end +-} +- +-num res(bool b) { +- if (b) { +- return 1; +- } +- return 2.0; +-} +-'''); +- } +- +- test_statements_return_multiple_ignoreInFunction() async { +- await indexTestUnit(''' +-int main() { +-// start +- localFunction() { +- return 'abc'; +- } +- return 42; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-int main() { +-// start +- return res(); +-// end +-} +- +-int res() { +- localFunction() { +- return 'abc'; +- } +- return 42; +-} +-'''); +- } +- +- test_statements_return_multiple_interfaceFunction() async { +- await indexTestUnit(''' +-main(bool b) { +-// start +- if (b) { +- return 1; +- } +- return () {}; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(bool b) { +-// start +- return res(b); +-// end +-} +- +-Object res(bool b) { +- if (b) { +- return 1; +- } +- return () {}; +-} +-'''); +- } +- +- test_statements_return_multiple_sameElementDifferentTypeArgs() async { +- await indexTestUnit(''' +-main(bool b) { +-// start +- if (b) { +- print(true); +- return []; +- } else { +- print(false); +- return []; +- } +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main(bool b) { +-// start +- return res(b); +-// end +-} +- +-List res(bool b) { +- if (b) { +- print(true); +- return []; +- } else { +- print(false); +- return []; +- } +-} +-'''); +- } +- +- test_statements_return_single() async { +- await indexTestUnit(''' +-main() { +-// start +- return 42; +-// end +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +-// start +- return res(); +-// end +-} +- +-int res() { +- return 42; +-} +-'''); +- } +- +- /** +- * We have 3 identical statements, but select only 2. +- * This should not cause problems. +- */ +- test_statements_twoOfThree() async { +- await indexTestUnit(''' +-main() { +-// start +- print(0); +- print(0); +-// end +- print(0); +-} +-'''); +- _createRefactoringForStartEndComments(); +- // apply refactoring +- return _assertSuccessfulRefactoring(''' +-main() { +-// start +- res(); +-// end +- print(0); +-} +- +-void res() { +- print(0); +- print(0); +-} +-'''); +- } +- +- void _addLibraryReturningAsync() { +- addSource('/asyncLib.dart', r''' +-library asyncLib; +-import 'dart:async'; +-Future newFuture() =3D> null; +-'''); +- } +- +- Future _assertConditionsError(String message) async { +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: message); +- } +- +- Future _assertConditionsFatal(String message) async { +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: message); +- } +- +- Future _assertFinalConditionsError(String message) async { +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: message); +- } +- +- Future _assertRefactoringChange(String expectedCode) async { +- SourceChange refactoringChange =3D await refactoring.createChange(); +- this.refactoringChange =3D refactoringChange; +- assertTestChangeResult(expectedCode); +- } +- +- /** +- * Checks that all conditions are OK and the result of applying the [Ch= ange] +- * to [testUnit] is [expectedCode]. +- */ +- Future _assertSuccessfulRefactoring(String expectedCode) async { +- await assertRefactoringConditionsOK(); +- refactoring.createGetter =3D false; +- return _assertRefactoringChange(expectedCode); +- } +- +- void _createRefactoring(int offset, int length) { +- refactoring =3D new ExtractMethodRefactoring( +- searchEngine, astProvider, testUnit, offset, length); +- refactoring.name =3D 'res'; +- } +- +- void _createRefactoringForStartEndComments() { +- int offset =3D findEnd('// start') + '\n'.length; +- int end =3D findOffset('// end'); +- _createRefactoring(offset, end - offset); +- } +- +- void _createRefactoringForStartEndString( +- String startSearch, String endSearch) { +- int offset =3D findOffset(startSearch); +- int end =3D findOffset(endSearch); +- _createRefactoring(offset, end - offset); +- } +- +- /** +- * Creates a new refactoring in [refactoring] for the selection range o= f the +- * given [search] pattern. +- */ +- void _createRefactoringForString(String search) { +- int offset =3D findOffset(search); +- int length =3D search.length; +- _createRefactoring(offset, length); +- } +- +- void _createRefactoringWithSuffix(String selectionSearch, String suffix= ) { +- int offset =3D findOffset(selectionSearch + suffix); +- int length =3D selectionSearch.length; +- _createRefactoring(offset, length); +- } +- +- /** +- * Returns a deep copy of [refactoring] parameters. +- * There was a bug masked by updating parameter instances shared betwee= n the +- * refactoring and the test. +- */ +- List _getParametersCopy() { +- return refactoring.parameters.map((p) { +- return new RefactoringMethodParameter(p.kind, p.type, p.name, id: p= .id); +- }).toList(); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/inline_local_te= st.dart b/pkg/analysis_server/test/services/refactoring/inline_local_test.d= art +deleted file mode 100644 +index 3c224eea170..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/inline_local_test.dart ++++ /dev/null +@@ -1,639 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/inline_local.dar= t'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(InlineLocalTest); +- }); +-} +- +-@reflectiveTest +-class InlineLocalTest extends RefactoringTest { +- InlineLocalRefactoringImpl refactoring; +- +- test_access() async { +- await indexTestUnit(''' +-main() { +- int test =3D 1 + 2; +- print(test); +- print(test); +-} +-'''); +- _createRefactoring('test =3D'); +- expect(refactoring.refactoringName, 'Inline Local Variable'); +- // check initial conditions and access +- await refactoring.checkInitialConditions(); +- expect(refactoring.variableName, 'test'); +- expect(refactoring.referenceCount, 2); +- } +- +- test_bad_selectionMethod() async { +- await indexTestUnit(r''' +-main() { +-} +-'''); +- _createRefactoring('main() {'); +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- _assert_fatalError_selection(status); +- } +- +- test_bad_selectionParameter() async { +- await indexTestUnit(r''' +-main(int test) { +-} +-'''); +- _createRefactoring('test) {'); +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- _assert_fatalError_selection(status); +- } +- +- test_bad_selectionVariable_hasAssignments_1() async { +- await indexTestUnit(r''' +-main() { +- int test =3D 0; +- test =3D 1; +-} +-'''); +- _createRefactoring('test =3D 0'); +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedContextSearch: 'test =3D 1'); +- } +- +- test_bad_selectionVariable_hasAssignments_2() async { +- await indexTestUnit(r''' +-main() { +- int test =3D 0; +- test +=3D 1; +-} +-'''); +- _createRefactoring('test =3D 0'); +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedContextSearch: 'test +=3D 1'); +- } +- +- test_bad_selectionVariable_notInBlock() async { +- await indexTestUnit(r''' +-main() { +- if (true) +- int test =3D 0; +-} +-'''); +- _createRefactoring('test =3D 0'); +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL); +- } +- +- test_bad_selectionVariable_notInitialized() async { +- await indexTestUnit(r''' +-main() { +- int test; +-} +-'''); +- _createRefactoring('test;'); +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL); +- } +- +- test_OK_cascade_intoCascade() async { +- await indexTestUnit(r''' +-class A { +- foo() {} +- bar() {} +-} +-main() { +- A test =3D new A()..foo(); +- test..bar(); +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-class A { +- foo() {} +- bar() {} +-} +-main() { +- new A()..foo()..bar(); +-} +-'''); +- } +- +- test_OK_cascade_intoNotCascade() async { +- await indexTestUnit(r''' +-class A { +- foo() {} +- bar() {} +-} +-main() { +- A test =3D new A()..foo(); +- test.bar(); +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-class A { +- foo() {} +- bar() {} +-} +-main() { +- (new A()..foo()).bar(); +-} +-'''); +- } +- +- test_OK_inSwitchCase() async { +- await indexTestUnit(''' +-main(int p) { +- switch (p) { +- case 0: +- int test =3D 42; +- print(test); +- break; +- } +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main(int p) { +- switch (p) { +- case 0: +- print(42); +- break; +- } +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_binaryExpression() async { +- await indexTestUnit(r''' +-main() { +- int test =3D 1 + 2; +- print('test =3D $test'); +- print('test =3D ${test}'); +- print('test =3D ${process(test)}'); +-} +-process(x) {} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- print('test =3D ${1 + 2}'); +- print('test =3D ${1 + 2}'); +- print('test =3D ${process(1 + 2)}'); +-} +-process(x) {} +-'''); +- } +- +- test_OK_intoStringInterpolation_simpleIdentifier() async { +- await indexTestUnit(r''' +-main() { +- int foo =3D 1 + 2; +- int test =3D foo; +- print('test =3D $test'); +- print('test =3D ${test}'); +- print('test =3D ${process(test)}'); +-} +-process(x) {} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- int foo =3D 1 + 2; +- print('test =3D $foo'); +- print('test =3D ${foo}'); +- print('test =3D ${process(foo)}'); +-} +-process(x) {} +-'''); +- } +- +- test_OK_intoStringInterpolation_string_differentQuotes() async { +- await indexTestUnit(r''' +-main() { +- String a =3D "aaa"; +- String b =3D '$a bbb'; +-} +-'''); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- String b =3D '${"aaa"} bbb'; +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_string_doubleQuotes() async { +- await indexTestUnit(r''' +-main() { +- String a =3D "aaa"; +- String b =3D "$a bbb"; +-} +-'''); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- String b =3D "aaa bbb"; +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_string_multiLineIntoMulti_leadingSpaces= () async { +- await indexTestUnit(r""" +-main() { +- String a =3D '''\ \ +-a +-a'''; +- String b =3D ''' +-$a +-bbb'''; +-} +-"""); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r""" +-main() { +- String b =3D ''' +-a +-a +-bbb'''; +-} +-"""); +- } +- +- test_OK_intoStringInterpolation_string_multiLineIntoMulti_unixEOL() asy= nc { +- await indexTestUnit(r""" +-main() { +- String a =3D ''' +-a +-a +-a'''; +- String b =3D ''' +-$a +-bbb'''; +-} +-"""); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r""" +-main() { +- String b =3D ''' +-a +-a +-a +-bbb'''; +-} +-"""); +- } +- +- test_OK_intoStringInterpolation_string_multiLineIntoMulti_windowsEOL() = async { +- await indexTestUnit(r""" +-main() { +- String a =3D ''' +-a +-a +-a'''; +- String b =3D ''' +-$a +-bbb'''; +-} +-""" +- .replaceAll('\n', '\r\n')); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r""" +-main() { +- String b =3D ''' +-a +-a +-a +-bbb'''; +-} +-""" +- .replaceAll('\n', '\r\n')); +- } +- +- test_OK_intoStringInterpolation_string_multiLineIntoSingle() async { +- await indexTestUnit(r''' +-main() { +- String a =3D """aaa"""; +- String b =3D "$a bbb"; +-} +-'''); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- String b =3D "${"""aaa"""} bbb"; +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_string_raw() async { +- await indexTestUnit(r''' +-main() { +- String a =3D r'an $ignored interpolation'; +- String b =3D '$a bbb'; +-} +-'''); +- _createRefactoring('a =3D'); +- // we don't unwrap raw strings +- return assertSuccessfulRefactoring(r''' +-main() { +- String b =3D '${r'an $ignored interpolation'} bbb'; +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_string_singleLineIntoMulti_doubleQuotes= () async { +- await indexTestUnit(r''' +-main() { +- String a =3D "aaa"; +- String b =3D """$a bbb"""; +-} +-'''); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- String b =3D """aaa bbb"""; +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_string_singleLineIntoMulti_singleQuotes= () async { +- await indexTestUnit(r""" +-main() { +- String a =3D 'aaa'; +- String b =3D '''$a bbb'''; +-} +-"""); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r""" +-main() { +- String b =3D '''aaa bbb'''; +-} +-"""); +- } +- +- test_OK_intoStringInterpolation_string_singleQuotes() async { +- await indexTestUnit(r''' +-main() { +- String a =3D 'aaa'; +- String b =3D '$a bbb'; +-} +-'''); +- _createRefactoring('a =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- String b =3D 'aaa bbb'; +-} +-'''); +- } +- +- test_OK_intoStringInterpolation_stringInterpolation() async { +- await indexTestUnit(r''' +-main() { +- String a =3D 'aaa'; +- String b =3D '$a bbb'; +- String c =3D '$b ccc'; +-} +-'''); +- _createRefactoring('b =3D'); +- // validate change +- return assertSuccessfulRefactoring(r''' +-main() { +- String a =3D 'aaa'; +- String c =3D '$a bbb ccc'; +-} +-'''); +- } +- +- /** +- *

    +- * https://code.google.com/p/dart/issues/detail?id=3D18587 +- */ +- test_OK_keepNextCommentedLine() async { +- await indexTestUnit(''' +-main() { +- int test =3D 1 + 2; +- // foo +- print(test); +- // bar +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- // foo +- print(1 + 2); +- // bar +-} +-'''); +- } +- +- test_OK_noUsages_1() async { +- await indexTestUnit(''' +-main() { +- int test =3D 1 + 2; +- print(0); +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- print(0); +-} +-'''); +- } +- +- test_OK_noUsages_2() async { +- await indexTestUnit(''' +-main() { +- int test =3D 1 + 2; +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +-} +-'''); +- } +- +- test_OK_oneUsage() async { +- await indexTestUnit(''' +-main() { +- int test =3D 1 + 2; +- print(test); +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- print(1 + 2); +-} +-'''); +- } +- +- test_OK_parenthesis_decrement_intoNegate() async { +- await indexTestUnit(''' +-main() { +- var a =3D 1; +- var test =3D --a; +- var b =3D -test; +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- var a =3D 1; +- var b =3D -(--a); +-} +-'''); +- } +- +- test_OK_parenthesis_instanceCreation_intoList() async { +- await indexTestUnit(''' +-class A {} +-main() { +- var test =3D new A(); +- var list =3D [test]; +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-class A {} +-main() { +- var list =3D [new A()]; +-} +-'''); +- } +- +- test_OK_parenthesis_intoIndexExpression_index() async { +- await indexTestUnit(''' +-main() { +- var items =3D []; +- var test =3D 1 + 2; +- items[test] * 5; +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- var items =3D []; +- items[1 + 2] * 5; +-} +-'''); +- } +- +- test_OK_parenthesis_intoParenthesizedExpression() async { +- await indexTestUnit(''' +-f(m, x, y) { +- int test =3D x as int; +- m[test] =3D y; +- return m[test]; +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-f(m, x, y) { +- m[x as int] =3D y; +- return m[x as int]; +-} +-'''); +- } +- +- test_OK_parenthesis_negate_intoNegate() async { +- await indexTestUnit(''' +-main() { +- var a =3D 1; +- var test =3D -a; +- var b =3D -test; +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- var a =3D 1; +- var b =3D -(-a); +-} +-'''); +- } +- +- test_OK_parenthesis_plus_intoMultiply() async { +- await indexTestUnit(''' +-main() { +- var test =3D 1 + 2; +- print(test * 3); +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- print((1 + 2) * 3); +-} +-'''); +- } +- +- test_OK_twoUsages() async { +- await indexTestUnit(''' +-main() { +- int test =3D 1 + 2; +- print(test); +- print(test); +-} +-'''); +- _createRefactoring('test =3D'); +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- print(1 + 2); +- print(1 + 2); +-} +-'''); +- } +- +- void _assert_fatalError_selection(RefactoringStatus status) { +- expect(refactoring.variableName, isNull); +- expect(refactoring.referenceCount, 0); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: 'Local variable declaration or reference must be= ' +- 'selected to activate this refactoring.'); +- } +- +- void _createRefactoring(String search) { +- int offset =3D findOffset(search); +- refactoring =3D +- new InlineLocalRefactoring(searchEngine, astProvider, testUnit, o= ffset); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/inline_method_t= est.dart b/pkg/analysis_server/test/services/refactoring/inline_method_test= .dart +deleted file mode 100644 +index 64c50e08954..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/inline_method_test.dart ++++ /dev/null +@@ -1,1761 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/inline_method.da= rt'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Eleme= nt; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(InlineMethodTest); +- }); +-} +- +-@reflectiveTest +-class InlineMethodTest extends RefactoringTest { +- InlineMethodRefactoringImpl refactoring; +- bool deleteSource; +- bool inlineAll; +- +- test_access_FunctionElement() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(1, 2)'); +- // validate state +- await refactoring.checkInitialConditions(); +- expect(refactoring.refactoringName, 'Inline Function'); +- expect(refactoring.className, isNull); +- expect(refactoring.methodName, 'test'); +- expect(refactoring.isDeclaration, isFalse); +- } +- +- test_access_MethodElement() async { +- await indexTestUnit(r''' +-class A { +- test(a, b) { +- return a + b; +- } +- main() { +- var res =3D test(1, 2); +- } +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate state +- await refactoring.checkInitialConditions(); +- expect(refactoring.refactoringName, 'Inline Method'); +- expect(refactoring.className, 'A'); +- expect(refactoring.methodName, 'test'); +- expect(refactoring.isDeclaration, isTrue); +- } +- +- test_bad_async_intoSyncStar() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future get test async =3D> 42; +- Iterable> foo() sync* { +- yield test; +- } +-} +-'''); +- _createRefactoring('test async'); +- // error +- return _assertConditionsFatal('Cannot inline async into sync*.'); +- } +- +- test_bad_async_targetIsSync_doesNotReturnFuture() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future get test async =3D> 42; +- double foo() { +- test; +- return 1.2; +- } +-} +-'''); +- _createRefactoring('test async'); +- // error +- return _assertConditionsFatal( +- 'Cannot inline async into a function that does not return a Futur= e.'); +- } +- +- test_bad_asyncStar() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Stream test() async* { +- yield 1; +- yield 2; +- } +- foo() { +- test(); +- } +-} +-'''); +- _createRefactoring('test() async*'); +- // error +- return _assertConditionsFatal('Cannot inline a generator.'); +- } +- +- test_bad_cascadeInvocation() async { +- await indexTestUnit(r''' +-class A { +- foo() {} +- bar() {} +- test() {} +-} +-main() { +- A a =3D new A(); +- a..foo()..test()..bar(); +-} +-'''); +- _createRefactoring('test() {'); +- // error +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- var location =3D new SourceRange(findOffset('..test()'), '..test()'.l= ength); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: 'Cannot inline cascade invocation.', +- expectedContextRange: location); +- } +- +- test_bad_constructor() async { +- await indexTestUnit(r''' +-class A { +- A.named() {} +-} +-'''); +- _createRefactoring('named() {}'); +- // error +- return _assertInvalidSelection(); +- } +- +- test_bad_deleteSource_inlineOne() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res1 =3D test(1, 2); +- var res2 =3D test(10, 20); +-} +-'''); +- _createRefactoring('test(1, 2)'); +- // initial conditions +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatusOK(status); +- refactoring.deleteSource =3D true; +- refactoring.inlineAll =3D false; +- // final conditions +- status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- 'All references must be inlined to remove the source.'); +- } +- +- test_bad_notExecutableElement() async { +- await indexTestUnit(r''' +-main() { +-} +-'''); +- _createRefactoring(') {'); +- // error +- return _assertInvalidSelection(); +- } +- +- test_bad_notSimpleIdentifier() async { +- await indexTestUnit(r''' +-main() { +- var test =3D 42; +- var res =3D test; +-} +-'''); +- _createRefactoring('test;'); +- // error +- return _assertInvalidSelection(); +- } +- +- test_bad_operator() async { +- await indexTestUnit(r''' +-class A { +- operator -(other) =3D> this; +-} +-'''); +- _createRefactoring('-(other)'); +- // error +- return _assertConditionsFatal('Cannot inline operator.'); +- } +- +- test_bad_propertyAccessor_synthetic() async { +- await indexTestUnit(r''' +-class A { +- int fff; +-} +- +-main(A a) { +- print(a.fff); +-} +-'''); +- _createRefactoring('fff);'); +- // error +- return _assertInvalidSelection(); +- } +- +- test_bad_reference_toClassMethod() async { +- await indexTestUnit(r''' +-class A { +- test(a, b) { +- print(a); +- print(b); +- } +-} +-main() { +- print(new A().test); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // error +- return _assertConditionsFatal('Cannot inline class method reference.'= ); +- } +- +- test_bad_severalReturns() async { +- await indexTestUnit(r''' +-test() { +- if (true) { +- return 1; +- } +- return 2; +-} +-main() { +- var res =3D test(); +-} +-'''); +- _createRefactoring('test() {'); +- // error +- return _assertConditionsError('Ambiguous return value.'); +- } +- +- test_cascadeInCascade() async { +- await indexTestUnit(r''' +-class Inner { +- String a; +- String b; +-} +- +-class Outer { +- Inner inner; +-} +- +-void main() { +- Inner createInner() =3D> new Inner() +- ..a =3D 'a' +- ..b =3D 'b'; +- +- final value =3D new Outer() +- ..inner =3D createInner(); +-} +-'''); +- _createRefactoring('createInner();'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class Inner { +- String a; +- String b; +-} +- +-class Outer { +- Inner inner; +-} +- +-void main() { +- Inner createInner() =3D> new Inner() +- ..a =3D 'a' +- ..b =3D 'b'; +- +- final value =3D new Outer() +- ..inner =3D (new Inner() +- ..a =3D 'a' +- ..b =3D 'b'); +-} +-'''); +- } +- +- test_fieldAccessor_getter() async { +- await indexTestUnit(r''' +-class A { +- var f; +- get foo { +- return f * 2; +- } +-} +-main() { +- A a =3D new A(); +- print(a.foo); +-} +-'''); +- _createRefactoring('foo {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var f; +-} +-main() { +- A a =3D new A(); +- print(a.f * 2); +-} +-'''); +- } +- +- test_fieldAccessor_getter_PropertyAccess() async { +- await indexTestUnit(r''' +-class A { +- var f; +- get foo { +- return f * 2; +- } +-} +-class B { +- A a =3D new A(); +-} +-main() { +- B b =3D new B(); +- print(b.a.foo); +-} +-'''); +- _createRefactoring('foo {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var f; +-} +-class B { +- A a =3D new A(); +-} +-main() { +- B b =3D new B(); +- print(b.a.f * 2); +-} +-'''); +- } +- +- test_fieldAccessor_setter() async { +- await indexTestUnit(r''' +-class A { +- var f; +- set foo(x) { +- f =3D x; +- } +-} +-main() { +- A a =3D new A(); +- a.foo =3D 0; +-} +-'''); +- _createRefactoring('foo(x) {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var f; +-} +-main() { +- A a =3D new A(); +- a.f =3D 0; +-} +-'''); +- } +- +- test_fieldAccessor_setter_PropertyAccess() async { +- await indexTestUnit(r''' +-class A { +- var f; +- set foo(x) { +- f =3D x; +- } +-} +-class B { +- A a =3D new A(); +-} +-main() { +- B b =3D new B(); +- b.a.foo =3D 0; +-} +-'''); +- _createRefactoring('foo(x) {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var f; +-} +-class B { +- A a =3D new A(); +-} +-main() { +- B b =3D new B(); +- b.a.f =3D 0; +-} +-'''); +- } +- +- test_function_expressionFunctionBody() async { +- await indexTestUnit(r''' +-test(a, b) =3D> a + b; +-main() { +- print(test(1, 2)); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(1 + 2); +-} +-'''); +- } +- +- test_function_hasReturn_assign() async { +- await indexTestUnit(r''' +-test(a, b) { +- print(a); +- print(b); +- return a + b; +-} +-main() { +- var v; +- v =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var v; +- print(1); +- print(2); +- v =3D 1 + 2; +-} +-'''); +- } +- +- test_function_hasReturn_hasReturnType() async { +- await indexTestUnit(r''' +-int test(a, b) { +- return a + b; +-} +-main() { +- var v =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var v =3D 1 + 2; +-} +-'''); +- } +- +- test_function_hasReturn_noVars_oneUsage() async { +- await indexTestUnit(r''' +-test(a, b) { +- print(a); +- print(b); +- return a + b; +-} +-main() { +- var v =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(1); +- print(2); +- var v =3D 1 + 2; +-} +-'''); +- } +- +- test_function_multilineString() async { +- await indexTestUnit(r""" +-main() { +- { +- test(); +- } +-} +-test() { +- print(''' +-first line +-second line +- '''); +-} +-"""); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r""" +-main() { +- { +- print(''' +-first line +-second line +- '''); +- } +-} +-"""); +- } +- +- test_function_noReturn_hasVars_hasConflict_fieldSuperClass() async { +- await indexTestUnit(r''' +-class A { +- var c; +-} +-class B extends A { +- foo() { +- test(1, 2); +- } +-} +-test(a, b) { +- var c =3D a + b; +- print(c); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var c; +-} +-class B extends A { +- foo() { +- var c2 =3D 1 + 2; +- print(c2); +- } +-} +-'''); +- } +- +- test_function_noReturn_hasVars_hasConflict_fieldThisClass() async { +- await indexTestUnit(r''' +-class A { +- var c; +- foo() { +- test(1, 2); +- } +-} +-test(a, b) { +- var c =3D a + b; +- print(c); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var c; +- foo() { +- var c2 =3D 1 + 2; +- print(c2); +- } +-} +-'''); +- } +- +- test_function_noReturn_hasVars_hasConflict_localAfter() async { +- await indexTestUnit(r''' +-test(a, b) { +- var c =3D a + b; +- print(c); +-} +-main() { +- test(1, 2); +- var c =3D 0; +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var c2 =3D 1 + 2; +- print(c2); +- var c =3D 0; +-} +-'''); +- } +- +- test_function_noReturn_hasVars_hasConflict_localBefore() async { +- await indexTestUnit(r''' +-test(a, b) { +- var c =3D a + b; +- print(c); +-} +-main() { +- var c =3D 0; +- test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var c =3D 0; +- var c2 =3D 1 + 2; +- print(c2); +-} +-'''); +- } +- +- test_function_noReturn_hasVars_noConflict() async { +- await indexTestUnit(r''' +-test(a, b) { +- var c =3D a + b; +- print(c); +-} +-main() { +- test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var c =3D 1 + 2; +- print(c); +-} +-'''); +- } +- +- test_function_noReturn_noVars_oneUsage() async { +- await indexTestUnit(r''' +-test(a, b) { +- print(a); +- print(b); +-} +-main() { +- test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(1); +- print(2); +-} +-'''); +- } +- +- test_function_noReturn_noVars_useIndentation() async { +- await indexTestUnit(r''' +-test(a, b) { +- print(a); +- print(b); +-} +-main() { +- { +- test(1, 2); +- } +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- { +- print(1); +- print(2); +- } +-} +-'''); +- } +- +- test_function_noReturn_voidReturnType() async { +- await indexTestUnit(r''' +-void test(a, b) { +- print(a + b); +-} +-main() { +- test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(1 + 2); +-} +-'''); +- } +- +- test_function_notStatement_oneStatement_assign() async { +- await indexTestUnit(r''' +-test(int p) { +- print(p * 2); +-} +-main() { +- var v; +- v =3D test(0); +-} +-'''); +- _createRefactoring('test(int p)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var v; +- v =3D (int p) { +- print(p * 2); +- }(0); +-} +-'''); +- } +- +- test_function_notStatement_oneStatement_variableDeclaration() async { +- await indexTestUnit(r''' +-test(int p) { +- print(p * 2); +-} +-main() { +- var v =3D test(0); +-} +-'''); +- _createRefactoring('test(int p)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var v =3D (int p) { +- print(p * 2); +- }(0); +-} +-'''); +- } +- +- test_function_notStatement_severalStatements() async { +- await indexTestUnit(r''' +-test(int p) { +- print(p); +- print(p * 2); +-} +-main() { +- var v =3D test(0); +-} +-'''); +- _createRefactoring('test(int p)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var v =3D (int p) { +- print(p); +- print(p * 2); +- }(0); +-} +-'''); +- } +- +- test_function_notStatement_zeroStatements() async { +- await indexTestUnit(r''' +-test(int p) { +-} +-main() { +- var v =3D test(0); +-} +-'''); +- _createRefactoring('test(int p)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var v =3D (int p) { +- }(0); +-} +-'''); +- } +- +- test_function_singleStatement() async { +- await indexTestUnit(r''' +-var topLevelField =3D 0; +-test() { +- print(topLevelField); +-} +-main() { +- test(); +-} +-'''); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-var topLevelField =3D 0; +-main() { +- print(topLevelField); +-} +-'''); +- } +- +- test_getter_async_targetIsAsync() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future get test async =3D> 42; +- Future foo() async { +- return test; +- } +-} +-'''); +- _createRefactoring('test async'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-import 'dart:async'; +-class A { +- Future foo() async { +- return 42; +- } +-} +-'''); +- } +- +- test_getter_async_targetIsAsyncStar() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future get test async =3D> 42; +- Stream foo() async* { +- yield await test; +- } +-} +-'''); +- _createRefactoring('test async'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-import 'dart:async'; +-class A { +- Stream foo() async* { +- yield await 42; +- } +-} +-'''); +- } +- +- test_getter_async_targetIsSync() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future get test async =3D> 42; +- Future foo() { +- return test; +- } +-} +-'''); +- _createRefactoring('test async'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-import 'dart:async'; +-class A { +- Future foo() async { +- return 42; +- } +-} +-'''); +- } +- +- test_getter_async_targetIsSync2() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future get test async =3D> 42; +- Future foo1() { +- return test; +- } +- Future foo2() { +- return test; +- } +-} +-'''); +- _createRefactoring('test async'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-import 'dart:async'; +-class A { +- Future foo1() async { +- return 42; +- } +- Future foo2() async { +- return 42; +- } +-} +-'''); +- } +- +- test_getter_classMember_instance() async { +- await indexTestUnit(r''' +-class A { +- int f; +- int get result =3D> f + 1; +-} +-main(A a) { +- print(a.result); +-} +-'''); +- _createRefactoring('result =3D>'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- int f; +-} +-main(A a) { +- print(a.f + 1); +-} +-'''); +- } +- +- test_getter_classMember_static() async { +- await indexTestUnit(r''' +-class A { +- static int get result =3D> 1 + 2; +-} +-main() { +- print(A.result); +-} +-'''); +- _createRefactoring('result =3D>'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +-} +-main() { +- print(1 + 2); +-} +-'''); +- } +- +- test_getter_topLevel() async { +- await indexTestUnit(r''' +-String get message =3D> 'Hello, World!'; +-main() { +- print(message); +-} +-'''); +- _createRefactoring('message =3D>'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print('Hello, World!'); +-} +-'''); +- } +- +- test_initialMode_all() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate state +- await refactoring.checkInitialConditions(); +- expect(refactoring.deleteSource, true); +- expect(refactoring.inlineAll, true); +- } +- +- test_initialMode_single() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res1 =3D test(1, 2); +- var res2 =3D test(10, 20); +-} +-'''); +- _createRefactoring('test(1, 2)'); +- deleteSource =3D false; +- // validate state +- await refactoring.checkInitialConditions(); +- expect(refactoring.deleteSource, false); +- expect(refactoring.inlineAll, false); +- } +- +- test_method_async() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future test() async =3D> 42; +- Future foo() { +- return test(); +- } +-} +-'''); +- _createRefactoring('test() async'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-import 'dart:async'; +-class A { +- Future foo() async { +- return 42; +- } +-} +-'''); +- } +- +- test_method_async2() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-class A { +- Future foo() async =3D> 42; +- Future test() async =3D> await foo(); +- Future bar() { +- return new Future.value([test(), test()]); +- } +-} +-'''); +- _createRefactoring('test() async'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-import 'dart:async'; +-class A { +- Future foo() async =3D> 42; +- Future bar() async { +- return new Future.value([(await foo()), (await foo())]); +- } +-} +-'''); +- } +- +- test_method_emptyBody() async { +- await indexTestUnit(r''' +-abstract class A { +- test(); +-} +-main(A a) { +- print(a.test()); +-} +-'''); +- _createRefactoring('test();'); +- // error +- return _assertConditionsFatal('Cannot inline method without body.'); +- } +- +- test_method_fieldInstance() async { +- await indexTestUnit(r''' +-class A { +- var fA; +-} +-class B extends A { +- var fB; +- test() { +- print(fA); +- print(fB); +- print(this.fA); +- print(this.fB); +- } +-} +-main() { +- B b =3D new B(); +- b.test(); +-} +-'''); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- var fA; +-} +-class B extends A { +- var fB; +-} +-main() { +- B b =3D new B(); +- print(b.fA); +- print(b.fB); +- print(b.fA); +- print(b.fB); +-} +-'''); +- } +- +- test_method_fieldStatic() async { +- await indexTestUnit(r''' +-class A { +- static var FA =3D 1; +-} +-class B extends A { +- static var FB =3D 2; +- test() { +- print(FB); +- print(A.FA); +- print(B.FB); +- } +-} +-main() { +- B b =3D new B(); +- b.test(); +-} +-'''); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- static var FA =3D 1; +-} +-class B extends A { +- static var FB =3D 2; +-} +-main() { +- B b =3D new B(); +- print(B.FB); +- print(A.FA); +- print(B.FB); +-} +-'''); +- } +- +- test_method_fieldStatic_sameClass() async { +- await indexTestUnit(r''' +-class A { +- static var F =3D 1; +- foo() { +- test(); +- } +- test() { +- print(A.F); +- } +-} +-'''); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- static var F =3D 1; +- foo() { +- print(A.F); +- } +-} +-'''); +- } +- +- test_method_methodInstance() async { +- await indexTestUnit(r''' +-class A { +- ma() {} +-} +-class B extends A { +- test() { +- ma(); +- mb(); +- } +- mb() {} +-} +-main(B b) { +- b.test(); +-} +-'''); +- _createRefactoring('test();'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- ma() {} +-} +-class B extends A { +- test() { +- ma(); +- mb(); +- } +- mb() {} +-} +-main(B b) { +- b.ma(); +- b.mb(); +-} +-'''); +- } +- +- test_method_methodStatic() async { +- await indexTestUnit(r''' +-class A { +- static ma() {} +-} +-class B extends A { +- static mb() {} +- test() { +- mb(); +- A.ma(); +- B.mb(); +- } +-} +-main(B b) { +- b.test(); +-} +-'''); +- _createRefactoring('test();'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- static ma() {} +-} +-class B extends A { +- static mb() {} +- test() { +- mb(); +- A.ma(); +- B.mb(); +- } +-} +-main(B b) { +- B.mb(); +- A.ma(); +- B.mb(); +-} +-'''); +- } +- +- test_method_singleStatement() async { +- await indexTestUnit(r''' +-class A { +- test() { +- print(0); +- } +- foo() { +- test(); +- } +-} +-'''); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- foo() { +- print(0); +- } +-} +-'''); +- } +- +- test_method_this() async { +- await indexTestUnit(r''' +-class A { +- accept(B b) {} +-} +-class B { +- test(A a) { +- print(this); +- a.accept(this); +- } +-} +-main() { +- B b =3D new B(); +- A a =3D new A(); +- b.test(a); +-} +-'''); +- _createRefactoring('test(A a) {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- accept(B b) {} +-} +-class B { +-} +-main() { +- B b =3D new B(); +- A a =3D new A(); +- print(b); +- a.accept(b); +-} +-'''); +- } +- +- test_method_unqualifiedInvocation() async { +- await indexTestUnit(r''' +-class A { +- test(a, b) { +- print(a); +- print(b); +- return a + b; +- } +- foo() { +- var v =3D test(1, 2); +- } +-} +-'''); +- _createRefactoring('test(a, b) {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- foo() { +- print(1); +- print(2); +- var v =3D 1 + 2; +- } +-} +-'''); +- } +- +- test_namedArgument_inBody() async { +- await indexTestUnit(r''' +-fa(pa) =3D> fb(pb: true); +-fb({pb: false}) {} +-main() { +- fa(null); +-} +-'''); +- _createRefactoring('fa(null)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-fa(pa) =3D> fb(pb: true); +-fb({pb: false}) {} +-main() { +- fb(pb: true); +-} +-'''); +- } +- +- test_namedArguments() async { +- await indexTestUnit(r''' +-test({a: 0, b: 2}) { +- print(a + b); +-} +-main() { +- test(a: 10, b: 20); +- test(b: 20, a: 10); +-} +-'''); +- _createRefactoring('test({'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(10 + 20); +- print(10 + 20); +-} +-'''); +- } +- +- test_noArgument_named_hasDefault() async { +- verifyNoTestUnitErrors =3D false; +- await indexTestUnit(r''' +-test({a: 42}) { +- print(a); +-} +-main() { +- test(); +-} +-'''); +- _createRefactoring('test('); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(42); +-} +-'''); +- } +- +- test_noArgument_positional_hasDefault() async { +- verifyNoTestUnitErrors =3D false; +- await indexTestUnit(r''' +-test([a =3D 42]) { +- print(a); +-} +-main() { +- test(); +-} +-'''); +- _createRefactoring('test('); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(42); +-} +-'''); +- } +- +- test_noArgument_positional_noDefault() async { +- verifyNoTestUnitErrors =3D false; +- await indexTestUnit(r''' +-test([a]) { +- print(a); +-} +-main() { +- test(); +-} +-'''); +- _createRefactoring('test('); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(null); +-} +-'''); +- } +- +- test_noArgument_required() async { +- verifyNoTestUnitErrors =3D false; +- await indexTestUnit(r''' +-test(a) { +- print(a); +-} +-main() { +- test(); +-} +-'''); +- _createRefactoring('test();'); +- // error +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- var location =3D new SourceRange(findOffset('test();'), 'test()'.leng= th); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: 'No argument for the parameter "a".', +- expectedContextRange: location); +- } +- +- test_reference_expressionBody() async { +- await indexTestUnit(r''' +-String message() =3D> 'Hello, World!'; +-main() { +- print(message); +-} +-'''); +- _createRefactoring('message()'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(() =3D> 'Hello, World!'); +-} +-'''); +- } +- +- test_reference_noStatement() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a || b; +-} +-foo(p1, p2, p3) =3D> p1 && test(p2, p3); +-bar() =3D> { +- 'name' : baz(test) +-}; +-baz(x) {} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-foo(p1, p2, p3) =3D> p1 && (p2 || p3); +-bar() =3D> { +- 'name' : baz((a, b) { +- return a || b; +- }) +-}; +-baz(x) {} +-'''); +- } +- +- test_reference_toLocal() async { +- await indexTestUnit(r''' +-main() { +- test(a, b) { +- print(a); +- print(b); +- } +- print(test); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print((a, b) { +- print(a); +- print(b); +- }); +-} +-'''); +- } +- +- test_reference_toTopLevel() async { +- await indexTestUnit(r''' +-test(a, b) { +- print(a); +- print(b); +-} +-main() { +- print(test); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print((a, b) { +- print(a); +- print(b); +- }); +-} +-'''); +- } +- +- test_removeEmptyLinesBefore_method() async { +- await indexTestUnit(r''' +-class A { +- before() { +- } +- +- +- test() { +- print(0); +- } +- +- foo() { +- test(); +- } +-} +-'''); +- _createRefactoring('test() {'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- before() { +- } +- +- foo() { +- print(0); +- } +-} +-'''); +- } +- +- test_setter_classMember_instance() async { +- await indexTestUnit(r''' +-class A { +- int f; +- void set result(x) { +- f =3D x + 1; +- } +-} +-main(A a) { +- a.result =3D 5; +-} +-'''); +- _createRefactoring('result(x)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-class A { +- int f; +-} +-main(A a) { +- a.f =3D 5 + 1; +-} +-'''); +- } +- +- test_setter_topLevel() async { +- await indexTestUnit(r''' +-void set result(x) { +- print(x + 1); +-} +-main() { +- result =3D 5; +-} +-'''); +- _createRefactoring('result(x)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- print(5 + 1); +-} +-'''); +- } +- +- test_singleExpression_oneUsage() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var res =3D 1 + 2; +-} +-'''); +- } +- +- test_singleExpression_oneUsage_keepMethod() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res =3D test(1, 2); +-} +-'''); +- _createRefactoring('test(a, b)'); +- deleteSource =3D false; +- // validate change +- return _assertSuccessfulRefactoring(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res =3D 1 + 2; +-} +-'''); +- } +- +- test_singleExpression_twoUsages() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res1 =3D test(1, 2); +- var res2 =3D test(10, 20); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var res1 =3D 1 + 2; +- var res2 =3D 10 + 20; +-} +-'''); +- } +- +- test_singleExpression_twoUsages_inlineOne() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res1 =3D test(1, 2); +- var res2 =3D test(10, 20); +-} +-'''); +- _createRefactoring('test(1, 2)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-test(a, b) { +- return a + b; +-} +-main() { +- var res1 =3D 1 + 2; +- var res2 =3D test(10, 20); +-} +-'''); +- } +- +- test_singleExpression_wrapIntoParenthesized_alreadyInMethod() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a * (b); +-} +-main() { +- var res =3D test(1, 2 + 3); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var res =3D 1 * (2 + 3); +-} +-'''); +- } +- +- test_singleExpression_wrapIntoParenthesized_asNeeded() async { +- await indexTestUnit(r''' +-test(a, b) { +- return a * b; +-} +-main() { +- var res1 =3D test(1, 2 + 3); +- var res2 =3D test(1, (2 + 3)); +-} +-'''); +- _createRefactoring('test(a, b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main() { +- var res1 =3D 1 * (2 + 3); +- var res2 =3D 1 * (2 + 3); +-} +-'''); +- } +- +- test_singleExpression_wrapIntoParenthesized_bool() async { +- await indexTestUnit(r''' +-test(bool a, bool b) { +- return a || b; +-} +-main(bool p, bool p2, bool p3) { +- var res1 =3D p && test(p2, p3); +- var res2 =3D p || test(p2, p3); +-} +-'''); +- _createRefactoring('test(bool a, bool b)'); +- // validate change +- return _assertSuccessfulRefactoring(r''' +-main(bool p, bool p2, bool p3) { +- var res1 =3D p && (p2 || p3); +- var res2 =3D p || p2 || p3; +-} +-'''); +- } +- +- Future _assertConditionsError(String message) async { +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: message); +- } +- +- Future _assertConditionsFatal(String message) async { +- RefactoringStatus status =3D await refactoring.checkAllConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: message); +- } +- +- Future _assertInvalidSelection() { +- return _assertConditionsFatal( +- 'Method declaration or reference must be selected to activate thi= s refactoring.'); +- } +- +- Future _assertSuccessfulRefactoring(String expectedCode) async { +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatusOK(status); +- // configure +- if (deleteSource !=3D null) { +- refactoring.deleteSource =3D deleteSource; +- } +- if (inlineAll !=3D null) { +- refactoring.inlineAll =3D inlineAll; +- } +- // final conditions +- status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- // change +- SourceChange change =3D await refactoring.createChange(); +- this.refactoringChange =3D change; +- assertTestChangeResult(expectedCode); +- } +- +- void _createRefactoring(String search) { +- int offset =3D findOffset(search); +- refactoring =3D new InlineMethodRefactoring( +- searchEngine, astProvider, testUnit, offset); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/naming_conventi= ons_test.dart b/pkg/analysis_server/test/services/refactoring/naming_conven= tions_test.dart +deleted file mode 100644 +index 736448b01c5..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/naming_conventions_tes= t.dart ++++ /dev/null +@@ -1,754 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/refactoring/naming_conventio= ns.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer_plugin/protocol/protocol_common.dart' +- show RefactoringProblemSeverity; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_refactoring.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(NamingConventionsTest); +- }); +-} +- +-@reflectiveTest +-class NamingConventionsTest extends RefactoringTest { +- @override +- Refactoring get refactoring =3D> null; +- +- void test_validateClassName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateClassName("newName"), RefactoringProblemSeverity.WARNING, +- expectedMessage: "Class name should start with an uppercase lette= r."); +- } +- +- void test_validateClassName_empty() { +- assertRefactoringStatus( +- validateClassName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not be empty."); +- } +- +- void test_validateClassName_leadingBlanks() { +- assertRefactoringStatus( +- validateClassName(" NewName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not start or end with a blank."= ); +- } +- +- void test_validateClassName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateClassName("New-Name"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not contain '-'."); +- } +- +- void test_validateClassName_notIdentifierStart() { +- assertRefactoringStatus( +- validateClassName("-NewName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Class name must begin with an uppercase letter or underscore= ."); +- } +- +- void test_validateClassName_null() { +- assertRefactoringStatus( +- validateClassName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not be null."); +- } +- +- void test_validateClassName_OK() { +- assertRefactoringStatusOK(validateClassName("NewName")); +- } +- +- void test_validateClassName_OK_leadingDollar() { +- assertRefactoringStatusOK(validateClassName("\$NewName")); +- } +- +- void test_validateClassName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateClassName("_NewName")); +- } +- +- void test_validateClassName_OK_middleDollar() { +- assertRefactoringStatusOK(validateClassName("New\$Name")); +- } +- +- void test_validateClassName_trailingBlanks() { +- assertRefactoringStatus( +- validateClassName("NewName "), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not start or end with a blank."= ); +- } +- +- void test_validateConstructorName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateConstructorName("NewName"), RefactoringProblemSeverity.WA= RNING, +- expectedMessage: +- "Constructor name should start with a lowercase letter."); +- } +- +- void test_validateConstructorName_empty() { +- assertRefactoringStatusOK(validateConstructorName("")); +- } +- +- void test_validateConstructorName_leadingBlanks() { +- assertRefactoringStatus( +- validateConstructorName(" newName"), RefactoringProblemSeverity.F= ATAL, +- expectedMessage: +- "Constructor name must not start or end with a blank."); +- } +- +- void test_validateConstructorName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateConstructorName("na-me"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Constructor name must not contain '-'."); +- } +- +- void test_validateConstructorName_notIdentifierStart() { +- assertRefactoringStatus( +- validateConstructorName("2name"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: +- "Constructor name must begin with a lowercase letter or under= score."); +- } +- +- void test_validateConstructorName_null() { +- assertRefactoringStatus( +- validateConstructorName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Constructor name must not be null."); +- } +- +- void test_validateConstructorName_OK() { +- assertRefactoringStatusOK(validateConstructorName("newName")); +- } +- +- void test_validateConstructorName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateConstructorName("_newName")); +- } +- +- void test_validateConstructorName_trailingBlanks() { +- assertRefactoringStatus( +- validateConstructorName("newName "), RefactoringProblemSeverity.F= ATAL, +- expectedMessage: +- "Constructor name must not start or end with a blank."); +- } +- +- void test_validateFieldName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateFieldName("NewName"), RefactoringProblemSeverity.WARNING, +- expectedMessage: "Field name should start with a lowercase letter= ."); +- } +- +- void test_validateFieldName_empty() { +- assertRefactoringStatus( +- validateFieldName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not be empty."); +- } +- +- void test_validateFieldName_leadingBlanks() { +- assertRefactoringStatus( +- validateFieldName(" newName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not start or end with a blank."= ); +- } +- +- void test_validateFieldName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateFieldName("new-Name"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not contain '-'."); +- } +- +- void test_validateFieldName_notIdentifierStart() { +- assertRefactoringStatus( +- validateFieldName("2newName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Field name must begin with a lowercase letter or underscore.= "); +- } +- +- void test_validateFieldName_notKeyword() { +- assertRefactoringStatus( +- validateFieldName("for"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not be a keyword."); +- } +- +- void test_validateFieldName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateFieldName("await"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not be a keyword."); +- } +- +- void test_validateFieldName_null() { +- assertRefactoringStatus( +- validateFieldName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not be null."); +- } +- +- void test_validateFieldName_OK() { +- assertRefactoringStatusOK(validateFieldName("newName")); +- } +- +- void test_validateFieldName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateFieldName("_newName")); +- } +- +- void test_validateFieldName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateFieldName("new_name")); +- } +- +- void test_validateFieldName_trailingBlanks() { +- assertRefactoringStatus( +- validateFieldName("newName "), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not start or end with a blank."= ); +- } +- +- void test_validateFunctionName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateFunctionName("NewName"), RefactoringProblemSeverity.WARNI= NG, +- expectedMessage: "Function name should start with a lowercase let= ter."); +- } +- +- void test_validateFunctionName_empty() { +- assertRefactoringStatus( +- validateFunctionName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be empty."); +- } +- +- void test_validateFunctionName_leadingBlanks() { +- assertRefactoringStatus( +- validateFunctionName(" newName"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Function name must not start or end with a blan= k."); +- } +- +- void test_validateFunctionName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateFunctionName("new-Name"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Function name must not contain '-'."); +- } +- +- void test_validateFunctionName_notIdentifierStart() { +- assertRefactoringStatus( +- validateFunctionName("2newName"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: +- "Function name must begin with a lowercase letter or undersco= re."); +- } +- +- void test_validateFunctionName_notKeyword() { +- assertRefactoringStatus( +- validateFunctionName("new"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be a keyword."); +- } +- +- void test_validateFunctionName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateFunctionName("yield"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be a keyword."); +- } +- +- void test_validateFunctionName_null() { +- assertRefactoringStatus( +- validateFunctionName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be null."); +- } +- +- void test_validateFunctionName_OK() { +- assertRefactoringStatusOK(validateFunctionName("newName")); +- } +- +- void test_validateFunctionName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateFunctionName("_newName")); +- } +- +- void test_validateFunctionName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateFunctionName("new_name")); +- } +- +- void test_validateFunctionName_trailingBlanks() { +- assertRefactoringStatus( +- validateFunctionName("newName "), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Function name must not start or end with a blan= k."); +- } +- +- void test_validateFunctionTypeAliasName_doesNotStartWithLowerCase() { +- assertRefactoringStatus(validateFunctionTypeAliasName("newName"), +- RefactoringProblemSeverity.WARNING, +- expectedMessage: +- "Function type alias name should start with an uppercase lett= er."); +- } +- +- void test_validateFunctionTypeAliasName_empty() { +- assertRefactoringStatus( +- validateFunctionTypeAliasName(""), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: "Function type alias name must not be empty."); +- } +- +- void test_validateFunctionTypeAliasName_leadingBlanks() { +- assertRefactoringStatus(validateFunctionTypeAliasName(" NewName"), +- RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Function type alias name must not start or end with a blank.= "); +- } +- +- void test_validateFunctionTypeAliasName_notIdentifierMiddle() { +- assertRefactoringStatus(validateFunctionTypeAliasName("New-Name"), +- RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function type alias name must not contain '-'."= ); +- } +- +- void test_validateFunctionTypeAliasName_notIdentifierStart() { +- assertRefactoringStatus(validateFunctionTypeAliasName("-NewName"), +- RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Function type alias name must begin with an uppercase letter= or underscore."); +- } +- +- void test_validateFunctionTypeAliasName_null() { +- assertRefactoringStatus( +- validateFunctionTypeAliasName(null), RefactoringProblemSeverity.F= ATAL, +- expectedMessage: "Function type alias name must not be null."); +- } +- +- void test_validateFunctionTypeAliasName_OK() { +- assertRefactoringStatusOK(validateFunctionTypeAliasName("NewName")); +- } +- +- void test_validateFunctionTypeAliasName_OK_leadingDollar() { +- assertRefactoringStatusOK(validateFunctionTypeAliasName("\$NewName")); +- } +- +- void test_validateFunctionTypeAliasName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateFunctionTypeAliasName("_NewName")); +- } +- +- void test_validateFunctionTypeAliasName_OK_middleDollar() { +- assertRefactoringStatusOK(validateFunctionTypeAliasName("New\$Name")); +- } +- +- void test_validateFunctionTypeAliasName_trailingBlanks() { +- assertRefactoringStatus(validateFunctionTypeAliasName("NewName "), +- RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Function type alias name must not start or end with a blank.= "); +- } +- +- void test_validateImportPrefixName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateImportPrefixName("NewName"), RefactoringProblemSeverity.W= ARNING, +- expectedMessage: +- "Import prefix name should start with a lowercase letter."); +- } +- +- void test_validateImportPrefixName_empty() { +- assertRefactoringStatusOK(validateImportPrefixName("")); +- } +- +- void test_validateImportPrefixName_leadingBlanks() { +- assertRefactoringStatus( +- validateImportPrefixName(" newName"), RefactoringProblemSeverity.= FATAL, +- expectedMessage: +- "Import prefix name must not start or end with a blank."); +- } +- +- void test_validateImportPrefixName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateImportPrefixName("new-Name"), RefactoringProblemSeverity.= FATAL, +- expectedMessage: "Import prefix name must not contain '-'."); +- } +- +- void test_validateImportPrefixName_notIdentifierStart() { +- assertRefactoringStatus( +- validateImportPrefixName("2newName"), RefactoringProblemSeverity.= FATAL, +- expectedMessage: +- "Import prefix name must begin with a lowercase letter or und= erscore."); +- } +- +- void test_validateImportPrefixName_notKeyword() { +- assertRefactoringStatus( +- validateImportPrefixName("while"), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: "Import prefix name must not be a keyword."); +- } +- +- void test_validateImportPrefixName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateImportPrefixName("await"), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: "Import prefix name must not be a keyword."); +- } +- +- void test_validateImportPrefixName_null() { +- assertRefactoringStatus( +- validateImportPrefixName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Import prefix name must not be null."); +- } +- +- void test_validateImportPrefixName_OK() { +- assertRefactoringStatusOK(validateImportPrefixName("newName")); +- } +- +- void test_validateImportPrefixName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateImportPrefixName("_newName")); +- } +- +- void test_validateImportPrefixName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateImportPrefixName("new_name")); +- } +- +- void test_validateImportPrefixName_trailingBlanks() { +- assertRefactoringStatus( +- validateImportPrefixName("newName "), RefactoringProblemSeverity.= FATAL, +- expectedMessage: +- "Import prefix name must not start or end with a blank."); +- } +- +- void test_validateLabelName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateLabelName("NewName"), RefactoringProblemSeverity.WARNING, +- expectedMessage: "Label name should start with a lowercase letter= ."); +- } +- +- void test_validateLabelName_empty() { +- assertRefactoringStatus( +- validateLabelName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not be empty."); +- } +- +- void test_validateLabelName_leadingBlanks() { +- assertRefactoringStatus( +- validateLabelName(" newName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not start or end with a blank."= ); +- } +- +- void test_validateLabelName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateLabelName("new-Name"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not contain '-'."); +- } +- +- void test_validateLabelName_notIdentifierStart() { +- assertRefactoringStatus( +- validateLabelName("2newName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Label name must begin with a lowercase letter or underscore.= "); +- } +- +- void test_validateLabelName_notKeyword() { +- assertRefactoringStatus( +- validateLabelName("for"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not be a keyword."); +- } +- +- void test_validateLabelName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateLabelName("await"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not be a keyword."); +- } +- +- void test_validateLabelName_null() { +- assertRefactoringStatus( +- validateLabelName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not be null."); +- } +- +- void test_validateLabelName_OK() { +- assertRefactoringStatusOK(validateLabelName("newName")); +- } +- +- void test_validateLabelName_OK_leadingDollar() { +- assertRefactoringStatusOK(validateLabelName("\$newName")); +- } +- +- void test_validateLabelName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateLabelName("_newName")); +- } +- +- void test_validateLabelName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateLabelName("new_name")); +- } +- +- void test_validateLabelName_trailingBlanks() { +- assertRefactoringStatus( +- validateLabelName("newName "), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not start or end with a blank."= ); +- } +- +- void test_validateLibraryName_blank() { +- assertRefactoringStatus( +- validateLibraryName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Library name must not be blank."); +- assertRefactoringStatus( +- validateLibraryName(" "), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Library name must not be blank."); +- } +- +- void test_validateLibraryName_blank_identifier() { +- assertRefactoringStatus( +- validateLibraryName("my..name"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Library name identifier must not be empty."); +- assertRefactoringStatus( +- validateLibraryName("my. .name"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: +- "Library name identifier must not start or end with a blank."= ); +- } +- +- void test_validateLibraryName_hasUpperCase() { +- assertRefactoringStatus( +- validateLibraryName("my.newName"), RefactoringProblemSeverity.WAR= NING, +- expectedMessage: +- "Library name should consist of lowercase identifier separate= d by dots."); +- } +- +- void test_validateLibraryName_leadingBlanks() { +- assertRefactoringStatus( +- validateLibraryName("my. name"), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Library name identifier must not start or end with a blank."= ); +- } +- +- void test_validateLibraryName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateLibraryName("my.ba-d.name"), RefactoringProblemSeverity.F= ATAL, +- expectedMessage: "Library name identifier must not contain '-'."); +- } +- +- void test_validateLibraryName_notIdentifierStart() { +- assertRefactoringStatus( +- validateLibraryName("my.2bad.name"), RefactoringProblemSeverity.F= ATAL, +- expectedMessage: +- "Library name identifier must begin with a lowercase letter o= r underscore."); +- } +- +- void test_validateLibraryName_notKeyword() { +- assertRefactoringStatus( +- validateLibraryName("my.yield.name"), RefactoringProblemSeverity.= FATAL, +- expectedMessage: "Library name identifier must not be a keyword."= ); +- } +- +- void test_validateLibraryName_null() { +- assertRefactoringStatus( +- validateLibraryName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Library name must not be null."); +- } +- +- void test_validateLibraryName_OK_oneIdentifier() { +- assertRefactoringStatusOK(validateLibraryName("name")); +- } +- +- void test_validateLibraryName_OK_severalIdentifiers() { +- assertRefactoringStatusOK(validateLibraryName("my.lib.name")); +- } +- +- void test_validateLibraryName_trailingBlanks() { +- assertRefactoringStatus( +- validateLibraryName("my.bad .name"), RefactoringProblemSeverity.F= ATAL, +- expectedMessage: +- "Library name identifier must not start or end with a blank."= ); +- } +- +- void test_validateMethodName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateMethodName("NewName"), RefactoringProblemSeverity.WARNING, +- expectedMessage: "Method name should start with a lowercase lette= r."); +- } +- +- void test_validateMethodName_empty() { +- assertRefactoringStatus( +- validateMethodName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be empty."); +- } +- +- void test_validateMethodName_keyword() { +- assertRefactoringStatus( +- validateMethodName("for"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be a keyword."); +- } +- +- void test_validateMethodName_leadingBlanks() { +- assertRefactoringStatus( +- validateMethodName(" newName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not start or end with a blank.= "); +- } +- +- void test_validateMethodName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateMethodName("new-Name"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not contain '-'."); +- } +- +- void test_validateMethodName_notIdentifierStart() { +- assertRefactoringStatus( +- validateMethodName("2newName"), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "Method name must begin with a lowercase letter or underscore= ."); +- } +- +- void test_validateMethodName_notKeyword() { +- assertRefactoringStatus( +- validateMethodName("do"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be a keyword."); +- } +- +- void test_validateMethodName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateMethodName("yield"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be a keyword."); +- } +- +- void test_validateMethodName_null() { +- assertRefactoringStatus( +- validateMethodName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be null."); +- } +- +- void test_validateMethodName_OK() { +- assertRefactoringStatusOK(validateMethodName("newName")); +- } +- +- void test_validateMethodName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateMethodName("_newName")); +- } +- +- void test_validateMethodName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateMethodName("new_name")); +- } +- +- void test_validateMethodName_trailingBlanks() { +- assertRefactoringStatus( +- validateMethodName("newName "), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not start or end with a blank.= "); +- } +- +- void test_validateParameterName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateParameterName("NewName"), RefactoringProblemSeverity.WARN= ING, +- expectedMessage: +- "Parameter name should start with a lowercase letter."); +- } +- +- void test_validateParameterName_empty() { +- assertRefactoringStatus( +- validateParameterName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Parameter name must not be empty."); +- } +- +- void test_validateParameterName_leadingBlanks() { +- assertRefactoringStatus( +- validateParameterName(" newName"), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: "Parameter name must not start or end with a bla= nk."); +- } +- +- void test_validateParameterName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateParameterName("new-Name"), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: "Parameter name must not contain '-'."); +- } +- +- void test_validateParameterName_notIdentifierStart() { +- assertRefactoringStatus( +- validateParameterName("2newName"), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: +- "Parameter name must begin with a lowercase letter or undersc= ore."); +- } +- +- void test_validateParameterName_notKeyword() { +- assertRefactoringStatus( +- validateParameterName("while"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Parameter name must not be a keyword."); +- } +- +- void test_validateParameterName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateParameterName("await"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Parameter name must not be a keyword."); +- } +- +- void test_validateParameterName_null() { +- assertRefactoringStatus( +- validateParameterName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Parameter name must not be null."); +- } +- +- void test_validateParameterName_OK() { +- assertRefactoringStatusOK(validateParameterName("newName")); +- } +- +- void test_validateParameterName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateParameterName("_newName")); +- } +- +- void test_validateParameterName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateParameterName("new_name")); +- } +- +- void test_validateParameterName_trailingBlanks() { +- assertRefactoringStatus( +- validateParameterName("newName "), RefactoringProblemSeverity.FAT= AL, +- expectedMessage: "Parameter name must not start or end with a bla= nk."); +- } +- +- void test_validateVariableName_doesNotStartWithLowerCase() { +- assertRefactoringStatus( +- validateVariableName("NewName"), RefactoringProblemSeverity.WARNI= NG, +- expectedMessage: "Variable name should start with a lowercase let= ter."); +- } +- +- void test_validateVariableName_empty() { +- assertRefactoringStatus( +- validateVariableName(""), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be empty."); +- } +- +- void test_validateVariableName_leadingBlanks() { +- assertRefactoringStatus( +- validateVariableName(" newName"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Variable name must not start or end with a blan= k."); +- } +- +- void test_validateVariableName_notIdentifierMiddle() { +- assertRefactoringStatus( +- validateVariableName("new-Name"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Variable name must not contain '-'."); +- } +- +- void test_validateVariableName_notIdentifierStart() { +- assertRefactoringStatus( +- validateVariableName("2newName"), RefactoringProblemSeverity.FATA= L, +- expectedMessage: +- "Variable name must begin with a lowercase letter or undersco= re."); +- } +- +- void test_validateVariableName_notKeyword() { +- assertRefactoringStatus( +- validateVariableName("for"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be a keyword."); +- } +- +- void test_validateVariableName_notPseudoKeyword() { +- assertRefactoringStatus( +- validateVariableName("await"), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be a keyword."); +- } +- +- void test_validateVariableName_null() { +- assertRefactoringStatus( +- validateVariableName(null), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be null."); +- } +- +- void test_validateVariableName_OK() { +- assertRefactoringStatusOK(validateVariableName("newName")); +- } +- +- void test_validateVariableName_OK_leadingDollar() { +- assertRefactoringStatusOK(validateVariableName("\$newName")); +- } +- +- void test_validateVariableName_OK_leadingUnderscore() { +- assertRefactoringStatusOK(validateVariableName("_newName")); +- } +- +- void test_validateVariableName_OK_middleUnderscore() { +- assertRefactoringStatusOK(validateVariableName("new_name")); +- } +- +- void test_validateVariableName_trailingBlanks() { +- assertRefactoringStatus( +- validateVariableName("newName "), RefactoringProblemSeverity.FATA= L, +- expectedMessage: "Variable name must not start or end with a blan= k."); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_class_me= mber_test.dart b/pkg/analysis_server/test/services/refactoring/rename_class= _member_test.dart +deleted file mode 100644 +index 18eb7d2e909..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_class_member_te= st.dart ++++ /dev/null +@@ -1,894 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameClassMemberTest); +- }); +-} +- +-@reflectiveTest +-class RenameClassMemberTest extends RenameRefactoringTest { +- test_checkFinalConditions_classNameConflict_sameClass() async { +- await indexTestUnit(''' +-class NewName { +- void test() {} +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Renamed method has the same name as the declaring class 'New= Name'.", +- expectedContextSearch: 'test() {}'); +- } +- +- test_checkFinalConditions_classNameConflict_subClass() async { +- await indexTestUnit(''' +-class A { +- void test() {} // 1 +-} +-class NewName extends A { +- void test() {} // 2 +-} +-'''); +- createRenameRefactoringAtString('test() {} // 1'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Renamed method has the same name as the declaring class 'New= Name'.", +- expectedContextSearch: 'test() {} // 2'); +- } +- +- test_checkFinalConditions_classNameConflict_superClass() async { +- await indexTestUnit(''' +-class NewName { +- void test() {} // 1 +-} +-class B extends NewName { +- void test() {} // 2 +-} +-'''); +- createRenameRefactoringAtString('test() {} // 2'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Renamed method has the same name as the declaring class 'New= Name'.", +- expectedContextSearch: 'test() {} // 1'); +- } +- +- test_checkFinalConditions_hasMember_MethodElement() async { +- await indexTestUnit(''' +-class A { +- test() {} +- newName() {} // existing +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Class 'A' already declares method with name 'newName'.", +- expectedContextSearch: 'newName() {} // existing'); +- } +- +- test_checkFinalConditions_OK_dropSuffix() async { +- await indexTestUnit(r''' +-abstract class A { +- void testOld(); +-} +-class B implements A { +- void testOld() {} +-} +-'''); +- createRenameRefactoringAtString('testOld() {}'); +- // check status +- refactoring.newName =3D 'test'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_OK_noShadow() async { +- await indexTestUnit(''' +-class A { +- int newName; +-} +-class B { +- test() {} +-} +-class C extends A { +- main() { +- print(newName); +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_publicToPrivate_usedInOtherLibrary() async { +- await indexTestUnit(''' +-class A { +- test() {} +-} +-'''); +- await indexUnit('/lib.dart', ''' +-library my.lib; +-import 'test.dart'; +- +-main(A a) { +- a.test(); +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D '_newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed method will be invisible in 'my.lib'."); +- } +- +- test_checkFinalConditions_shadowed_byLocalFunction_inSameClass() async { +- await indexTestUnit(''' +-class A { +- test() {} +- main() { +- newName() {} +- test(); // marker +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Usage of renamed method will be shadowed by function 'newNam= e'.", +- expectedContextSearch: 'test(); // marker'); +- } +- +- test_checkFinalConditions_shadowed_byLocalVariable_inSameClass() async { +- await indexTestUnit(''' +-class A { +- test() {} +- main() { +- var newName; +- test(); // marker +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Usage of renamed method will be shadowed by local variable '= newName'.", +- expectedContextSearch: 'test(); // marker'); +- } +- +- test_checkFinalConditions_shadowed_byLocalVariable_inSubClass() async { +- await indexTestUnit(''' +-class A { +- test() {} +-} +-class B extends A { +- main() { +- var newName; +- test(); // marker +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Usage of renamed method will be shadowed by local variable '= newName'.", +- expectedContextSearch: 'test(); // marker'); +- } +- +- test_checkFinalConditions_shadowed_byLocalVariable_OK_qualifiedReferenc= e() async { +- await indexTestUnit(''' +-class A { +- test() {} +- main() { +- var newName; +- this.test(); // marker +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_shadowed_byLocalVariable_OK_renamedNotUsed() = async { +- await indexTestUnit(''' +-class A { +- test() {} +- main() { +- var newName; +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_shadowed_byParameter_inSameClass() async { +- await indexTestUnit(''' +-class A { +- test() {} +- main(newName) { +- test(); // marker +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Usage of renamed method will be shadowed by parameter 'newNa= me'.", +- expectedContextSearch: 'test(); // marker'); +- } +- +- test_checkFinalConditions_shadowedBySub_MethodElement() async { +- await indexTestUnit(''' +-class A { +- test() {} +-} +-class B extends A { +- newName() {} // marker +- main() { +- test(); +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Renamed method will be shadowed by method 'B.newName'.", +- expectedContextSearch: 'newName() {} // marker'); +- } +- +- test_checkFinalConditions_shadowsSuper_FieldElement() async { +- await indexTestUnit(''' +-class A { +- int newName; // marker +-} +-class B extends A { +- test() {} +-} +-class C extends B { +- main() { +- print(newName); +- } +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed method will shadow field 'A.newName'.", +- expectedContextSearch: 'newName; // marker'); +- } +- +- test_checkFinalConditions_shadowsSuper_MethodElement() async { +- await indexTestUnit(''' +-class A { +- newName() {} // marker +-} +-class B extends A { +- test() {} +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed method will shadow method 'A.newName'.", +- expectedContextSearch: 'newName() {} // marker'); +- } +- +- test_checkFinalConditions_shadowsSuper_MethodElement_otherLib() async { +- var libCode =3D r''' +-class A { +- newName() {} // marker +-} +-'''; +- await indexUnit('/lib.dart', libCode); +- await indexTestUnit(''' +-import 'lib.dart'; +-class B extends A { +- test() {} +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed method will shadow method 'A.newName'.", +- expectedContextRange: new SourceRange( +- libCode.indexOf('newName() {} // marker'), 'newName'.length)); +- } +- +- test_checkInitialConditions_inSDK() async { +- await indexTestUnit(''' +-main() { +- 'abc'.toUpperCase(); +-} +-'''); +- createRenameRefactoringAtString('toUpperCase()'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The method 'String.toUpperCase' is defined in the SDK, so ca= nnot be renamed."); +- } +- +- test_checkInitialConditions_operator() async { +- await indexTestUnit(''' +-class A { +- operator -(other) =3D> this; +-} +-'''); +- createRenameRefactoringAtString('-(other)'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL); +- } +- +- test_checkNewName_FieldElement() async { +- await indexTestUnit(''' +-class A { +- int test; +-} +-'''); +- createRenameRefactoringAtString('test;'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Field name must not be null."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_MethodElement() async { +- await indexTestUnit(''' +-class A { +- test() {} +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Method name must not be empty."); +- // same +- refactoring.newName =3D 'test'; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The new name must be different than the current name."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_createChange_FieldElement() async { +- await indexTestUnit(''' +-class A { +- int test; // marker +- main() { +- print(test); +- test =3D 1; +- test +=3D 2; +- } +-} +-class B extends A { +-} +-class C extends B { +- get test =3D> 1; +- set test(x) {} +-} +-main() { +- A a =3D new A(); +- B b =3D new B(); +- C c =3D new C(); +- print(a.test); +- a.test =3D 1; +- a.test +=3D 2; +- print(b.test); +- b.test =3D 1; +- print(c.test); +- c.test =3D 1; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test; // marker'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.elementKindName, 'field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- int newName; // marker +- main() { +- print(newName); +- newName =3D 1; +- newName +=3D 2; +- } +-} +-class B extends A { +-} +-class C extends B { +- get newName =3D> 1; +- set newName(x) {} +-} +-main() { +- A a =3D new A(); +- B b =3D new B(); +- C c =3D new C(); +- print(a.newName); +- a.newName =3D 1; +- a.newName +=3D 2; +- print(b.newName); +- b.newName =3D 1; +- print(c.newName); +- c.newName =3D 1; +-} +-'''); +- } +- +- test_createChange_FieldElement_constructorFieldInitializer() async { +- await indexTestUnit(''' +-class A { +- final test; +- A() : test =3D 5; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test;'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- final newName; +- A() : newName =3D 5; +-} +-'''); +- } +- +- test_createChange_FieldElement_fieldFormalParameter() async { +- await indexTestUnit(''' +-class A { +- final test; +- A(this.test); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test;'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- final newName; +- A(this.newName); +-} +-'''); +- } +- +- test_createChange_FieldElement_fieldFormalParameter_named() async { +- await indexTestUnit(''' +-class A { +- final test; +- A({this.test}); +-} +-main() { +- new A(test: 42); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test;'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- final newName; +- A({this.newName}); +-} +-main() { +- new A(newName: 42); +-} +-'''); +- } +- +- test_createChange_FieldElement_invocation() async { +- await indexTestUnit(''' +-typedef F(a); +-class A { +- F test; +- main() { +- test(1); +- } +-} +-main() { +- A a =3D new A(); +- a.test(2); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test(2);'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-typedef F(a); +-class A { +- F newName; +- main() { +- newName(1); +- } +-} +-main() { +- A a =3D new A(); +- a.newName(2); +-} +-'''); +- } +- +- test_createChange_MethodElement() async { +- await indexTestUnit(''' +-class A { +- test() {} +-} +-class B extends A { +- test() {} // marker +-} +-class C extends B { +- test() {} +-} +-class D implements A { +- test() {} +-} +-class E { +- test() {} +-} +-main() { +- A a =3D new A(); +- B b =3D new B(); +- C c =3D new C(); +- D d =3D new D(); +- E e =3D new E(); +- a.test(); +- b.test(); +- c.test(); +- d.test(); +- e.test(); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test() {} // marker'); +- expect(refactoring.refactoringName, 'Rename Method'); +- expect(refactoring.elementKindName, 'method'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- newName() {} +-} +-class B extends A { +- newName() {} // marker +-} +-class C extends B { +- newName() {} +-} +-class D implements A { +- newName() {} +-} +-class E { +- test() {} +-} +-main() { +- A a =3D new A(); +- B b =3D new B(); +- C c =3D new C(); +- D d =3D new D(); +- E e =3D new E(); +- a.newName(); +- b.newName(); +- c.newName(); +- d.newName(); +- e.test(); +-} +-'''); +- } +- +- test_createChange_MethodElement_potential() async { +- await indexTestUnit(''' +-class A { +- test() {} +-} +-main(var a) { +- a.test(); // 1 +- new A().test(); +- a.test(); // 2 +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test() {}'); +- expect(refactoring.refactoringName, 'Rename Method'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- await assertSuccessfulRefactoring(''' +-class A { +- newName() {} +-} +-main(var a) { +- a.newName(); // 1 +- new A().newName(); +- a.newName(); // 2 +-} +-'''); +- assertPotentialEdits(['test(); // 1', 'test(); // 2']); +- } +- +- test_createChange_MethodElement_potential_inPubCache() async { +- String pkgLib =3D '/.pub-cache/lib.dart'; +- await indexUnit(pkgLib, r''' +-processObj(p) { +- p.test(); +-} +-'''); +- await indexTestUnit(''' +-import '$pkgLib'; +-class A { +- test() {} +-} +-main(var a) { +- a.test(); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test() {}'); +- expect(refactoring.refactoringName, 'Rename Method'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- await assertSuccessfulRefactoring(''' +-import '/.pub-cache/lib.dart'; +-class A { +- newName() {} +-} +-main(var a) { +- a.newName(); +-} +-'''); +- SourceFileEdit fileEdit =3D refactoringChange.getFileEdit(pkgLib); +- expect(fileEdit, isNull); +- } +- +- test_createChange_MethodElement_potential_private_otherLibrary() async { +- await indexUnit('/lib.dart', ''' +-library lib; +-main(p) { +- p._test(); +-} +-'''); +- await indexTestUnit(''' +-class A { +- _test() {} +-} +-main(var a) { +- a._test(); +- new A()._test(); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('_test() {}'); +- expect(refactoring.refactoringName, 'Rename Method'); +- expect(refactoring.oldName, '_test'); +- refactoring.newName =3D 'newName'; +- // validate change +- await assertSuccessfulRefactoring(''' +-class A { +- newName() {} +-} +-main(var a) { +- a.newName(); +- new A().newName(); +-} +-'''); +- assertNoFileChange('/lib.dart'); +- } +- +- test_createChange_PropertyAccessorElement_getter() async { +- await indexTestUnit(''' +-class A { +- get test {} // marker +- set test(x) {} +- main() { +- print(test); +- test =3D 1; +- } +-} +-class B extends A { +- get test {} +- set test(x) {} +-} +-main() { +- A a =3D new A(); +- print(a.test); +- a.test =3D 2; +- +- B b =3D new B(); +- print(b.test); +- b.test =3D 2; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test {} // marker'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- get newName {} // marker +- set newName(x) {} +- main() { +- print(newName); +- newName =3D 1; +- } +-} +-class B extends A { +- get newName {} +- set newName(x) {} +-} +-main() { +- A a =3D new A(); +- print(a.newName); +- a.newName =3D 2; +- +- B b =3D new B(); +- print(b.newName); +- b.newName =3D 2; +-} +-'''); +- } +- +- test_createChange_PropertyAccessorElement_setter() async { +- await indexTestUnit(''' +-class A { +- get test {} +- set test(x) {} // marker +- main() { +- print(test); +- test =3D 1; +- } +-} +-class B extends A { +- get test {} +- set test(x) {} +-} +-main() { +- A a =3D new A(); +- print(a.test); +- a.test =3D 2; +- +- B b =3D new B(); +- print(b.test); +- b.test =3D 2; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test(x) {} // marker'); +- expect(refactoring.refactoringName, 'Rename Field'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- get newName {} +- set newName(x) {} // marker +- main() { +- print(newName); +- newName =3D 1; +- } +-} +-class B extends A { +- get newName {} +- set newName(x) {} +-} +-main() { +- A a =3D new A(); +- print(a.newName); +- a.newName =3D 2; +- +- B b =3D new B(); +- print(b.newName); +- b.newName =3D 2; +-} +-'''); +- } +- +- test_createChange_TypeParameterElement() async { +- await indexTestUnit(''' +-class A { +- Test field; +- List items; +- Test method(Test p) =3D> null; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('Test> {'); +- expect(refactoring.refactoringName, 'Rename Type Parameter'); +- expect(refactoring.elementKindName, 'type parameter'); +- expect(refactoring.oldName, 'Test'); +- refactoring.newName =3D 'NewName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A { +- NewName field; +- List items; +- NewName method(NewName p) =3D> null; +-} +-'''); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_construc= tor_test.dart b/pkg/analysis_server/test/services/refactoring/rename_constr= uctor_test.dart +deleted file mode 100644 +index 1434a051cd0..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_constructor_tes= t.dart ++++ /dev/null +@@ -1,249 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analysis_server/src/services/refactoring/refactoring.dart= '; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameConstructorTest); +- }); +-} +- +-@reflectiveTest +-class RenameConstructorTest extends RenameRefactoringTest { +- test_checkInitialConditions_inSDK() async { +- await indexTestUnit(''' +-main() { +- new String.fromCharCodes([]); +-} +-'''); +- createRenameRefactoringAtString('fromCharCodes('); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The constructor 'String.fromCharCodes' is defined in the SDK= , so cannot be renamed."); +- } +- +- test_checkNewName() async { +- await indexTestUnit(''' +-class A { +- A.test() {} +-} +-'''); +- createRenameRefactoringAtString('test() {}'); +- expect(refactoring.oldName, 'test'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Constructor name must not be null."); +- // same +- refactoring.newName =3D 'test'; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The new name must be different than the current name."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_hasMember_constructor() async { +- await indexTestUnit(''' +-class A { +- A.test() {} +- A.newName() {} // existing +-} +-'''); +- _createConstructorDeclarationRefactoring('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D refactoring.checkNewName(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Class 'A' already declares constructor with name 'newName'.", +- expectedContextSearch: 'newName() {} // existing'); +- } +- +- test_checkNewName_hasMember_method() async { +- await indexTestUnit(''' +-class A { +- A.test() {} +- newName() {} // existing +-} +-'''); +- _createConstructorDeclarationRefactoring('test() {}'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D refactoring.checkNewName(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Class 'A' already declares method with name 'newName'.", +- expectedContextSearch: 'newName() {} // existing'); +- } +- +- test_createChange_add() async { +- await indexTestUnit(''' +-class A { +- A() {} // marker +- factory A._() =3D A; +-} +-class B extends A { +- B() : super() {} +-} +-main() { +- new A(); +-} +-'''); +- // configure refactoring +- _createConstructorDeclarationRefactoring('() {} // marker'); +- expect(refactoring.refactoringName, 'Rename Constructor'); +- expect(refactoring.elementKindName, 'constructor'); +- expect(refactoring.oldName, ''); +- // validate change +- refactoring.newName =3D 'newName'; +- return assertSuccessfulRefactoring(''' +-class A { +- A.newName() {} // marker +- factory A._() =3D A.newName; +-} +-class B extends A { +- B() : super.newName() {} +-} +-main() { +- new A.newName(); +-} +-'''); +- } +- +- test_createChange_add_toSynthetic() async { +- await indexTestUnit(''' +-class A { +-} +-class B extends A { +- B() : super() {} +-} +-main() { +- new A(); +-} +-'''); +- // configure refactoring +- _createConstructorInvocationRefactoring('new A();'); +- expect(refactoring.refactoringName, 'Rename Constructor'); +- expect(refactoring.elementKindName, 'constructor'); +- expect(refactoring.oldName, ''); +- // validate change +- refactoring.newName =3D 'newName'; +- return assertSuccessfulRefactoring(''' +-class A { +- A.newName(); +-} +-class B extends A { +- B() : super.newName() {} +-} +-main() { +- new A.newName(); +-} +-'''); +- } +- +- test_createChange_change() async { +- await indexTestUnit(''' +-class A { +- A.test() {} // marker +- factory A._() =3D A.test; +-} +-class B extends A { +- B() : super.test() {} +-} +-main() { +- new A.test(); +-} +-'''); +- // configure refactoring +- _createConstructorDeclarationRefactoring('test() {} // marker'); +- expect(refactoring.refactoringName, 'Rename Constructor'); +- expect(refactoring.elementKindName, 'constructor'); +- expect(refactoring.oldName, 'test'); +- // validate change +- refactoring.newName =3D 'newName'; +- return assertSuccessfulRefactoring(''' +-class A { +- A.newName() {} // marker +- factory A._() =3D A.newName; +-} +-class B extends A { +- B() : super.newName() {} +-} +-main() { +- new A.newName(); +-} +-'''); +- } +- +- test_createChange_remove() async { +- await indexTestUnit(''' +-class A { +- A.test() {} // marker +- factory A._() =3D A.test; +-} +-class B extends A { +- B() : super.test() {} +-} +-main() { +- new A.test(); +-} +-'''); +- // configure refactoring +- _createConstructorDeclarationRefactoring('test() {} // marker'); +- expect(refactoring.refactoringName, 'Rename Constructor'); +- expect(refactoring.elementKindName, 'constructor'); +- expect(refactoring.oldName, 'test'); +- // validate change +- refactoring.newName =3D ''; +- return assertSuccessfulRefactoring(''' +-class A { +- A() {} // marker +- factory A._() =3D A; +-} +-class B extends A { +- B() : super() {} +-} +-main() { +- new A(); +-} +-'''); +- } +- +- test_newInstance_nullElement() async { +- RenameRefactoring refactoring =3D +- new RenameRefactoring(searchEngine, null, null); +- expect(refactoring, isNull); +- } +- +- void _createConstructorDeclarationRefactoring(String search) { +- ConstructorElement element =3D findNodeElementAtString( +- search, (node) =3D> node is ConstructorDeclaration); +- createRenameRefactoringForElement(element); +- } +- +- void _createConstructorInvocationRefactoring(String search) { +- ConstructorElement element =3D findNodeElementAtString( +- search, (node) =3D> node is InstanceCreationExpression); +- createRenameRefactoringForElement(element); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_import_t= est.dart b/pkg/analysis_server/test/services/refactoring/rename_import_test= .dart +deleted file mode 100644 +index ed29086e76b..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_import_test.dart ++++ /dev/null +@@ -1,230 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameImportTest); +- }); +-} +- +-@reflectiveTest +-class RenameImportTest extends RenameRefactoringTest { +- test_checkNewName() async { +- await indexTestUnit("import 'dart:async' as test;"); +- _createRefactoring("import 'dart:"); +- expect(refactoring.oldName, 'test'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Import prefix name must not be null."); +- // same +- refactoring.newName =3D 'test'; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The new name must be different than the current name."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_createChange_add() async { +- await indexTestUnit(''' +-import 'dart:async'; +-import 'dart:math' show Random, min hide max; +-main() { +- Future f; +- Random r; +- min(1, 2); +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:math"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-import 'dart:async'; +-import 'dart:math' as newName show Random, min hide max; +-main() { +- Future f; +- newName.Random r; +- newName.min(1, 2); +-} +-'''); +- } +- +- test_createChange_add_interpolationExpression_hasCurlyBrackets() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-main() { +- Future f; +- print('Future type: ${Future}'); +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:async"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(r''' +-import 'dart:async' as newName; +-main() { +- newName.Future f; +- print('Future type: ${newName.Future}'); +-} +-'''); +- } +- +- test_createChange_add_interpolationExpression_noCurlyBrackets() async { +- await indexTestUnit(r''' +-import 'dart:async'; +-main() { +- Future f; +- print('Future type: $Future'); +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:async"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(r''' +-import 'dart:async' as newName; +-main() { +- newName.Future f; +- print('Future type: ${newName.Future}'); +-} +-'''); +- } +- +- test_createChange_change_className() async { +- await indexTestUnit(''' +-import 'dart:math' as test; +-import 'dart:async' as test; +-main() { +- test.Future f; +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:async"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-import 'dart:math' as test; +-import 'dart:async' as newName; +-main() { +- newName.Future f; +-} +-'''); +- } +- +- test_createChange_change_function() async { +- await indexTestUnit(''' +-import 'dart:math' as test; +-import 'dart:async' as test; +-main() { +- test.max(1, 2); +- test.Future f; +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:math"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-import 'dart:math' as newName; +-import 'dart:async' as test; +-main() { +- newName.max(1, 2); +- test.Future f; +-} +-'''); +- } +- +- test_createChange_change_onPrefixElement() async { +- await indexTestUnit(''' +-import 'dart:async' as test; +-import 'dart:math' as test; +-main() { +- test.Future f; +- test.PI; +- test.E; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test.PI'); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-import 'dart:async' as test; +-import 'dart:math' as newName; +-main() { +- test.Future f; +- newName.PI; +- newName.E; +-} +-'''); +- } +- +- test_createChange_remove() async { +- await indexTestUnit(''' +-import 'dart:math' as test; +-import 'dart:async' as test; +-main() { +- test.Future f; +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:async"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D ''; +- // validate change +- return assertSuccessfulRefactoring(''' +-import 'dart:math' as test; +-import 'dart:async'; +-main() { +- Future f; +-} +-'''); +- } +- +- test_oldName_empty() async { +- await indexTestUnit(''' +-import 'dart:math'; +-import 'dart:async'; +-main() { +- Future f; +-} +-'''); +- // configure refactoring +- _createRefactoring("import 'dart:async"); +- expect(refactoring.refactoringName, 'Rename Import Prefix'); +- expect(refactoring.oldName, ''); +- } +- +- void _createRefactoring(String search) { +- ImportDirective directive =3D +- findNodeAtString(search, (node) =3D> node is ImportDirective); +- createRenameRefactoringForElement(directive.element); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_label_te= st.dart b/pkg/analysis_server/test/services/refactoring/rename_label_test.d= art +deleted file mode 100644 +index 076ec774931..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_label_test.dart ++++ /dev/null +@@ -1,83 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameLabelTest); +- }); +-} +- +-@reflectiveTest +-class RenameLabelTest extends RenameRefactoringTest { +- test_checkNewName_LocalVariableElement() async { +- await indexTestUnit(''' +-main() { +-test: +- while (true) { +- break test; +- } +-} +-'''); +- createRenameRefactoringAtString('test:'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Label name must not be empty."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_createChange() async { +- await indexTestUnit(''' +-main() { +-test: +- while (true) { +- break test; +- } +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test:'); +- expect(refactoring.refactoringName, 'Rename Label'); +- expect(refactoring.elementKindName, 'label'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +-newName: +- while (true) { +- break newName; +- } +-} +-'''); +- } +- +- test_oldName() async { +- await indexTestUnit(''' +-main() { +-test: +- while (true) { +- break test; +- } +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test:'); +- // old name +- expect(refactoring.oldName, 'test'); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_library_= test.dart b/pkg/analysis_server/test/services/refactoring/rename_library_te= st.dart +deleted file mode 100644 +index 1acca7dc124..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_library_test.da= rt ++++ /dev/null +@@ -1,91 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameLibraryTest); +- }); +-} +- +-@reflectiveTest +-class RenameLibraryTest extends RenameRefactoringTest { +- test_checkNewName() async { +- await indexTestUnit(''' +-library my.app; +-'''); +- _createRenameRefactoring(); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Library name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Library name must not be blank."); +- // same name +- refactoring.newName =3D 'my.app'; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The new name must be different than the current name."); +- } +- +- test_createChange() async { +- addSource('/part.dart', ''' +-part of my.app; +-'''); +- await indexTestUnit(''' +-library my.app; +-part 'part.dart'; +-'''); +- // configure refactoring +- _createRenameRefactoring(); +- expect(refactoring.refactoringName, 'Rename Library'); +- expect(refactoring.elementKindName, 'library'); +- refactoring.newName =3D 'the.new.name'; +- // validate change +- await assertSuccessfulRefactoring(''' +-library the.new.name; +-part 'part.dart'; +-'''); +- assertFileChangeResult('/part.dart', ''' +-part of the.new.name; +-'''); +- } +- +- test_createChange_hasWhitespaces() async { +- addSource('/part.dart', ''' +-part of my . app; +-'''); +- await indexTestUnit(''' +-library my . app; +-part 'part.dart'; +-'''); +- // configure refactoring +- _createRenameRefactoring(); +- expect(refactoring.refactoringName, 'Rename Library'); +- expect(refactoring.elementKindName, 'library'); +- refactoring.newName =3D 'the.new.name'; +- // validate change +- await assertSuccessfulRefactoring(''' +-library the.new.name; +-part 'part.dart'; +-'''); +- assertFileChangeResult('/part.dart', ''' +-part of the.new.name; +-'''); +- } +- +- void _createRenameRefactoring() { +- createRenameRefactoringForElement(testUnitElement.library); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_local_te= st.dart b/pkg/analysis_server/test/services/refactoring/rename_local_test.d= art +deleted file mode 100644 +index 8533be07c98..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_local_test.dart ++++ /dev/null +@@ -1,545 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameLocalTest); +- }); +-} +- +-@reflectiveTest +-class RenameLocalTest extends RenameRefactoringTest { +- test_checkFinalConditions_hasLocalFunction_after() async { +- await indexTestUnit(''' +-main() { +- int test =3D 0; +- newName() =3D> 1; +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Duplicate function 'newName'.", +- expectedContextSearch: 'newName() =3D> 1'); +- } +- +- test_checkFinalConditions_hasLocalFunction_before() async { +- await indexTestUnit(''' +-main() { +- newName() =3D> 1; +- int test =3D 0; +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Duplicate function 'newName'."); +- } +- +- test_checkFinalConditions_hasLocalVariable_after() async { +- await indexTestUnit(''' +-main() { +- int test =3D 0; +- var newName =3D 1; +- print(newName); +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- expect(status.problems, hasLength(1)); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Duplicate local variable 'newName'.", +- expectedContextSearch: 'newName =3D 1;'); +- } +- +- test_checkFinalConditions_hasLocalVariable_before() async { +- await indexTestUnit(''' +-main() { +- var newName =3D 1; +- int test =3D 0; +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Duplicate local variable 'newName'.", +- expectedContextSearch: 'newName =3D 1;'); +- } +- +- test_checkFinalConditions_hasLocalVariable_otherBlock() async { +- await indexTestUnit(''' +-main() { +- { +- var newName =3D 1; +- } +- { +- int test =3D 0; +- } +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- return assertRefactoringConditionsOK(); +- } +- +- test_checkFinalConditions_hasLocalVariable_otherForEachLoop() async { +- await indexTestUnit(''' +-main() { +- for (int newName in []) {} +- for (int test in []) {} +-} +-'''); +- createRenameRefactoringAtString('test in'); +- // check status +- refactoring.newName =3D 'newName'; +- return assertRefactoringConditionsOK(); +- } +- +- test_checkFinalConditions_hasLocalVariable_otherForLoop() async { +- await indexTestUnit(''' +-main() { +- for (int newName =3D 0; newName < 10; newName++) {} +- for (int test =3D 0; test < 10; test++) {} +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- return assertRefactoringConditionsOK(); +- } +- +- test_checkFinalConditions_hasLocalVariable_otherFunction() async { +- await indexTestUnit(''' +-main() { +- int test =3D 0; +-} +-main2() { +- var newName =3D 1; +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- return assertRefactoringConditionsOK(); +- } +- +- test_checkFinalConditions_shadows_classMember() async { +- await indexTestUnit(''' +-class A { +- var newName =3D 1; +- main() { +- var test =3D 0; +- print(newName); +- } +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: 'Usage of field "A.newName" declared in "test.da= rt" ' +- 'will be shadowed by renamed local variable.', +- expectedContextSearch: 'newName);'); +- } +- +- test_checkFinalConditions_shadows_classMember_namedParameter() async { +- await indexTestUnit(''' +-class A { +- foo({test: 1}) { // in A +- } +-} +-class B extends A { +- var newName =3D 1; +- foo({test: 1}) { +- print(newName); +- } +-} +-'''); +- createRenameRefactoringAtString('test: 1}) { // in A'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: 'Usage of field "B.newName" declared in "test.da= rt" ' +- 'will be shadowed by renamed parameter.', +- expectedContextSearch: 'newName);'); +- } +- +- test_checkFinalConditions_shadows_classMemberOK_qualifiedReference() as= ync { +- await indexTestUnit(''' +-class A { +- var newName =3D 1; +- main() { +- var test =3D 0; +- print(this.newName); +- } +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- return assertRefactoringConditionsOK(); +- } +- +- test_checkFinalConditions_shadows_OK_namedParameterReference() async { +- await indexTestUnit(''' +-void f({newName}) {} +-main() { +- var test =3D 0; +- f(newName: test); +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- return assertRefactoringFinalConditionsOK(); +- } +- +- test_checkFinalConditions_shadows_topLevelFunction() async { +- await indexTestUnit(''' +-newName() {} +-main() { +- var test =3D 0; +- newName(); // ref +-} +-'''); +- createRenameRefactoringAtString('test =3D 0'); +- // check status +- refactoring.newName =3D 'newName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedContextSearch: 'newName(); // ref'); +- } +- +- test_checkNewName_FunctionElement() async { +- await indexTestUnit(''' +-main() { +- int test() =3D> 0; +-} +-'''); +- createRenameRefactoringAtString('test() =3D> 0;'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be null."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_LocalVariableElement() async { +- await indexTestUnit(''' +-main() { +- int test =3D 0; +-} +-'''); +- createRenameRefactoringAtString('test =3D 0;'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be empty."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_ParameterElement() async { +- await indexTestUnit(''' +-main(test) { +-} +-'''); +- createRenameRefactoringAtString('test) {'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Parameter name must not be null."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_createChange_localFunction() async { +- await indexTestUnit(''' +-main() { +- int test() =3D> 0; +- print(test); +- print(test()); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test() =3D> 0'); +- expect(refactoring.refactoringName, 'Rename Local Function'); +- expect(refactoring.elementKindName, 'function'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- int newName() =3D> 0; +- print(newName); +- print(newName()); +-} +-'''); +- } +- +- test_createChange_localFunction_sameNameDifferenceScopes() async { +- await indexTestUnit(''' +-main() { +- { +- int test() =3D> 0; +- print(test); +- } +- { +- int test() =3D> 1; +- print(test); +- } +- { +- int test() =3D> 2; +- print(test); +- } +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test() =3D> 1'); +- expect(refactoring.refactoringName, 'Rename Local Function'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- { +- int test() =3D> 0; +- print(test); +- } +- { +- int newName() =3D> 1; +- print(newName); +- } +- { +- int test() =3D> 2; +- print(test); +- } +-} +-'''); +- } +- +- test_createChange_localVariable() async { +- await indexTestUnit(''' +-main() { +- int test =3D 0; +- test =3D 1; +- test +=3D 2; +- print(test); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test =3D 0'); +- expect(refactoring.refactoringName, 'Rename Local Variable'); +- expect(refactoring.elementKindName, 'local variable'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- int newName =3D 0; +- newName =3D 1; +- newName +=3D 2; +- print(newName); +-} +-'''); +- } +- +- test_createChange_localVariable_sameNameDifferenceScopes() async { +- await indexTestUnit(''' +-main() { +- { +- int test =3D 0; +- print(test); +- } +- { +- int test =3D 1; +- print(test); +- } +- { +- int test =3D 2; +- print(test); +- } +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test =3D 1'); +- expect(refactoring.refactoringName, 'Rename Local Variable'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-main() { +- { +- int test =3D 0; +- print(test); +- } +- { +- int newName =3D 1; +- print(newName); +- } +- { +- int test =3D 2; +- print(test); +- } +-} +-'''); +- } +- +- test_createChange_parameter() async { +- await indexTestUnit(''' +-myFunction({int test}) { +- test =3D 1; +- test +=3D 2; +- print(test); +-} +-main() { +- myFunction(test: 2); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test}) {'); +- expect(refactoring.refactoringName, 'Rename Parameter'); +- expect(refactoring.elementKindName, 'parameter'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-myFunction({int newName}) { +- newName =3D 1; +- newName +=3D 2; +- print(newName); +-} +-main() { +- myFunction(newName: 2); +-} +-'''); +- } +- +- test_createChange_parameter_named_inOtherFile() async { +- await indexTestUnit(''' +-class A { +- A({test}); +-} +-'''); +- await indexUnit('/test2.dart', ''' +-import 'test.dart'; +-main() { +- new A(test: 2); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test});'); +- expect(refactoring.refactoringName, 'Rename Parameter'); +- refactoring.newName =3D 'newName'; +- // validate change +- await assertSuccessfulRefactoring(''' +-class A { +- A({newName}); +-} +-'''); +- assertFileChangeResult('/test2.dart', ''' +-import 'test.dart'; +-main() { +- new A(newName: 2); +-} +-'''); +- } +- +- test_createChange_parameter_named_updateHierarchy() async { +- await indexUnit('/test2.dart', ''' +-library test2; +-class A { +- void foo({int test: 1}) { +- print(test); +- } +-} +-class B extends A { +- void foo({int test: 2}) { +- print(test); +- } +-} +-'''); +- await indexTestUnit(''' +-import 'test2.dart'; +-main() { +- new A().foo(test: 10); +- new B().foo(test: 20); +- new C().foo(test: 30); +-} +-class C extends A { +- void foo({int test: 3}) { +- print(test); +- } +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test: 20'); +- expect(refactoring.refactoringName, 'Rename Parameter'); +- refactoring.newName =3D 'newName'; +- // validate change +- await assertSuccessfulRefactoring(''' +-import 'test2.dart'; +-main() { +- new A().foo(newName: 10); +- new B().foo(newName: 20); +- new C().foo(newName: 30); +-} +-class C extends A { +- void foo({int newName: 3}) { +- print(newName); +- } +-} +-'''); +- assertFileChangeResult('/test2.dart', ''' +-library test2; +-class A { +- void foo({int newName: 1}) { +- print(newName); +- } +-} +-class B extends A { +- void foo({int newName: 2}) { +- print(newName); +- } +-} +-'''); +- } +- +- test_oldName() async { +- await indexTestUnit(''' +-main() { +- int test =3D 0; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test =3D 0'); +- // old name +- expect(refactoring.oldName, 'test'); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/rename_unit_mem= ber_test.dart b/pkg/analysis_server/test/services/refactoring/rename_unit_m= ember_test.dart +deleted file mode 100644 +index 80085b4ced9..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/rename_unit_member_tes= t.dart ++++ /dev/null +@@ -1,607 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/services/correction/status.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'abstract_rename.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RenameUnitMemberTest); +- }); +-} +- +-@reflectiveTest +-class RenameUnitMemberTest extends RenameRefactoringTest { +- test_checkFinalConditions_hasTopLevel_ClassElement() async { +- await indexTestUnit(''' +-class Test {} +-class NewName {} // existing +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Library already declares class with name 'NewNa= me'.", +- expectedContextSearch: 'NewName {} // existing'); +- } +- +- test_checkFinalConditions_hasTopLevel_FunctionTypeAliasElement() async { +- await indexTestUnit(''' +-class Test {} +-typedef NewName(); // existing +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Library already declares function type alias with name 'NewN= ame'.", +- expectedContextSearch: 'NewName(); // existing'); +- } +- +- test_checkFinalConditions_OK_qualifiedSuper_MethodElement() async { +- await indexTestUnit(''' +-class Test {} +-class A { +- NewName() {} +-} +-class B extends A { +- main() { +- super.NewName(); // super-ref +- } +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_publicToPrivate_usedInOtherLibrary() async { +- await indexTestUnit(''' +-class Test {} +-'''); +- await indexUnit('/lib.dart', ''' +-library my.lib; +-import 'test.dart'; +- +-main() { +- new Test(); +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D '_NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed class will be invisible in 'my.lib'."); +- } +- +- test_checkFinalConditions_shadowedBy_MethodElement() async { +- await indexTestUnit(''' +-class Test {} +-class A { +- void NewName() {} +- main() { +- new Test(); +- } +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: +- "Reference to renamed class will be shadowed by method 'A.New= Name'.", +- expectedContextSearch: 'NewName() {}'); +- } +- +- test_checkFinalConditions_shadowsInSubClass_importedLib() async { +- await indexTestUnit(''' +-class Test {} +-'''); +- await indexUnit('/lib.dart', ''' +-library my.lib; +-import 'test.dart'; +-class A { +- NewName() {} +-} +-class B extends A { +- main() { +- NewName(); // super-ref +- }", +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed class will shadow method 'A.NewName'."); +- } +- +- test_checkFinalConditions_shadowsInSubClass_importedLib_hideCombinator(= ) async { +- await indexTestUnit(''' +-class Test {} +-'''); +- await indexUnit('/lib.dart', ''' +-library my.lib; +-import 'test.dart' hide Test; +-class A { +- NewName() {} +-} +-class B extends A { +- main() { +- NewName(); // super-ref +- }", +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_shadowsInSubClass_MethodElement() async { +- await indexTestUnit(''' +-class Test {} +-class A { +- NewName() {} +-} +-class B extends A { +- main() { +- NewName(); // super-ref +- } +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatus(status, RefactoringProblemSeverity.ERROR, +- expectedMessage: "Renamed class will shadow method 'A.NewName'.", +- expectedContextSearch: 'NewName(); // super-ref'); +- } +- +- test_checkFinalConditions_shadowsInSubClass_notImportedLib() async { +- await indexUnit('/lib.dart', ''' +-library my.lib; +-class A { +- NewName() {} +-} +-class B extends A { +- main() { +- NewName(); // super-ref +- }", +-} +-'''); +- await indexTestUnit(''' +-class Test {} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkFinalConditions_shadowsInSubClass_notSubClass() async { +- await indexTestUnit(''' +-class Test {} +-class A { +- NewName() {} +-} +-class B { +- main(A a) { +- a.NewName(); +- } +-} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkFinalConditions(); +- assertRefactoringStatusOK(status); +- } +- +- test_checkInitialConditions_inPubCache_posix() async { +- addSource('/.pub-cache/lib.dart', r''' +-class A {} +-'''); +- await indexTestUnit(''' +-import '/.pub-cache/lib.dart'; +-main() { +- A a; +-} +-'''); +- createRenameRefactoringAtString('A a'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The class 'A' is defined in a pub package, so cannot be rena= med."); +- } +- +- test_checkInitialConditions_inPubCache_windows() async { +- addSource('/Pub/Cache/lib.dart', r''' +-class A {} +-'''); +- await indexTestUnit(''' +-import '/Pub/Cache/lib.dart'; +-main() { +- A a; +-} +-'''); +- createRenameRefactoringAtString('A a'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The class 'A' is defined in a pub package, so cannot be rena= med."); +- } +- +- test_checkInitialConditions_inSDK() async { +- await indexTestUnit(''' +-main() { +- String s; +-} +-'''); +- createRenameRefactoringAtString('String s'); +- // check status +- refactoring.newName =3D 'NewName'; +- RefactoringStatus status =3D await refactoring.checkInitialConditions= (); +- assertRefactoringStatus(status, RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The class 'String' is defined in the SDK, so cannot be renam= ed."); +- } +- +- test_checkNewName_ClassElement() async { +- await indexTestUnit(''' +-class Test {} +-'''); +- createRenameRefactoringAtString('Test {}'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Class name must not be empty."); +- // same +- refactoring.newName =3D 'Test'; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: +- "The new name must be different than the current name."); +- // OK +- refactoring.newName =3D 'NewName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_FunctionElement() async { +- await indexTestUnit(''' +-test() {} +-'''); +- createRenameRefactoringAtString('test() {}'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function name must not be empty."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_FunctionTypeAliasElement() async { +- await indexTestUnit(''' +-typedef Test(); +-'''); +- createRenameRefactoringAtString('Test();'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Function type alias name must not be null."); +- // OK +- refactoring.newName =3D 'NewName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_checkNewName_TopLevelVariableElement() async { +- await indexTestUnit(''' +-var test; +-'''); +- createRenameRefactoringAtString('test;'); +- // null +- refactoring.newName =3D null; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be null."); +- // empty +- refactoring.newName =3D ''; +- assertRefactoringStatus( +- refactoring.checkNewName(), RefactoringProblemSeverity.FATAL, +- expectedMessage: "Variable name must not be empty."); +- // OK +- refactoring.newName =3D 'newName'; +- assertRefactoringStatusOK(refactoring.checkNewName()); +- } +- +- test_createChange_ClassElement() async { +- await indexTestUnit(''' +-class Test implements Other { +- Test() {} +- Test.named() {} +-} +-class Other { +- factory Other.a() =3D Test; +- factory Other.b() =3D Test.named; +-} +-main() { +- Test t1 =3D new Test(); +- Test t2 =3D new Test.named(); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('Test implements'); +- expect(refactoring.refactoringName, 'Rename Class'); +- expect(refactoring.elementKindName, 'class'); +- expect(refactoring.oldName, 'Test'); +- refactoring.newName =3D 'NewName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class NewName implements Other { +- NewName() {} +- NewName.named() {} +-} +-class Other { +- factory Other.a() =3D NewName; +- factory Other.b() =3D NewName.named; +-} +-main() { +- NewName t1 =3D new NewName(); +- NewName t2 =3D new NewName.named(); +-} +-'''); +- } +- +- test_createChange_ClassElement_invocation() async { +- verifyNoTestUnitErrors =3D false; +- await indexTestUnit(''' +-class Test { +-} +-main() { +- Test(); // invalid code, but still a reference +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('Test();'); +- expect(refactoring.refactoringName, 'Rename Class'); +- expect(refactoring.elementKindName, 'class'); +- expect(refactoring.oldName, 'Test'); +- refactoring.newName =3D 'NewName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class NewName { +-} +-main() { +- NewName(); // invalid code, but still a reference +-} +-'''); +- } +- +- test_createChange_ClassElement_parameterTypeNested() async { +- await indexTestUnit(''' +-class Test { +-} +-main(f(Test p)) { +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('Test {'); +- expect(refactoring.refactoringName, 'Rename Class'); +- expect(refactoring.oldName, 'Test'); +- refactoring.newName =3D 'NewName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class NewName { +-} +-main(f(NewName p)) { +-} +-'''); +- } +- +- test_createChange_ClassElement_typeAlias() async { +- await indexTestUnit(''' +-class A {} +-class Test =3D Object with A; +-main(Test t) { +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('Test =3D'); +- expect(refactoring.refactoringName, 'Rename Class'); +- expect(refactoring.elementKindName, 'class'); +- expect(refactoring.oldName, 'Test'); +- refactoring.newName =3D 'NewName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-class A {} +-class NewName =3D Object with A; +-main(NewName t) { +-} +-'''); +- } +- +- test_createChange_FunctionElement() async { +- await indexTestUnit(''' +-test() {} +-foo() {} +-main() { +- print(test); +- print(test()); +- foo(); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test() {}'); +- expect(refactoring.refactoringName, 'Rename Top-Level Function'); +- expect(refactoring.elementKindName, 'function'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-newName() {} +-foo() {} +-main() { +- print(newName); +- print(newName()); +- foo(); +-} +-'''); +- } +- +- test_createChange_FunctionElement_imported() async { +- await indexUnit('/foo.dart', r''' +-test() {} +-foo() {} +-'''); +- await indexTestUnit(''' +-import 'foo.dart'; +-main() { +- print(test); +- print(test()); +- foo(); +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString('test);'); +- expect(refactoring.refactoringName, 'Rename Top-Level Function'); +- expect(refactoring.elementKindName, 'function'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- await assertSuccessfulRefactoring(''' +-import 'foo.dart'; +-main() { +- print(newName); +- print(newName()); +- foo(); +-} +-'''); +- assertFileChangeResult('/foo.dart', ''' +-newName() {} +-foo() {} +-'''); +- } +- +- test_createChange_PropertyAccessorElement_getter_declaration() async { +- await _test_createChange_PropertyAccessorElement("test {}"); +- } +- +- test_createChange_PropertyAccessorElement_getter_usage() async { +- await _test_createChange_PropertyAccessorElement("test);"); +- } +- +- test_createChange_PropertyAccessorElement_mix() async { +- await _test_createChange_PropertyAccessorElement("test +=3D 2"); +- } +- +- test_createChange_PropertyAccessorElement_setter_declaration() async { +- await _test_createChange_PropertyAccessorElement("test(x) {}"); +- } +- +- test_createChange_PropertyAccessorElement_setter_usage() async { +- await _test_createChange_PropertyAccessorElement("test =3D 1"); +- } +- +- test_createChange_TopLevelVariableElement_field() async { +- await _test_createChange_TopLevelVariableElement("test =3D 0"); +- } +- +- test_createChange_TopLevelVariableElement_getter() async { +- await _test_createChange_TopLevelVariableElement("test);"); +- } +- +- test_createChange_TopLevelVariableElement_mix() async { +- await _test_createChange_TopLevelVariableElement("test +=3D 2"); +- } +- +- test_createChange_TopLevelVariableElement_setter() async { +- await _test_createChange_TopLevelVariableElement("test =3D 1"); +- } +- +- _test_createChange_PropertyAccessorElement(String search) async { +- await indexTestUnit(''' +-get test {} +-set test(x) {} +-main() { +- print(test); +- test =3D 1; +- test +=3D 2; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString(search); +- expect(refactoring.refactoringName, 'Rename Top-Level Variable'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-get newName {} +-set newName(x) {} +-main() { +- print(newName); +- newName =3D 1; +- newName +=3D 2; +-} +-'''); +- } +- +- _test_createChange_TopLevelVariableElement(String search) async { +- await indexTestUnit(''' +-int test =3D 0; +-main() { +- print(test); +- test =3D 1; +- test +=3D 2; +-} +-'''); +- // configure refactoring +- createRenameRefactoringAtString(search); +- expect(refactoring.refactoringName, 'Rename Top-Level Variable'); +- expect(refactoring.elementKindName, 'top level variable'); +- expect(refactoring.oldName, 'test'); +- refactoring.newName =3D 'newName'; +- // validate change +- return assertSuccessfulRefactoring(''' +-int newName =3D 0; +-main() { +- print(newName); +- newName =3D 1; +- newName +=3D 2; +-} +-'''); +- } +-} +diff --git a/pkg/analysis_server/test/services/refactoring/test_all.dart b= /pkg/analysis_server/test/services/refactoring/test_all.dart +deleted file mode 100644 +index b845a983e45..00000000000 +--- a/pkg/analysis_server/test/services/refactoring/test_all.dart ++++ /dev/null +@@ -1,40 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'convert_getter_to_method_test.dart' as convert_getter_to_method_t= est; +-import 'convert_method_to_getter_test.dart' as convert_method_to_getter_t= est; +-import 'extract_local_test.dart' as extract_local_test; +-import 'extract_method_test.dart' as extract_method_test; +-import 'inline_local_test.dart' as inline_local_test; +-import 'inline_method_test.dart' as inline_method_test; +-import 'naming_conventions_test.dart' as naming_conventions_test; +-import 'rename_class_member_test.dart' as rename_class_member_test; +-import 'rename_constructor_test.dart' as rename_constructor_test; +-import 'rename_import_test.dart' as rename_import_test; +-import 'rename_label_test.dart' as rename_label_test; +-import 'rename_library_test.dart' as rename_library_test; +-import 'rename_local_test.dart' as rename_local_test; +-import 'rename_unit_member_test.dart' as rename_unit_member_test; +- +-/// Utility for manually running all tests. +-main() { +- defineReflectiveSuite(() { +- convert_getter_to_method_test.main(); +- convert_method_to_getter_test.main(); +- extract_local_test.main(); +- extract_method_test.main(); +- inline_local_test.main(); +- inline_method_test.main(); +- naming_conventions_test.main(); +- rename_class_member_test.main(); +- rename_constructor_test.main(); +- rename_import_test.main(); +- rename_label_test.main(); +- rename_library_test.main(); +- rename_local_test.main(); +- rename_unit_member_test.main(); +- }, name: 'refactoring'); +-} +diff --git a/pkg/analysis_server/test/services/search/hierarchy_test.dart = b/pkg/analysis_server/test/services/search/hierarchy_test.dart +deleted file mode 100644 +index d81893de9d0..00000000000 +--- a/pkg/analysis_server/test/services/search/hierarchy_test.dart ++++ /dev/null +@@ -1,362 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/search/hierarchy.dart'; +-import 'package:analysis_server/src/services/search/search_engine_interna= l.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(HierarchyTest); +- }); +-} +- +-@reflectiveTest +-class HierarchyTest extends AbstractSingleUnitTest { +- SearchEngineImpl searchEngine; +- +- void setUp() { +- super.setUp(); +- searchEngine =3D new SearchEngineImpl([driver]); +- } +- +- test_getClassMembers() async { +- await _indexTestUnit(''' +-class A { +- A() {} +- var ma1; +- ma2() {} +-} +-class B extends A { +- B() {} +- B.named() {} +- var mb1; +- mb2() {} +-} +-'''); +- { +- ClassElement classA =3D findElement('A'); +- List members =3D getClassMembers(classA); +- expect(members.map((e) =3D> e.name), unorderedEquals(['ma1', 'ma2']= )); +- } +- { +- ClassElement classB =3D findElement('B'); +- List members =3D getClassMembers(classB); +- expect(members.map((e) =3D> e.name), unorderedEquals(['mb1', 'mb2']= )); +- } +- } +- +- test_getHierarchyMembers_constructors() async { +- await _indexTestUnit(''' +-class A { +- A() {} +-} +-class B extends A { +- B() {} +-} +-'''); +- ClassElement classA =3D findElement("A"); +- ClassElement classB =3D findElement("B"); +- ClassMemberElement memberA =3D classA.constructors[0]; +- ClassMemberElement memberB =3D classB.constructors[0]; +- var futureA =3D getHierarchyMembers(searchEngine, memberA).then((memb= ers) { +- expect(members, unorderedEquals([memberA])); +- }); +- var futureB =3D getHierarchyMembers(searchEngine, memberB).then((memb= ers) { +- expect(members, unorderedEquals([memberB])); +- }); +- return Future.wait([futureA, futureB]); +- } +- +- test_getHierarchyMembers_fields() async { +- await _indexTestUnit(''' +-class A { +- int foo; +-} +-class B extends A { +- get foo =3D> null; +-} +-class C extends B { +- set foo(x) {} +-} +-class D { +- int foo; +-} +-'''); +- ClassElement classA =3D findElement("A"); +- ClassElement classB =3D findElement("B"); +- ClassElement classC =3D findElement("C"); +- ClassElement classD =3D findElement("D"); +- ClassMemberElement memberA =3D classA.fields[0]; +- ClassMemberElement memberB =3D classB.fields[0]; +- ClassMemberElement memberC =3D classC.fields[0]; +- ClassMemberElement memberD =3D classD.fields[0]; +- var futureA =3D getHierarchyMembers(searchEngine, memberA).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberC])); +- }); +- var futureB =3D getHierarchyMembers(searchEngine, memberB).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberC])); +- }); +- var futureC =3D getHierarchyMembers(searchEngine, memberC).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberC])); +- }); +- var futureD =3D getHierarchyMembers(searchEngine, memberD).then((memb= ers) { +- expect(members, unorderedEquals([memberD])); +- }); +- return Future.wait([futureA, futureB, futureC, futureD]); +- } +- +- test_getHierarchyMembers_fields_static() async { +- await _indexTestUnit(''' +-class A { +- static int foo; +-} +-class B extends A { +- static get foo =3D> null; +-} +-class C extends B { +- static set foo(x) {} +-} +-'''); +- ClassElement classA =3D findElement('A'); +- ClassElement classB =3D findElement('B'); +- ClassElement classC =3D findElement('C'); +- ClassMemberElement memberA =3D classA.fields[0]; +- ClassMemberElement memberB =3D classB.fields[0]; +- ClassMemberElement memberC =3D classC.fields[0]; +- { +- Set members =3D +- await getHierarchyMembers(searchEngine, memberA); +- expect(members, unorderedEquals([memberA])); +- } +- { +- Set members =3D +- await getHierarchyMembers(searchEngine, memberB); +- expect(members, unorderedEquals([memberB])); +- } +- { +- Set members =3D +- await getHierarchyMembers(searchEngine, memberC); +- expect(members, unorderedEquals([memberC])); +- } +- } +- +- test_getHierarchyMembers_methods() async { +- await _indexTestUnit(''' +-class A { +- foo() {} +-} +-class B extends A { +- foo() {} +-} +-class C extends B { +- foo() {} +-} +-class D { +- foo() {} +-} +-class E extends D { +- foo() {} +-} +-'''); +- ClassElement classA =3D findElement("A"); +- ClassElement classB =3D findElement("B"); +- ClassElement classC =3D findElement("C"); +- ClassElement classD =3D findElement("D"); +- ClassElement classE =3D findElement("E"); +- ClassMemberElement memberA =3D classA.methods[0]; +- ClassMemberElement memberB =3D classB.methods[0]; +- ClassMemberElement memberC =3D classC.methods[0]; +- ClassMemberElement memberD =3D classD.methods[0]; +- ClassMemberElement memberE =3D classE.methods[0]; +- var futureA =3D getHierarchyMembers(searchEngine, memberA).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberC])); +- }); +- var futureB =3D getHierarchyMembers(searchEngine, memberB).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberC])); +- }); +- var futureC =3D getHierarchyMembers(searchEngine, memberC).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberC])); +- }); +- var futureD =3D getHierarchyMembers(searchEngine, memberD).then((memb= ers) { +- expect(members, unorderedEquals([memberD, memberE])); +- }); +- var futureE =3D getHierarchyMembers(searchEngine, memberE).then((memb= ers) { +- expect(members, unorderedEquals([memberD, memberE])); +- }); +- return Future.wait([futureA, futureB, futureC, futureD, futureE]); +- } +- +- test_getHierarchyMembers_methods_static() async { +- await _indexTestUnit(''' +-class A { +- static foo() {} +-} +-class B extends A { +- static foo() {} +-} +-'''); +- ClassElement classA =3D findElement('A'); +- ClassElement classB =3D findElement('B'); +- ClassMemberElement memberA =3D classA.methods[0]; +- ClassMemberElement memberB =3D classB.methods[0]; +- { +- Set members =3D +- await getHierarchyMembers(searchEngine, memberA); +- expect(members, unorderedEquals([memberA])); +- } +- { +- Set members =3D +- await getHierarchyMembers(searchEngine, memberB); +- expect(members, unorderedEquals([memberB])); +- } +- } +- +- test_getHierarchyMembers_withInterfaces() async { +- await _indexTestUnit(''' +-class A { +- foo() {} +-} +-class B implements A { +- foo() {} +-} +-abstract class C implements A { +-} +-class D extends C { +- foo() {} +-} +-class E { +- foo() {} +-} +-'''); +- ClassElement classA =3D findElement("A"); +- ClassElement classB =3D findElement("B"); +- ClassElement classD =3D findElement("D"); +- ClassMemberElement memberA =3D classA.methods[0]; +- ClassMemberElement memberB =3D classB.methods[0]; +- ClassMemberElement memberD =3D classD.methods[0]; +- var futureA =3D getHierarchyMembers(searchEngine, memberA).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberD])); +- }); +- var futureB =3D getHierarchyMembers(searchEngine, memberB).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberD])); +- }); +- var futureD =3D getHierarchyMembers(searchEngine, memberD).then((memb= ers) { +- expect(members, unorderedEquals([memberA, memberB, memberD])); +- }); +- return Future.wait([futureA, futureB, futureD]); +- } +- +- test_getMembers() async { +- await _indexTestUnit(''' +-class A { +- A() {} +- var ma1; +- ma2() {} +-} +-class B extends A { +- B() {} +- B.named() {} +- var mb1; +- mb2() {} +-} +-'''); +- { +- ClassElement classA =3D findElement('A'); +- List members =3D getMembers(classA); +- expect( +- members.map((e) =3D> e.name), +- unorderedEquals([ +- 'ma1', +- 'ma2', +- '=3D=3D', +- 'toString', +- 'hashCode', +- 'noSuchMethod', +- 'runtimeType' +- ])); +- } +- { +- ClassElement classB =3D findElement('B'); +- List members =3D getMembers(classB); +- expect( +- members.map((e) =3D> e.name), +- unorderedEquals([ +- 'mb1', +- 'mb2', +- 'ma1', +- 'ma2', +- '=3D=3D', +- 'toString', +- 'hashCode', +- 'noSuchMethod', +- 'runtimeType' +- ])); +- } +- } +- +- test_getSuperClasses() async { +- await _indexTestUnit(''' +-class A {} +-class B extends A {} +-class C extends B {} +-class D extends B implements A {} +-class M {} +-class E extends A with M {} +-class F implements A {} +-'''); +- ClassElement classA =3D findElement("A"); +- ClassElement classB =3D findElement("B"); +- ClassElement classC =3D findElement("C"); +- ClassElement classD =3D findElement("D"); +- ClassElement classE =3D findElement("E"); +- ClassElement classF =3D findElement("F"); +- ClassElement objectElement =3D classA.supertype.element; +- // Object +- { +- Set supers =3D getSuperClasses(objectElement); +- expect(supers, isEmpty); +- } +- // A +- { +- Set supers =3D getSuperClasses(classA); +- expect(supers, unorderedEquals([objectElement])); +- } +- // B +- { +- Set supers =3D getSuperClasses(classB); +- expect(supers, unorderedEquals([objectElement, classA])); +- } +- // C +- { +- Set supers =3D getSuperClasses(classC); +- expect(supers, unorderedEquals([objectElement, classA, classB])); +- } +- // D +- { +- Set supers =3D getSuperClasses(classD); +- expect(supers, unorderedEquals([objectElement, classA, classB])); +- } +- // E +- { +- Set supers =3D getSuperClasses(classE); +- expect(supers, unorderedEquals([objectElement, classA])); +- } +- // F +- { +- Set supers =3D getSuperClasses(classF); +- expect(supers, unorderedEquals([objectElement, classA])); +- } +- } +- +- Future _indexTestUnit(String code) async { +- await resolveTestUnit(code); +- } +-} +diff --git a/pkg/analysis_server/test/services/search/search_engine_test.d= art b/pkg/analysis_server/test/services/search/search_engine_test.dart +deleted file mode 100644 +index 7f65d45ce60..00000000000 +--- a/pkg/analysis_server/test/services/search/search_engine_test.dart ++++ /dev/null +@@ -1,422 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/services/search/search_engine.dart'; +-import 'package:analysis_server/src/services/search/search_engine_interna= l.dart'; +-import 'package:analyzer/dart/element/element.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/file_state.dart'; +-import 'package:analyzer/src/generated/engine.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:front_end/byte_store.dart'; +-import 'package:front_end/src/base/performance_logger.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../mock_sdk.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(SearchEngineImpl2Test); +- }); +-} +- +-@reflectiveTest +-class SearchEngineImpl2Test { +- final MemoryResourceProvider provider =3D new MemoryResourceProvider(); +- DartSdk sdk; +- final ByteStore byteStore =3D new MemoryByteStore(); +- final FileContentOverlay contentOverlay =3D new FileContentOverlay(); +- +- final StringBuffer logBuffer =3D new StringBuffer(); +- PerformanceLog logger; +- +- AnalysisDriverScheduler scheduler; +- +- void setUp() { +- sdk =3D new MockSdk(resourceProvider: provider); +- logger =3D new PerformanceLog(logBuffer); +- scheduler =3D new AnalysisDriverScheduler(logger); +- scheduler.start(); +- } +- +- test_membersOfSubtypes_hasMembers() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- var c =3D _p('/test/c.dart'); +- +- provider.newFile(a, ''' +-class A { +- void a() {} +- void b() {} +- void c() {} +-} +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-class B extends A { +- void a() {} +-} +-'''); +- provider.newFile(c, ''' +-import 'a.dart'; +-class C extends A { +- void b() {} +-} +-'''); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- driver2.addFile(c); +- await scheduler.waitForIdle(); +- +- var resultA =3D await driver1.getResult(a); +- ClassElement elementA =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- Set members =3D await searchEngine.membersOfSubtypes(elementA= ); +- expect(members, unorderedEquals(['a', 'b'])); +- } +- +- test_membersOfSubtypes_noMembers() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class A { +- void a() {} +- void b() {} +- void c() {} +-} +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-class B extends A {} +-'''); +- +- var driver =3D _newDriver(); +- +- driver.addFile(a); +- driver.addFile(b); +- await scheduler.waitForIdle(); +- +- var resultA =3D await driver.getResult(a); +- ClassElement elementA =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver]); +- Set members =3D await searchEngine.membersOfSubtypes(elementA= ); +- expect(members, isEmpty); +- } +- +- test_membersOfSubtypes_noSubtypes() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class A { +- void a() {} +- void b() {} +- void c() {} +-} +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-class B { +- void a() {} +-} +-'''); +- +- var driver =3D _newDriver(); +- +- driver.addFile(a); +- driver.addFile(b); +- await scheduler.waitForIdle(); +- +- var resultA =3D await driver.getResult(a); +- ClassElement elementA =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver]); +- Set members =3D await searchEngine.membersOfSubtypes(elementA= ); +- expect(members, isNull); +- } +- +- test_membersOfSubtypes_private() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class A { +- void a() {} +- void _b() {} +- void _c() {} +-} +-class B extends A { +- void _b() {} +-} +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-class C extends A { +- void a() {} +- void _c() {} +-} +-class D extends B { +- void _c() {} +-} +-'''); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- await scheduler.waitForIdle(); +- +- var resultA =3D await driver1.getResult(a); +- ClassElement elementA =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- Set members =3D await searchEngine.membersOfSubtypes(elementA= ); +- expect(members, unorderedEquals(['a', '_b'])); +- } +- +- test_searchAllSubtypes() async { +- var p =3D _p('/test.dart'); +- +- provider.newFile(p, ''' +-class T {} +-class A extends T {} +-class B extends A {} +-class C implements B {} +-'''); +- +- var driver =3D _newDriver(); +- driver.addFile(p); +- +- var resultA =3D await driver.getResult(p); +- ClassElement element =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver]); +- Set subtypes =3D await searchEngine.searchAllSubtypes(e= lement); +- expect(subtypes, hasLength(3)); +- expect(subtypes, contains(predicate((ClassElement e) =3D> e.name =3D= =3D 'A'))); +- expect(subtypes, contains(predicate((ClassElement e) =3D> e.name =3D= =3D 'B'))); +- expect(subtypes, contains(predicate((ClassElement e) =3D> e.name =3D= =3D 'C'))); +- } +- +- test_searchAllSubtypes_acrossDrivers() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class T {} +-class A extends T {} +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-class B extends A {} +-class C extends B {} +-'''); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- +- var resultA =3D await driver1.getResult(a); +- ClassElement element =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- Set subtypes =3D await searchEngine.searchAllSubtypes(e= lement); +- expect(subtypes, hasLength(3)); +- expect(subtypes, contains(predicate((ClassElement e) =3D> e.name =3D= =3D 'A'))); +- expect(subtypes, contains(predicate((ClassElement e) =3D> e.name =3D= =3D 'B'))); +- expect(subtypes, contains(predicate((ClassElement e) =3D> e.name =3D= =3D 'C'))); +- } +- +- test_searchMemberDeclarations() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- var codeA =3D ''' +-class A { +- int test; // 1 +- int testTwo; +-} +-'''; +- var codeB =3D ''' +-class B { +- void test() {} // 2 +- void testTwo() {} +-} +-int test; +-'''; +- +- provider.newFile(a, codeA); +- provider.newFile(b, codeB); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- +- while (scheduler.isAnalyzing) { +- await new Future.delayed(new Duration(milliseconds: 1)); +- } +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- List matches =3D +- await searchEngine.searchMemberDeclarations('test'); +- expect(matches, hasLength(2)); +- +- void assertHasElement(String name, int nameOffset) { +- expect( +- matches, +- contains(predicate((SearchMatch m) =3D> +- m.kind =3D=3D MatchKind.DECLARATION && +- m.element.name =3D=3D name && +- m.element.nameOffset =3D=3D nameOffset))); +- } +- +- assertHasElement('test', codeA.indexOf('test; // 1')); +- assertHasElement('test', codeB.indexOf('test() {} // 2')); +- } +- +- test_searchMemberReferences() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class A { +- int test; +-} +-foo(p) { +- p.test; +-} +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-bar(p) { +- p.test =3D 1; +-} +-'''); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- List matches =3D +- await searchEngine.searchMemberReferences('test'); +- expect(matches, hasLength(2)); +- expect( +- matches, +- contains(predicate((SearchMatch m) =3D> +- m.element.name =3D=3D 'foo' || m.kind =3D=3D MatchKind.READ))= ); +- expect( +- matches, +- contains(predicate((SearchMatch m) =3D> +- m.element.name =3D=3D 'bar' || m.kind =3D=3D MatchKind.WRITE)= )); +- } +- +- test_searchReferences() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class T {} +-T a; +-'''); +- provider.newFile(b, ''' +-import 'a.dart'; +-T b; +-'''); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- +- var resultA =3D await driver1.getResult(a); +- ClassElement element =3D resultA.unit.element.types[0]; +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- List matches =3D await searchEngine.searchReferences(ele= ment); +- expect(matches, hasLength(2)); +- expect( +- matches, contains(predicate((SearchMatch m) =3D> m.element.name = =3D=3D 'a'))); +- expect( +- matches, contains(predicate((SearchMatch m) =3D> m.element.name = =3D=3D 'b'))); +- } +- +- test_searchTopLevelDeclarations() async { +- var a =3D _p('/test/a.dart'); +- var b =3D _p('/test/b.dart'); +- +- provider.newFile(a, ''' +-class A {} +-int a; +-'''); +- provider.newFile(b, ''' +-class B {} +-get b =3D> 42; +-'''); +- +- var driver1 =3D _newDriver(); +- var driver2 =3D _newDriver(); +- +- driver1.addFile(a); +- driver2.addFile(b); +- +- while (scheduler.isAnalyzing) { +- await new Future.delayed(new Duration(milliseconds: 1)); +- } +- +- var searchEngine =3D new SearchEngineImpl([driver1, driver2]); +- List matches =3D +- await searchEngine.searchTopLevelDeclarations('.*'); +- expect( +- matches.where((match) =3D> !match.libraryElement.isInSdk), hasLen= gth(4)); +- +- void assertHasElement(String name) { +- expect( +- matches, +- contains(predicate((SearchMatch m) =3D> +- m.kind =3D=3D MatchKind.DECLARATION && m.element.name =3D= =3D name))); +- } +- +- assertHasElement('A'); +- assertHasElement('a'); +- assertHasElement('B'); +- assertHasElement('b'); +- } +- +- AnalysisDriver _newDriver() =3D> new AnalysisDriver( +- scheduler, +- logger, +- provider, +- byteStore, +- contentOverlay, +- null, +- new SourceFactory( +- [new DartUriResolver(sdk), new ResourceUriResolver(provider)], +- null, +- provider), +- new AnalysisOptionsImpl()..strongMode =3D true); +- +- String _p(String path) =3D> provider.convertPath(path); +-} +diff --git a/pkg/analysis_server/test/services/search/test_all.dart b/pkg/= analysis_server/test/services/search/test_all.dart +deleted file mode 100644 +index 0bc46de88e2..00000000000 +--- a/pkg/analysis_server/test/services/search/test_all.dart ++++ /dev/null +@@ -1,18 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'hierarchy_test.dart' as hierarchy_test; +-import 'search_engine_test.dart' as search_engine_test; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- defineReflectiveSuite(() { +- hierarchy_test.main(); +- search_engine_test.main(); +- }, name: 'search'); +-} +diff --git a/pkg/analysis_server/test/services/test_all.dart b/pkg/analysi= s_server/test/services/test_all.dart +deleted file mode 100644 +index 2d77c254c4a..00000000000 +--- a/pkg/analysis_server/test/services/test_all.dart ++++ /dev/null +@@ -1,21 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'completion/test_all.dart' as completion_all; +-import 'correction/test_all.dart' as correction_all; +-import 'linter/test_all.dart' as linter_all; +-import 'refactoring/test_all.dart' as refactoring_all; +-import 'search/test_all.dart' as search_all; +- +-main() { +- defineReflectiveSuite(() { +- completion_all.main(); +- correction_all.main(); +- linter_all.main(); +- refactoring_all.main(); +- search_all.main(); +- }); +-} +diff --git a/pkg/analysis_server/test/socket_server_test.dart b/pkg/analys= is_server/test/socket_server_test.dart +deleted file mode 100644 +index 244e7c86f08..00000000000 +--- a/pkg/analysis_server/test/socket_server_test.dart ++++ /dev/null +@@ -1,142 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_constants.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/analysis_server.dart'; +-import 'package:analysis_server/src/socket_server.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer/src/dart/sdk/sdk.dart'; +-import 'package:analyzer/src/generated/sdk.dart'; +-import 'package:test/test.dart'; +- +-import 'mocks.dart'; +- +-main() { +- group('SocketServer', () { +- test('createAnalysisServer_successful', +- SocketServerTest.createAnalysisServer_successful); +- test('createAnalysisServer_alreadyStarted', +- SocketServerTest.createAnalysisServer_alreadyStarted); +- test('requestHandler_exception', SocketServerTest.requestHandler_exce= ption); +- test('requestHandler_futureException', +- SocketServerTest.requestHandler_futureException); +- }); +-} +- +-class SocketServerTest { +- static void createAnalysisServer_alreadyStarted() { +- SocketServer server =3D _createSocketServer(); +- MockServerChannel channel1 =3D new MockServerChannel(); +- MockServerChannel channel2 =3D new MockServerChannel(); +- server.createAnalysisServer(channel1); +- expect( +- channel1.notificationsReceived[0].event, SERVER_NOTIFICATION_CONN= ECTED); +- server.createAnalysisServer(channel2); +- channel1.expectMsgCount(notificationCount: 1); +- channel2.expectMsgCount(responseCount: 1); +- expect(channel2.responsesReceived[0].id, equals('')); +- expect(channel2.responsesReceived[0].error, isNotNull); +- expect(channel2.responsesReceived[0].error.code, +- equals(RequestErrorCode.SERVER_ALREADY_STARTED)); +- channel2 +- .sendRequest(new ServerShutdownParams().toRequest('0')) +- .then((Response response) { +- expect(response.id, equals('0')); +- expect(response.error, isNotNull); +- expect( +- response.error.code, equals(RequestErrorCode.SERVER_ALREADY_STA= RTED)); +- channel2.expectMsgCount(responseCount: 2); +- }); +- } +- +- static Future createAnalysisServer_successful() { +- SocketServer server =3D _createSocketServer(); +- MockServerChannel channel =3D new MockServerChannel(); +- server.createAnalysisServer(channel); +- channel.expectMsgCount(notificationCount: 1); +- expect( +- channel.notificationsReceived[0].event, SERVER_NOTIFICATION_CONNE= CTED); +- return channel +- .sendRequest(new ServerShutdownParams().toRequest('0')) +- .then((Response response) { +- expect(response.id, equals('0')); +- expect(response.error, isNull); +- channel.expectMsgCount(responseCount: 1, notificationCount: 1); +- }); +- } +- +- static Future requestHandler_exception() { +- SocketServer server =3D _createSocketServer(); +- MockServerChannel channel =3D new MockServerChannel(); +- server.createAnalysisServer(channel); +- channel.expectMsgCount(notificationCount: 1); +- expect( +- channel.notificationsReceived[0].event, SERVER_NOTIFICATION_CONNE= CTED); +- _MockRequestHandler handler =3D new _MockRequestHandler(false); +- server.analysisServer.handlers =3D [handler]; +- var request =3D new ServerGetVersionParams().toRequest('0'); +- return channel.sendRequest(request).then((Response response) { +- expect(response.id, equals('0')); +- expect(response.error, isNotNull); +- expect(response.error.code, equals(RequestErrorCode.SERVER_ERROR)); +- expect(response.error.message, equals('mock request exception')); +- expect(response.error.stackTrace, isNotNull); +- expect(response.error.stackTrace, isNotEmpty); +- channel.expectMsgCount(responseCount: 1, notificationCount: 1); +- }); +- } +- +- static Future requestHandler_futureException() { +- SocketServer server =3D _createSocketServer(); +- MockServerChannel channel =3D new MockServerChannel(); +- server.createAnalysisServer(channel); +- _MockRequestHandler handler =3D new _MockRequestHandler(true); +- server.analysisServer.handlers =3D [handler]; +- var request =3D new ServerGetVersionParams().toRequest('0'); +- return channel.sendRequest(request).then((Response response) { +- expect(response.id, equals('0')); +- expect(response.error, isNull); +- channel.expectMsgCount(responseCount: 1, notificationCount: 2); +- expect(channel.notificationsReceived[1].event, SERVER_NOTIFICATION_= ERROR); +- }); +- } +- +- static SocketServer _createSocketServer() { +- PhysicalResourceProvider resourceProvider =3D +- PhysicalResourceProvider.INSTANCE; +- return new SocketServer( +- new AnalysisServerOptions(), +- new DartSdkManager('', false), +- new FolderBasedDartSdk(resourceProvider, +- FolderBasedDartSdk.defaultSdkDirectory(resourceProvider)), +- InstrumentationService.NULL_SERVICE, +- null, +- null, +- null); +- } +-} +- +-class _MockRequestHandler implements RequestHandler { +- final bool futureException; +- +- _MockRequestHandler(this.futureException); +- +- @override +- Response handleRequest(Request request) { +- if (futureException) { +- new Future(throwException); +- return new Response(request.id); +- } +- throw 'mock request exception'; +- } +- +- void throwException() { +- throw 'mock future exception'; +- } +-} +diff --git a/pkg/analysis_server/test/src/computer/closingLabels_computer_= test.dart b/pkg/analysis_server/test/src/computer/closingLabels_computer_te= st.dart +deleted file mode 100644 +index 533d072a61c..00000000000 +--- a/pkg/analysis_server/test/src/computer/closingLabels_computer_test.da= rt ++++ /dev/null +@@ -1,346 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/computer/computer_closingLabels.dart'; +-import 'package:analyzer/dart/analysis/results.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_context.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ClosingLabelsComputerTest); +- }); +-} +- +-@reflectiveTest +-class ClosingLabelsComputerTest extends AbstractContextTest { +- String sourcePath; +- +- setUp() { +- super.setUp(); +- sourcePath =3D provider.convertPath('/p/lib/source.dart'); +- } +- +- test_adjacentLinesExcluded() async { +- String content =3D """ +-void myMethod() { +- return /*1*/new Thing(1, +- 2)/*1:Thing*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- /// When constructors span many like this, the node's start position is= on the first line +- /// of the expression and not where the opening paren is, so this test = ensures we +- /// don't end up with lots of unwanted labels on each line here. +- test_chainedConstructorOverManyLines() async { +- String content =3D """ +-main() { +- return new thing +- .whatIsSplit +- .acrossManyLines(1, 2); +-} +- """; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 0); +- } +- +- /// When chaining methods like this, the node's start position is on th= e first line +- /// of the expression and not where the opening paren is, so this test = ensures we +- /// don't end up with lots of unwanted labels on each line here. +- test_chainedMethodsOverManyLines() async { +- String content =3D """ +-List compute() { +- _unit.accept(new _DartUnitClosingLabelsComputerVisitor(this)); +- return _closingLabelsByEndLine.values +- .where((l) =3D> l.any((cl) =3D> cl.spannedLines >=3D 2)) +- .expand((cls) =3D> cls) +- .map((clwlc) =3D> clwlc.label) +- .toList(); +-} +- """; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 0); +- } +- +- test_constConstructor() async { +- String content =3D """ +-void myMethod() { +- return /*1*/const Class( +- 1, +- 2 +- )/*1:Class*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_constNamedConstructor() async { +- String content =3D """ +-void myMethod() { +- return /*1*/const Class.fromThing( +- 1, +- 2 +- )/*1:Class.fromThing*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_knownBadCode1() async { +- // This code crashed during testing when I accidentally inserted a te= st snippet. +- String content =3D """ +-@override +-Widget build(BuildContext context) { +- new SliverGrid( +- gridDelegate: gridDelegate, +- delegate: myMethod([ +- "a", +- 'b', +- "c", +- ]), +- ), +- ), +- ], +- ), +- ); +-} +-"""; +- +- // TODO(dantup) Results here are currently bad so this test is just c= hecking +- // that we don't crash. Need to confirm what to do here; the bad labe= ls +- // might not be fixed until the code is using the new shared parser. +- // https://github.com/dart-lang/sdk/issues/30370 +- await _computeElements(content); +- } +- +- test_listLiterals() async { +- String content =3D """ +-void myMethod() { +- return Widget.createWidget(/*1*/[ +- 1, +- 2 +- ]/*1:[]*/); +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- /// When a line contains the end of a label, we need to ensure we also = include any +- /// other labels that end on the same line, even if they are 1-2 lines,= otherwise +- /// it isn't obvious which closing bracket goes with the label. +- test_mixedLineSpanning() async { +- String content =3D """ +-main() { +- /*1*/new Foo((m) { +- /*2*/new Bar( +- labels, +- /*3*/new Padding( +- new ClosingLabel(expectedStart, expectedLength, expectedLab= el))/*3:Padding*/)/*2:Bar*/; +- })/*1:Foo*/; +- } +-} +- """; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 3); +- } +- +- test_multipleNested() async { +- String content =3D """ +-Widget build(BuildContext context) { +- return /*1*/new Row( +- children: /*2*/[ +- /*3*/new RaisedButton( +- onPressed: increment, +- child: /*4*/new Text( +- 'Increment' +- )/*4:Text*/, +- )/*3:RaisedButton*/, +- _makeWidget( +- 'a', +- 'b' +- ), +- new Text('Count: \$counter'), +- ]/*2:[]*/, +- )/*1:Row*/; +-} +-"""; +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 4); +- } +- +- test_newConstructor() async { +- String content =3D """ +-void myMethod() { +- return /*1*/new Class( +- 1, +- 2 +- )/*1:Class*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_newNamedConstructor() async { +- String content =3D """ +-void myMethod() { +- return /*1*/new Class.fromThing( +- 1, +- 2 +- )/*1:Class.fromThing*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_NoLabelsFromInterpolatedStrings() async { +- String content =3D """ +-void main(HighlightRegionType type, int offset, int length) { +- /*1*/new Fail( +- 'Not expected to find (offset=3D\$offset; length=3D\$length; type= =3D\$type) in\\n' +- '\${regions.join('\\n')}')/*1:Fail*/; +-} +- """; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_prefixedConstConstructor() async { +- String content =3D """ +-import 'dart:async' as a; +-void myMethod() { +- return /*1*/const a.Future( +- 1, +- 2 +- )/*1:a.Future*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_prefixedConstNamedConstructor() async { +- String content =3D """ +-import 'dart:async' as a; +-void myMethod() { +- return /*1*/const a.Future.delayed( +- 1, +- 2 +- )/*1:a.Future.delayed*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_prefixedNewConstructor() async { +- String content =3D """ +-import 'dart:async' as a; +-void myMethod() { +- return /*1*/new a.Future( +- 1, +- 2 +- )/*1:a.Future*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_prefixedNewNamedConstructor() async { +- String content =3D """ +-import 'dart:async' as a; +-void myMethod() { +- return /*1*/new a.Future.delayed( +- 1, +- 2 +- )/*1:a.Future.delayed*/; +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 1); +- } +- +- test_sameLineExcluded() async { +- String content =3D """ +-void myMethod() { +- return new Thing(); +-} +-"""; +- +- var labels =3D await _computeElements(content); +- _compareLabels(labels, content, expectedLabelCount: 0); +- } +- +- /// Compares provided closing labels with expected +- /// labels extracted from the comments in the provided content. +- _compareLabels(List labels, String content, +- {int expectedLabelCount}) { +- // Require the test pass us the expected count to guard +- // against expected annotations being mistyped and not +- // extracted by the regex. +- expect(labels, hasLength(expectedLabelCount)); +- +- // Find all numeric markers for label starts. +- var regex =3D new RegExp("/\\*(\\d+)\\*/"); +- var expectedLabels =3D regex.allMatches(content); +- +- // Check we didn't get more than expected, since the loop below only +- // checks for the presence of matches, not absence. +- expect(labels, hasLength(expectedLabels.length)); +- +- // Go through each marker, find the expected label/end and +- // ensure it's in the results. +- expectedLabels.forEach((m) { +- var i =3D m.group(1); +- // Find the end marker. +- var endMatch =3D new RegExp("/\\*$i:(.+?)\\*/").firstMatch(content); +- +- var expectedStart =3D m.end; +- var expectedLength =3D endMatch.start - expectedStart; +- var expectedLabel =3D endMatch.group(1); +- +- expect( +- labels, +- contains( +- new ClosingLabel(expectedStart, expectedLength, expectedLab= el))); +- }); +- } +- +- Future> _computeElements(String sourceContent) async= { +- provider.newFile(sourcePath, sourceContent); +- ResolveResult result =3D await driver.getResult(sourcePath); +- DartUnitClosingLabelsComputer computer =3D +- new DartUnitClosingLabelsComputer(result.lineInfo, result.unit); +- return computer.compute(); +- } +-} +diff --git a/pkg/analysis_server/test/src/computer/import_elements_compute= r_test.dart b/pkg/analysis_server/test/src/computer/import_elements_compute= r_test.dart +deleted file mode 100644 +index 63d54320ca9..00000000000 +--- a/pkg/analysis_server/test/src/computer/import_elements_computer_test.= dart ++++ /dev/null +@@ -1,343 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/computer/import_elements_computer.dar= t'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:front_end/src/base/source.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_context.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ImportElementsComputerTest); +- }); +-} +- +-@reflectiveTest +-class ImportElementsComputerTest extends AbstractContextTest { +- String path; +- String originalContent; +- ImportElementsComputer computer; +- SourceFileEdit sourceFileEdit; +- +- void assertChanges(String expectedContent) { +- String resultCode =3D +- SourceEdit.applySequence(originalContent, sourceFileEdit.edits); +- expect(resultCode, expectedContent); +- } +- +- void assertNoChanges() { +- expect(sourceFileEdit.edits, isEmpty); +- } +- +- Future computeChanges(List importedElements) as= ync { +- SourceChange change =3D await computer.createEdits(importedElements); +- expect(change, isNotNull); +- List edits =3D change.edits; +- expect(edits, hasLength(1)); +- sourceFileEdit =3D edits[0]; +- expect(sourceFileEdit, isNotNull); +- } +- +- Future createBuilder(String content) async { +- originalContent =3D content; +- provider.newFile(path, content); +- AnalysisResult result =3D await driver.getResult(path); +- computer =3D new ImportElementsComputer(provider, result); +- } +- +- void setUp() { +- super.setUp(); +- path =3D provider.convertPath('/test.dart'); +- } +- +- test_createEdits_addImport_noDirectives() async { +- await createBuilder(''' +-main() { +- // paste here +-} +-'''); +- await computeChanges([ +- new ImportedElements('/lib/math/math.dart', '', ['Random']) +- ]); +- assertChanges(''' +-import 'dart:math'; +- +-main() { +- // paste here +-} +-'''); +- } +- +- test_createEdits_addImport_noPrefix() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' as foo; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' as foo; +-import 'package:pkg/foo.dart'; +-'''); +- } +- +- test_createEdits_addImport_prefix() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart'; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, 'foo', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart'; +-import 'package:pkg/foo.dart' as foo; +-'''); +- } +- +- test_createEdits_addShow_multipleNames() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' show B; +-import 'package:pkg/foo.dart' as foo; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A', 'C']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' show B, A, C; +-import 'package:pkg/foo.dart' as foo; +-'''); +- } +- +- test_createEdits_addShow_removeHide() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' show A, B hide C, D; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['C']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' show A, B, C hide D; +-'''); +- } +- +- test_createEdits_addShow_singleName_noPrefix() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' show B; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' show B, A; +-'''); +- } +- +- test_createEdits_addShow_singleName_prefix() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' show C; +-import 'package:pkg/foo.dart' as foo show B; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, 'foo', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' show C; +-import 'package:pkg/foo.dart' as foo show B, A; +-'''); +- } +- +- test_createEdits_alreadyImported_noCombinators() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart'; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A', 'B']) +- ]); +- assertNoChanges(); +- } +- +- test_createEdits_alreadyImported_withPrefix() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' as foo; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, 'foo', ['A', 'B']) +- ]); +- assertNoChanges(); +- } +- +- test_createEdits_alreadyImported_withShow() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' show A; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A']) +- ]); +- assertNoChanges(); +- } +- +- test_createEdits_importSelf() async { +- await createBuilder(''' +-class A { +- A parent; +-} +-'''); +- await computeChanges([ +- new ImportedElements(path, '', ['A']) +- ]); +- assertNoChanges(); +- } +- +- test_createEdits_noElements() async { +- await createBuilder(''); +- await computeChanges([]); +- assertNoChanges(); +- } +- +- test_createEdits_removeHide_firstInCombinator() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A, B, C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide B, C; +-'''); +- } +- +- test_createEdits_removeHide_lastInCombinator() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A, B, C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['C']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide A, B; +-'''); +- } +- +- test_createEdits_removeHide_middleInCombinator() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A, B, C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['B']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide A, C; +-'''); +- } +- +- test_createEdits_removeHide_multipleCombinators() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A, B, C hide A, B, C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['B']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide A, C hide A, C; +-'''); +- } +- +- test_createEdits_removeHide_multipleNames() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A, B, C hide D, E, F hide G, H, I; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A', 'E', 'I'= ]) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide B, C hide D, F hide G, H; +-'''); +- } +- +- test_createEdits_removeHideCombinator_first() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A hide B hide C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide B hide C; +-'''); +- } +- +- test_createEdits_removeHideCombinator_last() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A hide B hide C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['C']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide A hide B; +-'''); +- } +- +- test_createEdits_removeHideCombinator_middle() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A hide B hide C; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['B']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart' hide A hide C; +-'''); +- } +- +- test_createEdits_removeHideCombinator_only() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart'; +-'''); +- } +- +- test_createEdits_removeHideCombinator_only_multiple() async { +- Source fooSource =3D addPackageSource('pkg', 'foo.dart', ''); +- await createBuilder(''' +-import 'package:pkg/foo.dart' hide A, B; +-'''); +- await computeChanges([ +- new ImportedElements(fooSource.fullName, '', ['A', 'B']) +- ]); +- assertChanges(''' +-import 'package:pkg/foo.dart'; +-'''); +- } +-} +diff --git a/pkg/analysis_server/test/src/computer/imported_elements_compu= ter_test.dart b/pkg/analysis_server/test/src/computer/imported_elements_com= puter_test.dart +deleted file mode 100644 +index adcf5f1c35f..00000000000 +--- a/pkg/analysis_server/test/src/computer/imported_elements_computer_tes= t.dart ++++ /dev/null +@@ -1,400 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/computer/imported_elements_computer.d= art'; +-import 'package:analyzer/dart/analysis/results.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_context.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ImportElementsComputerTest); +- }); +-} +- +-@reflectiveTest +-class ImportElementsComputerTest extends AbstractContextTest { +- String sourcePath; +- +- setUp() { +- super.setUp(); +- sourcePath =3D provider.convertPath('/p/lib/source.dart'); +- } +- +- test_dartAsync_noPrefix() async { +- String selection =3D "Future f =3D null;"; +- String content =3D """ +-import 'dart:async'; +-printer() { +- $selection +- print(await f); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(2)); +- ImportedElements elements1 =3D elementsList[0]; +- ImportedElements elements2 =3D elementsList[1]; +- ImportedElements asyncElements; +- ImportedElements coreElements; +- if (elements1.path =3D=3D '/lib/core/core.dart') { +- coreElements =3D elements1; +- asyncElements =3D elements2; +- } else { +- coreElements =3D elements2; +- asyncElements =3D elements1; +- } +- expect(coreElements, isNotNull); +- expect(coreElements.path, '/lib/core/core.dart'); +- expect(coreElements.prefix, ''); +- expect(coreElements.elements, unorderedEquals(['String'])); +- +- expect(asyncElements, isNotNull); +- expect(asyncElements.path, '/lib/async/async.dart'); +- expect(asyncElements.prefix, ''); +- expect(asyncElements.elements, unorderedEquals(['Future'])); +- } +- +- test_dartAsync_prefix() async { +- String selection =3D "a.Future f =3D null;"; +- String content =3D """ +-import 'dart:async' as a; +-printer() { +- $selection +- print(await f); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(2)); +- ImportedElements elements1 =3D elementsList[0]; +- ImportedElements elements2 =3D elementsList[1]; +- ImportedElements asyncElements; +- ImportedElements coreElements; +- if (elements1.path =3D=3D '/lib/core/core.dart') { +- coreElements =3D elements1; +- asyncElements =3D elements2; +- } else { +- coreElements =3D elements2; +- asyncElements =3D elements1; +- } +- expect(coreElements, isNotNull); +- expect(coreElements.path, '/lib/core/core.dart'); +- expect(coreElements.prefix, ''); +- expect(coreElements.elements, unorderedEquals(['String'])); +- +- expect(asyncElements, isNotNull); +- expect(asyncElements.path, '/lib/async/async.dart'); +- expect(asyncElements.prefix, 'a'); +- expect(asyncElements.elements, unorderedEquals(['Future'])); +- } +- +- test_dartCore_noPrefix() async { +- String selection =3D "String s =3D '';"; +- String content =3D """ +-blankLine() { +- $selection +- print(s); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/lib/core/core.dart'); +- expect(elements.prefix, ''); +- expect(elements.elements, unorderedEquals(['String'])); +- } +- +- test_dartCore_prefix() async { +- String selection =3D "core.String s =3D '';"; +- String content =3D """ +-import 'dart:core' as core; +-blankLine() { +- $selection +- print(s); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/lib/core/core.dart'); +- expect(elements.prefix, 'core'); +- expect(elements.elements, unorderedEquals(['String'])); +- } +- +- test_dartMath_noPrefix() async { +- String selection =3D "new Random();"; +- String content =3D """ +-import 'dart:math'; +-bool randomBool() { +- Random r =3D $selection +- return r.nextBool(); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/lib/math/math.dart'); +- expect(elements.prefix, ''); +- expect(elements.elements, unorderedEquals(['Random'])); +- } +- +- test_multiple() async { +- String selection =3D r''' +-main() { +- Random r =3D new Random(); +- String s =3D r.nextBool().toString(); +- print(s); +-} +-'''; +- String content =3D ''' +-import 'dart:math'; +- +-$selection +-'''; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(2)); +- +- ImportedElements mathElements =3D elementsList[0]; +- expect(mathElements, isNotNull); +- expect(mathElements.path, '/lib/math/math.dart'); +- expect(mathElements.prefix, ''); +- expect(mathElements.elements, unorderedEquals(['Random'])); +- +- ImportedElements coreElements =3D elementsList[1]; +- expect(coreElements, isNotNull); +- expect(coreElements.path, '/lib/core/core.dart'); +- expect(coreElements.prefix, ''); +- expect(coreElements.elements, unorderedEquals(['String', 'print'])); +- } +- +- test_none_comment() async { +- String selection =3D 'comment'; +- String content =3D """ +-// Method $selection. +-blankLine() { +- print(''); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(0)); +- } +- +- test_none_constructorDeclarationReturnType() async { +- String selection =3D r''' +-class A { +- A(); +- A.named(); +-} +-'''; +- String content =3D """ +-$selection +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(0)); +- } +- +- test_none_partialNames() async { +- String selection =3D 'x + y'; +- String content =3D """ +-plusThree(int xx) { +- int yy =3D 2; +- print(x${selection}y); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(0)); +- } +- +- test_none_wholeNames() async { +- String selection =3D 'x + y + 1'; +- String content =3D """ +-plusThree(int x) { +- int y =3D 2; +- print($selection); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(0)); +- } +- +- test_package_multipleInSame() async { +- addPackageSource('foo', 'foo.dart', ''' +-class A { +- static String a =3D ''; +-} +-class B { +- static String b =3D ''; +-} +-'''); +- String selection =3D "A.a + B.b"; +- String content =3D """ +-import 'package:foo/foo.dart'; +-blankLine() { +- print($selection); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/pubcache/foo/lib/foo.dart'); +- expect(elements.prefix, ''); +- expect(elements.elements, unorderedEquals(['A', 'B'])); +- } +- +- test_package_noPrefix() async { +- addPackageSource('foo', 'foo.dart', ''' +-class Foo { +- static String first =3D ''; +-} +-'''); +- String selection =3D "Foo.first"; +- String content =3D """ +-import 'package:foo/foo.dart'; +-blankLine() { +- print($selection); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/pubcache/foo/lib/foo.dart'); +- expect(elements.prefix, ''); +- expect(elements.elements, unorderedEquals(['Foo'])); +- } +- +- test_package_prefix_selected() async { +- addPackageSource('foo', 'foo.dart', ''' +-class Foo { +- static String first =3D ''; +-} +-'''); +- String selection =3D "f.Foo.first"; +- String content =3D """ +-import 'package:foo/foo.dart' as f; +-blankLine() { +- print($selection); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/pubcache/foo/lib/foo.dart'); +- expect(elements.prefix, 'f'); +- expect(elements.elements, unorderedEquals(['Foo'])); +- } +- +- test_package_prefix_unselected() async { +- addPackageSource('foo', 'foo.dart', ''' +-class Foo { +- static String first =3D ''; +-} +-'''); +- String selection =3D "Foo.first"; +- String content =3D """ +-import 'package:foo/foo.dart' as f; +-blankLine() { +- print(f.$selection); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, '/pubcache/foo/lib/foo.dart'); +- expect(elements.prefix, ''); +- expect(elements.elements, unorderedEquals(['Foo'])); +- } +- +- test_package_prefixedAndNot() async { +- addPackageSource('foo', 'foo.dart', ''' +-class Foo { +- static String first =3D ''; +- static String second =3D ''; +-} +-'''); +- String selection =3D "f.Foo.first + Foo.second"; +- String content =3D """ +-import 'package:foo/foo.dart'; +-import 'package:foo/foo.dart' as f; +-blankLine() { +- print($selection); +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- +- expect(elementsList, hasLength(2)); +- ImportedElements elements1 =3D elementsList[0]; +- ImportedElements elements2 =3D elementsList[1]; +- ImportedElements notPrefixedElements; +- ImportedElements prefixedElements; +- if (elements1.prefix =3D=3D '') { +- prefixedElements =3D elements2; +- notPrefixedElements =3D elements1; +- } else { +- prefixedElements =3D elements1; +- notPrefixedElements =3D elements2; +- } +- +- expect(notPrefixedElements, isNotNull); +- expect(notPrefixedElements.path, '/pubcache/foo/lib/foo.dart'); +- expect(notPrefixedElements.prefix, ''); +- expect(notPrefixedElements.elements, unorderedEquals(['Foo'])); +- +- expect(prefixedElements, isNotNull); +- expect(prefixedElements.path, '/pubcache/foo/lib/foo.dart'); +- expect(prefixedElements.prefix, 'f'); +- expect(prefixedElements.elements, unorderedEquals(['Foo'])); +- } +- +- test_self() async { +- String selection =3D 'A parent;'; +- String content =3D """ +-class A { +- $selection +-} +-"""; +- List elementsList =3D await _computeElements( +- content, content.indexOf(selection), selection.length); +- expect(elementsList, hasLength(1)); +- ImportedElements elements =3D elementsList[0]; +- expect(elements, isNotNull); +- expect(elements.path, sourcePath); +- expect(elements.prefix, ''); +- expect(elements.elements, unorderedEquals(['A'])); +- } +- +- Future> _computeElements( +- String sourceContent, int offset, int length) async { +- provider.newFile(sourcePath, sourceContent); +- ResolveResult result =3D await driver.getResult(sourcePath); +- ImportedElementsComputer computer =3D +- new ImportedElementsComputer(result.unit, offset, length); +- return computer.compute(); +- } +-} +diff --git a/pkg/analysis_server/test/src/computer/outline_computer_test.d= art b/pkg/analysis_server/test/src/computer/outline_computer_test.dart +deleted file mode 100644 +index 2b887045275..00000000000 +--- a/pkg/analysis_server/test/src/computer/outline_computer_test.dart ++++ /dev/null +@@ -1,1022 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/computer/computer_outline.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:meta/meta.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_context.dart'; +-import '../utilities/flutter_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FlutterOutlineComputerTest); +- defineReflectiveTests(OutlineComputerTest); +- }); +-} +- +-class AbstractOutlineComputerTest extends AbstractContextTest { +- String testPath; +- String testCode; +- +- @override +- void setUp() { +- super.setUp(); +- testPath =3D provider.convertPath('/test.dart'); +- } +- +- Future _computeOutline(String code) async { +- testCode =3D code; +- provider.newFile(testPath, code); +- AnalysisResult analysisResult =3D await driver.getResult(testPath); +- return new DartUnitOutlineComputer( +- testPath, analysisResult.lineInfo, analysisResult.unit) +- .compute(); +- } +-} +- +-@reflectiveTest +-class FlutterOutlineComputerTest extends AbstractOutlineComputerTest { +- @override +- void setUp() { +- super.setUp(); +- Folder libFolder =3D configureFlutterPackage(provider); +- packageMap['flutter'] =3D [libFolder]; +- } +- +- test_columnWithChildren() async { +- Outline unitOutline =3D await _computeOutline(''' +-import 'package:flutter/widgets.dart'; +- +-class MyWidget extends StatelessWidget { +- @override +- Widget build(BuildContext context) { +- return new Column(children: [ +- const Text('aaa'), +- const Text('bbb'), +- ]); // Column +- } +-} +-'''); +- expect(_toText(unitOutline), r''' +-MyWidget +- build +- Column +- Text('aaa') +- Text('bbb') +-'''); +- var myWidget =3D unitOutline.children[0]; +- var build =3D myWidget.children[0]; +- +- var columnOutline =3D build.children[0]; +- { +- int offset =3D testCode.indexOf('new Column'); +- int length =3D testCode.indexOf('; // Column') - offset; +- _expect(columnOutline, +- name: 'Column', +- elementOffset: offset, +- offset: offset, +- length: length); +- } +- +- { +- var textOutline =3D columnOutline.children[0]; +- String text =3D "const Text('aaa')"; +- int offset =3D testCode.indexOf(text); +- _expect(textOutline, +- name: "Text('aaa')", +- elementOffset: offset, +- offset: offset, +- length: text.length); +- } +- +- { +- var textOutline =3D columnOutline.children[1]; +- String text =3D "const Text('bbb')"; +- int offset =3D testCode.indexOf(text); +- _expect(textOutline, +- name: "Text('bbb')", +- elementOffset: offset, +- offset: offset, +- length: text.length); +- } +- } +- +- void _expect(Outline outline, +- {@required String name, +- @required int elementOffset, +- @required int offset, +- @required int length}) { +- Element element =3D outline.element; +- expect(element.name, name); +- expect(element.location.offset, elementOffset); +- expect(outline.offset, offset); +- expect(outline.length, length); +- } +- +- static String _toText(Outline outline) { +- var buffer =3D new StringBuffer(); +- +- void writeOutline(Outline outline, String indent) { +- buffer.write(indent); +- buffer.writeln(outline.element.name); +- for (var child in outline.children ?? const []) { +- writeOutline(child, '$indent '); +- } +- } +- +- for (var child in outline.children) { +- writeOutline(child, ''); +- } +- return buffer.toString(); +- } +-} +- +-@reflectiveTest +-class OutlineComputerTest extends AbstractOutlineComputerTest { +- test_class() async { +- Outline unitOutline =3D await _computeOutline(''' +-class A { +- int fa, fb; +- String fc; +- A(int i, String s); +- A.name(num p); +- A._privateName(num p); +- static String ma(int pa) =3D> null; +- _mb(int pb); +- String get propA =3D> null; +- set propB(int v) {} +-} +-class B { +- B(int p); +-}"); +-'''); +- List topOutlines =3D unitOutline.children; +- expect(topOutlines, hasLength(2)); +- // A +- { +- Outline outline_A =3D topOutlines[0]; +- Element element_A =3D outline_A.element; +- expect(element_A.kind, ElementKind.CLASS); +- expect(element_A.name, "A"); +- expect(element_A.typeParameters, ""); +- { +- Location location =3D element_A.location; +- expect(location.offset, testCode.indexOf("A {")); +- expect(location.length, 1); +- } +- expect(element_A.parameters, null); +- expect(element_A.returnType, null); +- // A children +- List outlines_A =3D outline_A.children; +- expect(outlines_A, hasLength(10)); +- { +- Outline outline =3D outlines_A[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fa"); +- expect(element.parameters, isNull); +- expect(element.returnType, "int"); +- } +- { +- Outline outline =3D outlines_A[1]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fb"); +- expect(element.parameters, isNull); +- expect(element.returnType, "int"); +- } +- { +- Outline outline =3D outlines_A[2]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fc"); +- expect(element.parameters, isNull); +- expect(element.returnType, "String"); +- } +- { +- Outline outline =3D outlines_A[3]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CONSTRUCTOR); +- expect(element.name, "A"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("A(int i, String s);")= ); +- expect(location.length, "A".length); +- } +- expect(element.parameters, "(int i, String s)"); +- expect(element.returnType, isNull); +- expect(element.isAbstract, isFalse); +- expect(element.isStatic, isFalse); +- } +- { +- Outline outline =3D outlines_A[4]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CONSTRUCTOR); +- expect(element.name, "A.name"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("name(num p);")); +- expect(location.length, "name".length); +- } +- expect(element.parameters, "(num p)"); +- expect(element.returnType, isNull); +- expect(element.isAbstract, isFalse); +- expect(element.isStatic, isFalse); +- } +- { +- Outline outline =3D outlines_A[5]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CONSTRUCTOR); +- expect(element.name, "A._privateName"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("_privateName(num p);"= )); +- expect(location.length, "_privateName".length); +- } +- expect(element.parameters, "(num p)"); +- expect(element.returnType, isNull); +- expect(element.isAbstract, isFalse); +- expect(element.isStatic, isFalse); +- } +- { +- Outline outline =3D outlines_A[6]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.METHOD); +- expect(element.name, "ma"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("ma(int pa) =3D> null;= ")); +- expect(location.length, "ma".length); +- } +- expect(element.parameters, "(int pa)"); +- expect(element.returnType, "String"); +- expect(element.isAbstract, isFalse); +- expect(element.isStatic, isTrue); +- } +- { +- Outline outline =3D outlines_A[7]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.METHOD); +- expect(element.name, "_mb"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("_mb(int pb);")); +- expect(location.length, "_mb".length); +- } +- expect(element.parameters, "(int pb)"); +- expect(element.returnType, ""); +- expect(element.isAbstract, isTrue); +- expect(element.isStatic, isFalse); +- } +- { +- Outline outline =3D outlines_A[8]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.GETTER); +- expect(element.name, "propA"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("propA =3D> null;")); +- expect(location.length, "propA".length); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, "String"); +- } +- { +- Outline outline =3D outlines_A[9]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.SETTER); +- expect(element.name, "propB"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("propB(int v) {}")); +- expect(location.length, "propB".length); +- } +- expect(element.parameters, "(int v)"); +- expect(element.returnType, ""); +- } +- } +- // B +- { +- Outline outline_B =3D topOutlines[1]; +- Element element_B =3D outline_B.element; +- expect(element_B.kind, ElementKind.CLASS); +- expect(element_B.name, "B"); +- expect(element_B.typeParameters, isNull); +- { +- Location location =3D element_B.location; +- expect(location.offset, testCode.indexOf("B {")); +- expect(location.length, 1); +- } +- expect(element_B.parameters, null); +- expect(element_B.returnType, null); +- // B children +- List outlines_B =3D outline_B.children; +- expect(outlines_B, hasLength(1)); +- { +- Outline outline =3D outlines_B[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CONSTRUCTOR); +- expect(element.name, "B"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("B(int p);")); +- expect(location.length, "B".length); +- } +- expect(element.parameters, "(int p)"); +- expect(element.returnType, isNull); +- } +- } +- } +- +- test_enum() async { +- Outline unitOutline =3D await _computeOutline(''' +-enum MyEnum { +- A, B, C +-} +-'''); +- List topOutlines =3D unitOutline.children; +- expect(topOutlines, hasLength(1)); +- // MyEnum +- { +- Outline outline_MyEnum =3D topOutlines[0]; +- Element element_MyEnum =3D outline_MyEnum.element; +- expect(element_MyEnum.kind, ElementKind.ENUM); +- expect(element_MyEnum.name, "MyEnum"); +- { +- Location location =3D element_MyEnum.location; +- expect(location.offset, testCode.indexOf("MyEnum {")); +- expect(location.length, 'MyEnum'.length); +- } +- expect(element_MyEnum.parameters, null); +- expect(element_MyEnum.returnType, null); +- // MyEnum children +- List outlines_MyEnum =3D outline_MyEnum.children; +- expect(outlines_MyEnum, hasLength(3)); +- _isEnumConstant(outlines_MyEnum[0], 'A'); +- _isEnumConstant(outlines_MyEnum[1], 'B'); +- _isEnumConstant(outlines_MyEnum[2], 'C'); +- } +- } +- +- test_groupAndTest() async { +- Outline outline =3D await _computeOutline(''' +-void group(name, closure) {} +-void test(name) {} +-void main() { +- group('group1', () { +- group('group1_1', () { +- test('test1_1_1'); +- test('test1_1_2'); +- }); +- group('group1_2', () { +- test('test1_2_1'); +- }); +- }); +- group('group2', () { +- test('test2_1'); +- test('test2_2'); +- }); +-} +-'''); +- // unit +- List unit_children =3D outline.children; +- expect(unit_children, hasLength(3)); +- // main +- Outline main_outline =3D unit_children[2]; +- _expect(main_outline, +- kind: ElementKind.FUNCTION, +- name: 'main', +- offset: testCode.indexOf("main() {"), +- parameters: '()', +- returnType: 'void'); +- List main_children =3D main_outline.children; +- expect(main_children, hasLength(2)); +- // group1 +- Outline group1_outline =3D main_children[0]; +- _expect(group1_outline, +- kind: ElementKind.UNIT_TEST_GROUP, +- length: 5, +- name: 'group("group1")', +- offset: testCode.indexOf("group('group1'")); +- List group1_children =3D group1_outline.children; +- expect(group1_children, hasLength(2)); +- // group1_1 +- Outline group1_1_outline =3D group1_children[0]; +- _expect(group1_1_outline, +- kind: ElementKind.UNIT_TEST_GROUP, +- length: 5, +- name: 'group("group1_1")', +- offset: testCode.indexOf("group('group1_1'")); +- List group1_1_children =3D group1_1_outline.children; +- expect(group1_1_children, hasLength(2)); +- // test1_1_1 +- Outline test1_1_1_outline =3D group1_1_children[0]; +- _expect(test1_1_1_outline, +- kind: ElementKind.UNIT_TEST_TEST, +- leaf: true, +- length: 4, +- name: 'test("test1_1_1")', +- offset: testCode.indexOf("test('test1_1_1'")); +- // test1_1_1 +- Outline test1_1_2_outline =3D group1_1_children[1]; +- _expect(test1_1_2_outline, +- kind: ElementKind.UNIT_TEST_TEST, +- leaf: true, +- length: 4, +- name: 'test("test1_1_2")', +- offset: testCode.indexOf("test('test1_1_2'")); +- // group1_2 +- Outline group1_2_outline =3D group1_children[1]; +- _expect(group1_2_outline, +- kind: ElementKind.UNIT_TEST_GROUP, +- length: 5, +- name: 'group("group1_2")', +- offset: testCode.indexOf("group('group1_2'")); +- List group1_2_children =3D group1_2_outline.children; +- expect(group1_2_children, hasLength(1)); +- // test2_1 +- Outline test1_2_1_outline =3D group1_2_children[0]; +- _expect(test1_2_1_outline, +- kind: ElementKind.UNIT_TEST_TEST, +- leaf: true, +- length: 4, +- name: 'test("test1_2_1")', +- offset: testCode.indexOf("test('test1_2_1'")); +- // group2 +- Outline group2_outline =3D main_children[1]; +- _expect(group2_outline, +- kind: ElementKind.UNIT_TEST_GROUP, +- length: 5, +- name: 'group("group2")', +- offset: testCode.indexOf("group('group2'")); +- List group2_children =3D group2_outline.children; +- expect(group2_children, hasLength(2)); +- // test2_1 +- Outline test2_1_outline =3D group2_children[0]; +- _expect(test2_1_outline, +- kind: ElementKind.UNIT_TEST_TEST, +- leaf: true, +- length: 4, +- name: 'test("test2_1")', +- offset: testCode.indexOf("test('test2_1'")); +- // test2_2 +- Outline test2_2_outline =3D group2_children[1]; +- _expect(test2_2_outline, +- kind: ElementKind.UNIT_TEST_TEST, +- leaf: true, +- length: 4, +- name: 'test("test2_2")', +- offset: testCode.indexOf("test('test2_2'")); +- } +- +- /** +- * Code like this caused NPE in the past. +- * +- * https://code.google.com/p/dart/issues/detail?id=3D21373 +- */ +- test_invalidGetterInConstructor() async { +- Outline outline =3D await _computeOutline(''' +-class A { +- A() { +- get badGetter { +- const int CONST =3D 0; +- } +- } +-} +-'''); +- expect(outline, isNotNull); +- } +- +- test_localFunctions() async { +- Outline unitOutline =3D await _computeOutline(''' +-class A { +- A() { +- int local_A() {} +- } +- m() { +- local_m() {} +- } +-} +-f() { +- local_f1(int i) {} +- local_f2(String s) { +- local_f21(int p) {} +- } +-} +-'''); +- List topOutlines =3D unitOutline.children; +- expect(topOutlines, hasLength(2)); +- // A +- { +- Outline outline_A =3D topOutlines[0]; +- Element element_A =3D outline_A.element; +- expect(element_A.kind, ElementKind.CLASS); +- expect(element_A.name, "A"); +- { +- Location location =3D element_A.location; +- expect(location.offset, testCode.indexOf("A {")); +- expect(location.length, "A".length); +- } +- expect(element_A.parameters, null); +- expect(element_A.returnType, null); +- // A children +- List outlines_A =3D outline_A.children; +- expect(outlines_A, hasLength(2)); +- { +- Outline constructorOutline =3D outlines_A[0]; +- Element constructorElement =3D constructorOutline.element; +- expect(constructorElement.kind, ElementKind.CONSTRUCTOR); +- expect(constructorElement.name, "A"); +- { +- Location location =3D constructorElement.location; +- expect(location.offset, testCode.indexOf("A() {")); +- expect(location.length, "A".length); +- } +- expect(constructorElement.parameters, "()"); +- expect(constructorElement.returnType, isNull); +- // local function +- List outlines_constructor =3D constructorOutline.childre= n; +- expect(outlines_constructor, hasLength(1)); +- { +- Outline outline =3D outlines_constructor[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FUNCTION); +- expect(element.name, "local_A"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("local_A() {}")); +- expect(location.length, "local_A".length); +- } +- expect(element.parameters, "()"); +- expect(element.returnType, "int"); +- } +- } +- { +- Outline outline_m =3D outlines_A[1]; +- Element element_m =3D outline_m.element; +- expect(element_m.kind, ElementKind.METHOD); +- expect(element_m.name, "m"); +- { +- Location location =3D element_m.location; +- expect(location.offset, testCode.indexOf("m() {")); +- expect(location.length, "m".length); +- } +- expect(element_m.parameters, "()"); +- expect(element_m.returnType, ""); +- // local function +- List methodChildren =3D outline_m.children; +- expect(methodChildren, hasLength(1)); +- { +- Outline outline =3D methodChildren[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FUNCTION); +- expect(element.name, "local_m"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("local_m() {}")); +- expect(location.length, "local_m".length); +- } +- expect(element.parameters, "()"); +- expect(element.returnType, ""); +- } +- } +- } +- // f() +- { +- Outline outline_f =3D topOutlines[1]; +- Element element_f =3D outline_f.element; +- expect(element_f.kind, ElementKind.FUNCTION); +- expect(element_f.name, "f"); +- { +- Location location =3D element_f.location; +- expect(location.offset, testCode.indexOf("f() {")); +- expect(location.length, "f".length); +- } +- expect(element_f.parameters, "()"); +- expect(element_f.returnType, ""); +- // f() children +- List outlines_f =3D outline_f.children; +- expect(outlines_f, hasLength(2)); +- { +- Outline outline_f1 =3D outlines_f[0]; +- Element element_f1 =3D outline_f1.element; +- expect(element_f1.kind, ElementKind.FUNCTION); +- expect(element_f1.name, "local_f1"); +- { +- Location location =3D element_f1.location; +- expect(location.offset, testCode.indexOf("local_f1(int i) {}")); +- expect(location.length, "local_f1".length); +- } +- expect(element_f1.parameters, "(int i)"); +- expect(element_f1.returnType, ""); +- } +- { +- Outline outline_f2 =3D outlines_f[1]; +- Element element_f2 =3D outline_f2.element; +- expect(element_f2.kind, ElementKind.FUNCTION); +- expect(element_f2.name, "local_f2"); +- { +- Location location =3D element_f2.location; +- expect(location.offset, testCode.indexOf("local_f2(String s) {"= )); +- expect(location.length, "local_f2".length); +- } +- expect(element_f2.parameters, "(String s)"); +- expect(element_f2.returnType, ""); +- // local_f2() local function +- List outlines_f2 =3D outline_f2.children; +- expect(outlines_f2, hasLength(1)); +- { +- Outline outline_f21 =3D outlines_f2[0]; +- Element element_f21 =3D outline_f21.element; +- expect(element_f21.kind, ElementKind.FUNCTION); +- expect(element_f21.name, "local_f21"); +- { +- Location location =3D element_f21.location; +- expect(location.offset, testCode.indexOf("local_f21(int p) {"= )); +- expect(location.length, "local_f21".length); +- } +- expect(element_f21.parameters, "(int p)"); +- expect(element_f21.returnType, ""); +- } +- } +- } +- } +- +- test_sourceRange_inClass() async { +- Outline unitOutline =3D await _computeOutline(''' +-class A { // leftA +- int methodA() {} // endA +- int methodB() {} // endB +-} +-'''); +- List outlines =3D unitOutline.children[0].children; +- expect(outlines, hasLength(2)); +- // methodA +- { +- Outline outline =3D outlines[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.METHOD); +- expect(element.name, "methodA"); +- { +- int offset =3D testCode.indexOf(" // leftA"); +- int end =3D testCode.indexOf(" // endA"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // methodB +- { +- Outline outline =3D outlines[1]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.METHOD); +- expect(element.name, "methodB"); +- { +- int offset =3D testCode.indexOf(" // endA"); +- int end =3D testCode.indexOf(" // endB"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- } +- +- test_sourceRange_inClass_inVariableList() async { +- Outline unitOutline =3D await _computeOutline(''' +-class A { // leftA +- int fieldA, fieldB, fieldC; // marker +- int fieldD; // marker2 +-} +-'''); +- List outlines =3D unitOutline.children[0].children; +- expect(outlines, hasLength(4)); +- // fieldA +- { +- Outline outline =3D outlines[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fieldA"); +- { +- int offset =3D testCode.indexOf(" // leftA"); +- int end =3D testCode.indexOf(", fieldB"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // fieldB +- { +- Outline outline =3D outlines[1]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fieldB"); +- { +- int offset =3D testCode.indexOf(", fieldB"); +- int end =3D testCode.indexOf(", fieldC"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // fieldC +- { +- Outline outline =3D outlines[2]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fieldC"); +- { +- int offset =3D testCode.indexOf(", fieldC"); +- int end =3D testCode.indexOf(" // marker"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // fieldD +- { +- Outline outline =3D outlines[3]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FIELD); +- expect(element.name, "fieldD"); +- { +- int offset =3D testCode.indexOf(" // marker"); +- int end =3D testCode.indexOf(" // marker2"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- } +- +- test_sourceRange_inUnit() async { +- Outline unitOutline =3D await _computeOutline(''' +-library lib; +-/// My first class. +-class A { +-} // endA +-class B { +-} // endB +-'''); +- List topOutlines =3D unitOutline.children; +- expect(topOutlines, hasLength(2)); +- // A +- { +- Outline outline =3D topOutlines[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CLASS); +- expect(element.name, "A"); +- { +- int offset =3D testCode.indexOf("/// My first class."); +- int end =3D testCode.indexOf(" // endA"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // B +- { +- Outline outline =3D topOutlines[1]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CLASS); +- expect(element.name, "B"); +- { +- int offset =3D testCode.indexOf(" // endA"); +- int end =3D testCode.indexOf(" // endB"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- } +- +- test_sourceRange_inUnit_inVariableList() async { +- Outline unitOutline =3D await _computeOutline(''' +-int fieldA, fieldB, fieldC; // marker +-int fieldD; // marker2 +-'''); +- List outlines =3D unitOutline.children; +- expect(outlines, hasLength(4)); +- // fieldA +- { +- Outline outline =3D outlines[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.TOP_LEVEL_VARIABLE); +- expect(element.name, "fieldA"); +- { +- int offset =3D 0; +- int end =3D testCode.indexOf(", fieldB"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // fieldB +- { +- Outline outline =3D outlines[1]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.TOP_LEVEL_VARIABLE); +- expect(element.name, "fieldB"); +- { +- int offset =3D testCode.indexOf(", fieldB"); +- int end =3D testCode.indexOf(", fieldC"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // fieldC +- { +- Outline outline =3D outlines[2]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.TOP_LEVEL_VARIABLE); +- expect(element.name, "fieldC"); +- { +- int offset =3D testCode.indexOf(", fieldC"); +- int end =3D testCode.indexOf(" // marker"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- // fieldD +- { +- Outline outline =3D outlines[3]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.TOP_LEVEL_VARIABLE); +- expect(element.name, "fieldD"); +- { +- int offset =3D testCode.indexOf(" // marker"); +- int end =3D testCode.indexOf(" // marker2"); +- expect(outline.offset, offset); +- expect(outline.length, end - offset); +- } +- } +- } +- +- test_topLevel() async { +- Outline unitOutline =3D await _computeOutline(''' +-typedef String FTA(int i, String s); +-typedef FTB(int p); +-class A {} +-class B {} +-class CTA =3D A with B; +-class CTB =3D A with B; +-String fA(int i, String s) =3D> null; +-fB(int p) =3D> null; +-String get propA =3D> null; +-set propB(int v) {} +-'''); +- List topOutlines =3D unitOutline.children; +- expect(topOutlines, hasLength(10)); +- // FTA +- { +- Outline outline =3D topOutlines[0]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FUNCTION_TYPE_ALIAS); +- expect(element.name, "FTA"); +- expect(element.typeParameters, ""); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("FTA(")); +- expect(location.length, "FTA".length); +- } +- expect(element.parameters, "(int i, String s)"); +- expect(element.returnType, "String"); +- } +- // FTB +- { +- Outline outline =3D topOutlines[1]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FUNCTION_TYPE_ALIAS); +- expect(element.name, "FTB"); +- expect(element.typeParameters, isNull); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("FTB(")); +- expect(location.length, "FTB".length); +- } +- expect(element.parameters, "(int p)"); +- expect(element.returnType, ""); +- } +- // CTA +- { +- Outline outline =3D topOutlines[4]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CLASS_TYPE_ALIAS); +- expect(element.name, "CTA"); +- expect(element.typeParameters, ''); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("CTA =3D")); +- expect(location.length, "CTA".length); +- } +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- } +- // CTB +- { +- Outline outline =3D topOutlines[5]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.CLASS_TYPE_ALIAS); +- expect(element.name, 'CTB'); +- expect(element.typeParameters, isNull); +- expect(element.returnType, isNull); +- } +- // fA +- { +- Outline outline =3D topOutlines[6]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FUNCTION); +- expect(element.name, "fA"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("fA(")); +- expect(location.length, "fA".length); +- } +- expect(element.parameters, "(int i, String s)"); +- expect(element.returnType, "String"); +- } +- // fB +- { +- Outline outline =3D topOutlines[7]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.FUNCTION); +- expect(element.name, "fB"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("fB(")); +- expect(location.length, "fB".length); +- } +- expect(element.parameters, "(int p)"); +- expect(element.returnType, ""); +- } +- // propA +- { +- Outline outline =3D topOutlines[8]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.GETTER); +- expect(element.name, "propA"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("propA =3D> null;")); +- expect(location.length, "propA".length); +- } +- expect(element.parameters, ""); +- expect(element.returnType, "String"); +- } +- // propB +- { +- Outline outline =3D topOutlines[9]; +- Element element =3D outline.element; +- expect(element.kind, ElementKind.SETTER); +- expect(element.name, "propB"); +- { +- Location location =3D element.location; +- expect(location.offset, testCode.indexOf("propB(int v) {}")); +- expect(location.length, "propB".length); +- } +- expect(element.parameters, "(int v)"); +- expect(element.returnType, ""); +- } +- } +- +- void _expect(Outline outline, +- {ElementKind kind, +- bool leaf: false, +- int length, +- String name, +- int offset, +- String parameters, +- String returnType}) { +- Element element =3D outline.element; +- Location location =3D element.location; +- +- if (kind !=3D null) { +- expect(element.kind, kind); +- } +- if (leaf) { +- expect(outline.children, isNull); +- } +- length ??=3D name?.length; +- if (length !=3D null) { +- expect(location.length, length); +- } +- if (name !=3D null) { +- expect(element.name, name); +- } +- if (offset !=3D null) { +- expect(location.offset, offset); +- } +- if (parameters !=3D null) { +- expect(element.parameters, parameters); +- } +- if (returnType !=3D null) { +- expect(element.returnType, returnType); +- } +- } +- +- void _isEnumConstant(Outline outline, String name) { +- Element element =3D outline.element; +- expect(element.kind, ElementKind.ENUM_CONSTANT); +- expect(element.name, name); +- expect(element.parameters, isNull); +- expect(element.returnType, isNull); +- } +-} +diff --git a/pkg/analysis_server/test/src/computer/test_all.dart b/pkg/ana= lysis_server/test/src/computer/test_all.dart +deleted file mode 100644 +index 4bf0a762dab..00000000000 +--- a/pkg/analysis_server/test/src/computer/test_all.dart ++++ /dev/null +@@ -1,20 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'closingLabels_computer_test.dart' as closingLabels_computer_test; +-import 'import_elements_computer_test.dart' as import_elements_computer_t= est; +-import 'imported_elements_computer_test.dart' +- as imported_elements_computer_test; +-import 'outline_computer_test.dart' as outline_computer_test; +- +-main() { +- defineReflectiveSuite(() { +- closingLabels_computer_test.main(); +- import_elements_computer_test.main(); +- imported_elements_computer_test.main(); +- outline_computer_test.main(); +- }); +-} +diff --git a/pkg/analysis_server/test/src/domain_abstract_test.dart b/pkg/= analysis_server/test/src/domain_abstract_test.dart +deleted file mode 100644 +index 6585efb1bb9..00000000000 +--- a/pkg/analysis_server/test/src/domain_abstract_test.dart ++++ /dev/null +@@ -1,105 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/domain_abstract.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/protocol_server.dart' hide Element; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../analysis_abstract.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(AbstractRequestHandlerTest); +- }); +-} +- +-@reflectiveTest +-class AbstractRequestHandlerTest extends AbstractAnalysisTest { +- test_waitForResponses_empty_noTimeout() async { +- AbstractRequestHandler handler =3D new TestAbstractRequestHandler(ser= ver); +- Map> futures =3D +- >{}; +- List responses =3D await handler.waitForResponses(fu= tures); +- expect(responses, isEmpty); +- } +- +- test_waitForResponses_empty_timeout() async { +- AbstractRequestHandler handler =3D new TestAbstractRequestHandler(ser= ver); +- Map> futures =3D +- >{}; +- List responses =3D +- await handler.waitForResponses(futures, timeout: 250); +- expect(responses, isEmpty); +- } +- +- test_waitForResponses_nonEmpty_noTimeout_immediate() async { +- AbstractRequestHandler handler =3D new TestAbstractRequestHandler(ser= ver); +- PluginInfo plugin1 =3D new DiscoveredPluginInfo('p1', '', '', null, n= ull); +- PluginInfo plugin2 =3D new DiscoveredPluginInfo('p2', '', '', null, n= ull); +- plugin.Response response1 =3D new plugin.Response('1', 1); +- plugin.Response response2 =3D new plugin.Response('2', 2); +- Map> futures =3D +- >{ +- plugin1: new Future.value(response1), +- plugin2: new Future.value(response2), +- }; +- List responses =3D await handler.waitForResponses(fu= tures); +- expect(responses, unorderedEquals([response1, response2])); +- } +- +- test_waitForResponses_nonEmpty_noTimeout_withError() async { +- AbstractRequestHandler handler =3D new TestAbstractRequestHandler(ser= ver); +- PluginInfo plugin1 =3D new DiscoveredPluginInfo('p1', '', '', null, n= ull); +- PluginInfo plugin2 =3D new DiscoveredPluginInfo('p2', '', '', null, n= ull); +- plugin.Response response1 =3D new plugin.Response('1', 1); +- plugin.Response response2 =3D new plugin.Response('2', 2, +- error: new plugin.RequestError( +- plugin.RequestErrorCode.PLUGIN_ERROR, 'message')); +- Map> futures =3D +- >{ +- plugin1: new Future.value(response1), +- plugin2: new Future.value(response2), +- }; +- List responses =3D await handler.waitForResponses(fu= tures); +- expect(responses, unorderedEquals([response1])); +- } +- +- test_waitForResponses_nonEmpty_timeout_someDelayed() async { +- AbstractRequestHandler handler =3D new TestAbstractRequestHandler(ser= ver); +- PluginInfo plugin1 =3D new DiscoveredPluginInfo('p1', '', '', null, n= ull); +- PluginInfo plugin2 =3D new DiscoveredPluginInfo('p2', '', '', null, n= ull); +- PluginInfo plugin3 =3D new DiscoveredPluginInfo('p3', '', '', null, n= ull); +- plugin.Response response1 =3D new plugin.Response('1', 1); +- plugin.Response response2 =3D new plugin.Response('2', 2); +- plugin.Response response3 =3D new plugin.Response('3', 3); +- Map> futures =3D +- >{ +- plugin1: +- new Future.delayed(new Duration(milliseconds: 500), () =3D> res= ponse1), +- plugin2: new Future.value(response2), +- plugin3: +- new Future.delayed(new Duration(milliseconds: 500), () =3D> res= ponse3) +- }; +- List responses =3D +- await handler.waitForResponses(futures, timeout: 50); +- expect(responses, unorderedEquals([response2])); +- } +-} +- +-class TestAbstractRequestHandler extends AbstractRequestHandler { +- TestAbstractRequestHandler(server) : super(server); +- +- @override +- Response handleRequest(Request request) { +- fail('Unexpected invocation of handleRequest'); +- return null; +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/notification_manager_test= .dart b/pkg/analysis_server/test/src/plugin/notification_manager_test.dart +deleted file mode 100644 +index 1b5dd99031c..00000000000 +--- a/pkg/analysis_server/test/src/plugin/notification_manager_test.dart ++++ /dev/null +@@ -1,511 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol.dart' as server; +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analysis_server/src/channel/channel.dart'; +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart' as plugin; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plug= in; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'protocol_test_utilities.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(NotificationManagerTest); +- }); +-} +- +-@reflectiveTest +-class NotificationManagerTest extends ProtocolTestUtilities { +- String testDir; +- String fileA; +- String fileB; +- +- TestChannel channel; +- +- NotificationManager manager; +- +- void setUp() { +- MemoryResourceProvider provider =3D new MemoryResourceProvider(); +- testDir =3D provider.convertPath('/test'); +- fileA =3D provider.convertPath('/test/a.dart'); +- fileB =3D provider.convertPath('/test/b.dart'); +- channel =3D new TestChannel(); +- manager =3D new NotificationManager(channel, provider); +- } +- +- void test_handlePluginNotification_errors() { +- manager.setAnalysisRoots([testDir], []); +- AnalysisError error1 =3D analysisError(0, 0, file: fileA); +- AnalysisError error2 =3D analysisError(3, 4, file: fileA); +- plugin.AnalysisErrorsParams params =3D +- new plugin.AnalysisErrorsParams(fileA, [error1, error2]); +- manager.handlePluginNotification('a', params.toNotification()); +- _verifyErrors(fileA, [error1, error2]); +- } +- +- void test_handlePluginNotification_folding() { +- manager.setSubscriptions({ +- server.AnalysisService.FOLDING: new Set.from([fileA, fileB]) +- }); +- FoldingRegion region1 =3D foldingRegion(10, 3); +- FoldingRegion region2 =3D foldingRegion(20, 6); +- plugin.AnalysisFoldingParams params =3D +- new plugin.AnalysisFoldingParams(fileA, [region1, region2]); +- manager.handlePluginNotification('a', params.toNotification()); +- _verifyFoldingRegions(fileA, [region1, region2]); +- } +- +- void test_handlePluginNotification_highlights() { +- manager.setSubscriptions({ +- server.AnalysisService.HIGHLIGHTS: new Set.from([fileA, fileB]) +- }); +- HighlightRegion region1 =3D highlightRegion(10, 3); +- HighlightRegion region2 =3D highlightRegion(20, 6); +- plugin.AnalysisHighlightsParams params =3D +- new plugin.AnalysisHighlightsParams(fileA, [region1, region2]); +- manager.handlePluginNotification('a', params.toNotification()); +- _verifyHighlightRegions(fileA, [region1, region2]); +- } +- +- void test_handlePluginNotification_naviation() { +- manager.setSubscriptions({ +- server.AnalysisService.NAVIGATION: new Set.from([fileA, fileB]) +- }); +- plugin.AnalysisNavigationParams pluginParams =3D +- pluginNavigationParams(0, 0, file: fileA); +- manager.handlePluginNotification('a', pluginParams.toNotification()); +- +- server.AnalysisNavigationParams serverParams =3D +- serverNavigationParams(0, 0, file: fileA); +- _verifyNavigationParams(serverParams); +- } +- +- void test_handlePluginNotification_occurences() { +- manager.setSubscriptions({ +- server.AnalysisService.OCCURRENCES: new Set.from([fileA, fileB]) +- }); +- Occurrences occurrences1 =3D occurrences(0, 0); +- Occurrences occurrences2 =3D occurrences(5, 7); +- plugin.AnalysisOccurrencesParams params =3D +- new plugin.AnalysisOccurrencesParams( +- fileA, [occurrences1, occurrences2]); +- +- manager.handlePluginNotification('a', params.toNotification()); +- _verifyOccurrences(fileA, [occurrences1, occurrences2]); +- } +- +- void test_handlePluginNotification_outline() { +- manager.setSubscriptions({ +- server.AnalysisService.OUTLINE: new Set.from([fileA, fileB]) +- }); +- Outline outline1 =3D outline(0, 0); +- plugin.AnalysisOutlineParams params =3D +- new plugin.AnalysisOutlineParams(fileA, [outline1]); +- manager.handlePluginNotification('a', params.toNotification()); +- +- _verifyOutlines(fileA, outline1); +- } +- +- void test_handlePluginNotification_pluginError() { +- bool isFatal =3D false; +- String message =3D 'message'; +- String stackTrace =3D 'stackTrace'; +- plugin.PluginErrorParams params =3D +- new plugin.PluginErrorParams(isFatal, message, stackTrace); +- manager.handlePluginNotification('a', params.toNotification()); +- _verifyPluginError(isFatal, message, stackTrace); +- } +- +- void test_recordAnalysisErrors_noSubscription() { +- AnalysisError error =3D analysisError(0, 0, file: fileA); +- manager.recordAnalysisErrors('a', fileA, [error]); +- expect(channel.sentNotification, isNull); +- } +- +- void test_recordAnalysisErrors_withSubscription() { +- manager.setAnalysisRoots([testDir], []); +- // +- // Errors should be reported when they are recorded. +- // +- AnalysisError error1 =3D analysisError(0, 0, file: fileA); +- AnalysisError error2 =3D analysisError(3, 4, file: fileA); +- manager.recordAnalysisErrors('a', fileA, [error1, error2]); +- _verifyErrors(fileA, [error1, error2]); +- // +- // Errors from different plugins should be cumulative. +- // +- AnalysisError error3 =3D analysisError(6, 8, file: fileA); +- manager.recordAnalysisErrors('b', fileA, [error3]); +- _verifyErrors(fileA, [error1, error2, error3]); +- // +- // Overwriting errors from one plugin should not affect errors from o= ther +- // plugins. +- // +- AnalysisError error4 =3D analysisError(9, 12, file: fileA); +- manager.recordAnalysisErrors('a', fileA, [error4]); +- _verifyErrors(fileA, [error4, error3]); +- // +- // Recording errors against a file should not affect the errors for o= ther +- // files. +- // +- AnalysisError error5 =3D analysisError(12, 16, file: fileB); +- manager.recordAnalysisErrors('a', fileB, [error5]); +- _verifyErrors(fileB, [error5]); +- } +- +- void test_recordFoldingRegions_noSubscription() { +- FoldingRegion region =3D foldingRegion(10, 5); +- manager.recordFoldingRegions('a', fileA, [region]); +- expect(channel.sentNotification, isNull); +- } +- +- void test_recordFoldingRegions_withSubscription() { +- manager.setSubscriptions({ +- server.AnalysisService.FOLDING: new Set.from([fileA, fileB]) +- }); +- // +- // Regions should be reported when they are recorded. +- // +- FoldingRegion region1 =3D foldingRegion(10, 3); +- FoldingRegion region2 =3D foldingRegion(20, 6); +- manager.recordFoldingRegions('a', fileA, [region1, region2]); +- _verifyFoldingRegions(fileA, [region1, region2]); +- // +- // Regions from different plugins should be cumulative. +- // +- FoldingRegion region3 =3D foldingRegion(30, 5); +- manager.recordFoldingRegions('b', fileA, [region3]); +- _verifyFoldingRegions(fileA, [region1, region2, region3]); +- // +- // Overwriting regions from one plugin should not affect regions from= other +- // plugins. +- // +- FoldingRegion region4 =3D foldingRegion(40, 2); +- manager.recordFoldingRegions('a', fileA, [region4]); +- _verifyFoldingRegions(fileA, [region4, region3]); +- // +- // Recording regions against a file should not affect the regions for= other +- // files. +- // +- FoldingRegion region5 =3D foldingRegion(50, 7); +- manager.recordFoldingRegions('a', fileB, [region5]); +- _verifyFoldingRegions(fileB, [region5]); +- } +- +- void test_recordHighlightRegions_noSubscription() { +- HighlightRegion region =3D highlightRegion(10, 5); +- manager.recordHighlightRegions('a', fileA, [region]); +- expect(channel.sentNotification, isNull); +- } +- +- void test_recordHighlightRegions_withSubscription() { +- manager.setSubscriptions({ +- server.AnalysisService.HIGHLIGHTS: new Set.from([fileA, fileB]) +- }); +- // +- // Regions should be reported when they are recorded. +- // +- HighlightRegion region1 =3D highlightRegion(10, 3); +- HighlightRegion region2 =3D highlightRegion(20, 6); +- manager.recordHighlightRegions('a', fileA, [region1, region2]); +- _verifyHighlightRegions(fileA, [region1, region2]); +- // +- // Regions from different plugins should be cumulative. +- // +- HighlightRegion region3 =3D highlightRegion(30, 5); +- manager.recordHighlightRegions('b', fileA, [region3]); +- _verifyHighlightRegions(fileA, [region1, region2, region3]); +- // +- // Overwriting regions from one plugin should not affect regions from= other +- // plugins. +- // +- HighlightRegion region4 =3D highlightRegion(40, 2); +- manager.recordHighlightRegions('a', fileA, [region4]); +- _verifyHighlightRegions(fileA, [region4, region3]); +- // +- // Recording regions against a file should not affect the regions for= other +- // files. +- // +- HighlightRegion region5 =3D highlightRegion(50, 7); +- manager.recordHighlightRegions('a', fileB, [region5]); +- _verifyHighlightRegions(fileB, [region5]); +- } +- +- void test_recordNavigationParams_noSubscription() { +- server.AnalysisNavigationParams params =3D +- serverNavigationParams(0, 0, file: fileA); +- manager.recordNavigationParams('a', fileA, params); +- expect(channel.sentNotification, isNull); +- } +- +- void test_recordNavigationParams_withSubscription() { +- manager.setSubscriptions({ +- server.AnalysisService.NAVIGATION: new Set.from([fileA, fileB]) +- }); +- // +- // Parameters should be reported when they are recorded. +- // +- server.AnalysisNavigationParams params1 =3D +- serverNavigationParams(0, 0, file: fileA); +- manager.recordNavigationParams('a', fileA, params1); +- _verifyNavigationParams(params1); +- // +- // Parameters from different plugins should be cumulative. +- // +- server.AnalysisNavigationParams params2 =3D +- serverNavigationParams(2, 4, file: fileA); +- manager.recordNavigationParams('b', fileA, params2); +- server.AnalysisNavigationParams params1and2 =3D +- new server.AnalysisNavigationParams(fileA, [ +- new NavigationRegion(0, 2, [0]), +- new NavigationRegion(4, 2, [1]) +- ], [ +- new NavigationTarget(ElementKind.FIELD, 0, 1, 2, 2, 3), +- new NavigationTarget(ElementKind.FIELD, 2, 5, 2, 6, 7) +- ], [ +- 'aa', +- 'ab', +- 'ac', +- 'ad' +- ]); +- _verifyNavigationParams(params1and2); +- // +- // Overwriting parameters from one plugin should not affect parameter= s from +- // other plugins. +- // +- server.AnalysisNavigationParams params3 =3D +- serverNavigationParams(4, 8, file: fileA); +- manager.recordNavigationParams('a', fileA, params3); +- server.AnalysisNavigationParams params3and2 =3D +- new server.AnalysisNavigationParams(fileA, [ +- new NavigationRegion(8, 2, [0]), +- new NavigationRegion(4, 2, [1]) +- ], [ +- new NavigationTarget(ElementKind.FIELD, 0, 9, 2, 10, 11), +- new NavigationTarget(ElementKind.FIELD, 2, 5, 2, 6, 7) +- ], [ +- 'ae', +- 'af', +- 'ac', +- 'ad' +- ]); +- _verifyNavigationParams(params3and2); +- // +- // Recording parameters against a file should not affect the paramete= rs for +- // other files. +- // +- server.AnalysisNavigationParams params4 =3D +- serverNavigationParams(6, 12, file: fileB); +- manager.recordNavigationParams('a', fileB, params4); +- _verifyNavigationParams(params4); +- } +- +- void test_recordOccurrences_noSubscription() { +- Occurrences occurrences1 =3D occurrences(0, 0); +- manager.recordOccurrences('a', fileA, [occurrences1]); +- expect(channel.sentNotification, isNull); +- } +- +- void test_recordOccurrences_withSubscription() { +- manager.setSubscriptions({ +- server.AnalysisService.OCCURRENCES: new Set.from([fileA, fileB]) +- }); +- // +- // Occurrences should be reported when they are recorded. +- // +- Occurrences occurrences1 =3D occurrences(0, 0); +- Occurrences occurrences2 =3D occurrences(5, 7); +- manager.recordOccurrences('a', fileA, [occurrences1, occurrences2]); +- _verifyOccurrences(fileA, [occurrences1, occurrences2]); +- // +- // Occurrences from different plugins should be cumulative. +- // +- Occurrences occurrences3 =3D occurrences(10, 14); +- manager.recordOccurrences('b', fileA, [occurrences3]); +- _verifyOccurrences(fileA, [occurrences1, occurrences2, occurrences3]); +- // +- // Overwriting occurrences from one plugin should not affect occurren= ces +- // from other plugins. +- // +- Occurrences occurrences4 =3D occurrences(15, 21); +- manager.recordOccurrences('a', fileA, [occurrences4]); +- _verifyOccurrences(fileA, [occurrences4, occurrences3]); +- // +- // Recording occurrences against a file should not affect the occurre= nces +- // for other files. +- // +- Occurrences occurrences5 =3D occurrences(20, 28); +- manager.recordOccurrences('a', fileB, [occurrences5]); +- _verifyOccurrences(fileB, [occurrences5]); +- } +- +- void test_recordOutlines_noSubscription() { +- Outline outline1 =3D outline(0, 0); +- manager.recordOutlines('a', fileA, [outline1]); +- expect(channel.sentNotification, isNull); +- } +- +- @failingTest +- void test_recordOutlines_withSubscription() { +- fail('The outline handling needs to be re-worked slightly'); +- // TODO(brianwilkerson) Figure out outlines. What should we do when m= erge +- // cannot produce a single outline? +- manager.setSubscriptions({ +- server.AnalysisService.OUTLINE: new Set.from([fileA, fileB]) +- }); +- // +- // Outlines should be reported when they are recorded. +- // +- Outline outline1 =3D outline(0, 0); +- Outline outline2 =3D outline(5, 7); +- manager.recordOutlines('a', fileA, [outline1, outline2]); +- // TODO(brianwilkerson) Figure out how to test this. +-// _verifyOutlines(fileA, [outline1, outline2]); +- // +- // Outlines from different plugins should be cumulative. +- // +- Outline outline3 =3D outline(10, 14); +- manager.recordOutlines('b', fileA, [outline3]); +- // TODO(brianwilkerson) Figure out how to test this. +-// _verifyOutlines(fileA, [outline1, outline2, outline3]); +- // +- // Overwriting outlines from one plugin should not affect outlines fr= om +- // other plugins. +- // +- Outline outline4 =3D outline(15, 21); +- manager.recordOutlines('a', fileA, [outline4]); +- // TODO(brianwilkerson) Figure out how to test this. +-// _verifyOutlines(fileA, [outline4, outline3]); +- // +- // Recording outlines against a file should not affect the outlines f= or +- // other files. +- // +- Outline outline5 =3D outline(20, 28); +- manager.recordOutlines('a', fileB, [outline5]); +- // TODO(brianwilkerson) Figure out how to test this. +-// _verifyOutlines(fileB, [outline5]); +- } +- +- void _verifyErrors(String fileName, List expectedErrors)= { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'analysis.errors'); +- server.AnalysisErrorsParams params =3D +- new server.AnalysisErrorsParams.fromNotification(notification); +- expect(params, isNotNull); +- expect(params.file, fileName); +- expect(params.errors, equals(expectedErrors)); +- channel.sentNotification =3D null; +- } +- +- void _verifyFoldingRegions( +- String fileName, List expectedRegions) { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'analysis.folding'); +- server.AnalysisFoldingParams params =3D +- new server.AnalysisFoldingParams.fromNotification(notification); +- expect(params, isNotNull); +- expect(params.file, fileName); +- expect(params.regions, equals(expectedRegions)); +- channel.sentNotification =3D null; +- } +- +- void _verifyHighlightRegions( +- String fileName, List expectedRegions) { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'analysis.highlights'); +- server.AnalysisHighlightsParams params =3D +- new server.AnalysisHighlightsParams.fromNotification(notification= ); +- expect(params, isNotNull); +- expect(params.file, fileName); +- expect(params.regions, equals(expectedRegions)); +- channel.sentNotification =3D null; +- } +- +- void _verifyNavigationParams(server.AnalysisNavigationParams expectedPa= rams) { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'analysis.navigation'); +- server.AnalysisNavigationParams params =3D +- new server.AnalysisNavigationParams.fromNotification(notification= ); +- expect(params, isNotNull); +- expect(params.file, expectedParams.file); +- expect(params.files, equals(expectedParams.files)); +- expect(params.regions, equals(expectedParams.regions)); +- expect(params.targets, equals(expectedParams.targets)); +- channel.sentNotification =3D null; +- } +- +- void _verifyOccurrences( +- String fileName, List expectedOccurrences) { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'analysis.occurrences'); +- server.AnalysisOccurrencesParams params =3D +- new server.AnalysisOccurrencesParams.fromNotification(notificatio= n); +- expect(params, isNotNull); +- expect(params.file, fileName); +- expect(params.occurrences, equals(expectedOccurrences)); +- channel.sentNotification =3D null; +- } +- +- void _verifyOutlines(String fileName, Outline expectedOutline) { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'analysis.outline'); +- server.AnalysisOutlineParams params =3D +- new server.AnalysisOutlineParams.fromNotification(notification); +- expect(params, isNotNull); +- expect(params.file, fileName); +- expect(params.outline, equals(expectedOutline)); +- channel.sentNotification =3D null; +- } +- +- void _verifyPluginError(bool isFatal, String message, String stackTrace= ) { +- server.Notification notification =3D channel.sentNotification; +- expect(notification, isNotNull); +- expect(notification.event, 'server.error'); +- server.ServerErrorParams params =3D +- new server.ServerErrorParams.fromNotification(notification); +- expect(params, isNotNull); +- expect(params.isFatal, isFatal); +- expect(params.message, message); +- expect(params.stackTrace, stackTrace); +- channel.sentNotification =3D null; +- } +-} +- +-class TestChannel implements ServerCommunicationChannel { +- server.Notification sentNotification; +- +- @override +- void close() { +- fail('Unexpected invocation of close'); +- } +- +- @override +- void listen(void onRequest(server.Request request), +- {Function onError, void onDone()}) { +- fail('Unexpected invocation of listen'); +- } +- +- @override +- void sendNotification(server.Notification notification) { +- sentNotification =3D notification; +- } +- +- @override +- void sendResponse(server.Response response) { +- fail('Unexpected invocation of sendResponse'); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart = b/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart +deleted file mode 100644 +index 38e71a9e0a0..00000000000 +--- a/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart ++++ /dev/null +@@ -1,96 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/plugin/plugin_locator.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(PluginLocatorTest); +- }); +-} +- +-@reflectiveTest +-class PluginLocatorTest { +- MemoryResourceProvider resourceProvider; +- String packageRoot; +- String pubspecPath; +- String defaultDirPath; +- PluginLocator locator; +- +- void setUp() { +- resourceProvider =3D new MemoryResourceProvider(); +- packageRoot =3D resourceProvider.convertPath('/package'); +- resourceProvider.newFolder(packageRoot); +- locator =3D new PluginLocator(resourceProvider); +- } +- +- @failingTest +- void test_findPlugin_inPubspec_defaultDir() { +- // Support for specifying plugin locations in the pubspec is temporar= ily +- // disabled. +- String dirPath =3D _createPubspecWithKey(); +- _createDefaultDir(); +- expect(locator.findPlugin(packageRoot), dirPath); +- } +- +- @failingTest +- void test_findPlugin_inPubspec_noDefaultDir() { +- // Support for specifying plugin locations in the pubspec is temporar= ily +- // disabled. +- String dirPath =3D _createPubspecWithKey(); +- expect(locator.findPlugin(packageRoot), dirPath); +- } +- +- void test_findPlugin_noPubspec_defaultDir() { +- _createDefaultDir(); +- expect(locator.findPlugin(packageRoot), defaultDirPath); +- } +- +- void test_findPlugin_noPubspec_noDefaultDir() { +- expect(locator.findPlugin(packageRoot), isNull); +- } +- +- void test_findPlugin_notInPubspec_defaultDir() { +- _createPubspecWithoutKey(); +- _createDefaultDir(); +- expect(locator.findPlugin(packageRoot), defaultDirPath); +- } +- +- void test_findPlugin_notInPubspec_noDefaultDir() { +- _createPubspecWithoutKey(); +- expect(locator.findPlugin(packageRoot), isNull); +- } +- +- void _createDefaultDir() { +- defaultDirPath =3D resourceProvider.pathContext.join(packageRoot, +- PluginLocator.toolsFolderName, PluginLocator.defaultPluginFolderN= ame); +- resourceProvider.newFolder(defaultDirPath); +- } +- +- void _createPubspec(String content) { +- pubspecPath =3D resourceProvider.pathContext +- .join(packageRoot, PluginLocator.pubspecFileName); +- resourceProvider.newFile(pubspecPath, content); +- } +- +- String _createPubspecWithKey() { +- String nonDefaultPath =3D +- resourceProvider.pathContext.join(packageRoot, 'pluginDir'); +- _createPubspec(''' +-name: test_project +-${PluginLocator.analyzerPluginKey}: $nonDefaultPath +-'''); +- resourceProvider.newFolder(nonDefaultPath); +- return nonDefaultPath; +- } +- +- void _createPubspecWithoutKey() { +- _createPubspec(''' +-name: test_project +-'''); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart = b/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart +deleted file mode 100644 +index c9665cd4423..00000000000 +--- a/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart ++++ /dev/null +@@ -1,918 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io' as io; +- +-import 'package:analysis_server/src/plugin/notification_manager.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:analyzer_plugin/channel/channel.dart'; +-import 'package:analyzer_plugin/protocol/protocol.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' +- hide ContextRoot; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +-import 'package:watcher/watcher.dart' as watcher; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(BuiltInPluginInfoTest); +- defineReflectiveTests(DiscoveredPluginInfoTest); +- defineReflectiveTests(PluginManagerTest); +- defineReflectiveTests(PluginManagerFromDiskTest); +- defineReflectiveTests(PluginSessionTest); +- defineReflectiveTests(PluginSessionFromDiskTest); +- }); +-} +- +-@reflectiveTest +-class BuiltInPluginInfoTest { +- TestNotificationManager notificationManager; +- BuiltInPluginInfo plugin; +- +- void setUp() { +- notificationManager =3D new TestNotificationManager(); +- plugin =3D new BuiltInPluginInfo(null, 'test plugin', notificationMan= ager, +- InstrumentationService.NULL_SERVICE); +- } +- +- test_addContextRoot() { +- ContextRoot contextRoot1 =3D new ContextRoot('/pkg1', []); +- plugin.addContextRoot(contextRoot1); +- expect(plugin.contextRoots, [contextRoot1]); +- plugin.addContextRoot(contextRoot1); +- expect(plugin.contextRoots, [contextRoot1]); +- } +- +- test_creation() { +- expect(plugin.pluginId, 'test plugin'); +- expect(plugin.notificationManager, notificationManager); +- expect(plugin.contextRoots, isEmpty); +- expect(plugin.currentSession, isNull); +- } +- +- test_removeContextRoot() { +- ContextRoot contextRoot1 =3D new ContextRoot('/pkg1', []); +- ContextRoot contextRoot2 =3D new ContextRoot('/pkg2', []); +- plugin.addContextRoot(contextRoot1); +- expect(plugin.contextRoots, unorderedEquals([contextRoot1])); +- plugin.addContextRoot(contextRoot2); +- expect(plugin.contextRoots, unorderedEquals([contextRoot1, contextRoo= t2])); +- plugin.removeContextRoot(contextRoot1); +- expect(plugin.contextRoots, unorderedEquals([contextRoot2])); +- plugin.removeContextRoot(contextRoot2); +- expect(plugin.contextRoots, isEmpty); +- } +- +- @failingTest +- test_start_notRunning() { +- fail('Not tested'); +- } +- +- test_start_running() async { +- plugin.currentSession =3D new PluginSession(plugin); +- try { +- await plugin.start('', ''); +- fail('Expected a StateError'); +- } on StateError { +- // Expected. +- } +- } +- +- test_stop_notRunning() { +- expect(() =3D> plugin.stop(), throwsStateError); +- } +- +- test_stop_running() async { +- PluginSession session =3D new PluginSession(plugin); +- TestServerCommunicationChannel channel =3D +- new TestServerCommunicationChannel(session); +- plugin.currentSession =3D session; +- await plugin.stop(); +- expect(plugin.currentSession, isNull); +- expect(channel.sentRequests, hasLength(1)); +- expect(channel.sentRequests[0].method, 'plugin.shutdown'); +- } +-} +- +-@reflectiveTest +-class DiscoveredPluginInfoTest { +- MemoryResourceProvider resourceProvider; +- TestNotificationManager notificationManager; +- String pluginPath =3D '/pluginDir'; +- String executionPath =3D '/pluginDir/bin/plugin.dart'; +- String packagesPath =3D '/pluginDir/.packages'; +- DiscoveredPluginInfo plugin; +- +- void setUp() { +- resourceProvider =3D new MemoryResourceProvider(); +- notificationManager =3D new TestNotificationManager(); +- plugin =3D new DiscoveredPluginInfo(pluginPath, executionPath, packag= esPath, +- notificationManager, InstrumentationService.NULL_SERVICE); +- } +- +- test_addContextRoot() { +- String optionsFilePath =3D '/pkg1/analysis_options.yaml'; +- ContextRoot contextRoot1 =3D new ContextRoot('/pkg1', []); +- contextRoot1.optionsFilePath =3D optionsFilePath; +- PluginSession session =3D new PluginSession(plugin); +- TestServerCommunicationChannel channel =3D +- new TestServerCommunicationChannel(session); +- plugin.currentSession =3D session; +- plugin.addContextRoot(contextRoot1); +- expect(plugin.contextRoots, [contextRoot1]); +- plugin.addContextRoot(contextRoot1); +- expect(plugin.contextRoots, [contextRoot1]); +- List sentRequests =3D channel.sentRequests; +- expect(sentRequests, hasLength(1)); +- List roots =3D sentRequests[0].params['roots']; +- expect(roots[0]['optionsFile'], optionsFilePath); +- } +- +- test_creation() { +- expect(plugin.path, pluginPath); +- expect(plugin.executionPath, executionPath); +- expect(plugin.notificationManager, notificationManager); +- expect(plugin.contextRoots, isEmpty); +- expect(plugin.currentSession, isNull); +- } +- +- test_removeContextRoot() { +- ContextRoot contextRoot1 =3D new ContextRoot('/pkg1', []); +- ContextRoot contextRoot2 =3D new ContextRoot('/pkg2', []); +- plugin.addContextRoot(contextRoot1); +- expect(plugin.contextRoots, unorderedEquals([contextRoot1])); +- plugin.addContextRoot(contextRoot2); +- expect(plugin.contextRoots, unorderedEquals([contextRoot1, contextRoo= t2])); +- plugin.removeContextRoot(contextRoot1); +- expect(plugin.contextRoots, unorderedEquals([contextRoot2])); +- plugin.removeContextRoot(contextRoot2); +- expect(plugin.contextRoots, isEmpty); +- } +- +- @failingTest +- test_start_notRunning() { +- fail('Not tested'); +- } +- +- test_start_running() async { +- plugin.currentSession =3D new PluginSession(plugin); +- try { +- await plugin.start('', ''); +- fail('Expected a StateError'); +- } on StateError { +- // Expected. +- } +- } +- +- test_stop_notRunning() { +- expect(() =3D> plugin.stop(), throwsStateError); +- } +- +- test_stop_running() async { +- PluginSession session =3D new PluginSession(plugin); +- TestServerCommunicationChannel channel =3D +- new TestServerCommunicationChannel(session); +- plugin.currentSession =3D session; +- await plugin.stop(); +- expect(plugin.currentSession, isNull); +- expect(channel.sentRequests, hasLength(1)); +- expect(channel.sentRequests[0].method, 'plugin.shutdown'); +- } +-} +- +-@reflectiveTest +-class PluginManagerFromDiskTest extends PluginTestSupport { +- String byteStorePath =3D '/byteStore'; +- PluginManager manager; +- +- void setUp() { +- super.setUp(); +- manager =3D new PluginManager(resourceProvider, byteStorePath, '', +- notificationManager, InstrumentationService.NULL_SERVICE); +- } +- +- test_addPluginToContextRoot() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin(test: (String pluginPath) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, pluginPath); +- await manager.stopAll(); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- @failingTest +- test_addPluginToContextRoot_pubspec() async { +- // We can't successfully run pub until after the analyzer_plugin pack= age has +- // been published. +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPubspecPlugin(test: (String pluginPath) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, pluginPath); +- String packagesPath =3D +- resourceProvider.pathContext.join(pluginPath, '.packages'); +- File packagesFile =3D resourceProvider.getFile(packagesPath); +- bool exists =3D packagesFile.exists; +- await manager.stopAll(); +- expect(exists, isTrue, reason: '.packages file was not created'); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_broadcastRequest_many() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin( +- pluginName: 'plugin1', +- test: (String plugin1Path) async { +- await withPlugin( +- pluginName: 'plugin2', +- test: (String plugin2Path) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, plugin1= Path); +- await manager.addPluginToContextRoot(contextRoot, plugin2= Path); +- +- Map> responses =3D +- manager.broadcastRequest( +- new CompletionGetSuggestionsParams( +- '/pkg1/lib/pkg1.dart', 100), +- contextRoot: contextRoot); +- expect(responses, hasLength(2)); +- +- await manager.stopAll(); +- }); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_broadcastRequest_many_noContextRoot() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin( +- pluginName: 'plugin1', +- test: (String plugin1Path) async { +- await withPlugin( +- pluginName: 'plugin2', +- test: (String plugin2Path) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, plugin1= Path); +- await manager.addPluginToContextRoot(contextRoot, plugin2= Path); +- +- Map> responses =3D +- manager.broadcastRequest(new CompletionGetSuggestions= Params( +- '/pkg1/lib/pkg1.dart', 100)); +- expect(responses, hasLength(2)); +- +- await manager.stopAll(); +- }); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_broadcastWatchEvent() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin( +- pluginName: 'plugin1', +- test: (String plugin1Path) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, plugin1Path); +- List plugins =3D manager.pluginsForContextRoot(cont= extRoot); +- expect(plugins, hasLength(1)); +- watcher.WatchEvent watchEvent =3D new watcher.WatchEvent( +- watcher.ChangeType.MODIFY, path.join(pkgPath, 'lib', 'lib.d= art')); +- List> responses =3D +- await manager.broadcastWatchEvent(watchEvent); +- expect(responses, hasLength(1)); +- Response response =3D await responses[0]; +- expect(response, isNotNull); +- expect(response.error, isNull); +- await manager.stopAll(); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_pluginsForContextRoot_multiple() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin( +- pluginName: 'plugin1', +- test: (String plugin1Path) async { +- await withPlugin( +- pluginName: 'plugin2', +- test: (String plugin2Path) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, plugin1= Path); +- await manager.addPluginToContextRoot(contextRoot, plugin2= Path); +- +- List plugins =3D +- manager.pluginsForContextRoot(contextRoot); +- expect(plugins, hasLength(2)); +- List paths =3D plugins +- .map((PluginInfo plugin) =3D> plugin.pluginId) +- .toList(); +- expect(paths, unorderedEquals([plugin1Path, plugin2Path])= ); +- +- await manager.stopAll(); +- }); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_pluginsForContextRoot_one() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin(test: (String pluginPath) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, pluginPath); +- +- List plugins =3D manager.pluginsForContextRoot(contextR= oot); +- expect(plugins, hasLength(1)); +- expect(plugins[0].pluginId, pluginPath); +- +- await manager.stopAll(); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_removedContextRoot() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkgPath =3D pkg1Dir.resolveSymbolicLinksSync(); +- await withPlugin(test: (String pluginPath) async { +- ContextRoot contextRoot =3D new ContextRoot(pkgPath, []); +- await manager.addPluginToContextRoot(contextRoot, pluginPath); +- +- manager.removedContextRoot(contextRoot); +- +- await manager.stopAll(); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +- +- test_restartPlugins() async { +- io.Directory pkg1Dir =3D io.Directory.systemTemp.createTempSync('pkg1= '); +- String pkg1Path =3D pkg1Dir.resolveSymbolicLinksSync(); +- io.Directory pkg2Dir =3D io.Directory.systemTemp.createTempSync('pkg2= '); +- String pkg2Path =3D pkg2Dir.resolveSymbolicLinksSync(); +- await withPlugin( +- pluginName: 'plugin1', +- test: (String plugin1Path) async { +- await withPlugin( +- pluginName: 'plugin2', +- test: (String plugin2Path) async { +- ContextRoot contextRoot1 =3D new ContextRoot(pkg1Path, []= ); +- ContextRoot contextRoot2 =3D new ContextRoot(pkg2Path, []= ); +- await manager.addPluginToContextRoot(contextRoot1, plugin= 1Path); +- await manager.addPluginToContextRoot(contextRoot1, plugin= 2Path); +- await manager.addPluginToContextRoot(contextRoot2, plugin= 1Path); +- +- await manager.restartPlugins(); +- List plugins =3D manager.plugins; +- expect(plugins, hasLength(2)); +- expect(plugins[0].currentSession, isNotNull); +- expect(plugins[1].currentSession, isNotNull); +- if (plugins[0].pluginId.contains('plugin1')) { +- expect(plugins[0].contextRoots, +- unorderedEquals([contextRoot1, contextRoot2])); +- expect( +- plugins[1].contextRoots, unorderedEquals([contextRo= ot1])); +- } else { +- expect( +- plugins[0].contextRoots, unorderedEquals([contextRo= ot1])); +- expect(plugins[1].contextRoots, +- unorderedEquals([contextRoot1, contextRoot2])); +- } +- await manager.stopAll(); +- }); +- }); +- pkg1Dir.deleteSync(recursive: true); +- } +-} +- +-@reflectiveTest +-class PluginManagerTest { +- MemoryResourceProvider resourceProvider; +- String byteStorePath; +- String sdkPath; +- TestNotificationManager notificationManager; +- PluginManager manager; +- +- void setUp() { +- resourceProvider =3D new MemoryResourceProvider(); +- byteStorePath =3D resourceProvider.convertPath('/byteStore'); +- sdkPath =3D resourceProvider.convertPath('/sdk'); +- notificationManager =3D new TestNotificationManager(); +- manager =3D new PluginManager(resourceProvider, byteStorePath, sdkPat= h, +- notificationManager, InstrumentationService.NULL_SERVICE); +- } +- +- void test_broadcastRequest_none() { +- ContextRoot contextRoot =3D new ContextRoot('/pkg1', []); +- Map> responses =3D manager.broadcastRequ= est( +- new CompletionGetSuggestionsParams('/pkg1/lib/pkg1.dart', 100), +- contextRoot: contextRoot); +- expect(responses, hasLength(0)); +- } +- +- void test_creation() { +- expect(manager.resourceProvider, resourceProvider); +- expect(manager.byteStorePath, byteStorePath); +- expect(manager.sdkPath, sdkPath); +- expect(manager.notificationManager, notificationManager); +- } +- +- void test_pathsFor_withPackagesFile() { +- path.Context context =3D resourceProvider.pathContext; +- // +- // Build the minimal directory structure for a plugin package that in= cludes +- // a .packages file. +- // +- String pluginDirPath =3D resourceProvider.convertPath('/plugin'); +- String pluginFilePath =3D context.join(pluginDirPath, 'bin', 'plugin.= dart'); +- resourceProvider.newFile(pluginFilePath, ''); +- String packagesFilePath =3D context.join(pluginDirPath, '.packages'); +- resourceProvider.newFile(packagesFilePath, ''); +- // +- // Test path computation. +- // +- List paths =3D manager.pathsFor(pluginDirPath); +- expect(paths, hasLength(2)); +- expect(paths[0], pluginFilePath); +- expect(paths[1], packagesFilePath); +- } +- +- void test_pathsFor_withPubspec_inBazelWorkspace() { +- path.Context context =3D resourceProvider.pathContext; +- // +- // Build a Bazel workspace containing four packages, including the pl= ugin. +- // +- String rootPath =3D resourceProvider.convertPath('/workspaceRoot'); +- resourceProvider.newFile(context.join(rootPath, 'WORKSPACE'), ''); +- resourceProvider.newFolder(context.join(rootPath, 'bazel-bin')); +- resourceProvider.newFolder(context.join(rootPath, 'bazel-genfiles')); +- +- String newPackage(String packageName, [List dependencies]) { +- String packageRoot =3D +- context.join(rootPath, 'third_party', 'dart', packageName); +- resourceProvider.newFile( +- context.join(packageRoot, 'lib', packageName + '.dart'), ''); +- StringBuffer buffer =3D new StringBuffer(); +- if (dependencies !=3D null) { +- buffer.writeln('dependencies:'); +- for (String dependency in dependencies) { +- buffer.writeln(' $dependency: any'); +- } +- } +- resourceProvider.newFile( +- context.join(packageRoot, 'pubspec.yaml'), buffer.toString()); +- return packageRoot; +- } +- +- String pluginDirPath =3D newPackage('plugin', ['b', 'c']); +- newPackage('b', ['d']); +- newPackage('c', ['d']); +- newPackage('d'); +- String pluginFilePath =3D context.join(pluginDirPath, 'bin', 'plugin.= dart'); +- resourceProvider.newFile(pluginFilePath, ''); +- // +- // Test path computation. +- // +- List paths =3D manager.pathsFor(pluginDirPath); +- expect(paths, hasLength(2)); +- expect(paths[0], pluginFilePath); +- File packagesFile =3D resourceProvider.getFile(paths[1]); +- expect(packagesFile.exists, isTrue); +- String content =3D packagesFile.readAsStringSync(); +- List lines =3D content.split('\n'); +- expect( +- lines, +- unorderedEquals([ +- 'plugin:file:///workspaceRoot/third_party/dart/plugin/lib', +- 'b:file:///workspaceRoot/third_party/dart/b/lib', +- 'c:file:///workspaceRoot/third_party/dart/c/lib', +- 'd:file:///workspaceRoot/third_party/dart/d/lib', +- '' +- ])); +- } +- +- void test_pluginsForContextRoot_none() { +- ContextRoot contextRoot =3D new ContextRoot('/pkg1', []); +- expect(manager.pluginsForContextRoot(contextRoot), isEmpty); +- } +- +- void test_stopAll_none() { +- manager.stopAll(); +- } +-} +- +-@reflectiveTest +-class PluginSessionFromDiskTest extends PluginTestSupport { +- test_start_notRunning() async { +- await withPlugin(test: (String pluginPath) async { +- String packagesPath =3D path.join(pluginPath, '.packages'); +- String mainPath =3D path.join(pluginPath, 'bin', 'plugin.dart'); +- String byteStorePath =3D path.join(pluginPath, 'byteStore'); +- new io.Directory(byteStorePath).createSync(); +- PluginInfo plugin =3D new DiscoveredPluginInfo( +- pluginPath, +- mainPath, +- packagesPath, +- notificationManager, +- InstrumentationService.NULL_SERVICE); +- PluginSession session =3D new PluginSession(plugin); +- plugin.currentSession =3D session; +- expect(await session.start(byteStorePath, ''), isTrue); +- await session.stop(); +- }); +- } +-} +- +-@reflectiveTest +-class PluginSessionTest { +- MemoryResourceProvider resourceProvider; +- TestNotificationManager notificationManager; +- String pluginPath; +- String executionPath; +- String packagesPath; +- String sdkPath; +- PluginInfo plugin; +- PluginSession session; +- +- void setUp() { +- resourceProvider =3D new MemoryResourceProvider(); +- notificationManager =3D new TestNotificationManager(); +- pluginPath =3D resourceProvider.convertPath('/pluginDir'); +- executionPath =3D resourceProvider.convertPath('/pluginDir/bin/plugin= .dart'); +- packagesPath =3D resourceProvider.convertPath('/pluginDir/.packages'); +- sdkPath =3D resourceProvider.convertPath('/sdk'); +- plugin =3D new DiscoveredPluginInfo(pluginPath, executionPath, packag= esPath, +- notificationManager, InstrumentationService.NULL_SERVICE); +- session =3D new PluginSession(plugin); +- } +- +- void test_handleNotification() { +- Notification notification =3D +- new AnalysisErrorsParams('/test.dart', []) +- .toNotification(); +- expect(notificationManager.notifications, hasLength(0)); +- session.handleNotification(notification); +- expect(notificationManager.notifications, hasLength(1)); +- expect(notificationManager.notifications[0], notification); +- } +- +- void test_handleOnDone() { +- TestServerCommunicationChannel channel =3D +- new TestServerCommunicationChannel(session); +- session.handleOnDone(); +- expect(channel.closeCount, 1); +- expect(session.pluginStoppedCompleter.isCompleted, isTrue); +- } +- +- @failingTest +- void test_handleOnError() { +- session.handleOnError(['message', 'trace']); +- fail('The method handleOnError is not implemented'); +- } +- +- test_handleResponse() async { +- new TestServerCommunicationChannel(session); +- Response response =3D new PluginVersionCheckResult( +- true, 'name', 'version', [], +- contactInfo: 'contactInfo') +- .toResponse('0', 1); +- Future future =3D +- session.sendRequest(new PluginVersionCheckParams('', '', '')); +- expect(session.pendingRequests, hasLength(1)); +- session.handleResponse(response); +- expect(session.pendingRequests, hasLength(0)); +- Response result =3D await future; +- expect(result, same(response)); +- } +- +- void test_nextRequestId() { +- expect(session.requestId, 0); +- expect(session.nextRequestId, '0'); +- expect(session.requestId, 1); +- } +- +- void test_sendRequest() { +- TestServerCommunicationChannel channel =3D +- new TestServerCommunicationChannel(session); +- session.sendRequest(new PluginVersionCheckParams('', '', '')); +- expect(channel.sentRequests, hasLength(1)); +- expect(channel.sentRequests[0].method, 'plugin.versionCheck'); +- } +- +- test_start_notCompatible() async { +- session.isCompatible =3D false; +- expect(await session.start(path.join(pluginPath, 'byteStore'), sdkPat= h), +- isFalse); +- } +- +- test_start_running() async { +- new TestServerCommunicationChannel(session); +- try { +- await session.start(null, ''); +- fail('Expected a StateError to be thrown'); +- } on StateError { +- // Expected behavior +- } +- } +- +- test_stop_notRunning() { +- expect(() =3D> session.stop(), throwsStateError); +- } +- +- test_stop_running() async { +- TestServerCommunicationChannel channel =3D +- new TestServerCommunicationChannel(session); +- await session.stop(); +- expect(channel.sentRequests, hasLength(1)); +- expect(channel.sentRequests[0].method, 'plugin.shutdown'); +- } +-} +- +-/** +- * A class designed to be used as a superclass for test classes that defi= ne +- * tests that require plugins to be created on disk. +- */ +-abstract class PluginTestSupport { +- PhysicalResourceProvider resourceProvider; +- TestNotificationManager notificationManager; +- +- /** +- * The content to be used for the '.packages' file, or `null` if the co= ntent +- * has not yet been computed. +- */ +- String _packagesFileContent; +- +- void setUp() { +- resourceProvider =3D PhysicalResourceProvider.INSTANCE; +- notificationManager =3D new TestNotificationManager(); +- } +- +- /** +- * Create a directory structure representing a plugin on disk, run the = given +- * [test] function, and then remove the directory. The directory will h= ave the +- * following structure: +- * ``` +- * pluginDirectory +- * .packages +- * bin +- * plugin.dart +- * ``` +- * The name of the plugin directory will be the [pluginName], if one is +- * provided (in order to allow more than one plugin to be created by a = single +- * test). The 'plugin.dart' file will contain the given [content], or d= efault +- * content that implements a minimal plugin if the contents are not giv= en. The +- * [test] function will be passed the path of the directory that was cr= eated. +- */ +- Future withPlugin( +- {String content, +- String pluginName, +- Future test(String pluginPath)}) async { +- io.Directory tempDirectory =3D +- io.Directory.systemTemp.createTempSync(pluginName ?? 'test_plugin= '); +- try { +- String pluginPath =3D tempDirectory.resolveSymbolicLinksSync(); +- // +- // Create a .packages file. +- // +- io.File packagesFile =3D new io.File(path.join(pluginPath, '.packag= es')); +- packagesFile.writeAsStringSync(_getPackagesFileContent()); +- // +- // Create the 'bin' directory. +- // +- String binPath =3D path.join(pluginPath, 'bin'); +- new io.Directory(binPath).createSync(); +- // +- // Create the 'plugin.dart' file. +- // +- io.File pluginFile =3D new io.File(path.join(binPath, 'plugin.dart'= )); +- pluginFile.writeAsStringSync(content ?? _defaultPluginContent()); +- // +- // Run the actual test code. +- // +- await test(pluginPath); +- } finally { +- tempDirectory.deleteSync(recursive: true); +- } +- } +- +- /** +- * Create a directory structure representing a plugin on disk, run the = given +- * [test] function, and then remove the directory. The directory will h= ave the +- * following structure: +- * ``` +- * pluginDirectory +- * pubspec.yaml +- * bin +- * plugin.dart +- * ``` +- * The name of the plugin directory will be the [pluginName], if one is +- * provided (in order to allow more than one plugin to be created by a = single +- * test). The 'plugin.dart' file will contain the given [content], or d= efault +- * content that implements a minimal plugin if the contents are not giv= en. The +- * [test] function will be passed the path of the directory that was cr= eated. +- */ +- Future withPubspecPlugin( +- {String content, +- String pluginName, +- Future test(String pluginPath)}) async { +- io.Directory tempDirectory =3D +- io.Directory.systemTemp.createTempSync(pluginName ?? 'test_plugin= '); +- try { +- String pluginPath =3D tempDirectory.resolveSymbolicLinksSync(); +- // +- // Create a pubspec.yaml file. +- // +- io.File pubspecFile =3D new io.File(path.join(pluginPath, 'pubspec.= yaml')); +- pubspecFile.writeAsStringSync(_getPubspecFileContent()); +- // +- // Create the 'bin' directory. +- // +- String binPath =3D path.join(pluginPath, 'bin'); +- new io.Directory(binPath).createSync(); +- // +- // Create the 'plugin.dart' file. +- // +- io.File pluginFile =3D new io.File(path.join(binPath, 'plugin.dart'= )); +- pluginFile.writeAsStringSync(content ?? _defaultPluginContent()); +- // +- // Run the actual test code. +- // +- await test(pluginPath); +- } finally { +- tempDirectory.deleteSync(recursive: true); +- } +- } +- +- /** +- * Convert the [sdkPackageMap] into a plugin-specific map by applying t= he +- * given relative path [delta] to each line. +- */ +- String _convertPackageMap(String sdkDirPath, List sdkPackageMap= ) { +- StringBuffer buffer =3D new StringBuffer(); +- for (String line in sdkPackageMap) { +- if (!line.startsWith('#')) { +- int index =3D line.indexOf(':'); +- String packageName =3D line.substring(0, index + 1); +- String relativePath =3D line.substring(index + 1); +- String absolutePath =3D path.join(sdkDirPath, relativePath); +- buffer.write(packageName); +- buffer.writeln(absolutePath); +- } +- } +- return buffer.toString(); +- } +- +- /** +- * The default content of the plugin. This is a minimal plugin that wil= l only +- * respond correctly to version checks and to shutdown requests. +- */ +- String _defaultPluginContent() { +- return r''' +-import 'dart:isolate'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/physical_file_system.dart'; +-import 'package:analyzer_plugin/plugin/plugin.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/starter.dart'; +-import 'package:pub_semver/pub_semver.dart'; +- +-void main(List args, SendPort sendPort) { +- MinimalPlugin plugin =3D new MinimalPlugin(PhysicalResourceProvider.INS= TANCE); +- new ServerPluginStarter(plugin).start(sendPort); +-} +- +-class MinimalPlugin extends ServerPlugin { +- MinimalPlugin(ResourceProvider provider) : super(provider); +- +- @override +- List get fileGlobsToAnalyze =3D> ['**/*.dart']; +- +- @override +- String get name =3D> 'minimal'; +- +- @override +- String get version =3D> '0.0.1'; +- +- @override +- AnalysisHandleWatchEventsResult handleAnalysisHandleWatchEvents( +- AnalysisHandleWatchEventsParams parameters) =3D> +- new AnalysisHandleWatchEventsResult(); +- +- @override +- bool isCompatibleWith(Version serverVersion) =3D> true; +-} +-'''; +- } +- +- /** +- * Return the content to be used for the '.packages' file. +- */ +- String _getPackagesFileContent() { +- if (_packagesFileContent =3D=3D null) { +- io.File sdkPackagesFile =3D new io.File(_sdkPackagesPath()); +- List sdkPackageMap =3D sdkPackagesFile.readAsLinesSync(); +- _packagesFileContent =3D +- _convertPackageMap(path.dirname(sdkPackagesFile.path), sdkPacka= geMap); +- } +- return _packagesFileContent; +- } +- +- /** +- * Return the content to be used for the 'pubspec.yaml' file. +- */ +- String _getPubspecFileContent() { +- return ''' +-name: 'test' +-dependencies: +- analyzer: any +- analyzer_plugin: any +-'''; +- } +- +- /** +- * Return the path to the '.packages' file in the root of the SDK check= out. +- */ +- String _sdkPackagesPath() { +- String packagesPath =3D io.Platform.script.toFilePath(); +- while (packagesPath.isNotEmpty && +- path.basename(packagesPath) !=3D 'analysis_server') { +- packagesPath =3D path.dirname(packagesPath); +- } +- packagesPath =3D path.dirname(packagesPath); +- packagesPath =3D path.dirname(packagesPath); +- return path.join(packagesPath, '.packages'); +- } +-} +- +-class TestNotificationManager implements NotificationManager { +- List notifications =3D []; +- +- Map>> recordedErrors =3D +- >>{}; +- +- @override +- void handlePluginNotification(String pluginId, Notification notificatio= n) { +- notifications.add(notification); +- } +- +- @override +- noSuchMethod(Invocation invocation) { +- fail('Unexpected invocation of ${invocation.memberName}'); +- } +- +- @override +- void recordAnalysisErrors( +- String pluginId, String filePath, List errorData) { +- recordedErrors.putIfAbsent( +- pluginId, () =3D> >{})[filePath] =3D = errorData; +- } +-} +- +-class TestServerCommunicationChannel implements ServerCommunicationChanne= l { +- final PluginSession session; +- int closeCount =3D 0; +- List sentRequests =3D []; +- +- TestServerCommunicationChannel(this.session) { +- session.channel =3D this; +- } +- +- @override +- void close() { +- closeCount++; +- } +- +- void kill() { +- fail('Unexpected invocation of kill'); +- } +- +- @override +- void listen(void onResponse(Response response), +- void onNotification(Notification notification), +- {Function onError, void onDone()}) { +- fail('Unexpected invocation of listen'); +- } +- +- @override +- void sendRequest(Request request) { +- sentRequests.add(request); +- if (request.method =3D=3D 'plugin.shutdown') { +- session.handleOnDone(); +- } +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart = b/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart +deleted file mode 100644 +index 4d8291c7bd1..00000000000 +--- a/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart ++++ /dev/null +@@ -1,187 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:typed_data'; +- +-import 'package:analysis_server/src/plugin/plugin_locator.dart'; +-import 'package:analysis_server/src/plugin/plugin_manager.dart'; +-import 'package:analysis_server/src/plugin/plugin_watcher.dart'; +-import 'package:analyzer/context/context_root.dart'; +-import 'package:analyzer/dart/analysis/session.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:analyzer/source/package_map_resolver.dart'; +-import 'package:analyzer/src/dart/analysis/driver.dart'; +-import 'package:analyzer/src/dart/analysis/file_state.dart'; +-import 'package:analyzer/src/dart/analysis/session.dart'; +-import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsI= mpl; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:front_end/byte_store.dart'; +-import 'package:front_end/src/base/performance_logger.dart'; +-import 'package:path/path.dart' as path; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../mock_sdk.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(PluginWatcherTest); +- }); +-} +- +-@reflectiveTest +-class PluginWatcherTest { +- MemoryResourceProvider resourceProvider; +- TestPluginManager manager; +- PluginWatcher watcher; +- +- void setUp() { +- resourceProvider =3D new MemoryResourceProvider(); +- manager =3D new TestPluginManager(); +- watcher =3D new PluginWatcher(resourceProvider, manager); +- } +- +- test_addedDriver() async { +- String pkg1Path =3D resourceProvider.convertPath('/pkg1'); +- resourceProvider.newFile( +- resourceProvider.convertPath('/pkg1/lib/test1.dart'), ''); +- resourceProvider.newFile( +- resourceProvider.convertPath('/pkg2/lib/pkg2.dart'), ''); +- resourceProvider.newFile( +- resourceProvider.convertPath('/pkg2/pubspec.yaml'), 'name: pkg2'); +- resourceProvider.newFile( +- resourceProvider.convertPath( +- '/pkg2/${PluginLocator.toolsFolderName}/${PluginLocator.defau= ltPluginFolderName}/bin/plugin.dart'), +- ''); +- +- ContextRoot contextRoot =3D new ContextRoot(pkg1Path, []); +- TestDriver driver =3D new TestDriver(resourceProvider, contextRoot); +- driver.analysisOptions.enabledPluginNames =3D ['pkg2']; +- watcher.addedDriver(driver, contextRoot); +- expect(manager.addedContextRoots, isEmpty); +- // +- // Test to see whether the listener was configured correctly. +- // +- // Use a file in the package being analyzed. +- // +-// await driver.computeResult('package:pkg1/test1.dart'); +-// expect(manager.addedContextRoots, isEmpty); +- // +- // Use a file that imports a package with a plugin. +- // +-// await driver.computeResult('package:pkg2/pk2.dart'); +- // +- // Wait until the timer associated with the driver's FileSystemState = is +- // guaranteed to have expired and the list of changed files will have= been +- // delivered. +- // +- await new Future.delayed(new Duration(seconds: 1)); +- expect(manager.addedContextRoots, hasLength(1)); +- } +- +- test_addedDriver_missingPackage() async { +- String pkg1Path =3D resourceProvider.convertPath('/pkg1'); +- resourceProvider.newFile( +- resourceProvider.convertPath('/pkg1/lib/test1.dart'), ''); +- +- ContextRoot contextRoot =3D new ContextRoot(pkg1Path, []); +- TestDriver driver =3D new TestDriver(resourceProvider, contextRoot); +- driver.analysisOptions.enabledPluginNames =3D ['pkg3']; +- watcher.addedDriver(driver, contextRoot); +- expect(manager.addedContextRoots, isEmpty); +- // +- // Wait until the timer associated with the driver's FileSystemState = is +- // guaranteed to have expired and the list of changed files will have= been +- // delivered. +- // +- await new Future.delayed(new Duration(seconds: 1)); +- expect(manager.addedContextRoots, isEmpty); +- } +- +- void test_creation() { +- expect(watcher.resourceProvider, resourceProvider); +- expect(watcher.manager, manager); +- } +- +- test_removedDriver() { +- String pkg1Path =3D resourceProvider.convertPath('/pkg1'); +- ContextRoot contextRoot =3D new ContextRoot(pkg1Path, []); +- TestDriver driver =3D new TestDriver(resourceProvider, contextRoot); +- watcher.addedDriver(driver, contextRoot); +- watcher.removedDriver(driver); +- expect(manager.removedContextRoots, equals([contextRoot])); +- } +-} +- +-class TestDriver implements AnalysisDriver { +- final MemoryResourceProvider resourceProvider; +- +- SourceFactory sourceFactory; +- FileSystemState fsState; +- AnalysisSession currentSession; +- AnalysisOptionsImpl analysisOptions =3D new AnalysisOptionsImpl(); +- +- final _resultController =3D new StreamController(); +- +- TestDriver(this.resourceProvider, ContextRoot contextRoot) { +- path.Context pathContext =3D resourceProvider.pathContext; +- MockSdk sdk =3D new MockSdk(resourceProvider: resourceProvider); +- String packageName =3D pathContext.basename(contextRoot.root); +- String libPath =3D pathContext.join(contextRoot.root, 'lib'); +- sourceFactory =3D new SourceFactory([ +- new DartUriResolver(sdk), +- new PackageMapUriResolver(resourceProvider, { +- packageName: [resourceProvider.getFolder(libPath)], +- 'pkg2': [ +- resourceProvider.getFolder(resourceProvider.convertPath('/pkg2/= lib')) +- ] +- }) +- ]); +- fsState =3D new FileSystemState( +- new PerformanceLog(null), +- new MemoryByteStore(), +- null, +- resourceProvider, +- sourceFactory, +- new AnalysisOptionsImpl(), +- new Uint32List(0)); +- currentSession =3D new AnalysisSessionImpl(this); +- } +- +- Stream get results =3D> _resultController.stream; +- +- Future computeResult(String uri) { +- FileState file =3D fsState.getFileForUri(Uri.parse(uri)); +- AnalysisResult result =3D new AnalysisResult( +- this, null, file.path, null, true, null, null, null, null, null, = null); +- _resultController.add(result); +- return new Future.delayed(new Duration(milliseconds: 1)); +- } +- +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +-} +- +-class TestPluginManager implements PluginManager { +- List addedContextRoots =3D []; +- +- List removedContextRoots =3D []; +- +- @override +- Future addPluginToContextRoot( +- ContextRoot contextRoot, String path) async { +- addedContextRoots.add(contextRoot); +- return null; +- } +- +- noSuchMethod(Invocation invocation) =3D> super.noSuchMethod(invocation); +- +- @override +- void recordPluginFailure(String hostPackageName, String message) {} +- +- @override +- void removedContextRoot(ContextRoot contextRoot) { +- removedContextRoots.add(contextRoot); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/protocol_test_utilities.d= art b/pkg/analysis_server/test/src/plugin/protocol_test_utilities.dart +deleted file mode 100644 +index c0afe6a2a01..00000000000 +--- a/pkg/analysis_server/test/src/plugin/protocol_test_utilities.dart ++++ /dev/null +@@ -1,192 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +- +-class ProtocolTestUtilities { +- static const List strings =3D const [ +- 'aa', +- 'ab', +- 'ac', +- 'ad', +- 'ae', +- 'af', +- 'ag', +- 'ah', +- 'ai', +- 'aj', +- 'ak', +- 'al', +- 'am', +- 'an', +- 'ao', +- 'ap', +- 'aq', +- 'ar', +- 'as', +- 'at', +- 'au', +- 'av', +- 'aw', +- 'ax', +- 'ay', +- 'az', +- 'ba', +- 'bb', +- 'bc', +- 'bd', +- 'be', +- 'bf', +- 'bg', +- 'bh', +- 'bi', +- 'bj', +- 'bk', +- 'bl', +- 'bm', +- 'bn', +- 'bo', +- 'bp', +- 'bq', +- 'br', +- 'bs', +- 'bt', +- 'bu', +- 'bv', +- 'bw', +- 'bx', +- 'by', +- 'bz', +- ]; +- +- /** +- * On return, increment [stringIndex] by 3 (or 4 if no [file] name is +- * provided) and [intIndex] by 4. +- */ +- AnalysisError analysisError(int stringIndex, int intIndex, {String file= }) { +- return new AnalysisError( +- AnalysisErrorSeverity.ERROR, +- AnalysisErrorType.COMPILE_TIME_ERROR, +- location(stringIndex, intIndex, file: file), +- strings[stringIndex++], +- strings[stringIndex++], +- correction: strings[stringIndex++], +- hasFix: true); +- } +- +- /** +- * On return, increment [stringIndex] by 5 and [intIndex] by 5. +- */ +- Element element(int stringIndex, int intIndex, {ElementKind kind}) =3D> +- new Element(kind ?? ElementKind.CLASS, strings[stringIndex++], intI= ndex++, +- location: new Location(fileName(stringIndex++), intIndex++, +- intIndex++, intIndex++, intIndex++), +- parameters: strings[stringIndex++], +- returnType: strings[stringIndex++], +- typeParameters: strings[stringIndex++]); +- +- String fileName(int stringIndex) =3D> '${strings[stringIndex]}.dart'; +- +- FoldingRegion foldingRegion(int offset, int length) =3D> +- new FoldingRegion(FoldingKind.COMMENT, offset, length); +- +- HighlightRegion highlightRegion(int offset, int length) =3D> +- new HighlightRegion(HighlightRegionType.FIELD, offset, length); +- +- /** +- * On return, increment [stringIndex] by 1 and [intIndex] by 4. +- */ +- Location location(int stringIndex, int intIndex, {String file}) =3D> +- new Location(file ?? fileName(stringIndex), intIndex++, intIndex++, +- intIndex++, intIndex++); +- +- /** +- * On return, increment [stringIndex] by 5 and [intIndex] by 7. +- */ +- Occurrences occurrences(int stringIndex, int intIndex) { +- Element referencedElement =3D element(stringIndex, intIndex); +- return new Occurrences(referencedElement, [intIndex + 5, intInde= x + 6], +- referencedElement.name.length); +- } +- +- /** +- * On return, increment [stringIndex] by 10 and [intIndex] by 14. +- */ +- Outline outline(int stringIndex, int intIndex) =3D> +- new Outline(element(stringIndex, intIndex), intIndex + 5, intIndex = + 6, +- children: [ +- new Outline( +- element(stringIndex + 5, intIndex + 7, +- kind: ElementKind.METHOD), +- intIndex + 12, +- intIndex + 13) +- ]); +- +- /** +- * On return, increment [stringIndex] by 2 (or 3 if no [file] name is +- * provided) and [intIndex] by 4. +- */ +- plugin.AnalysisNavigationParams pluginNavigationParams( +- int stringIndex, int intIndex, {String file}) =3D> +- new plugin.AnalysisNavigationParams( +- file ?? fileName(stringIndex++), [ +- new NavigationRegion(intIndex++, 2, [0]) +- ], [ +- new NavigationTarget( +- ElementKind.FIELD, 0, intIndex++, 2, intIndex++, intIndex++) +- ], [ +- strings[stringIndex++], +- strings[stringIndex++] +- ]); +- +- /** +- * On return, increment [stringIndex] by 2 and [intIndex] by 4. +- */ +- RefactoringProblem refactoringProblem(int stringIndex, int intIndex) { +- return new RefactoringProblem( +- RefactoringProblemSeverity.FATAL, strings[stringIndex++], +- location: location(stringIndex, intIndex)); +- } +- +- /** +- * On return, increment [stringIndex] by 2 (or 3 if no [file] name is +- * provided) and [intIndex] by 4. +- */ +- server.AnalysisNavigationParams serverNavigationParams( +- int stringIndex, int intIndex, {String file}) =3D> +- new server.AnalysisNavigationParams( +- file ?? fileName(stringIndex++), [ +- new NavigationRegion(intIndex++, 2, [0]) +- ], [ +- new NavigationTarget( +- ElementKind.FIELD, 0, intIndex++, 2, intIndex++, intIndex++) +- ], [ +- strings[stringIndex++], +- strings[stringIndex++] +- ]); +- +- /** +- * On return, increment [stringIndex] by 6 and [intIndex] by 6. +- */ +- SourceChange sourceChange(int stringIndex, int intIndex) =3D> +- new SourceChange(strings[stringIndex++], +- edits: [ +- new SourceFileEdit(fileName(stringIndex), intIndex++, +- edits: [ +- new SourceEdit(intIndex++, intIndex++, strings[stringIn= dex++]) +- ]) +- ], +- linkedEditGroups: [ +- new LinkedEditGroup( +- [new Position(fileName(stringIndex), intIndex++= )], +- intIndex++, +- [ +- new LinkedEditSuggestion( +- strings[stringIndex++], LinkedEditSuggestionKind.ME= THOD) +- ]) +- ], +- selection: new Position(fileName(stringIndex), intIndex++)); +-} +diff --git a/pkg/analysis_server/test/src/plugin/request_converter_test.da= rt b/pkg/analysis_server/test/src/plugin/request_converter_test.dart +deleted file mode 100644 +index f306b92a480..00000000000 +--- a/pkg/analysis_server/test/src/plugin/request_converter_test.dart ++++ /dev/null +@@ -1,82 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analysis_server/src/plugin/request_converter.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart' as s= erver; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'protocol_test_utilities.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(RequestConverterTest); +- }); +-} +- +-@reflectiveTest +-class RequestConverterTest extends ProtocolTestUtilities { +- RequestConverter converter =3D new RequestConverter(); +- +- void test_convertAnalysisService() { +- Map kindMap =3D +- { +- plugin.AnalysisService.FOLDING: server.AnalysisService.FOLDING, +- plugin.AnalysisService.HIGHLIGHTS: server.AnalysisService.HIGHLIGHT= S, +- plugin.AnalysisService.NAVIGATION: server.AnalysisService.NAVIGATIO= N, +- plugin.AnalysisService.OCCURRENCES: server.AnalysisService.OCCURREN= CES, +- plugin.AnalysisService.OUTLINE: server.AnalysisService.OUTLINE, +- }; +- kindMap.forEach( +- (plugin.AnalysisService pluginKind, server.AnalysisService server= Kind) { +- expect(converter.convertAnalysisService(serverKind), pluginKind); +- }); +- } +- +- void test_convertAnalysisSetPriorityFilesParams() { +- List files =3D ['a', 'b', 'c']; +- plugin.AnalysisSetPriorityFilesParams result =3D +- converter.convertAnalysisSetPriorityFilesParams( +- new server.AnalysisSetPriorityFilesParams(files)); +- expect(result, isNotNull); +- expect(result.files, files); +- } +- +- void test_convertAnalysisSetSubscriptionsParams() { +- Map> serverSubscriptions =3D +- >{ +- server.AnalysisService.HIGHLIGHTS: ['a', 'b'], +- server.AnalysisService.OUTLINE: ['c'], +- server.AnalysisService.OVERRIDES: ['d', 'e'] +- }; +- plugin.AnalysisSetSubscriptionsParams result =3D +- converter.convertAnalysisSetSubscriptionsParams( +- new server.AnalysisSetSubscriptionsParams(serverSubscriptions= )); +- expect(result, isNotNull); +- Map> pluginSubscriptions =3D +- result.subscriptions; +- expect(pluginSubscriptions, hasLength(2)); +- expect( +- pluginSubscriptions[plugin.AnalysisService.HIGHLIGHTS], hasLength= (2)); +- expect(pluginSubscriptions[plugin.AnalysisService.OUTLINE], hasLength= (1)); +- } +- +- void test_convertAnalysisUpdateContentParams() { +- Map serverFiles =3D { +- 'file1': new AddContentOverlay('content1'), +- 'file2': new AddContentOverlay('content2'), +- }; +- plugin.AnalysisUpdateContentParams result =3D +- converter.convertAnalysisUpdateContentParams( +- new server.AnalysisUpdateContentParams(serverFiles)); +- expect(result, isNotNull); +- Map pluginFiles =3D result.files; +- expect(pluginFiles, hasLength(2)); +- expect(pluginFiles['file1'], new isInstanceOf()); +- expect(pluginFiles['file2'], new isInstanceOf()); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/result_collector_test.dar= t b/pkg/analysis_server/test/src/plugin/result_collector_test.dart +deleted file mode 100644 +index e6372c6f268..00000000000 +--- a/pkg/analysis_server/test/src/plugin/result_collector_test.dart ++++ /dev/null +@@ -1,110 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/plugin/result_collector.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ResultCollectorTest); +- }); +-} +- +-@reflectiveTest +-class ResultCollectorTest { +- static const String serverId =3D 'server'; +- +- ResultCollector collector =3D new ResultCollector(serve= rId); +- +- void test_clearResultsForFile() { +- String filePath1 =3D 'test1.dart'; +- String filePath2 =3D 'test2.dart'; +- String value1 =3D 'r1'; +- String value2 =3D 'r2'; +- collector.startCollectingFor(filePath1); +- collector.startCollectingFor(filePath2); +- collector.putResults(filePath1, 'p', value1); +- collector.putResults(filePath2, 'p', value2); +- expect(collector.getResults(filePath1), contains(value1)); +- expect(collector.getResults(filePath2), contains(value2)); +- +- collector.clearResultsForFile(filePath2); +- expect(collector.getResults(filePath1), contains(value1)); +- expect(collector.getResults(filePath2), isEmpty); +- } +- +- void test_clearResultsFromPlugin() { +- String filePath =3D 'test.dart'; +- String p1Name =3D 'p1'; +- String p2Name =3D 'p2'; +- String p1Value =3D 'r1'; +- String p2Value =3D 'r2'; +- +- collector.startCollectingFor(filePath); +- collector.putResults(filePath, p1Name, p1Value); +- collector.putResults(filePath, p2Name, p2Value); +- expect(collector.getResults(filePath), contains(p1Value)); +- expect(collector.getResults(filePath), contains(p2Value)); +- +- collector.clearResultsFromPlugin(p1Name); +- expect(collector.getResults(filePath), isNot(contains(p1Value))); +- expect(collector.getResults(filePath), contains(p2Value)); +- } +- +- void test_getResults_emptyCollector() { +- expect(collector.getResults('test.dart'), isEmpty); +- } +- +- void test_getResults_serverFirst() { +- // This is a flaky test in that it is possible for the test to pass e= ven +- // when the code is broken. +- String filePath =3D 'test.dart'; +- String value1 =3D 'r1'; +- String value2 =3D 'r2'; +- collector.startCollectingFor(filePath); +- collector.putResults(filePath, 'p', value1); +- collector.putResults(filePath, serverId, value2); +- expect(collector.getResults(filePath), [value2, value1]); +- } +- +- void test_putResults_collecting() { +- String filePath1 =3D 'test1.dart'; +- String filePath2 =3D 'test2.dart'; +- String value1 =3D 'r1'; +- String value2 =3D 'r2'; +- expect(collector.getResults(filePath1), isEmpty); +- expect(collector.getResults(filePath2), isEmpty); +- +- collector.startCollectingFor(filePath1); +- collector.startCollectingFor(filePath2); +- collector.putResults(filePath1, 'p', value1); +- collector.putResults(filePath2, 'p', value2); +- expect(collector.getResults(filePath1), contains(value1)); +- expect(collector.getResults(filePath1), isNot(contains(value2))); +- expect(collector.getResults(filePath2), contains(value2)); +- expect(collector.getResults(filePath2), isNot(contains(value1))); +- } +- +- void test_putResults_notCollecting() { +- String filePath =3D 'test.dart'; +- expect(collector.getResults(filePath), isEmpty); +- +- collector.putResults(filePath, 'p', 'r'); +- expect(collector.getResults(filePath), isEmpty); +- } +- +- void test_stopCollectingFor() { +- String filePath =3D 'test.dart'; +- String value =3D 'r'; +- collector.startCollectingFor(filePath); +- collector.putResults(filePath, 'p', value); +- expect(collector.getResults(filePath), contains(value)); +- +- collector.stopCollectingFor(filePath); +- expect(collector.getResults(filePath), isEmpty); +- collector.putResults(filePath, 'p', value); +- expect(collector.getResults(filePath), isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/result_converter_test.dar= t b/pkg/analysis_server/test/src/plugin/result_converter_test.dart +deleted file mode 100644 +index ffe30cdb91b..00000000000 +--- a/pkg/analysis_server/test/src/plugin/result_converter_test.dart ++++ /dev/null +@@ -1,128 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart' as serv= er; +-import 'package:analysis_server/src/plugin/result_converter.dart'; +-import 'package:analysis_server/src/protocol/protocol_internal.dart' as s= erver; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'protocol_test_utilities.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ResultConverterTest); +- }); +-} +- +-@reflectiveTest +-class ResultConverterTest extends ProtocolTestUtilities { +- static const List strings =3D const [ +- 'a', +- 'b', +- 'c', +- 'd', +- 'e', +- 'f', +- 'g', +- 'h', +- 'i', +- 'j', +- 'k', +- 'l', +- 'm', +- 'n' +- ]; +- +- ResultConverter converter =3D new ResultConverter(); +- +- void test_convertAnalysisErrorFixes() { +- AnalysisError error =3D analysisError(0, 0); +- SourceChange change =3D sourceChange(4, 4); +- plugin.AnalysisErrorFixes initial =3D new plugin.AnalysisErrorFixes(e= rror, +- fixes: [ +- new plugin.PrioritizedSourceChange(100, change) +- ]); +- server.AnalysisErrorFixes expected =3D +- new server.AnalysisErrorFixes(error, fixes: [change= ]); +- expect(converter.convertAnalysisErrorFixes(initial), expected); +- } +- +- void test_convertAnalysisNavigationParams() { +- plugin.AnalysisNavigationParams initial =3D +- new plugin.AnalysisNavigationParams('a.dart', [ +- new NavigationRegion(1, 2, [3, 4]) +- ], [ +- new NavigationTarget(ElementKind.FIELD, 5, 6, 7, 8, 9) +- ], [ +- 'a', +- 'b' +- ]); +- server.AnalysisNavigationParams expected =3D +- new server.AnalysisNavigationParams('a.dart', [ +- new NavigationRegion(1, 2, [3, 4]) +- ], [ +- new NavigationTarget(ElementKind.FIELD, 5, 6, 7, 8, 9) +- ], [ +- 'a', +- 'b' +- ]); +- expect(converter.convertAnalysisNavigationParams(initial), expected); +- } +- +- void test_convertEditGetRefactoringResult_inlineMethod() { +- RefactoringProblem problem1 =3D refactoringProblem(0, 0); +- RefactoringProblem problem2 =3D refactoringProblem(2, 4); +- RefactoringProblem problem3 =3D refactoringProblem(4, 8); +- SourceChange change =3D sourceChange(6, 12); +- plugin.EditGetRefactoringResult initial =3D +- new plugin.EditGetRefactoringResult([problem1= ], +- [problem2], [problem3= ], +- feedback: +- new plugin.InlineMethodFeedback('a', true, className: 'b'= ), +- change: change, +- potentialEdits: ['f']); +- server.EditGetRefactoringResult expected =3D +- new server.EditGetRefactoringResult([problem1= ], +- [problem2], [problem3= ], +- feedback: +- new server.InlineMethodFeedback('a', true, className: 'b'= ), +- change: change, +- potentialEdits: ['f']); +- expect( +- converter.convertEditGetRefactoringResult( +- RefactoringKind.INLINE_METHOD, initial), +- expected); +- } +- +- void test_convertEditGetRefactoringResult_moveFile() { +- RefactoringProblem problem1 =3D refactoringProblem(0, 0); +- RefactoringProblem problem2 =3D refactoringProblem(2, 4); +- RefactoringProblem problem3 =3D refactoringProblem(4, 8); +- SourceChange change =3D sourceChange(6, 12); +- plugin.EditGetRefactoringResult initial =3D +- new plugin.EditGetRefactoringResult([problem1= ], +- [problem2], [problem3= ], +- feedback: new plugin.MoveFileFeedback(), +- change: change, +- potentialEdits: ['f']); +- server.EditGetRefactoringResult expected =3D +- new server.EditGetRefactoringResult([problem1= ], +- [problem2], [problem3= ], +- change: change, potentialEdits: ['f']); +- expect( +- converter.convertEditGetRefactoringResult( +- RefactoringKind.MOVE_FILE, initial), +- expected); +- } +- +- void test_convertPrioritizedSourceChange() { +- SourceChange change =3D sourceChange(0, 0); +- plugin.PrioritizedSourceChange initial =3D +- new plugin.PrioritizedSourceChange(100, change); +- expect(converter.convertPrioritizedSourceChange(initial), change); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/result_merger_test.dart b= /pkg/analysis_server/test/src/plugin/result_merger_test.dart +deleted file mode 100644 +index 98a63fda6b5..00000000000 +--- a/pkg/analysis_server/test/src/plugin/result_merger_test.dart ++++ /dev/null +@@ -1,738 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analysis_server/src/plugin/result_merger.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plug= in; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(ResultMergerTest); +- }); +-} +- +-@reflectiveTest +-class ResultMergerTest { +- // +- // The tests in this class should always perform the merge operation tw= ice +- // using the same input values in order to ensure that the input values= are +- // not modified by the merge operation. +- // +- +- ResultMerger merger =3D new ResultMerger(); +- +- void test_mergeAnalysisErrorFixes() { +- AnalysisError createError(int offset) { +- AnalysisErrorSeverity severity =3D AnalysisErrorSeverity.ERROR; +- AnalysisErrorType type =3D AnalysisErrorType.HINT; +- Location location =3D new Location('test.dart', offset, 2, 3, 4); +- return new AnalysisError(severity, type, location, '', ''); +- } +- +- AnalysisError error1 =3D createError(10); +- AnalysisError error2 =3D createError(20); +- AnalysisError error3 =3D createError(30); +- AnalysisError error4 =3D createError(40); +- plugin.PrioritizedSourceChange change1 =3D +- new plugin.PrioritizedSourceChange(1, new SourceChange('a')); +- plugin.PrioritizedSourceChange change2 =3D +- new plugin.PrioritizedSourceChange(2, new SourceChange('b')); +- plugin.PrioritizedSourceChange change3 =3D +- new plugin.PrioritizedSourceChange(3, new SourceChange('c')); +- plugin.PrioritizedSourceChange change4 =3D +- new plugin.PrioritizedSourceChange(4, new SourceChange('d')); +- plugin.PrioritizedSourceChange change5 =3D +- new plugin.PrioritizedSourceChange(5, new SourceChange('e')); +- plugin.AnalysisErrorFixes fix1 =3D +- new plugin.AnalysisErrorFixes(error1, fixes: [change1]); +- plugin.AnalysisErrorFixes fix2 =3D +- new plugin.AnalysisErrorFixes(error2, fixes: [change2]); +- plugin.AnalysisErrorFixes fix3 =3D +- new plugin.AnalysisErrorFixes(error2, fixes: [change3]); +- plugin.AnalysisErrorFixes fix4 =3D +- new plugin.AnalysisErrorFixes(error3, fixes: [change4]); +- plugin.AnalysisErrorFixes fix5 =3D +- new plugin.AnalysisErrorFixes(error4, fixes: [change5]); +- plugin.AnalysisErrorFixes fix2and3 =3D +- new plugin.AnalysisErrorFixes(error2, fixes: [change2, change3]); +- +- void runTest() { +- expect( +- merger.mergeAnalysisErrorFixes([ +- [fix1, fix2], +- [fix3, fix4], +- [fix5], +- [] +- ]), +- unorderedEquals([fix1, fix2and3, fix4, fix5])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeAnalysisErrors() { +- AnalysisError createError(int offset) { +- AnalysisErrorSeverity severity =3D AnalysisErrorSeverity.ERROR; +- AnalysisErrorType type =3D AnalysisErrorType.HINT; +- Location location =3D new Location('test.dart', offset, 2, 3, 4); +- return new AnalysisError(severity, type, location, '', ''); +- } +- +- AnalysisError error1 =3D createError(10); +- AnalysisError error2 =3D createError(20); +- AnalysisError error3 =3D createError(30); +- AnalysisError error4 =3D createError(40); +- +- void runTest() { +- expect( +- merger.mergeAnalysisErrors([ +- [error1, error2], +- [error3], +- [], +- [error4] +- ]), +- unorderedEquals([error1, error2, error3, error4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeCompletionSuggestions() { +- CompletionSuggestion createSuggestion(String completion) =3D> +- new CompletionSuggestion(CompletionSuggestionKind.IDENTIFIER, 50, +- completion, 0, 3, false, false); +- +- CompletionSuggestion suggestion1 =3D createSuggestion('a'); +- CompletionSuggestion suggestion2 =3D createSuggestion('b'); +- CompletionSuggestion suggestion3 =3D createSuggestion('c'); +- CompletionSuggestion suggestion4 =3D createSuggestion('d'); +- +- void runTest() { +- expect( +- merger.mergeCompletionSuggestions([ +- [suggestion1], +- [suggestion2, suggestion3, suggestion4], +- [] +- ]), +- unorderedEquals( +- [suggestion1, suggestion2, suggestion3, suggestion4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeFoldingRegion() { +- FoldingKind kind =3D FoldingKind.COMMENT; +- FoldingRegion region1 =3D new FoldingRegion(kind, 30, 5); +- FoldingRegion region2 =3D new FoldingRegion(kind, 0, 4); +- FoldingRegion region3 =3D new FoldingRegion(kind, 20, 6); +- FoldingRegion region4 =3D new FoldingRegion(kind, 10, 3); +- FoldingRegion region5 =3D new FoldingRegion(kind, 2, 6); // overlaps +- +- void runTest() { +- expect( +- merger.mergeFoldingRegions([ +- [region1, region2], +- [], +- [region3], +- [region4, region5] +- ]), +- unorderedEquals([region1, region2, region3, region4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeHighlightRegions() { +- HighlightRegionType type =3D HighlightRegionType.COMMENT_BLOCK; +- HighlightRegion region1 =3D new HighlightRegion(type, 30, 5); +- HighlightRegion region2 =3D new HighlightRegion(type, 0, 4); +- HighlightRegion region3 =3D new HighlightRegion(type, 20, 6); +- HighlightRegion region4 =3D new HighlightRegion(type, 10, 3); +- +- void runTest() { +- expect( +- merger.mergeHighlightRegions([ +- [region1, region2], +- [], +- [region3], +- [region4] +- ]), +- unorderedEquals([region1, region2, region3, region4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeNavigation() { +- NavigationTarget target(int fileIndex, int offset) { +- return new NavigationTarget( +- ElementKind.CLASS, fileIndex, offset, 1, 0, 0); +- } +- +- // +- // Create the parameters from the server. +- // +- NavigationTarget target1_1 =3D target(0, 1); +- NavigationTarget target1_2 =3D target(0, 2); +- NavigationTarget target2_1 =3D target(1, 3); +- NavigationTarget target2_2 =3D target(1, 4); +- NavigationRegion region1_1 =3D new NavigationRegion(10, 4, [0]); +- NavigationRegion region1_2 =3D new NavigationRegion(20, 4, [1]); +- NavigationRegion region2_1 =3D new NavigationRegion(30, 4, [2]); +- NavigationRegion region2_2 =3D new NavigationRegion(40, 4, [3]); +- AnalysisNavigationParams params1 =3D new AnalysisNavigationParams( +- 'a.dart', +- [region1_1, region1_2, region2_1, region2_2], +- [target1_1, target1_2, target2_1, target2_2], +- ['one.dart', 'two.dart']); +- // +- // Create the parameters from the second plugin. +- // +- // same file and offset as target 2_2 +- NavigationTarget target2_3 =3D target(0, 4); +- NavigationTarget target2_4 =3D target(0, 5); +- NavigationTarget target3_1 =3D target(1, 6); +- NavigationTarget target3_2 =3D target(1, 7); +- // same region and target as region2_2 +- NavigationRegion region2_3 =3D new NavigationRegion(40, 4, [0]); +- // same region as region2_2, but a different target +- NavigationRegion region2_4 =3D new NavigationRegion(40, 4, [2]); +- NavigationRegion region2_5 =3D new NavigationRegion(50, 4, [1]); +- NavigationRegion region3_1 =3D new NavigationRegion(60, 4, [2]); +- NavigationRegion region3_2 =3D new NavigationRegion(70, 4, [3]); +- AnalysisNavigationParams params2 =3D new AnalysisNavigationParams( +- 'a.dart', +- [region2_3, region2_4, region2_5, region3_1, region3_2], +- [target2_3, target2_4, target3_1, target3_2], +- ['two.dart', 'three.dart']); +- AnalysisNavigationParams expected =3D new AnalysisNavigationParams('a= .dart', [ +- region1_1, +- region1_2, +- region2_1, +- new NavigationRegion(40, 4, [3, 5]), // union of region2_2 and regi= on2_4 +- new NavigationRegion(50, 4, [4]), // region2_5 +- new NavigationRegion(60, 4, [5]), // region3_1 +- new NavigationRegion(70, 4, [6]), // region3_2 +- ], [ +- target1_1, +- target1_2, +- target2_1, +- target2_2, +- target(1, 5), // target2_4 +- target(2, 6), // target3_1 +- target(2, 7), // target3_2 +- ], [ +- 'one.dart', +- 'two.dart', +- 'three.dart' +- ]); +- +- void runTest() { +- expect(merger.mergeNavigation([params1, params2]), expected); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeOccurrences() { +- Element element1 =3D new Element(ElementKind.CLASS, 'e1', 0); +- Element element2 =3D new Element(ElementKind.CLASS, 'e2', 0); +- Element element3 =3D new Element(ElementKind.CLASS, 'e3', 0); +- Occurrences occurrence1 =3D new Occurrences(element1, [1, 2, 4], 2); +- Occurrences occurrence2 =3D new Occurrences(element2, [5], 2); +- Occurrences occurrence3 =3D new Occurrences(element1, [2, 3], 2); +- Occurrences occurrence4 =3D new Occurrences(element3, [8], 2); +- Occurrences occurrence5 =3D new Occurrences(element2, [6], 2); +- Occurrences occurrence6 =3D new Occurrences(element3, [7, 9], 2); +- Occurrences result1 =3D new Occurrences(element1, [1, 2, 3, 4], 2); +- Occurrences result2 =3D new Occurrences(element2, [5, 6], 2); +- Occurrences result3 =3D new Occurrences(element3, [7, 8, 9], 2); +- +- void runTest() { +- expect( +- merger.mergeOccurrences([ +- [occurrence1, occurrence2], +- [], +- [occurrence3, occurrence4], +- [occurrence5, occurrence6] +- ]), +- unorderedEquals([result1, result2, result3])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeOutline() { +- Element element(ElementKind kind, int offset) { +- Location location =3D new Location('', offset, 0, 0, 0); +- return new Element(kind, '', 0, location: location); +- } +- +- Element element1 =3D element(ElementKind.CLASS, 100); +- Element element1_1 =3D element(ElementKind.METHOD, 110); +- Element element1_2 =3D element(ElementKind.METHOD, 120); +- Element element2 =3D element(ElementKind.CLASS, 200); +- Element element2_1 =3D element(ElementKind.METHOD, 210); +- Element element2_2 =3D element(ElementKind.METHOD, 220); +- Element element3_1 =3D element(ElementKind.METHOD, 220); // same as 2= _2 +- Element element3_2 =3D element(ElementKind.METHOD, 230); +- Element element4 =3D element(ElementKind.CLASS, 300); +- Element element4_1 =3D element(ElementKind.METHOD, 310); +- // +- // Unique, contributed from first plugin. +- // +- // element1 +- // - element1_1 +- // - element1_2 +- // +- Outline outline1_1 =3D new Outline(element1_1, 0, 0, children: []); +- Outline outline1_2 =3D new Outline(element1_2, 0, 0, children: []); +- Outline outline1 =3D +- new Outline(element1, 0, 0, children: [outline1_1, outline1_2]); +- // +- // Same top level element, common child. +- // +- // element2 +- // - element2_1 +- // - element2_2 +- // element2 +- // - element3_1 +- // - element3_2 +- // +- Outline outline2_1 =3D new Outline(element2_1, 0, 0, children: []); +- Outline outline2_2 =3D new Outline(element2_2, 0, 0, children: []); +- Outline outline3_1 =3D new Outline(element3_1, 0, 0, children: []); +- Outline outline3_2 =3D new Outline(element3_2, 0, 0, children: []); +- Outline outline2 =3D +- new Outline(element2, 0, 0, children: [outline2_1, outline2_2]); +- Outline outline3 =3D +- new Outline(element2, 0, 0, children: [outline3_1, outline3_2]); +- Outline outline2and3 =3D new Outline(element2, 0, 0, +- children: [outline2_1, outline2_2, outline3_2]); +- // +- // Unique, contributed from second plugin. +- // +- // element4 +- // - element4_1 +- // +- Outline outline4_1 =3D new Outline(element4_1, 0, 0, children: []); +- Outline outline4 =3D new Outline(element4, 0, 0, children: [outline4_= 1]); +- +- void runTest() { +- expect( +- merger.mergeOutline([ +- [outline1, outline2], +- [], +- [outline3, outline4] +- ]), +- unorderedEquals([outline1, outline2and3, outline4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergePrioritizedSourceChanges() { +- plugin.PrioritizedSourceChange kind1 =3D +- new plugin.PrioritizedSourceChange(1, new SourceChange('')); +- plugin.PrioritizedSourceChange kind2 =3D +- new plugin.PrioritizedSourceChange(1, new SourceChange('')); +- plugin.PrioritizedSourceChange kind3 =3D +- new plugin.PrioritizedSourceChange(1, new SourceChange('')); +- plugin.PrioritizedSourceChange kind4 =3D +- new plugin.PrioritizedSourceChange(1, new SourceChange('')); +- +- void runTest() { +- expect( +- merger.mergePrioritizedSourceChanges([ +- [kind3, kind2], +- [], +- [kind4], +- [kind1] +- ]), +- unorderedEquals([kind1, kind2, kind3, kind4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_convertGetterToMethodFeedback() { +- RefactoringFeedback feedback1 =3D new ConvertGetterToMethodFeedback(); +- RefactoringFeedback feedback2 =3D new ConvertGetterToMethodFeedback(); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(feedback1)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_convertMethodToGetterFeedback() { +- RefactoringFeedback feedback1 =3D new ConvertMethodToGetterFeedback(); +- RefactoringFeedback feedback2 =3D new ConvertMethodToGetterFeedback(); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(feedback1)); +- } +- +- runTest(); +- runTest(); +- } +- +- void +- test_mergeRefactoringFeedbacks_extractLocalVariableFeedback_addEver= ything() { +- List names1 =3D ['a', 'b', 'c']; +- List offsets1 =3D [10, 20]; +- List lengths1 =3D [4, 5]; +- List coveringOffsets1 =3D [100, 150, 200]; +- List coveringLengths1 =3D [200, 100, 20]; +- RefactoringFeedback feedback1 =3D new ExtractLocalVariableFeedback( +- names1, offsets1, lengths1, +- coveringExpressionOffsets: coveringOffsets1, +- coveringExpressionLengths: coveringLengths1); +- List names2 =3D ['c', 'd']; +- List offsets2 =3D [30]; +- List lengths2 =3D [6]; +- List coveringOffsets2 =3D [210]; +- List coveringLengths2 =3D [5]; +- RefactoringFeedback feedback2 =3D new ExtractLocalVariableFeedback( +- names2, offsets2, lengths2, +- coveringExpressionOffsets: coveringOffsets2, +- coveringExpressionLengths: coveringLengths2); +- List resultNames =3D ['a', 'b', 'c', 'd']; +- List resultOffsets =3D new List.from(offsets1)..addAll(offs= ets2); +- List resultLengths =3D new List.from(lengths1)..addAll(leng= ths2); +- List resultCoveringOffsets =3D new List.from(coveringOffset= s1) +- ..addAll(coveringOffsets2); +- List resultCoveringLengths =3D new List.from(coveringLength= s1) +- ..addAll(coveringLengths2); +- RefactoringFeedback result =3D new ExtractLocalVariableFeedback( +- resultNames, resultOffsets, resultLengths, +- coveringExpressionOffsets: resultCoveringOffsets, +- coveringExpressionLengths: resultCoveringLengths); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(result)); +- } +- +- runTest(); +- runTest(); +- } +- +- void +- test_mergeRefactoringFeedbacks_extractLocalVariableFeedback_addOffs= etsAndLengths() { +- List names1 =3D ['a', 'b', 'c']; +- List offsets1 =3D [10, 20]; +- List lengths1 =3D [4, 5]; +- List coveringOffsets1 =3D [100, 150, 200]; +- List coveringLengths1 =3D [200, 100, 20]; +- RefactoringFeedback feedback1 =3D new ExtractLocalVariableFeedback( +- names1, offsets1, lengths1, +- coveringExpressionOffsets: coveringOffsets1, +- coveringExpressionLengths: coveringLengths1); +- List names2 =3D []; +- List offsets2 =3D [30]; +- List lengths2 =3D [6]; +- RefactoringFeedback feedback2 =3D +- new ExtractLocalVariableFeedback(names2, offsets2, lengths2); +- List resultOffsets =3D new List.from(offsets1)..addAll(offs= ets2); +- List resultLengths =3D new List.from(lengths1)..addAll(leng= ths2); +- RefactoringFeedback result =3D new ExtractLocalVariableFeedback( +- names1, resultOffsets, resultLengths, +- coveringExpressionOffsets: coveringOffsets1, +- coveringExpressionLengths: coveringLengths1); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(result)); +- } +- +- runTest(); +- runTest(); +- } +- +- void +- test_mergeRefactoringFeedbacks_extractLocalVariableFeedback_noCover= ings() { +- List names1 =3D ['a', 'b', 'c']; +- List offsets1 =3D [10, 20]; +- List lengths1 =3D [4, 5]; +- RefactoringFeedback feedback1 =3D +- new ExtractLocalVariableFeedback(names1, offsets1, lengths1); +- List names2 =3D []; +- List offsets2 =3D [30]; +- List lengths2 =3D [6]; +- RefactoringFeedback feedback2 =3D +- new ExtractLocalVariableFeedback(names2, offsets2, lengths2); +- List resultOffsets =3D new List.from(offsets1)..addAll(offs= ets2); +- List resultLengths =3D new List.from(lengths1)..addAll(leng= ths2); +- RefactoringFeedback result =3D +- new ExtractLocalVariableFeedback(names1, resultOffsets, resultLen= gths); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(result)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_extractMethodFeedback() { +- int offset1 =3D 20; +- int length1 =3D 5; +- String returnType1 =3D 'int'; +- List names1 =3D ['a', 'b', 'c']; +- bool canCreateGetter1 =3D false; +- List parameters1 =3D +- []; +- List offsets1 =3D [10, 20]; +- List lengths1 =3D [4, 5]; +- RefactoringFeedback feedback1 =3D new ExtractMethodFeedback(offset1, = length1, +- returnType1, names1, canCreateGetter1, parameters1, offsets1, len= gths1); +- List names2 =3D ['c', 'd']; +- bool canCreateGetter2 =3D true; +- List parameters2 =3D +- []; +- List offsets2 =3D [30]; +- List lengths2 =3D [6]; +- RefactoringFeedback feedback2 =3D new ExtractMethodFeedback( +- 0, 0, '', names2, canCreateGetter2, parameters2, offsets2, length= s2); +- List resultNames =3D ['a', 'b', 'c', 'd']; +- List resultOffsets =3D new List.from(offsets1)..addAll(offs= ets2); +- List resultLengths =3D new List.from(lengths1)..addAll(leng= ths2); +- RefactoringFeedback result =3D new ExtractMethodFeedback( +- offset1, +- length1, +- returnType1, +- resultNames, +- false, +- parameters1, +- resultOffsets, +- resultLengths); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(result)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_inlineLocalVariableFeedback() { +- RefactoringFeedback feedback1 =3D new InlineLocalVariableFeedback('a'= , 2); +- RefactoringFeedback feedback2 =3D new InlineLocalVariableFeedback('a'= , 3); +- RefactoringFeedback result =3D new InlineLocalVariableFeedback('a', 5= ); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(result)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_inlineMethodFeedback() { +- RefactoringFeedback feedback1 =3D new InlineMethodFeedback('a', false= ); +- RefactoringFeedback feedback2 =3D new InlineMethodFeedback('a', false= ); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(feedback1)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_moveFileFeedback() { +- RefactoringFeedback feedback1 =3D new MoveFileFeedback(); +- RefactoringFeedback feedback2 =3D new MoveFileFeedback(); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(feedback1)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringFeedbacks_renameFeedback() { +- RefactoringFeedback feedback1 =3D new RenameFeedback(10, 0, '', ''); +- RefactoringFeedback feedback2 =3D new RenameFeedback(20, 0, '', ''); +- +- void runTest() { +- expect(merger.mergeRefactoringFeedbacks([feedback1, feedback2]), +- equals(feedback1)); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactoringKinds() { +- RefactoringKind kind1 =3D RefactoringKind.CONVERT_GETTER_TO_METHOD; +- RefactoringKind kind2 =3D RefactoringKind.EXTRACT_LOCAL_VARIABLE; +- RefactoringKind kind3 =3D RefactoringKind.INLINE_LOCAL_VARIABLE; +- RefactoringKind kind4 =3D RefactoringKind.MOVE_FILE; +- RefactoringKind kind5 =3D RefactoringKind.EXTRACT_LOCAL_VARIABLE; +- +- void runTest() { +- expect( +- merger.mergeRefactoringKinds([ +- [kind1, kind2], +- [kind3], +- [], +- [kind4, kind5] +- ]), +- unorderedEquals([kind1, kind2, kind3, kind4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeRefactorings() { +- RefactoringProblem problem(String message) =3D> +- new RefactoringProblem(RefactoringProblemSeverity.ERROR, message); +- RefactoringProblem problem1 =3D problem('1'); +- RefactoringProblem problem2 =3D problem('2'); +- RefactoringProblem problem3 =3D problem('3'); +- RefactoringProblem problem4 =3D problem('4'); +- RefactoringProblem problem5 =3D problem('5'); +- RefactoringProblem problem6 =3D problem('6'); +- +- List initialProblems1 =3D [ +- problem1, +- problem2 +- ]; +- List optionsProblems1 =3D [pr= oblem3]; +- List finalProblems1 =3D [prob= lem4]; +- RefactoringFeedback feedback1 =3D new RenameFeedback(10, 0, '', ''); +- SourceFileEdit edit1 =3D +- new SourceFileEdit('file1.dart', 11, edits: [ +- new SourceEdit(12, 2, 'w', id: 'e1'), +- new SourceEdit(13, 3, 'x'), +- ]); +- SourceChange change1 =3D +- new SourceChange('c1', edits: [edit1]); +- List potentialEdits1 =3D ['e1']; +- EditGetRefactoringResult result1 =3D new EditGetRefactoringResult( +- initialProblems1, optionsProblems1, finalProblems1, +- feedback: feedback1, change: change1, potentialEdits: potentialEd= its1); +- List initialProblems2 =3D [pr= oblem5]; +- List optionsProblems2 =3D []; +- List finalProblems2 =3D [prob= lem6]; +- RefactoringFeedback feedback2 =3D new RenameFeedback(20, 0, '', ''); +- SourceFileEdit edit2 =3D +- new SourceFileEdit('file2.dart', 21, edits: [ +- new SourceEdit(12, 2, 'y', id: 'e2'), +- new SourceEdit(13, 3, 'z'), +- ]); +- SourceChange change2 =3D +- new SourceChange('c2', edits: [edit2]); +- List potentialEdits2 =3D ['e2']; +- EditGetRefactoringResult result2 =3D new EditGetRefactoringResult( +- initialProblems2, optionsProblems2, finalProblems2, +- feedback: feedback2, change: change2, potentialEdits: potentialEd= its2); +- List mergedInitialProblems =3D [ +- problem1, +- problem2, +- problem5 +- ]; +- List mergedOptionsProblems =3D [ +- problem3 +- ]; +- List mergedFinalProblems =3D [ +- problem4, +- problem6 +- ]; +- SourceChange mergedChange =3D +- new SourceChange('c1', edits: [edit1, edit2]); +- List mergedPotentialEdits =3D ['e1', 'e2']; +- EditGetRefactoringResult mergedResult =3D new EditGetRefactoringResul= t( +- mergedInitialProblems, mergedOptionsProblems, mergedFinalProblems, +- feedback: merger.mergeRefactoringFeedbacks([feedback1, feedback2]= ), +- change: mergedChange, +- potentialEdits: mergedPotentialEdits); +- +- void runTest() { +- expect(merger.mergeRefactorings([result1, result2]), mergedResult); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_mergeSourceChanges() { +- SourceChange kind1 =3D new SourceChange(''); +- SourceChange kind2 =3D new SourceChange(''); +- SourceChange kind3 =3D new SourceChange(''); +- SourceChange kind4 =3D new SourceChange(''); +- +- void runTest() { +- expect( +- merger.mergeSourceChanges([ +- [kind1, kind2], +- [], +- [kind3], +- [kind4] +- ]), +- unorderedEquals([kind1, kind2, kind3, kind4])); +- } +- +- runTest(); +- runTest(); +- } +- +- void test_overlaps_false_nested_left() { +- expect(merger.overlaps(3, 5, 1, 7, allowNesting: true), isFalse); +- } +- +- void test_overlaps_false_nested_right() { +- expect(merger.overlaps(1, 7, 3, 5, allowNesting: true), isFalse); +- } +- +- void test_overlaps_false_onLeft() { +- expect(merger.overlaps(1, 3, 5, 7), isFalse); +- } +- +- void test_overlaps_false_onRight() { +- expect(merger.overlaps(5, 7, 1, 3), isFalse); +- } +- +- void test_overlaps_true_nested_left() { +- expect(merger.overlaps(3, 5, 1, 7), isTrue); +- } +- +- void test_overlaps_true_nested_right() { +- expect(merger.overlaps(1, 7, 3, 5), isTrue); +- } +- +- void test_overlaps_true_onLeft() { +- expect(merger.overlaps(1, 5, 3, 7), isTrue); +- } +- +- void test_overlaps_true_onRight() { +- expect(merger.overlaps(3, 7, 1, 5), isTrue); +- } +-} +diff --git a/pkg/analysis_server/test/src/plugin/test_all.dart b/pkg/analy= sis_server/test/src/plugin/test_all.dart +deleted file mode 100644 +index a1f75646d00..00000000000 +--- a/pkg/analysis_server/test/src/plugin/test_all.dart ++++ /dev/null +@@ -1,27 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'notification_manager_test.dart' as notification_manager_test; +-import 'plugin_locator_test.dart' as plugin_locator_test; +-import 'plugin_manager_test.dart' as plugin_manager_test; +-import 'plugin_watcher_test.dart' as plugin_watcher_test; +-import 'request_converter_test.dart' as request_converter_test; +-import 'result_collector_test.dart' as result_collector_test; +-import 'result_converter_test.dart' as result_converter_test; +-import 'result_merger_test.dart' as result_merger_test; +- +-main() { +- defineReflectiveSuite(() { +- notification_manager_test.main(); +- plugin_locator_test.main(); +- plugin_manager_test.main(); +- plugin_watcher_test.main(); +- request_converter_test.main(); +- result_collector_test.main(); +- result_converter_test.main(); +- result_merger_test.main(); +- }); +-} +diff --git a/pkg/analysis_server/test/src/test_all.dart b/pkg/analysis_ser= ver/test/src/test_all.dart +deleted file mode 100644 +index 70858b061d0..00000000000 +--- a/pkg/analysis_server/test/src/test_all.dart ++++ /dev/null +@@ -1,24 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'computer/test_all.dart' as computer_all; +-import 'domain_abstract_test.dart' as domain_abstract_test; +-import 'plugin/test_all.dart' as plugin_all; +-import 'utilities/test_all.dart' as utilities_all; +-import 'watch_manager_test.dart' as watch_manager_test; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- defineReflectiveSuite(() { +- computer_all.main(); +- domain_abstract_test.main(); +- plugin_all.main(); +- utilities_all.main(); +- watch_manager_test.main(); +- }, name: 'src'); +-} +diff --git a/pkg/analysis_server/test/src/utilities/flutter_test.dart b/pk= g/analysis_server/test/src/utilities/flutter_test.dart +deleted file mode 100644 +index 26e38eb9a81..00000000000 +--- a/pkg/analysis_server/test/src/utilities/flutter_test.dart ++++ /dev/null +@@ -1,156 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analysis_server/src/utilities/flutter.dart'; +-import 'package:analyzer/dart/ast/ast.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../../abstract_single_unit.dart'; +-import 'flutter_util.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(FlutterTest); +- }); +-} +- +-@reflectiveTest +-class FlutterTest extends AbstractSingleUnitTest { +- @override +- void setUp() { +- super.setUp(); +- Folder libFolder =3D configureFlutterPackage(provider); +- packageMap['flutter'] =3D [libFolder]; +- } +- +- test_getWidgetPresentationText_icon() async { +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D const Icon(Icons.book); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect(getWidgetPresentationText(w), "Icon(Icons.book)"); +- } +- +- test_getWidgetPresentationText_icon_withoutArguments() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D const Icon(); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect(getWidgetPresentationText(w), "Icon"); +- } +- +- test_getWidgetPresentationText_notWidget() async { +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D new Object(); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect(getWidgetPresentationText(w), isNull); +- } +- +- test_getWidgetPresentationText_text() async { +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D const Text('foo'); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect(getWidgetPresentationText(w), "Text('foo')"); +- } +- +- test_getWidgetPresentationText_text_longText() async { +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D const Text('${'abc' * 100}'); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect( +- getWidgetPresentationText(w), "Text('abcabcabcabcab...cabcabcabca= bc')"); +- } +- +- test_getWidgetPresentationText_text_withoutArguments() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D const Text(); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect(getWidgetPresentationText(w), "Text"); +- } +- +- test_getWidgetPresentationText_unresolved() async { +- verifyNoTestUnitErrors =3D false; +- await resolveTestUnit(''' +-import 'package:flutter/material.dart'; +-var w =3D new Foo(); +-'''); +- var w =3D _getTopVariableCreation('w'); +- expect(getWidgetPresentationText(w), isNull); +- } +- +- test_isWidget() async { +- await resolveTestUnit(''' +-import 'package:flutter/widgets.dart'; +- +-class MyStatelessWidget extends StatelessWidget {} +-class MyStatefulWidget extends StatefulWidget {} +-class MyContainer extends Container {} +-class NotFlutter {} +-class NotWidget extends State {} +-'''); +- var myStatelessWidget =3D testUnitElement.getType('MyStatelessWidget'= ); +- expect(isWidget(myStatelessWidget), isTrue); +- +- var myStatefulWidget =3D testUnitElement.getType('MyStatefulWidget'); +- expect(isWidget(myStatefulWidget), isTrue); +- +- var myContainer =3D testUnitElement.getType('MyContainer'); +- expect(isWidget(myContainer), isTrue); +- +- var notFlutter =3D testUnitElement.getType('NotFlutter'); +- expect(isWidget(notFlutter), isFalse); +- +- var notWidget =3D testUnitElement.getType('NotWidget'); +- expect(isWidget(notWidget), isFalse); +- } +- +- test_isWidgetCreation() async { +- await resolveTestUnit(''' +-import 'package:flutter/widgets.dart'; +- +-var a =3D new Object(); +-var b =3D new Text('bbb'); +-'''); +- InstanceCreationExpression a =3D _getTopVariableCreation('a'); +- expect(isWidgetCreation(a), isFalse); +- +- InstanceCreationExpression b =3D _getTopVariableCreation('b'); +- expect(isWidgetCreation(b), isTrue); +- } +- +- VariableDeclaration _getTopVariable(String name, [CompilationUnit unit]= ) { +- unit ??=3D testUnit; +- for (var topDeclaration in unit.declarations) { +- if (topDeclaration is TopLevelVariableDeclaration) { +- for (var variable in topDeclaration.variables.variables) { +- if (variable.name.name =3D=3D name) { +- return variable; +- } +- } +- } +- } +- fail('Not found $name in $unit'); +- return null; +- } +- +- InstanceCreationExpression _getTopVariableCreation(String name, +- [CompilationUnit unit]) { +- return _getTopVariable(name, unit).initializer +- as InstanceCreationExpression; +- } +-} +diff --git a/pkg/analysis_server/test/src/utilities/flutter_util.dart b/pk= g/analysis_server/test/src/utilities/flutter_util.dart +deleted file mode 100644 +index 5ff909a0c2d..00000000000 +--- a/pkg/analysis_server/test/src/utilities/flutter_util.dart ++++ /dev/null +@@ -1,205 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +- +-String flutterPkgLibPath =3D '/packages/flutter/lib'; +- +-String get flutter_framework_code =3D> ''' +-class Widget {} +-class RenderObjectWidget extends Widget {} +-class StatelessWidget extends Widget {} +-abstract class StatefulWidget extends Widget { } +-class SingleChildRenderObjectWidget extends RenderObjectWidget {} +-class Transform extends SingleChildRenderObjectWidget {} +-class ClipRect extends SingleChildRenderObjectWidget { ClipRect.rect(){} } +-class AspectRatio extends SingleChildRenderObjectWidget {} +-class Container extends StatelessWidget { Container({child: null, width: = null, height: null}){}} +-class Center extends StatelessWidget { Center({child: null, key: null}){}} +-class DefaultTextStyle extends StatelessWidget { DefaultTextStyle({child:= null}){}} +-class Row extends Widget { Row({List children: null, key: null}){= }} +-class GestureDetector extends SingleChildRenderObjectWidget { GestureDete= ctor({child: null, onTap: null}){}} +-class AppBar extends StatefulWidget implements PreferredSizeWidget { AppB= ar(title: null, color: null, key: null) } +-class Scaffold extends Widget { Scaffold({body: null, PreferredSizeWidget= appBar: null}){}} +-class PreferredSizeWidget implements Widget {} +-'''; +- +-/** +- * Add some Flutter libraries and types to the given [provider] and return +- * the `lib` folder. +- */ +-Folder configureFlutterPackage(MemoryResourceProvider provider) { +- File newFile(String path, String content) =3D> +- provider.newFile(provider.convertPath(path), content ?? ''); +- +- Folder newFolder(String path) =3D> +- provider.newFolder(provider.convertPath(path)); +- +- newFile('/flutter/lib/material.dart', r''' +-export 'widgets.dart'; +-export 'src/material/icons.dart'; +-'''); +- +- newFile('/flutter/lib/widgets.dart', r''' +-export 'src/widgets/basic.dart'; +-export 'src/widgets/container.dart'; +-export 'src/widgets/framework.dart'; +-export 'src/widgets/icon.dart'; +-export 'src/widgets/text.dart'; +-'''); +- +- void createSrcMaterial() { +- newFile('/flutter/lib/src/material/icons.dart', r''' +-import 'package:flutter/widgets.dart'; +- +-class Icons { +- static const IconData alarm =3D +- const IconData(0xe855, fontFamily: 'MaterialIcons'); +- static const IconData book =3D +- const IconData(0xe865, fontFamily: 'MaterialIcons'); +- Icons._(); +-} +-'''); +- } +- +- void createSrcWidgets() { +- newFile('/flutter/lib/src/widgets/basic.dart', r''' +-import 'framework.dart'; +- +-class Column extends Flex { +- Column({ +- Key key, +- List children: const [], +- }); +-} +- +-class Row extends Flex { +- Row({ +- Key key, +- List children: const [], +- }); +-} +- +-class Flex extends Widget { +- Flex({ +- Key key, +- List children: const [], +- }); +-} +-'''); +- +- newFile('/flutter/lib/src/widgets/container.dart', r''' +-import 'framework.dart'; +- +-class Container extends StatelessWidget { +- final Widget child; +- Container({ +- Key key, +- double width, +- double height, +- this.child, +- }) +- : super(key: key); +- +- @override +- Widget build(BuildContext context) =3D> child; +-} +-'''); +- +- newFile('/flutter/lib/src/widgets/framework.dart', r''' +-typedef void VoidCallback(); +- +-abstract class BuildContext { +- Widget get widget; +-} +- +-abstract class Key { +- const factory Key(String value) =3D ValueKey; +- +- const Key._(); +-} +- +-abstract class LocalKey extends Key { +- const LocalKey() : super._(); +-} +- +-abstract class State { +- BuildContext get context =3D> null; +- +- T get widget =3D> null; +- +- Widget build(BuildContext context) {} +- +- void dispose() {} +- +- void setState(VoidCallback fn) {} +-} +- +-abstract class StatefulWidget extends Widget { +- const StatefulWidget({Key key}) : super(key: key); +- +- State createState() =3D> null +-} +- +-abstract class StatelessWidget extends Widget { +- const StatelessWidget({Key key}) : super(key: key); +- +- Widget build(BuildContext context) =3D> null; +-} +- +-class ValueKey extends LocalKey { +- final T value; +- +- const ValueKey(this.value); +-} +- +-class Widget { +- final Key key; +- +- const Widget({this.key}); +-} +-'''); +- +- newFile('/flutter/lib/src/widgets/icon.dart', r''' +-import 'framework.dart'; +- +-class Icon extends StatelessWidget { +- final IconData icon; +- const Icon( +- this.icon, { +- Key key, +- }) +- : super(key: key); +-} +- +-class IconData { +- final int codePoint; +- final String fontFamily; +- const IconData( +- this.codePoint, { +- this.fontFamily, +- }); +-} +-'''); +- +- newFile('/flutter/lib/src/widgets/text.dart', r''' +-import 'framework.dart'; +- +-class Text extends StatelessWidget { +- final String data; +- const Text( +- this.data, { +- Key key, +- }) +- : super(key: key); +-} +-'''); +- } +- +- createSrcMaterial(); +- createSrcWidgets(); +- +- return newFolder('/flutter/lib'); +-} +diff --git a/pkg/analysis_server/test/src/utilities/profiling_test.dart b/= pkg/analysis_server/test/src/utilities/profiling_test.dart +deleted file mode 100644 +index 4906c4bc7b7..00000000000 +--- a/pkg/analysis_server/test/src/utilities/profiling_test.dart ++++ /dev/null +@@ -1,30 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:analysis_server/src/utilities/profiling.dart'; +-import 'package:test/test.dart'; +- +-main() { +- group('ProcessProfiler', () { +- // Skip on windows. +- if (Platform.isWindows) { +- return; +- } +- +- test('getProfilerForPlatform', () async { +- expect(ProcessProfiler.getProfilerForPlatform(), isNotNull); +- }); +- +- test('getProcessUsage', () async { +- ProcessProfiler profiler =3D ProcessProfiler.getProfilerForPlatform= (); +- UsageInfo info =3D await profiler.getProcessUsage(pid); +- +- expect(info, isNotNull); +- expect(info.cpuPercentage, greaterThanOrEqualTo(0.0)); +- expect(info.memoryKB, greaterThanOrEqualTo(0)); +- }); +- }); +-} +diff --git a/pkg/analysis_server/test/src/utilities/test_all.dart b/pkg/an= alysis_server/test/src/utilities/test_all.dart +deleted file mode 100644 +index cf5d6fca361..00000000000 +--- a/pkg/analysis_server/test/src/utilities/test_all.dart ++++ /dev/null +@@ -1,15 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import 'flutter_test.dart' as flutter_test; +-import 'profiling_test.dart' as profiling_test; +- +-main() { +- defineReflectiveSuite(() { +- flutter_test.main(); +- profiling_test.main(); +- }); +-} +diff --git a/pkg/analysis_server/test/src/watch_manager_test.dart b/pkg/an= alysis_server/test/src/watch_manager_test.dart +deleted file mode 100644 +index 19b72c91f58..00000000000 +--- a/pkg/analysis_server/test/src/watch_manager_test.dart ++++ /dev/null +@@ -1,350 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +- +-import 'package:analysis_server/src/watch_manager.dart'; +-import 'package:analyzer/file_system/file_system.dart'; +-import 'package:analyzer/file_system/memory_file_system.dart'; +-import 'package:test/test.dart'; +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +-import 'package:watcher/watcher.dart'; +- +-import '../mocks.dart'; +- +-main() { +- defineReflectiveSuite(() { +- defineReflectiveTests(WatchManagerTest); +- defineReflectiveTests(WatchNodeTest); +- }); +-} +- +-/** +- * Tokens that can be used for testing purposes. +- */ +-class Token { +- /** +- * A name used for debugging. +- */ +- final String name; +- +- /** +- * Initialize a newly created token to have the given name. +- */ +- Token(this.name); +- +- @override +- String toString() =3D> name; +-} +- +-/** +- * A listener that captures the state of watch events so that they can be +- * tested. +- */ +-class WatchListener { +- /** +- * The event that was passed to the listener method. +- */ +- WatchEvent event; +- +- /** +- * The tokens that were passed to the listener method. +- */ +- List tokens; +- +- /** +- * Clear the state so that we can distinguish between not receiving an = event +- * and receiving the wrong event. +- */ +- void clear() { +- this.event =3D null; +- this.tokens =3D null; +- } +- +- /** +- * The listener method. +- */ +- void handleWatchEvent(WatchEvent event, List tokens) { +- this.event =3D event; +- this.tokens =3D tokens; +- } +-} +- +-@reflectiveTest +-class WatchManagerTest { +- MemoryResourceProvider provider; +- WatchListener listener; +- WatchManager manager; +- +- void setUp() { +- provider =3D new MemoryResourceProvider(); +- listener =3D new WatchListener(); +- manager =3D new WatchManager(provider, listener.handleWatchEve= nt); +- } +- +- Future test_addFolder_folderAndSubfolder() async { +- Folder topFolder =3D provider.getFolder('/a/b'); +- Folder childFolder =3D provider.getFolder('/a/b/c/d'); +- Token topToken =3D new Token('topToken'); +- Token childToken =3D new Token('childToken'); +- manager.addFolder(topFolder, topToken); +- manager.addFolder(childFolder, childToken); +- +- File newFile1 =3D provider.newFile('/a/b/c/lib.dart', ''); +- await _expectEvent(ChangeType.ADD, newFile1.path, [topToken]); +- +- File newFile2 =3D provider.newFile('/a/b/c/d/lib.dart', ''); +- return _expectEvent(ChangeType.ADD, newFile2.path, [topToken, childTo= ken]); +- } +- +- Future test_addFolder_singleFolder_multipleTokens() { +- Folder folder =3D provider.getFolder('/a/b'); +- Token token1 =3D new Token('token1'); +- Token token2 =3D new Token('token2'); +- manager.addFolder(folder, token1); +- manager.addFolder(folder, token2); +- +- File newFile =3D provider.newFile('/a/b/lib.dart', ''); +- return _expectEvent(ChangeType.ADD, newFile.path, [token1, token2]); +- } +- +- Future test_addFolder_singleFolder_singleToken() async { +- Folder folder =3D provider.getFolder('/a/b'); +- Token token =3D new Token('token'); +- manager.addFolder(folder, token); +- +- Folder newFolder =3D provider.newFolder('/a/b/c'); +- await _expectEvent(ChangeType.ADD, newFolder.path, [token]); +- +- File newFile =3D provider.newFile('/a/b/c/lib.dart', ''); +- return _expectEvent(ChangeType.ADD, newFile.path, [token]); +- } +- +- Future test_addFolder_unrelatedFolders() async { +- Folder folder1 =3D provider.getFolder('/a/b'); +- Folder folder2 =3D provider.getFolder('/c/d'); +- Token token1 =3D new Token('token1'); +- Token token2 =3D new Token('token2'); +- manager.addFolder(folder1, token1); +- manager.addFolder(folder2, token2); +- +- File newFile1 =3D provider.newFile('/a/b/lib.dart', ''); +- await _expectEvent(ChangeType.ADD, newFile1.path, [token1]); +- +- File newFile2 =3D provider.newFile('/c/d/lib.dart', ''); +- return _expectEvent(ChangeType.ADD, newFile2.path, [token2]); +- } +- +- void test_creation() { +- expect(manager, isNotNull); +- } +- +- Future test_removeFolder_multipleTokens() { +- Folder folder =3D provider.getFolder('/a/b'); +- Token token1 =3D new Token('token1'); +- Token token2 =3D new Token('token2'); +- manager.addFolder(folder, token1); +- manager.addFolder(folder, token2); +- manager.removeFolder(folder, token2); +- +- File newFile =3D provider.newFile('/a/b/lib.dart', ''); +- return _expectEvent(ChangeType.ADD, newFile.path, [token1]); +- } +- +- Future test_removeFolder_withChildren() async { +- Folder topFolder =3D provider.getFolder('/a/b'); +- Folder childFolder =3D provider.getFolder('/a/b/c/d'); +- Token topToken =3D new Token('topToken'); +- Token childToken =3D new Token('childToken'); +- manager.addFolder(topFolder, topToken); +- manager.addFolder(childFolder, childToken); +- manager.removeFolder(topFolder, topToken); +- +- File newFile =3D provider.newFile('/a/b/c/d/lib.dart', ''); +- await _expectEvent(ChangeType.ADD, newFile.path, [childToken]); +- +- provider.newFile('/a/b/lib.dart', ''); +- return _expectNoEvent(); +- } +- +- Future test_removeFolder_withNoChildren() { +- Folder folder =3D provider.getFolder('/a/b'); +- Token token =3D new Token('token'); +- manager.addFolder(folder, token); +- manager.removeFolder(folder, token); +- +- provider.newFile('/a/b/lib.dart', ''); +- return _expectNoEvent(); +- } +- +- Future _expectEvent(ChangeType expectedType, String expectedPath, +- List expectedTokens) async { +- await pumpEventQueue(); +- WatchEvent event =3D listener.event; +- expect(event, isNotNull); +- expect(event.type, expectedType); +- expect(event.path, expectedPath); +- expect(listener.tokens, unorderedEquals(expectedTokens)); +- listener.clear(); +- } +- +- Future _expectNoEvent() async { +- await pumpEventQueue(); +- expect(listener.event, isNull); +- expect(listener.tokens, isNull); +- } +-} +- +-@reflectiveTest +-class WatchNodeTest { +- MemoryResourceProvider provider =3D new MemoryResourceProvider(); +- +- void test_creation_folder() { +- Folder folder =3D provider.getFolder('/a/b'); +- WatchNode node =3D new WatchNode(folder); +- expect(node, isNotNull); +- expect(node.children, isEmpty); +- expect(node.folder, folder); +- expect(node.parent, isNull); +- expect(node.subscription, isNull); +- expect(node.tokens, isEmpty); +- } +- +- void test_creation_noFolder() { +- WatchNode node =3D new WatchNode(null); +- expect(node, isNotNull); +- expect(node.children, isEmpty); +- expect(node.folder, isNull); +- expect(node.parent, isNull); +- expect(node.subscription, isNull); +- expect(node.tokens, isEmpty); +- } +- +- void test_delete_nested_child() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- WatchNode grandchildNode =3D new WatchNode(provider.getFolder('/a/b/c= /d/e')); +- rootNode.insert(topNode); +- rootNode.insert(childNode); +- rootNode.insert(grandchildNode); +- +- childNode.delete(); +- expect(rootNode.children, equals([topNode])); +- expect(topNode.children, equals([grandchildNode])); +- expect(topNode.parent, rootNode); +- expect(grandchildNode.parent, topNode); +- } +- +- void test_delete_nested_noChild() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- rootNode.insert(topNode); +- rootNode.insert(childNode); +- +- childNode.delete(); +- expect(rootNode.children, equals([topNode])); +- expect(topNode.children, isEmpty); +- expect(topNode.parent, rootNode); +- } +- +- void test_delete_top_child() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- rootNode.insert(topNode); +- rootNode.insert(childNode); +- +- topNode.delete(); +- expect(rootNode.children, equals([childNode])); +- expect(childNode.parent, rootNode); +- } +- +- void test_delete_top_noChild() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- rootNode.insert(topNode); +- +- topNode.delete(); +- expect(rootNode.children, isEmpty); +- } +- +- void test_findParent_childOfLeaf() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- rootNode.insert(topNode); +- +- expect(rootNode.findParent('/a/b/c'), topNode); +- } +- +- void test_findParent_childOfNonLeaf() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- rootNode.insert(topNode); +- rootNode.insert(childNode); +- +- expect(rootNode.findParent('/a/b/c'), topNode); +- } +- +- void test_findParent_noMatch() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- rootNode.insert(topNode); +- +- expect(rootNode.findParent('/c/d'), rootNode); +- } +- +- void test_insert_intermediate_afterParentAndChild() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- WatchNode intermediateNode =3D new WatchNode(provider.getFolder('/a/b= /c')); +- +- rootNode.insert(topNode); +- rootNode.insert(childNode); +- rootNode.insert(intermediateNode); +- expect(topNode.parent, rootNode); +- expect(topNode.children, equals([intermediateNode])); +- expect(intermediateNode.parent, topNode); +- expect(intermediateNode.children, equals([childNode])); +- expect(childNode.parent, intermediateNode); +- expect(childNode.children, isEmpty); +- } +- +- void test_insert_nested_afterParent() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- +- rootNode.insert(topNode); +- rootNode.insert(childNode); +- expect(childNode.parent, topNode); +- expect(childNode.children, isEmpty); +- expect(topNode.children, equals([childNode])); +- } +- +- void test_insert_nested_beforeParent() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- WatchNode childNode =3D new WatchNode(provider.getFolder('/a/b/c/d')); +- +- rootNode.insert(childNode); +- rootNode.insert(topNode); +- expect(childNode.parent, topNode); +- expect(childNode.children, isEmpty); +- expect(topNode.children, equals([childNode])); +- } +- +- void test_insert_top() { +- WatchNode rootNode =3D new WatchNode(null); +- WatchNode topNode =3D new WatchNode(provider.getFolder('/a/b')); +- +- rootNode.insert(topNode); +- expect(rootNode.children, equals([topNode])); +- expect(topNode.parent, rootNode); +- expect(topNode.children, isEmpty); +- } +-} +diff --git a/pkg/analysis_server/test/stress/replay/operation.dart b/pkg/a= nalysis_server/test/stress/replay/operation.dart +deleted file mode 100644 +index dbacce9f95a..00000000000 +--- a/pkg/analysis_server/test/stress/replay/operation.dart ++++ /dev/null +@@ -1,80 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Operations to be performed during the simulation. +- */ +-import '../utilities/server.dart'; +- +-/** +- * An operation that will send an 'analysis.updateContent' request. +- */ +-class Analysis_UpdateContent extends ServerOperation { +- /** +- * The path of the file whose content is being updated. +- */ +- final String filePath; +- +- /** +- * The overlay used to update the content. +- */ +- final dynamic overlay; +- +- /** +- * Initialize an operation to send an 'analysis.updateContent' request = with +- * the given [filePath] and [overlay] as parameters. +- */ +- Analysis_UpdateContent(this.filePath, this.overlay); +- +- @override +- void perform(Server server) { +- server.sendAnalysisUpdateContent({filePath: overlay}); +-// if (overlay is ChangeContentOverlay) { +-// List edits =3D (overlay as ChangeContentOverlay).edit= s; +-// if (edits.length =3D=3D 1) { +-// SourceEdit edit =3D edits[0]; +-// if (edit.replacement.endsWith('.')) { +-// int offset =3D edit.offset + edit.replacement.length - 1; +-// server.sendCompletionGetSuggestions(filePath, offset); +-// } +-// } +-// } +- } +-} +- +-/** +- * An operation that will send a 'completion.getSuggestions' request. +- */ +-class Completion_GetSuggestions extends ServerOperation { +- /** +- * The path of the file in which completions are being requested. +- */ +- final String filePath; +- +- /** +- * The offset at which completions are being requested. +- */ +- final int offset; +- +- /** +- * Initialize an operation to send a 'completion.getSuggestions' reques= t with +- * the given [filePath] and [offset] as parameters. +- */ +- Completion_GetSuggestions(this.filePath, this.offset); +- +- @override +- void perform(Server server) { +- server.sendCompletionGetSuggestions(filePath, offset); +- } +-} +- +-/** +- * An operation to be performed during the simulation. +- */ +-abstract class ServerOperation { +- /** +- * Perform this operation by communicating with the given [server]. +- */ +- void perform(Server server); +-} +diff --git a/pkg/analysis_server/test/stress/replay/replay.dart b/pkg/anal= ysis_server/test/stress/replay/replay.dart +deleted file mode 100644 +index 36ef8fddc90..00000000000 +--- a/pkg/analysis_server/test/stress/replay/replay.dart ++++ /dev/null +@@ -1,707 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * A stress test for the analysis server. +- */ +-import 'dart:async'; +-import 'dart:io'; +-import 'dart:math' as math; +- +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer/dart/ast/token.dart'; +-import 'package:analyzer/error/listener.dart' as error; +-import 'package:analyzer/src/dart/scanner/reader.dart'; +-import 'package:analyzer/src/dart/scanner/scanner.dart'; +-import 'package:analyzer/src/generated/java_engine.dart'; +-import 'package:analyzer/src/generated/source.dart'; +-import 'package:analyzer/src/util/glob.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:args/args.dart'; +-import 'package:path/path.dart' as path; +- +-import '../utilities/git.dart'; +-import '../utilities/logger.dart'; +-import '../utilities/server.dart'; +-import 'operation.dart'; +- +-/** +- * Run the simulation based on the given command-line [arguments]. +- */ +-Future main(List arguments) async { +- Driver driver =3D new Driver(); +- await driver.run(arguments); +-} +- +-/** +- * The driver class that runs the simulation. +- */ +-class Driver { +- /** +- * The value of the [OVERLAY_STYLE_OPTION_NAME] indicating that modific= ations +- * to a file should be represented by an add overlay, followed by zero = or more +- * change overlays, followed by a remove overlay. +- */ +- static String CHANGE_OVERLAY_STYLE =3D 'change'; +- +- /** +- * The name of the command-line flag that will print help text. +- */ +- static String HELP_FLAG_NAME =3D 'help'; +- +- /** +- * The value of the [OVERLAY_STYLE_OPTION_NAME] indicating that modific= ations +- * to a file should be represented by an add overlay, followed by zero = or more +- * additional add overlays, followed by a remove overlay. +- */ +- static String MULTIPLE_ADD_OVERLAY_STYLE =3D 'multipleAdd'; +- +- /** +- * The name of the command-line option used to specify the style of +- * interaction to use when making `analysis.updateContent` requests. +- */ +- static String OVERLAY_STYLE_OPTION_NAME =3D 'overlay-style'; +- +- /** +- * The name of the pubspec file. +- */ +- static const String PUBSPEC_FILE_NAME =3D 'pubspec.yaml'; +- +- /** +- * The name of the branch used to clean-up after making temporary chang= es. +- */ +- static const String TEMP_BRANCH_NAME =3D 'temp'; +- +- /** +- * The name of the command-line flag that will cause verbose output to = be +- * produced. +- */ +- static String VERBOSE_FLAG_NAME =3D 'verbose'; +- +- /** +- * The style of interaction to use for analysis.updateContent requests. +- */ +- OverlayStyle overlayStyle; +- +- /** +- * The absolute path of the repository. +- */ +- String repositoryPath; +- +- /** +- * The absolute paths to the analysis roots. +- */ +- List analysisRoots; +- +- /** +- * The git repository. +- */ +- GitRepository repository; +- +- /** +- * The connection to the analysis server. +- */ +- Server server; +- +- /** +- * A list of the glob patterns used to identify the files being analyze= d by +- * the server. +- */ +- List fileGlobs; +- +- /** +- * An object gathering statistics about the simulation. +- */ +- Statistics statistics; +- +- /** +- * A flag indicating whether verbose output should be provided. +- */ +- bool verbose =3D false; +- +- /** +- * The logger to which verbose logging data will be written. +- */ +- Logger logger; +- +- /** +- * Initialize a newly created driver. +- */ +- Driver() { +- statistics =3D new Statistics(this); +- } +- +- /** +- * Allow the output from the server to be read and processed. +- */ +- Future readServerOutput() async { +- await new Future.delayed(new Duration(milliseconds: 2)); +- } +- +- /** +- * Run the simulation based on the given command-line arguments ([args]= ). +- */ +- Future run(List args) async { +- // +- // Process the command-line arguments. +- // +- if (!_processCommandLine(args)) { +- return null; +- } +- if (verbose) { +- stdout.writeln(); +- stdout.writeln('-' * 80); +- stdout.writeln(); +- } +- // +- // Simulate interactions with the server. +- // +- await _runSimulation(); +- // +- // Print out statistics gathered while performing the simulation. +- // +- if (verbose) { +- stdout.writeln(); +- stdout.writeln('-' * 80); +- } +- stdout.writeln(); +- statistics.print(); +- if (verbose) { +- stdout.writeln(); +- server.printStatistics(); +- } +- exit(0); +- return null; +- } +- +- /** +- * Create and return a parser that can be used to parse the command-line +- * arguments. +- */ +- ArgParser _createArgParser() { +- ArgParser parser =3D new ArgParser(); +- parser.addFlag(HELP_FLAG_NAME, +- abbr: 'h', +- help: 'Print usage information', +- defaultsTo: false, +- negatable: false); +- parser.addOption(OVERLAY_STYLE_OPTION_NAME, +- help: +- 'The style of interaction to use for analysis.updateContent r= equests', +- allowed: [CHANGE_OVERLAY_STYLE, MULTIPLE_ADD_OVERLAY_STYLE], +- allowedHelp: { +- CHANGE_OVERLAY_STYLE: ' * ', +- MULTIPLE_ADD_OVERLAY_STYLE: '+ ' +- }, +- defaultsTo: 'change'); +- parser.addFlag(VERBOSE_FLAG_NAME, +- abbr: 'v', +- help: 'Produce verbose output for debugging', +- defaultsTo: false, +- negatable: false); +- return parser; +- } +- +- /** +- * Add source edits to the given [fileEdit] based on the given [blobDif= f]. +- */ +- void _createSourceEdits(FileEdit fileEdit, BlobDiff blobDiff) { +- LineInfo info =3D fileEdit.lineInfo; +- for (DiffHunk hunk in blobDiff.hunks) { +- int srcStart =3D info.getOffsetOfLine(hunk.srcLine); +- int srcEnd =3D info.getOffsetOfLine( +- math.min(hunk.srcLine + hunk.removeLines.length, info.lineCount= - 1)); +- String addedText =3D _join(hunk.addLines); +- // +- // Create the source edits. +- // +- List breakOffsets =3D _getBreakOffsets(addedText); +- int breakCount =3D breakOffsets.length; +- List sourceEdits =3D []; +- if (breakCount =3D=3D 0) { +- sourceEdits +- .add(new SourceEdit(srcStart, srcEnd - srcStart + 1, addedTex= t)); +- } else { +- int previousOffset =3D breakOffsets[0]; +- String string =3D addedText.substring(0, previousOffset); +- sourceEdits +- .add(new SourceEdit(srcStart, srcEnd - srcStart + 1, string)); +- String reconstruction =3D string; +- for (int i =3D 1; i < breakCount; i++) { +- int offset =3D breakOffsets[i]; +- string =3D addedText.substring(previousOffset, offset); +- reconstruction +=3D string; +- sourceEdits.add(new SourceEdit(srcStart + previousOffset, 0, st= ring)); +- previousOffset =3D offset; +- } +- string =3D addedText.substring(previousOffset); +- reconstruction +=3D string; +- sourceEdits.add(new SourceEdit(srcStart + previousOffset, 0, stri= ng)); +- if (reconstruction !=3D addedText) { +- throw new AssertionError(); +- } +- } +- fileEdit.addSourceEdits(sourceEdits); +- } +- } +- +- /** +- * Return the absolute paths of all of the pubspec files in all of the +- * analysis roots. +- */ +- Iterable _findPubspecsInAnalysisRoots() { +- List pubspecFiles =3D []; +- for (String directoryPath in analysisRoots) { +- Directory directory =3D new Directory(directoryPath); +- List children =3D +- directory.listSync(recursive: true, followLinks: false); +- for (FileSystemEntity child in children) { +- String filePath =3D child.path; +- if (path.basename(filePath) =3D=3D PUBSPEC_FILE_NAME) { +- pubspecFiles.add(filePath); +- } +- } +- } +- return pubspecFiles; +- } +- +- /** +- * Return a list of offsets into the given [text] that represent good p= laces +- * to break the text when building edits. +- */ +- List _getBreakOffsets(String text) { +- List breakOffsets =3D []; +- Scanner scanner =3D new Scanner(null, new CharSequenceReader(text), +- error.AnalysisErrorListener.NULL_LISTENER); +- Token token =3D scanner.tokenize(); +- // TODO(brianwilkerson) Randomize. Sometimes add zero (0) as a break = point. +- while (token.type !=3D TokenType.EOF) { +- // TODO(brianwilkerson) Break inside comments? +-// Token comment =3D token.precedingComments; +- int offset =3D token.offset; +- int length =3D token.length; +- breakOffsets.add(offset); +- if (token.type =3D=3D TokenType.IDENTIFIER && length > 3) { +- breakOffsets.add(offset + (length ~/ 2)); +- } +- token =3D token.next; +- } +- return breakOffsets; +- } +- +- /** +- * Join the given [lines] into a single string. +- */ +- String _join(List lines) { +- StringBuffer buffer =3D new StringBuffer(); +- for (int i =3D 0; i < lines.length; i++) { +- buffer.writeln(lines[i]); +- } +- return buffer.toString(); +- } +- +- /** +- * Process the command-line [arguments]. Return `true` if the simulation +- * should be run. +- */ +- bool _processCommandLine(List args) { +- ArgParser parser =3D _createArgParser(); +- ArgResults results; +- try { +- results =3D parser.parse(args); +- } catch (exception) { +- _showUsage(parser); +- return false; +- } +- +- if (results[HELP_FLAG_NAME]) { +- _showUsage(parser); +- return false; +- } +- +- String overlayStyleValue =3D results[OVERLAY_STYLE_OPTION_NAME]; +- if (overlayStyleValue =3D=3D CHANGE_OVERLAY_STYLE) { +- overlayStyle =3D OverlayStyle.change; +- } else if (overlayStyleValue =3D=3D MULTIPLE_ADD_OVERLAY_STYLE) { +- overlayStyle =3D OverlayStyle.multipleAdd; +- } +- +- if (results[VERBOSE_FLAG_NAME]) { +- verbose =3D true; +- logger =3D new Logger(stdout); +- } +- +- List arguments =3D results.rest; +- if (arguments.length < 2) { +- _showUsage(parser); +- return false; +- } +- repositoryPath =3D path.normalize(arguments[0]); +- repository =3D new GitRepository(repositoryPath, logger: logger); +- +- analysisRoots =3D arguments +- .sublist(1) +- .map((String analysisRoot) =3D> path.normalize(analysisRoot)) +- .toList(); +- for (String analysisRoot in analysisRoots) { +- if (repositoryPath !=3D analysisRoot && +- !path.isWithin(repositoryPath, analysisRoot)) { +- _showUsage(parser, +- 'Analysis roots must be contained within the repository: $ana= lysisRoot'); +- return false; +- } +- } +- return true; +- } +- +- /** +- * Replay the changes in each commit. +- */ +- Future _replayChanges() async { +- // +- // Get the revision history of the repo. +- // +- LinearCommitHistory history =3D repository.getCommitHistory(); +- statistics.commitCount =3D history.commitIds.length; +- LinearCommitHistoryIterator iterator =3D history.iterator(); +- try { +- // +- // Iterate over the history, applying changes. +- // +- bool firstCheckout =3D true; +- ErrorMap expectedErrors =3D null; +- Iterable changedPubspecs; +- while (iterator.moveNext()) { +- // +- // Checkout the commit on which the changes are based. +- // +- String commit =3D iterator.srcCommit; +- repository.checkout(commit); +- if (expectedErrors !=3D null) { +-// ErrorMap actualErrors =3D +- await server.computeErrorMap(server.analyzedDartFiles); +-// String difference =3D expectedErrors.expectErrorMap(actualErr= ors); +-// if (difference !=3D null) { +-// stdout.write('Mismatched errors after commit '); +-// stdout.writeln(commit); +-// stdout.writeln(); +-// stdout.writeln(difference); +-// return; +-// } +- } +- if (firstCheckout) { +- changedPubspecs =3D _findPubspecsInAnalysisRoots(); +- server.sendAnalysisSetAnalysisRoots(analysisRoots, []); +- firstCheckout =3D false; +- } else { +- server.removeAllOverlays(); +- } +- await readServerOutput(); +- expectedErrors =3D await server.computeErrorMap(server.analyzedDa= rtFiles); +- for (String filePath in changedPubspecs) { +- _runPub(filePath); +- } +- // +- // Apply the changes. +- // +- CommitDelta commitDelta =3D iterator.next(); +- commitDelta.filterDiffs(analysisRoots, fileGlobs); +- if (commitDelta.hasDiffs) { +- statistics.commitsWithChangeInRootCount++; +- await _replayDiff(commitDelta); +- } +- changedPubspecs =3D commitDelta.filesMatching(PUBSPEC_FILE_NAME); +- } +- } finally { +- // Ensure that the repository is left at the most recent commit. +- if (history.commitIds.length > 0) { +- repository.checkout(history.commitIds[0]); +- } +- } +- server.removeAllOverlays(); +- await readServerOutput(); +- stdout.writeln(); +- } +- +- /** +- * Replay the changes between two commits, as represented by the given +- * [commitDelta]. +- */ +- Future _replayDiff(CommitDelta commitDelta) async { +- List editList =3D []; +- for (DiffRecord record in commitDelta.diffRecords) { +- FileEdit edit =3D new FileEdit(overlayStyle, record); +- _createSourceEdits(edit, record.getBlobDiff()); +- editList.add(edit); +- } +- // +- // TODO(brianwilkerson) Randomize. +- // Randomly select operations from different files to simulate a user +- // editing multiple files simultaneously. +- // +- for (FileEdit edit in editList) { +- List currentFile =3D [edit.filePath]; +- server.sendAnalysisSetPriorityFiles(currentFile); +- server.sendAnalysisSetSubscriptions({ +- AnalysisService.FOLDING: currentFile, +- AnalysisService.HIGHLIGHTS: currentFile, +- AnalysisService.IMPLEMENTED: currentFile, +- AnalysisService.NAVIGATION: currentFile, +- AnalysisService.OCCURRENCES: currentFile, +- AnalysisService.OUTLINE: currentFile, +- AnalysisService.OVERRIDES: currentFile +- }); +- for (ServerOperation operation in edit.getOperations()) { +- statistics.editCount++; +- operation.perform(server); +- await readServerOutput(); +- } +- } +- } +- +- /** +- * Run `pub` on the pubspec with the given [filePath]. +- */ +- void _runPub(String filePath) { +- String directoryPath =3D path.dirname(filePath); +- if (new Directory(directoryPath).existsSync()) { +- Process.runSync( +- '/Users/brianwilkerson/Dev/dart/dart-sdk/bin/pub', ['get'], +- workingDirectory: directoryPath); +- } +- } +- +- /** +- * Run the simulation by starting up a server and sending it requests. +- */ +- Future _runSimulation() async { +- server =3D new Server(logger: logger); +- Stopwatch stopwatch =3D new Stopwatch(); +- statistics.stopwatch =3D stopwatch; +- stopwatch.start(); +- await server.start(); +- server.sendServerSetSubscriptions([ServerService.STATUS]); +- server.sendAnalysisSetGeneralSubscriptions( +- [GeneralAnalysisService.ANALYZED_FILES]); +- // TODO(brianwilkerson) Get the list of glob patterns from the server= after +- // an API for getting them has been implemented. +- fileGlobs =3D [ +- new Glob(path.context.separator, '**.dart'), +- new Glob(path.context.separator, '**.html'), +- new Glob(path.context.separator, '**.htm'), +- new Glob(path.context.separator, '**/.analysisOptions') +- ]; +- try { +- await _replayChanges(); +- } finally { +- // TODO(brianwilkerson) This needs to be moved into a Zone in order= to +- // ensure that it is always run. +- server.sendServerShutdown(); +- repository.checkout('master'); +- } +- stopwatch.stop(); +- } +- +- /** +- * Display usage information, preceded by the [errorMessage] if one is = given. +- */ +- void _showUsage(ArgParser parser, [String errorMessage =3D null]) { +- if (errorMessage !=3D null) { +- stderr.writeln(errorMessage); +- stderr.writeln(); +- } +- stderr.writeln(''' +-Usage: replay [options...] repositoryPath analysisRoot... +- +-Uses the commit history of the git repository at the given repository pat= h to +-simulate the development of a code base while using the analysis server to +-analyze the code base. +- +-The repository path must be the absolute path of a directory containing a= git +-repository. +- +-There must be at least one analysis root, and all of the analysis roots m= ust be +-the absolute path of a directory contained within the repository director= y. The +-analysis roots represent the portions of the repository that will be anal= yzed by +-the analysis server. +- +-OPTIONS:'''); +- stderr.writeln(parser.usage); +- } +-} +- +-/** +- * A representation of the edits to be applied to a single file. +- */ +-class FileEdit { +- /** +- * The style of interaction to use for analysis.updateContent requests. +- */ +- OverlayStyle overlayStyle; +- +- /** +- * The absolute path of the file to be edited. +- */ +- String filePath; +- +- /** +- * The content of the file before any edits have been applied. +- */ +- String content; +- +- /** +- * The line info for the file before any edits have been applied. +- */ +- LineInfo lineInfo; +- +- /** +- * The lists of source edits, one list for each hunk being edited. +- */ +- List> editLists =3D >[]; +- +- /** +- * The current content of the file. This field is only used if the over= lay +- * style is [OverlayStyle.multipleAdd]. +- */ +- String currentContent; +- +- /** +- * Initialize a collection of edits to be associated with the file at t= he +- * given [filePath]. +- */ +- FileEdit(this.overlayStyle, DiffRecord record) { +- filePath =3D record.srcPath; +- if (record.isAddition) { +- content =3D ''; +- lineInfo =3D new LineInfo([0]); +- } else if (record.isCopy || record.isRename || record.isTypeChange) { +- throw new ArgumentError('Unhandled change of type ${record.status}'= ); +- } else { +- content =3D new File(filePath).readAsStringSync(); +- lineInfo =3D new LineInfo(StringUtilities.computeLineStarts(content= )); +- } +- currentContent =3D content; +- } +- +- /** +- * Add a list of source edits that, taken together, transform a single = hunk in +- * the file. +- */ +- void addSourceEdits(List sourceEdits) { +- editLists.add(sourceEdits); +- } +- +- /** +- * Return a list of operations to be sent to the server. +- */ +- List getOperations() { +- List operations =3D []; +- void addUpdateContent(var overlay) { +- operations.add(new Analysis_UpdateContent(filePath, overlay)); +- } +- +- // TODO(brianwilkerson) Randomize. +- // Make the order of edits random. Doing so will require updating the +- // offsets of edits after the selected edit point. +- addUpdateContent(new AddContentOverlay(content)); +- for (List editList in editLists.reversed) { +- for (SourceEdit edit in editList.reversed) { +- var overlay =3D null; +- if (overlayStyle =3D=3D OverlayStyle.change) { +- overlay =3D new ChangeContentOverlay([edit]); +- } else if (overlayStyle =3D=3D OverlayStyle.multipleAdd) { +- currentContent =3D edit.apply(currentContent); +- overlay =3D new AddContentOverlay(currentContent); +- } else { +- throw new StateError( +- 'Failed to handle overlay style =3D $overlayStyle'); +- } +- if (overlay !=3D null) { +- addUpdateContent(overlay); +- } +- } +- } +- addUpdateContent(new RemoveContentOverlay()); +- return operations; +- } +-} +- +-/** +- * The possible styles of interaction to use for analysis.updateContent r= equests. +- */ +-enum OverlayStyle { change, multipleAdd } +- +-/** +- * A set of statistics related to the execution of the simulation. +- */ +-class Statistics { +- /** +- * The driver driving the simulation. +- */ +- final Driver driver; +- +- /** +- * The stopwatch being used to time the simulation. +- */ +- Stopwatch stopwatch; +- +- /** +- * The total number of commits in the repository. +- */ +- int commitCount; +- +- /** +- * The number of commits in the repository that touched one of the file= s in +- * one of the analysis roots. +- */ +- int commitsWithChangeInRootCount =3D 0; +- +- /** +- * The total number of edits that were applied. +- */ +- int editCount =3D 0; +- +- /** +- * Initialize a newly created set of statistics. +- */ +- Statistics(this.driver); +- +- /** +- * Print the statistics to [stdout]. +- */ +- void print() { +- stdout.write('Replay commits in '); +- stdout.writeln(driver.repositoryPath); +- stdout.write(' replay took '); +- stdout.writeln(_printTime(stopwatch.elapsedMilliseconds)); +- stdout.write(' analysis roots =3D '); +- stdout.writeln(driver.analysisRoots); +- stdout.write(' number of commits =3D '); +- stdout.writeln(commitCount); +- stdout.write(' number of commits with a change in an analysis root = =3D '); +- stdout.writeln(commitsWithChangeInRootCount); +- stdout.write(' number of edits =3D '); +- stdout.writeln(editCount); +- } +- +- /** +- * Return a textual representation of the given duration, represented in +- * [milliseconds]. +- */ +- String _printTime(int milliseconds) { +- int seconds =3D milliseconds ~/ 1000; +- milliseconds -=3D seconds * 1000; +- int minutes =3D seconds ~/ 60; +- seconds -=3D minutes * 60; +- int hours =3D minutes ~/ 60; +- minutes -=3D hours * 60; +- +- if (hours > 0) { +- return '$hours:$minutes:$seconds.$milliseconds'; +- } else if (minutes > 0) { +- return '$minutes:$seconds.$milliseconds'; +- } +- return '$seconds.$milliseconds'; +- } +-} +diff --git a/pkg/analysis_server/test/stress/utilities/git.dart b/pkg/anal= ysis_server/test/stress/utilities/git.dart +deleted file mode 100644 +index cfcef4fb7aa..00000000000 +--- a/pkg/analysis_server/test/stress/utilities/git.dart ++++ /dev/null +@@ -1,551 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Support for interacting with a git repository. +- */ +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analyzer/src/util/glob.dart'; +-import 'package:path/path.dart' as path; +- +-import 'logger.dart'; +- +-/** +- * A representation of the differences between two blobs. +- */ +-class BlobDiff { +- /** +- * The regular expression used to identify the beginning of a hunk. +- */ +- static final RegExp hunkHeaderRegExp =3D +- new RegExp(r'@@ -([0-9]+)(?:,[0-9]+)? \+([0-9]+)(?:,[0-9]+)? @@'); +- +- /** +- * A list of the hunks in the diff. +- */ +- List hunks =3D []; +- +- /** +- * Initialize a newly created blob diff by parsing the result of the gi= t diff +- * command (the [input]). +- * +- * This is only intended to be invoked from [GitRepository.getBlobDiff]. +- */ +- BlobDiff._(List input) { +- _parseInput(input); +- } +- +- /** +- * Parse the result of the git diff command (the [input]). +- */ +- void _parseInput(List input) { +- for (String line in input) { +- _parseLine(line); +- } +- } +- +- /** +- * Parse a single [line] from the result of the git diff command. +- */ +- void _parseLine(String line) { +- DiffHunk currentHunk =3D hunks.isEmpty ? null : hunks.last; +- if (line.startsWith('@@')) { +- Match match =3D hunkHeaderRegExp.matchAsPrefix(line); +- int srcLine =3D int.parse(match.group(1)); +- int dstLine =3D int.parse(match.group(2)); +- hunks.add(new DiffHunk(srcLine, dstLine)); +- } else if (currentHunk !=3D null && line.startsWith('+')) { +- currentHunk.addLines.add(line.substring(1)); +- } else if (currentHunk !=3D null && line.startsWith('-')) { +- currentHunk.removeLines.add(line.substring(1)); +- } +- } +-} +- +-/** +- * A representation of the differences between two commits. +- */ +-class CommitDelta { +- /** +- * The length (in characters) of a SHA. +- */ +- static final int SHA_LENGTH =3D 40; +- +- /** +- * The code-point for a colon (':'). +- */ +- static final int COLON =3D ':'.codeUnitAt(0); +- +- /** +- * The code-point for a nul character. +- */ +- static final int NUL =3D 0; +- +- /** +- * The code-point for a tab. +- */ +- static final int TAB =3D '\t'.codeUnitAt(0); +- +- /** +- * The repository from which the commits were taken. +- */ +- final GitRepository repository; +- +- /** +- * The records of the files that were changed. +- */ +- final List diffRecords =3D []; +- +- /** +- * Initialize a newly created representation of the differences between= two +- * commits. The differences are computed by parsing the result of a git= diff +- * command (the [diffResults]). +- * +- * This is only intended to be invoked from [GitRepository.getBlobDiff]. +- */ +- CommitDelta._(this.repository, String diffResults) { +- _parseInput(diffResults); +- } +- +- /** +- * Return `true` if there are differences. +- */ +- bool get hasDiffs =3D> diffRecords.isNotEmpty; +- +- /** +- * Return the absolute paths of all of the files in this commit whose n= ame +- * matches the given [fileName]. +- */ +- Iterable filesMatching(String fileName) { +- return diffRecords +- .where((DiffRecord record) =3D> record.isFor(fileName)) +- .map((DiffRecord record) =3D> record.srcPath); +- } +- +- /** +- * Remove any diffs for files that are either (a) outside the given +- * [inclusionPaths], or (b) are files that do not match one of the given +- * [globPatterns]. +- */ +- void filterDiffs(List inclusionPaths, List globPatterns) { +- diffRecords.retainWhere((DiffRecord record) { +- String filePath =3D record.srcPath ?? record.dstPath; +- for (String inclusionPath in inclusionPaths) { +- if (path.isWithin(inclusionPath, filePath)) { +- for (Glob glob in globPatterns) { +- if (glob.matches(filePath)) { +- return true; +- } +- } +- } +- } +- return false; +- }); +- } +- +- /** +- * Return the index of the first nul character in the given [string] th= at is +- * at or after the given [start] index. +- */ +- int _findEnd(String string, int start) { +- int length =3D string.length; +- int end =3D start; +- while (end < length && string.codeUnitAt(end) !=3D NUL) { +- end++; +- } +- return end; +- } +- +- /** +- * Return the result of converting the given [relativePath] to an absol= ute +- * path. The path is assumed to be relative to the root of the reposito= ry. +- */ +- String _makeAbsolute(String relativePath) { +- return path.join(repository.path, relativePath); +- } +- +- /** +- * Parse all of the diff records in the given [input]. +- */ +- void _parseInput(String input) { +- int length =3D input.length; +- int start =3D 0; +- while (start < length) { +- start =3D _parseRecord(input, start); +- } +- } +- +- /** +- * Parse a single record from the given [input], assuming that the reco= rd +- * starts at the given [startIndex]. +- * +- * Each record is formatted as a sequence of fields. The fields are, fr= om the +- * left to the right: +- * +- * 1. a colon. +- * 2. mode for "src"; 000000 if creation or unmerged. +- * 3. a space. +- * 4. mode for "dst"; 000000 if deletion or unmerged. +- * 5. a space. +- * 6. sha1 for "src"; 0{40} if creation or unmerged. +- * 7. a space. +- * 8. sha1 for "dst"; 0{40} if creation, unmerged or "look at work tree= ". +- * 9. a space. +- * 10. status, followed by optional "score" number. +- * 11. a tab or a NUL when -z option is used. +- * 12. path for "src" +- * 13. a tab or a NUL when -z option is used; only exists for C or R. +- * 14. path for "dst"; only exists for C or R. +- * 15. an LF or a NUL when -z option is used, to terminate the record. +- */ +- int _parseRecord(String input, int startIndex) { +- // Skip the first five fields. +- startIndex +=3D 15; +- // Parse field 6 +- String srcSha =3D input.substring(startIndex, startIndex + SHA_LENGTH= ); +- startIndex +=3D SHA_LENGTH + 1; +- // Parse field 8 +- String dstSha =3D input.substring(startIndex, startIndex + SHA_LENGTH= ); +- startIndex +=3D SHA_LENGTH + 1; +- // Parse field 10 +- int endIndex =3D _findEnd(input, startIndex); +- String status =3D input.substring(startIndex, endIndex); +- startIndex =3D endIndex + 1; +- // Parse field 12 +- endIndex =3D _findEnd(input, startIndex); +- String srcPath =3D _makeAbsolute(input.substring(startIndex, endIndex= )); +- startIndex =3D endIndex + 1; +- // Parse field 14 +- String dstPath =3D null; +- if (status.startsWith('C') || status.startsWith('R')) { +- endIndex =3D _findEnd(input, startIndex); +- dstPath =3D _makeAbsolute(input.substring(startIndex, endIndex)); +- } +- // Create the record. +- diffRecords.add( +- new DiffRecord(repository, srcSha, dstSha, status, srcPath, dstPa= th)); +- return endIndex + 1; +- } +-} +- +-/** +- * Representation of a single diff hunk. +- */ +-class DiffHunk { +- /** +- * The index of the first line that was changed in the src as returned = by the +- * diff command. The diff command numbers lines starting at 1, but it +- * subtracts 1 from the line number if there are no lines on the source= side +- * of the hunk. +- */ +- int diffSrcLine; +- +- /** +- * The index of the first line that was changed in the dst as returned = by the +- * diff command. The diff command numbers lines starting at 1, but it +- * subtracts 1 from the line number if there are no lines on the destin= ation +- * side of the hunk. +- */ +- int diffDstLine; +- +- /** +- * A list of the individual lines that were removed from the src. +- */ +- List removeLines =3D []; +- +- /** +- * A list of the individual lines that were added to the dst. +- */ +- List addLines =3D []; +- +- /** +- * Initialize a newly created hunk. The lines will be added after the o= bject +- * has been created. +- */ +- DiffHunk(this.diffSrcLine, this.diffDstLine); +- +- /** +- * Return the index of the first line that was changed in the dst. Unli= ke the +- * [diffDstLine] field, this getter adjusts the line number to be consi= stent +- * whether or not there were any changed lines. +- */ +- int get dstLine { +- return addLines.isEmpty ? diffDstLine : diffDstLine - 1; +- } +- +- /** +- * Return the index of the first line that was changed in the src. Unli= ke the +- * [diffDstLine] field, this getter adjusts the line number to be consi= stent +- * whether or not there were any changed lines. +- */ +- int get srcLine { +- return removeLines.isEmpty ? diffSrcLine : diffSrcLine - 1; +- } +-} +- +-/** +- * A representation of a single line (record) from a raw diff. +- */ +-class DiffRecord { +- /** +- * The repository containing the file(s) that were modified. +- */ +- final GitRepository repository; +- +- /** +- * The SHA1 of the blob in the src. +- */ +- final String srcBlob; +- +- /** +- * The SHA1 of the blob in the dst. +- */ +- final String dstBlob; +- +- /** +- * The status of the change. Valid values are: +- * * A: addition of a file +- * * C: copy of a file into a new one +- * * D: deletion of a file +- * * M: modification of the contents or mode of a file +- * * R: renaming of a file +- * * T: change in the type of the file +- * * U: file is unmerged (you must complete the merge before it can be = committed) +- * * X: "unknown" change type (most probably a bug, please report it) +- * +- * Status letters C and R are always followed by a score (denoting the +- * percentage of similarity between the source and target of the move or +- * copy), and are the only ones to be so. +- */ +- final String status; +- +- /** +- * The path of the src. +- */ +- final String srcPath; +- +- /** +- * The path of the dst if this was either a copy or a rename operation. +- */ +- final String dstPath; +- +- /** +- * Initialize a newly created diff record. +- */ +- DiffRecord(this.repository, this.srcBlob, this.dstBlob, this.status, +- this.srcPath, this.dstPath); +- +- /** +- * Return `true` if this record represents a file that was added. +- */ +- bool get isAddition =3D> status =3D=3D 'A'; +- +- /** +- * Return `true` if this record represents a file that was copied. +- */ +- bool get isCopy =3D> status.startsWith('C'); +- +- /** +- * Return `true` if this record represents a file that was deleted. +- */ +- bool get isDeletion =3D> status =3D=3D 'D'; +- +- /** +- * Return `true` if this record represents a file that was modified. +- */ +- bool get isModification =3D> status =3D=3D 'M'; +- +- /** +- * Return `true` if this record represents a file that was renamed. +- */ +- bool get isRename =3D> status.startsWith('R'); +- +- /** +- * Return `true` if this record represents an entity whose type was cha= nged +- * (for example, from a file to a directory). +- */ +- bool get isTypeChange =3D> status =3D=3D 'T'; +- +- /** +- * Return a representation of the individual blobs within this diff. +- */ +- BlobDiff getBlobDiff() =3D> repository.getBlobDiff(srcBlob, dstBlob); +- +- /** +- * Return `true` if this diff applies to a file with the given name. +- */ +- bool isFor(String fileName) =3D> +- (srcPath !=3D null && fileName =3D=3D path.basename(srcPath)) || +- (dstPath !=3D null && fileName =3D=3D path.basename(dstPath)); +- +- @override +- String toString() =3D> srcPath ?? dstPath; +-} +- +-/** +- * A representation of a git repository. +- */ +-class GitRepository { +- /** +- * The absolute path of the directory containing the repository. +- */ +- final String path; +- +- /** +- * The logger to which git commands should be written, or `null` if the +- * commands should not be written. +- */ +- final Logger logger; +- +- /** +- * Initialize a newly created repository to represent the git repositor= y at +- * the given [path]. +- * +- * If a [commandSink] is provided, any calls to git will be written to = it. +- */ +- GitRepository(this.path, {this.logger =3D null}); +- +- /** +- * Checkout the given [commit] from the repository. This is done by run= ning +- * the command `git checkout `. +- */ +- void checkout(String commit) { +- _run(['checkout', commit]); +- } +- +- /** +- * Return details about the differences between the two blobs identifie= d by +- * the SHA1 of the [srcBlob] and the SHA1 of the [dstBlob]. This is don= e by +- * running the command `git diff `. +- */ +- BlobDiff getBlobDiff(String srcBlob, String dstBlob) { +- ProcessResult result =3D _run(['diff', '-U0', srcBlob, dstBlob]); +- List diffResults =3D LineSplitter.split(result.stdout).toList= (); +- return new BlobDiff._(diffResults); +- } +- +- /** +- * Return details about the differences between the two commits identif= ied by +- * the [srcCommit] and [dstCommit]. This is done by running the command +- * `git diff --raw --no-abbrev --no-renames -z `. +- */ +- CommitDelta getCommitDiff(String srcCommit, String dstCommit) { +- // Consider --find-renames instead of --no-renames if rename informat= ion is +- // desired. +- ProcessResult result =3D _run([ +- 'diff', +- '--raw', +- '--no-abbrev', +- '--no-renames', +- '-z', +- srcCommit, +- dstCommit +- ]); +- return new CommitDelta._(this, result.stdout); +- } +- +- /** +- * Return a representation of the history of this repository. This is d= one by +- * running the command `git rev-list --first-parent HEAD`. +- */ +- LinearCommitHistory getCommitHistory() { +- ProcessResult result =3D _run(['rev-list', '--first-parent', 'HEAD']); +- List commitIds =3D LineSplitter.split(result.stdout).toList(); +- return new LinearCommitHistory(this, commitIds); +- } +- +- /** +- * Synchronously run the given [executable] with the given [arguments].= Return +- * the result of running the process. +- */ +- ProcessResult _run(List arguments) { +- logger?.log('git', 'git', arguments: arguments); +- return Process.runSync('git', arguments, +- stderrEncoding: UTF8, stdoutEncoding: UTF8, workingDirectory: pat= h); +- } +-} +- +-/** +- * A representation of the history of a Git repository. This only represe= nts a +- * single linear path in the history graph. +- */ +-class LinearCommitHistory { +- /** +- * The repository whose history is being represented. +- */ +- final GitRepository repository; +- +- /** +- * The id's (SHA's) of the commits in the repository, with the most rec= ent +- * commit being first and the oldest commit being last. +- */ +- final List commitIds; +- +- /** +- * Initialize a commit history for the given [repository] to have the g= iven +- * [commitIds]. +- */ +- LinearCommitHistory(this.repository, this.commitIds); +- +- /** +- * Return an iterator that can be used to iterate over this commit hist= ory. +- */ +- LinearCommitHistoryIterator iterator() { +- return new LinearCommitHistoryIterator(this); +- } +-} +- +-/** +- * An iterator over the history of a Git repository. +- */ +-class LinearCommitHistoryIterator { +- /** +- * The commit history being iterated over. +- */ +- final LinearCommitHistory history; +- +- /** +- * The index of the current commit in the list of [commitIds]. +- */ +- int currentCommit; +- +- /** +- * Initialize a newly created iterator to iterate over the commits with= the +- * given [commitIds]; +- */ +- LinearCommitHistoryIterator(this.history) { +- currentCommit =3D history.commitIds.length; +- } +- +- /** +- * Return the SHA1 of the commit after the current commit (the 'dst' of= the +- * [next] diff). +- */ +- String get dstCommit =3D> history.commitIds[currentCommit - 1]; +- +- /** +- * Return the SHA1 of the current commit (the 'src' of the [next] diff). +- */ +- String get srcCommit =3D> history.commitIds[currentCommit]; +- +- /** +- * Advance to the next commit in the history. Return `true` if it is sa= fe to +- * ask for the [next] diff. +- */ +- bool moveNext() { +- if (currentCommit <=3D 1) { +- return false; +- } +- currentCommit--; +- return true; +- } +- +- /** +- * Return the difference between the current commit and the commit that +- * followed it. +- */ +- CommitDelta next() =3D> history.repository.getCommitDiff(srcCommit, dst= Commit); +-} +diff --git a/pkg/analysis_server/test/stress/utilities/logger.dart b/pkg/a= nalysis_server/test/stress/utilities/logger.dart +deleted file mode 100644 +index acf7a742bae..00000000000 +--- a/pkg/analysis_server/test/stress/utilities/logger.dart ++++ /dev/null +@@ -1,49 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * A utility class used to write logging information during a test. +- */ +-class Logger { +- /** +- * The width of the field in which labels are printed. +- */ +- static const int _labelWidth =3D 8; +- +- /** +- * The separator used to separate the label from the content. +- */ +- static const String _separator =3D ' : '; +- +- /** +- * The sink to which the logged information should be written. +- */ +- final StringSink sink; +- +- /** +- * Initialize a newly created logger to write to the given [sink]. +- */ +- Logger(this.sink); +- +- /** +- * Log the given information. +- * +- * The [label] is used to indicate the kind of information being logged= , while +- * the [content] contains the actual information. If a list of [argumen= ts] is +- * provided, then they will be written after the content. +- */ +- void log(String label, String content, {List arguments =3D null= }) { +- for (int i =3D _labelWidth - label.length; i > 0; i--) { +- sink.write(' '); +- } +- sink.write(label); +- sink.write(_separator); +- sink.write(content); +- arguments?.forEach((String argument) { +- sink.write(' '); +- sink.write(argument); +- }); +- sink.writeln(); +- } +-} +diff --git a/pkg/analysis_server/test/stress/utilities/server.dart b/pkg/a= nalysis_server/test/stress/utilities/server.dart +deleted file mode 100644 +index 533281badba..00000000000 +--- a/pkg/analysis_server/test/stress/utilities/server.dart ++++ /dev/null +@@ -1,1081 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Support for interacting with an analysis server that is running in a s= eparate +- * process. +- */ +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:convert' hide JsonDecoder; +-import 'dart:io'; +-import 'dart:math' as math; +- +-import 'package:analysis_server/protocol/protocol.dart'; +-import 'package:analysis_server/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:path/path.dart' as path; +- +-import 'logger.dart'; +- +-/** +- * Return the current time expressed as milliseconds since the epoch. +- */ +-int get currentTime =3D> new DateTime.now().millisecondsSinceEpoch; +- +-/** +- * ??? +- */ +-class ErrorMap { +- /** +- * A table mapping file paths to the errors associated with that file. +- */ +- final Map> pathMap =3D +- new HashMap>(); +- +- /** +- * Initialize a newly created error map. +- */ +- ErrorMap(); +- +- /** +- * Initialize a newly created error map to contain the same mapping as = the +- * given [errorMap]. +- */ +- ErrorMap.from(ErrorMap errorMap) { +- pathMap.addAll(errorMap.pathMap); +- } +- +- void operator []=3D(String filePath, List errors) { +- pathMap[filePath] =3D errors; +- } +- +- /** +- * Compare the this error map with the state captured in the given [err= orMap]. +- * Throw an exception if the two maps do not agree. +- */ +- String expectErrorMap(ErrorMap errorMap) { +- StringBuffer buffer =3D new StringBuffer(); +- _ErrorComparator comparator =3D new _ErrorComparator(buffer); +- comparator.compare(pathMap, errorMap.pathMap); +- if (buffer.length > 0) { +- return buffer.toString(); +- } +- return null; +- } +-} +- +-/** +- * Data that has been collected about a request sent to the server. +- */ +-class RequestData { +- /** +- * The unique id of the request. +- */ +- final String id; +- +- /** +- * The method that was requested. +- */ +- final String method; +- +- /** +- * The request parameters. +- */ +- final Map params; +- +- /** +- * The time at which the request was sent. +- */ +- final int requestTime; +- +- /** +- * The time at which the response was received, or `null` if no respons= e has +- * been received. +- */ +- int responseTime =3D null; +- +- /** +- * The response that was received. +- */ +- Response _response; +- +- /** +- * The completer that will be completed when a response is received. +- */ +- Completer _responseCompleter; +- +- /** +- * Initialize a newly created set of request data. +- */ +- RequestData(this.id, this.method, this.params, this.requestTime); +- +- /** +- * Return the number of milliseconds that elapsed between the request a= nd the +- * response. This getter assumes that the response was received. +- */ +- int get elapsedTime =3D> responseTime - requestTime; +- +- /** +- * Return a future that will complete when a response is received. +- */ +- Future get respondedTo { +- if (_response !=3D null) { +- return new Future.value(_response); +- } +- if (_responseCompleter =3D=3D null) { +- _responseCompleter =3D new Completer(); +- } +- return _responseCompleter.future; +- } +- +- /** +- * Record that the given [response] was received. +- */ +- void recordResponse(Response response) { +- if (_response !=3D null) { +- stdout.writeln( +- 'Received a second response to a $method request (id =3D $id)'); +- return; +- } +- responseTime =3D currentTime; +- _response =3D response; +- if (_responseCompleter !=3D null) { +- _responseCompleter.complete(response); +- _responseCompleter =3D null; +- } +- } +-} +- +-/** +- * A utility for starting and communicating with an analysis server that = is +- * running in a separate process. +- */ +-class Server { +- /** +- * The label used for communications from the client. +- */ +- static const String fromClient =3D 'client'; +- +- /** +- * The label used for normal communications from the server. +- */ +- static const String fromServer =3D 'server'; +- +- /** +- * The label used for output written by the server on [fromStderr]. +- */ +- static const String fromStderr =3D 'stderr'; +- +- /** +- * The logger to which the communications log should be written, or `nu= ll` if +- * the log should not be written. +- */ +- final Logger logger; +- +- /** +- * The process in which the server is running, or `null` if the server = hasn't +- * been started yet. +- */ +- Process _process =3D null; +- +- /** +- * Number that should be used to compute the 'id' to send in the next c= ommand +- * sent to the server. +- */ +- int _nextId =3D 0; +- +- /** +- * The analysis roots that are included. +- */ +- List _analysisRootIncludes =3D []; +- +- /** +- * A list containing the paths of files for which an overlay has been c= reated. +- */ +- List filesWithOverlays =3D []; +- +- /** +- * The files that the server reported as being analyzed. +- */ +- List _analyzedFiles =3D []; +- +- /** +- * A mapping from the absolute paths of files to the most recent set of= errors +- * received for that file. +- */ +- ErrorMap _errorMap =3D new ErrorMap(); +- +- /** +- * The completer that will be completed the next time a 'server.status' +- * notification is received from the server with 'analyzing' set to fal= se. +- */ +- Completer _analysisFinishedCompleter; +- +- /** +- * The completer that will be completed the next time a 'server.connect= ed' +- * notification is received from the server. +- */ +- Completer _serverConnectedCompleter; +- +- /** +- * A table mapping the ids of requests that have been sent to the serve= r to +- * data about those requests. +- */ +- final Map _requestDataMap =3D {}; +- +- /** +- * A table mapping the number of times a request whose 'event' is equal= to the +- * key was sent to the server. +- */ +- final Map _notificationCountMap =3D {}; +- +- /** +- * Initialize a new analysis server. The analysis server is not running= and +- * must be started using [start]. +- * +- * If a [logger] is provided, the communications between the client (th= is +- * test) and the server will be written to it. +- */ +- Server({this.logger =3D null}); +- +- /** +- * Return a future that will complete when a 'server.status' notificati= on is +- * received from the server with 'analyzing' set to false. +- * +- * The future will only be completed by 'server.status' notifications t= hat are +- * received after this function call, so it is safe to use this getter +- * multiple times in one test; each time it is used it will wait afresh= for +- * analysis to finish. +- */ +- Future get analysisFinished { +- if (_analysisFinishedCompleter =3D=3D null) { +- _analysisFinishedCompleter =3D new Completer(); +- } +- return _analysisFinishedCompleter.future; +- } +- +- /** +- * Return a list of the paths of files that are currently being analyze= d. +- */ +- List get analyzedDartFiles { +- bool isAnalyzed(String filePath) { +- // TODO(brianwilkerson) This should use the path package to determi= ne +- // inclusion, and needs to take exclusions into account. +- for (String includedRoot in _analysisRootIncludes) { +- if (filePath.startsWith(includedRoot)) { +- return true; +- } +- } +- return false; +- } +- +- List analyzedFiles =3D []; +- for (String filePath in _analyzedFiles) { +- if (filePath.endsWith('.dart') && isAnalyzed(filePath)) { +- analyzedFiles.add(filePath); +- } +- } +- return analyzedFiles; +- } +- +- /** +- * Return a table mapping the absolute paths of files to the most recen= t set +- * of errors received for that file. The content of the map will not ch= ange +- * when new sets of errors are received. +- */ +- ErrorMap get errorMap =3D> new ErrorMap.from(_errorMap); +- +- /** +- * Compute a mapping from each of the file paths in the given list of +- * [filePaths] to the list of errors in the file at that path. +- */ +- Future computeErrorMap(List filePaths) async { +- ErrorMap errorMap =3D new ErrorMap(); +- List futures =3D []; +- for (String filePath in filePaths) { +- RequestData requestData =3D sendAnalysisGetErrors(filePath); +- futures.add(requestData.respondedTo.then((Response response) { +- if (response.result !=3D null) { +- AnalysisGetErrorsResult result =3D +- new AnalysisGetErrorsResult.fromResponse(response); +- errorMap[filePath] =3D result.errors; +- } +- })); +- } +- await Future.wait(futures); +- return errorMap; +- } +- +- /** +- * Print information about the communications with the server. +- */ +- void printStatistics() { +- void writeSpaces(int count) { +- for (int i =3D 0; i < count; i++) { +- stdout.write(' '); +- } +- } +- +- // +- // Print information about the requests that were sent. +- // +- stdout.writeln('Request Counts'); +- if (_requestDataMap.isEmpty) { +- stdout.writeln(' none'); +- } else { +- Map> requestsByMethod =3D +- >{}; +- _requestDataMap.values.forEach((RequestData requestData) { +- requestsByMethod +- .putIfAbsent(requestData.method, () =3D> []) +- .add(requestData); +- }); +- List keys =3D requestsByMethod.keys.toList(); +- keys.sort(); +- int maxCount =3D requestsByMethod.values +- .fold(0, (int count, List list) =3D> count + list.= length); +- int countWidth =3D maxCount.toString().length; +- for (String key in keys) { +- List requests =3D requestsByMethod[key]; +- int noResponseCount =3D 0; +- int responseCount =3D 0; +- int minTime =3D -1; +- int maxTime =3D -1; +- int totalTime =3D 0; +- requests.forEach((RequestData data) { +- if (data.responseTime =3D=3D null) { +- noResponseCount++; +- } else { +- responseCount++; +- int time =3D data.elapsedTime; +- minTime =3D minTime < 0 ? time : math.min(minTime, time); +- maxTime =3D math.max(maxTime, time); +- totalTime +=3D time; +- } +- }); +- String count =3D requests.length.toString(); +- writeSpaces(countWidth - count.length); +- stdout.write(' '); +- stdout.write(count); +- stdout.write(' - '); +- stdout.write(key); +- if (noResponseCount > 0) { +- stdout.write(', '); +- stdout.write(noResponseCount); +- stdout.write(' with no response'); +- } +- if (maxTime >=3D 0) { +- stdout.write(' ('); +- stdout.write(minTime); +- stdout.write(', '); +- stdout.write(totalTime / responseCount); +- stdout.write(', '); +- stdout.write(maxTime); +- stdout.write(')'); +- } +- stdout.writeln(); +- } +- } +- // +- // Print information about the notifications that were received. +- // +- stdout.writeln(); +- stdout.writeln('Notification Counts'); +- if (_notificationCountMap.isEmpty) { +- stdout.writeln(' none'); +- } else { +- List keys =3D _notificationCountMap.keys.toList(); +- keys.sort(); +- int maxCount =3D _notificationCountMap.values.fold(0, math.max); +- int countWidth =3D maxCount.toString().length; +- for (String key in keys) { +- String count =3D _notificationCountMap[key].toString(); +- writeSpaces(countWidth - count.length); +- stdout.write(' '); +- stdout.write(count); +- stdout.write(' - '); +- stdout.writeln(key); +- } +- } +- } +- +- /** +- * Remove any existing overlays. +- */ +- void removeAllOverlays() { +- Map files =3D new HashMap(); +- for (String path in filesWithOverlays) { +- files[path] =3D new RemoveContentOverlay(); +- } +- sendAnalysisUpdateContent(files); +- } +- +- RequestData sendAnalysisGetErrors(String file) { +- var params =3D new AnalysisGetErrorsParams(file).toJson(); +- return _send("analysis.getErrors", params); +- } +- +- RequestData sendAnalysisGetHover(String file, int offset) { +- var params =3D new AnalysisGetHoverParams(file, offset).toJson(); +- return _send("analysis.getHover", params); +- } +- +- RequestData sendAnalysisGetLibraryDependencies() { +- return _send("analysis.getLibraryDependencies", null); +- } +- +- RequestData sendAnalysisGetNavigation(String file, int offset, int leng= th) { +- var params =3D new AnalysisGetNavigationParams(file, offset, length).= toJson(); +- return _send("analysis.getNavigation", params); +- } +- +- RequestData sendAnalysisGetReachableSources(String file) { +- var params =3D new AnalysisGetReachableSourcesParams(file).toJson(); +- return _send("analysis.getReachableSources", params); +- } +- +- void sendAnalysisReanalyze({List roots}) { +- var params =3D new AnalysisReanalyzeParams(roots: roots).toJson(); +- _send("analysis.reanalyze", params); +- } +- +- void sendAnalysisSetAnalysisRoots( +- List included, List excluded, +- {Map packageRoots}) { +- _analysisRootIncludes =3D included; +- var params =3D new AnalysisSetAnalysisRootsParams(included, excluded, +- packageRoots: packageRoots) +- .toJson(); +- _send("analysis.setAnalysisRoots", params); +- } +- +- void sendAnalysisSetGeneralSubscriptions( +- List subscriptions) { +- var params =3D +- new AnalysisSetGeneralSubscriptionsParams(subscriptions).toJson(); +- _send("analysis.setGeneralSubscriptions", params); +- } +- +- void sendAnalysisSetPriorityFiles(List files) { +- var params =3D new AnalysisSetPriorityFilesParams(files).toJson(); +- _send("analysis.setPriorityFiles", params); +- } +- +- void sendAnalysisSetSubscriptions( +- Map> subscriptions) { +- var params =3D new AnalysisSetSubscriptionsParams(subscriptions).toJs= on(); +- _send("analysis.setSubscriptions", params); +- } +- +- void sendAnalysisUpdateContent(Map files) { +- files.forEach((String path, dynamic overlay) { +- if (overlay is AddContentOverlay) { +- filesWithOverlays.add(path); +- } else if (overlay is RemoveContentOverlay) { +- filesWithOverlays.remove(path); +- } +- }); +- var params =3D new AnalysisUpdateContentParams(files).toJson(); +- _send('analysis.updateContent', params); +- } +- +- void sendAnalysisUpdateOptions(AnalysisOptions options) { +- var params =3D new AnalysisUpdateOptionsParams(options).toJson(); +- _send("analysis.updateOptions", params); +- } +- +- void sendCompletionGetSuggestions(String file, int offset) { +- var params =3D new CompletionGetSuggestionsParams(file, offset).toJso= n(); +- _send("completion.getSuggestions", params); +- } +- +- RequestData sendDiagnosticGetDiagnostics() { +- return _send("diagnostic.getDiagnostics", null); +- } +- +- RequestData sendEditFormat( +- String file, int selectionOffset, int selectionLength, +- {int lineLength}) { +- var params =3D new EditFormatParams(file, selectionOffset, selectionL= ength, +- lineLength: lineLength) +- .toJson(); +- return _send("edit.format", params); +- } +- +- RequestData sendEditGetAssists(String file, int offset, int length) { +- var params =3D new EditGetAssistsParams(file, offset, length).toJson(= ); +- return _send("edit.getAssists", params); +- } +- +- RequestData sendEditGetAvailableRefactorings( +- String file, int offset, int length) { +- var params =3D +- new EditGetAvailableRefactoringsParams(file, offset, length).toJs= on(); +- return _send("edit.getAvailableRefactorings", params); +- } +- +- RequestData sendEditGetFixes(String file, int offset) { +- var params =3D new EditGetFixesParams(file, offset).toJson(); +- return _send("edit.getFixes", params); +- } +- +- RequestData sendEditGetRefactoring(RefactoringKind kind, String file, +- int offset, int length, bool validateOnly, +- {RefactoringOptions options}) { +- var params =3D new EditGetRefactoringParams( +- kind, file, offset, length, validateOnly, +- options: options) +- .toJson(); +- return _send("edit.getRefactoring", params); +- } +- +- RequestData sendEditOrganizeDirectives(String file) { +- var params =3D new EditOrganizeDirectivesParams(file).toJson(); +- return _send("edit.organizeDirectives", params); +- } +- +- RequestData sendEditSortMembers(String file) { +- var params =3D new EditSortMembersParams(file).toJson(); +- return _send("edit.sortMembers", params); +- } +- +- RequestData sendExecutionCreateContext(String contextRoot) { +- var params =3D new ExecutionCreateContextParams(contextRoot).toJson(); +- return _send("execution.createContext", params); +- } +- +- RequestData sendExecutionDeleteContext(String id) { +- var params =3D new ExecutionDeleteContextParams(id).toJson(); +- return _send("execution.deleteContext", params); +- } +- +- RequestData sendExecutionMapUri(String id, {String file, String uri}) { +- var params =3D new ExecutionMapUriParams(id, file: file, uri: uri).to= Json(); +- return _send("execution.mapUri", params); +- } +- +- RequestData sendExecutionSetSubscriptions( +- List subscriptions) { +- var params =3D new ExecutionSetSubscriptionsParams(subscriptions).toJ= son(); +- return _send("execution.setSubscriptions", params); +- } +- +- void sendSearchFindElementReferences( +- String file, int offset, bool includePotential) { +- var params =3D +- new SearchFindElementReferencesParams(file, offset, includePotent= ial) +- .toJson(); +- _send("search.findElementReferences", params); +- } +- +- void sendSearchFindMemberDeclarations(String name) { +- var params =3D new SearchFindMemberDeclarationsParams(name).toJson(); +- _send("search.findMemberDeclarations", params); +- } +- +- void sendSearchFindMemberReferences(String name) { +- var params =3D new SearchFindMemberReferencesParams(name).toJson(); +- _send("search.findMemberReferences", params); +- } +- +- void sendSearchFindTopLevelDeclarations(String pattern) { +- var params =3D new SearchFindTopLevelDeclarationsParams(pattern).toJs= on(); +- _send("search.findTopLevelDeclarations", params); +- } +- +- void sendSearchGetTypeHierarchy(String file, int offset, {bool superOnl= y}) { +- var params =3D +- new SearchGetTypeHierarchyParams(file, offset, superOnly: superOn= ly) +- .toJson(); +- _send("search.getTypeHierarchy", params); +- } +- +- RequestData sendServerGetVersion() { +- return _send("server.getVersion", null); +- } +- +- void sendServerSetSubscriptions(List subscriptions) { +- var params =3D new ServerSetSubscriptionsParams(subscriptions).toJson= (); +- _send("server.setSubscriptions", params); +- } +- +- void sendServerShutdown() { +- _send("server.shutdown", null); +- } +- +- /** +- * Start the server and listen for communications from it. +- * +- * If [checked] is `true`, the server's VM will be running in checked m= ode. +- * +- * If [diagnosticPort] is not `null`, the server will serve status page= s to +- * the specified port. +- * +- * If [profileServer] is `true`, the server will be started with "--obs= erve" +- * and "--pause-isolates-on-exit", allowing the observatory to be used. +- * +- * If [useAnalysisHighlight2] is `true`, the server will use the new hi= ghlight +- * APIs. +- */ +- Future start( +- {bool checked: true, +- int diagnosticPort, +- bool profileServer: false, +- String sdkPath, +- int servicesPort, +- bool useAnalysisHighlight2: false}) async { +- if (_process !=3D null) { +- throw new Exception('Process already started'); +- } +- String dartBinary =3D Platform.executable; +- String rootDir =3D +- _findRoot(Platform.script.toFilePath(windows: Platform.isWindows)= ); +- String serverPath =3D +- path.normalize(path.join(rootDir, 'bin', 'server.dart')); +- List arguments =3D []; +- // +- // Add VM arguments. +- // +- if (profileServer) { +- if (servicesPort =3D=3D null) { +- arguments.add('--observe'); +- } else { +- arguments.add('--observe=3D$servicesPort'); +- } +- arguments.add('--pause-isolates-on-exit'); +- } else if (servicesPort !=3D null) { +- arguments.add('--enable-vm-service=3D$servicesPort'); +- } +- if (Platform.packageRoot !=3D null) { +- arguments.add('--package-root=3D${Platform.packageRoot}'); +- } +- if (Platform.packageConfig !=3D null) { +- arguments.add('--packages=3D${Platform.packageConfig}'); +- } +- if (checked) { +- arguments.add('--checked'); +- } +- // +- // Add the server executable. +- // +- arguments.add(serverPath); +- // +- // Add server arguments. +- // +- if (diagnosticPort !=3D null) { +- arguments.add('--port'); +- arguments.add(diagnosticPort.toString()); +- } +- if (sdkPath !=3D null) { +- arguments.add('--sdk=3D$sdkPath'); +- } +- if (useAnalysisHighlight2) { +- arguments.add('--useAnalysisHighlight2'); +- } +-// stdout.writeln('Launching $serverPath'); +-// stdout.writeln('$dartBinary ${arguments.join(' ')}'); +- _process =3D await Process.start(dartBinary, arguments); +- _process.exitCode.then((int code) { +- if (code !=3D 0) { +- throw new StateError('Server terminated with exit code $code'); +- } +- }); +- _listenToOutput(); +- _serverConnectedCompleter =3D new Completer(); +- return _serverConnectedCompleter.future; +- } +- +- /** +- * Find the root directory of the analysis_server package by proceeding +- * upward to the 'test' dir, and then going up one more directory. +- */ +- String _findRoot(String pathname) { +- while (!['benchmark', 'test'].contains(path.basename(pathname))) { +- String parent =3D path.dirname(pathname); +- if (parent.length >=3D pathname.length) { +- throw new Exception("Can't find root directory"); +- } +- pathname =3D parent; +- } +- return path.dirname(pathname); +- } +- +- /** +- * Handle a [notification] received from the server. +- */ +- void _handleNotification(Notification notification) { +- switch (notification.event) { +- case "server.connected": +-// new ServerConnectedParams.fromNotification(notification); +- _serverConnectedCompleter.complete(null); +- break; +- case "server.error": +-// new ServerErrorParams.fromNotification(notification); +- throw new StateError('Server error: ${notification.toJson()}'); +- break; +- case "server.status": +- if (_analysisFinishedCompleter !=3D null) { +- ServerStatusParams params =3D +- new ServerStatusParams.fromNotification(notification); +- var analysis =3D params.analysis; +- if (analysis !=3D null && !analysis.isAnalyzing) { +- _analysisFinishedCompleter.complete(null); +- } +- } +- break; +- case "analysis.analyzedFiles": +- AnalysisAnalyzedFilesParams params =3D +- new AnalysisAnalyzedFilesParams.fromNotification(notification= ); +- _analyzedFiles =3D params.directories; +- break; +- case "analysis.errors": +- AnalysisErrorsParams params =3D +- new AnalysisErrorsParams.fromNotification(notification); +- _errorMap.pathMap[params.file] =3D params.errors; +- break; +- case "analysis.flushResults": +-// new AnalysisFlushResultsParams.fromNotification(notification); +- _errorMap.pathMap.clear(); +- break; +- case "analysis.folding": +-// new AnalysisFoldingParams.fromNotification(notification); +- break; +- case "analysis.highlights": +-// new AnalysisHighlightsParams.fromNotification(notification); +- break; +- case "analysis.implemented": +-// new AnalysisImplementedParams.fromNotification(notification); +- break; +- case "analysis.invalidate": +-// new AnalysisInvalidateParams.fromNotification(notification); +- break; +- case "analysis.navigation": +-// new AnalysisNavigationParams.fromNotification(notification); +- break; +- case "analysis.occurrences": +-// new AnalysisOccurrencesParams.fromNotification(notification); +- break; +- case "analysis.outline": +-// new AnalysisOutlineParams.fromNotification(notification); +- break; +- case "analysis.overrides": +-// new AnalysisOverridesParams.fromNotification(notification); +- break; +- case "completion.results": +-// new CompletionResultsParams.fromNotification(notification); +- break; +- case "search.results": +-// new SearchResultsParams.fromNotification(notification); +- break; +- case "execution.launchData": +-// new ExecutionLaunchDataParams.fromNotification(notification); +- break; +- default: +- throw new StateError( +- 'Unhandled notification: ${notification.toJson()}'); +- } +- } +- +- /** +- * Handle a [response] received from the server. +- */ +- void _handleResponse(Response response) { +- String id =3D response.id.toString(); +- RequestData requestData =3D _requestDataMap[id]; +- requestData.recordResponse(response); +-// switch (requestData.method) { +-// case "analysis.getErrors": +-// break; +-// case "analysis.getHover": +-// break; +-// case "analysis.getLibraryDependencies": +-// break; +-// case "analysis.getNavigation": +-// break; +-// case "analysis.getReachableSources": +-// break; +-// case "analysis.reanalyze": +-// break; +-// case "analysis.setAnalysisRoots": +-// break; +-// case "analysis.setGeneralSubscriptions": +-// break; +-// case "analysis.setPriorityFiles": +-// break; +-// case "analysis.setSubscriptions": +-// break; +-// case 'analysis.updateContent': +-// break; +-// case "analysis.updateOptions": +-// break; +-// case "completion.getSuggestions": +-// break; +-// case "diagnostic.getDiagnostics": +-// break; +-// case "edit.format": +-// break; +-// case "edit.getAssists": +-// break; +-// case "edit.getAvailableRefactorings": +-// break; +-// case "edit.getFixes": +-// break; +-// case "edit.getRefactoring": +-// break; +-// case "edit.organizeDirectives": +-// break; +-// case "edit.sortMembers": +-// break; +-// case "execution.createContext": +-// break; +-// case "execution.deleteContext": +-// break; +-// case "execution.mapUri": +-// break; +-// case "execution.setSubscriptions": +-// break; +-// case "search.findElementReferences": +-// break; +-// case "search.findMemberDeclarations": +-// break; +-// case "search.findMemberReferences": +-// break; +-// case "search.findTopLevelDeclarations": +-// break; +-// case "search.getTypeHierarchy": +-// break; +-// case "server.getVersion": +-// break; +-// case "server.setSubscriptions": +-// break; +-// case "server.shutdown": +-// break; +-// default: +-// throw new StateError('Unhandled response: ${response.toJson()}'= ); +-// } +- } +- +- /** +- * Handle a [line] of input read from stderr. +- */ +- void _handleStdErr(String line) { +- String trimmedLine =3D line.trim(); +- logger?.log(fromStderr, '$trimmedLine'); +- throw new StateError('Message received on stderr: "$trimmedLine"'); +- } +- +- /** +- * Handle a [line] of input read from stdout. +- */ +- void _handleStdOut(String line) { +- /** +- * Cast the given [value] to a Map, or throw an [ArgumentError] if th= e value +- * cannot be cast. +- */ +- Map asMap(Object value) { +- if (value is Map) { +- return value; +- } +- throw new ArgumentError('Expected a Map, found a ${value.runtimeTyp= e}'); +- } +- +- String trimmedLine =3D line.trim(); +- if (trimmedLine.isEmpty || +- trimmedLine.startsWith('Observatory listening on ')) { +- return; +- } +- logger?.log(fromServer, '$trimmedLine'); +- Map message =3D asMap(JSON.decoder.convert(trimmedLine)); +- if (message.containsKey('id')) { +- // The message is a response. +- Response response =3D new Response.fromJson(message); +- _handleResponse(response); +- } else { +- // The message is a notification. +- Notification notification =3D new Notification.fromJson(message); +- String event =3D notification.event; +- _notificationCountMap[event] =3D (_notificationCountMap[event] ?? 0= ) + 1; +- _handleNotification(notification); +- } +- } +- +- /** +- * Start listening to output from the server. +- */ +- void _listenToOutput() { +- /** +- * Install the given [handler] to listen to transformed output from t= he +- * given [stream]. +- */ +- void installHandler(Stream> stream, handler(String line)) { +- stream +- .transform((new Utf8Codec()).decoder) +- .transform(new LineSplitter()) +- .listen(handler); +- } +- +- installHandler(_process.stdout, _handleStdOut); +- installHandler(_process.stderr, _handleStdErr); +- } +- +- /** +- * Send a command to the server. An 'id' will be automatically assigned. +- */ +- RequestData _send(String method, Map params, +- {void onResponse(Response response)}) { +- String id =3D '${_nextId++}'; +- RequestData requestData =3D new RequestData(id, method, params, curre= ntTime); +- _requestDataMap[id] =3D requestData; +- Map command =3D { +- 'id': id, +- 'method': method +- }; +- if (params !=3D null) { +- command['params'] =3D params; +- } +- String line =3D JSON.encode(command); +- _process.stdin.add(UTF8.encoder.convert('$line\n')); +- logger?.log(fromClient, '$line'); +- return requestData; +- } +-} +- +-/** +- * A utility class used to compare two sets of errors. +- */ +-class _ErrorComparator { +- /** +- * An empty list of analysis errors. +- */ +- static final List NO_ERRORS =3D []; +- +- /** +- * The buffer to which an error description will be written if any of t= he +- * files have different errors than are expected. +- */ +- final StringBuffer buffer; +- +- /** +- * Initialize a newly created comparator to write to the given [buffer]. +- */ +- _ErrorComparator(this.buffer); +- +- /** +- * Compare the [actualErrorMap] and the [expectedErrorMap], writing a +- * description to the [buffer] if they are not the same. The error maps= are +- * expected to be maps from absolute file paths to the list of actual or +- * expected errors. +- */ +- void compare(Map> actualErrorMap, +- Map> expectedErrorMap) { +- Set allFiles =3D new HashSet(); +- allFiles.addAll(actualErrorMap.keys); +- allFiles.addAll(expectedErrorMap.keys); +- List sortedFiles =3D allFiles.toList()..sort(); +- for (String filePath in sortedFiles) { +- List actualErrors =3D actualErrorMap[filePath]; +- List expectedErrors =3D expectedErrorMap[filePath]; +- _compareLists( +- filePath, actualErrors ?? NO_ERRORS, expectedErrors ?? NO_ERROR= S); +- } +- } +- +- /** +- * Compare the [actualErrors] and [expectedErrors], writing a descripti= on to +- * the [buffer] if they are not the same. +- */ +- void _compareLists(String filePath, List actualErrors, +- List expectedErrors) { +- List remainingExpected =3D +- new List.from(expectedErrors); +- for (AnalysisError actualError in actualErrors) { +- AnalysisError expectedError =3D _findError(remainingExpected, actua= lError); +- if (expectedError =3D=3D null) { +- _writeReport(filePath, actualErrors, expectedErrors); +- return; +- } +- remainingExpected.remove(expectedError); +- } +- if (remainingExpected.isNotEmpty) { +- _writeReport(filePath, actualErrors, expectedErrors); +- } +- } +- +- /** +- * Return `true` if the [firstError] and the [secondError] are equivale= nt. +- */ +- bool _equalErrors(AnalysisError firstError, AnalysisError secondError) = =3D> +- firstError.severity =3D=3D secondError.severity && +- firstError.type =3D=3D secondError.type && +- _equalLocations(firstError.location, secondError.location) && +- firstError.message =3D=3D secondError.message; +- +- /** +- * Return `true` if the [firstLocation] and the [secondLocation] are +- * equivalent. +- */ +- bool _equalLocations(Location firstLocation, Location secondLocation) = =3D> +- firstLocation.file =3D=3D secondLocation.file && +- firstLocation.offset =3D=3D secondLocation.offset && +- firstLocation.length =3D=3D secondLocation.length; +- +- /** +- * Search through the given list of [errors] for an error that is equal= to the +- * [targetError]. If one is found, return it, otherwise return `null`. +- */ +- AnalysisError _findError( +- List errors, AnalysisError targetError) { +- for (AnalysisError error in errors) { +- if (_equalErrors(error, targetError)) { +- return error; +- } +- } +- return null; +- } +- +- /** +- * Write the given list of [errors], preceded by a header beginning wit= h the +- * given [prefix]. +- */ +- void _writeErrors(String prefix, List errors) { +- buffer.write(prefix); +- buffer.write(errors.length); +- buffer.write(' errors:'); +- for (AnalysisError error in errors) { +- buffer.writeln(); +- Location location =3D error.location; +- int offset =3D location.offset; +- buffer.write(' '); +- buffer.write(location.file); +- buffer.write(' ('); +- buffer.write(offset); +- buffer.write('..'); +- buffer.write(offset + location.length); +- buffer.write(') '); +- buffer.write(error.severity); +- buffer.write(', '); +- buffer.write(error.type); +- buffer.write(' : '); +- buffer.write(error.message); +- } +- } +- +- /** +- * Write a report of the differences between the [actualErrors] and the +- * [expectedErrors]. The errors are reported as being from the file at = the +- * given [filePath]. +- */ +- void _writeReport(String filePath, List actualErrors, +- List expectedErrors) { +- if (buffer.length > 0) { +- buffer.writeln(); +- buffer.writeln(); +- } +- buffer.writeln(filePath); +- _writeErrors(' Expected ', expectedErrors); +- buffer.writeln(); +- _writeErrors(' Found ', actualErrors); +- } +-} +diff --git a/pkg/analysis_server/test/test_all.dart b/pkg/analysis_server/= test/test_all.dart +deleted file mode 100644 +index a736732eab6..00000000000 +--- a/pkg/analysis_server/test/test_all.dart ++++ /dev/null +@@ -1,61 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:test_reflective_loader/test_reflective_loader.dart'; +- +-import '../tool/spec/check_all_test.dart' as check_spec; +-import 'analysis/test_all.dart' as analysis_all; +-import 'analysis_server_test.dart' as analysis_server_test; +-import 'channel/test_all.dart' as channel_test; +-import 'completion_test.dart' as completion_test; +-import 'context_manager_test.dart' as context_manager_test; +-import 'domain_analysis_test.dart' as domain_analysis_test; +-import 'domain_completion_test.dart' as domain_completion_test; +-import 'domain_diagnostic_test.dart' as domain_experimental_test; +-import 'domain_execution_test.dart' as domain_execution_test; +-import 'domain_server_test.dart' as domain_server_test; +-import 'edit/test_all.dart' as edit_all; +-import 'plugin/test_all.dart' as plugin_all; +-import 'protocol_server_test.dart' as protocol_server_test; +-import 'protocol_test.dart' as protocol_test; +-import 'search/test_all.dart' as search_all; +-import 'services/test_all.dart' as services_all; +-import 'socket_server_test.dart' as socket_server_test; +-import 'src/test_all.dart' as src_all; +- +-/** +- * Utility for manually running all tests. +- */ +-main() { +- defineReflectiveSuite(() { +- analysis_all.main(); +- analysis_server_test.main(); +- channel_test.main(); +- completion_test.main(); +- context_manager_test.main(); +- domain_analysis_test.main(); +- domain_completion_test.main(); +- domain_execution_test.main(); +- domain_experimental_test.main(); +- domain_server_test.main(); +- edit_all.main(); +- plugin_all.main(); +- protocol_server_test.main(); +- protocol_test.main(); +- search_all.main(); +- services_all.main(); +- socket_server_test.main(); +- src_all.main(); +- defineReflectiveSuite(() { +- defineReflectiveTests(SpecTest); +- }, name: 'spec'); +- }, name: 'analysis_server'); +-} +- +-@reflectiveTest +-class SpecTest { +- test_specHasBeenGenerated() { +- check_spec.main(); +- } +-} +diff --git a/pkg/analysis_server/test/timing/completion/completion_simple.= dart b/pkg/analysis_server/test/timing/completion/completion_simple.dart +deleted file mode 100644 +index 50cbaa2ed08..00000000000 +--- a/pkg/analysis_server/test/timing/completion/completion_simple.dart ++++ /dev/null +@@ -1,111 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +-import 'package:path/path.dart'; +- +-import '../timing_framework.dart'; +- +-/** +- * Perform the timing test, printing the minimum, average and maximum tim= es, as +- * well as the standard deviation to the output. +- */ +-void main(List args) { +- SimpleTest test =3D new SimpleTest(); +- test.run().then((TimingResult result) { +- print('minTime =3D ${result.minTime}'); +- print('averageTime =3D ${result.averageTime}'); +- print('maxTime =3D ${result.maxTime}'); +- print('standardDeviation =3D ${result.standardDeviation}'); +- print(''); +- print('Press return to exit'); +- return stdin.first; +- }); +-} +- +-/** +- * A test of how long it takes to get code completion results after makin= g a +- * minor change inside a method body. +- */ +-class SimpleTest extends TimingTest { +- /** +- * The path to the file in which code completion is to be performed. +- */ +- String mainFilePath; +- +- /** +- * The original content of the file. +- */ +- String originalContent; +- +- /** +- * The offset of the cursor when requesting code completion. +- */ +- int cursorOffset; +- +- /** +- * A completer that will be completed when code completion results have= been +- * received from the server. +- */ +- Completer completionReceived; +- +- /** +- * Initialize a newly created test. +- */ +- SimpleTest(); +- +- @override +- Future oneTimeSetUp() { +- return super.oneTimeSetUp().then((_) { +- mainFilePath =3D sourcePath('test.dart'); +- originalContent =3D r''' +-class C { +- m() { +- return 0; +- } +-} +- +-f(C c) { +- return c; +-} +-'''; +- cursorOffset =3D originalContent.indexOf('c;') + 1; +- writeFile(mainFilePath, originalContent); +- }); +- } +- +- @override +- Future perform() { +- sendAnalysisUpdateContent({ +- mainFilePath: +- new ChangeContentOverlay([new SourceEdit(cursorOffset, 0, '.')]) +- }); +- sendCompletionGetSuggestions(mainFilePath, cursorOffset + 1); +- return completionReceived.future; +- } +- +- @override +- Future setUp() { +- completionReceived =3D new Completer(); +- onCompletionResults.listen((_) { +- // We only care about the time to the first response. +- if (!completionReceived.isCompleted) { +- completionReceived.complete(); +- } +- }); +- sendAnalysisSetAnalysisRoots([dirname(mainFilePath)], []); +- sendAnalysisUpdateContent( +- {mainFilePath: new AddContentOverlay(originalContent)}); +- return new Future.value(); +- } +- +- @override +- Future tearDown() { +- sendAnalysisSetAnalysisRoots([], []); +- return new Future.value(); +- } +-} +diff --git a/pkg/analysis_server/test/timing/timing_framework.dart b/pkg/a= nalysis_server/test/timing/timing_framework.dart +deleted file mode 100644 +index 9c4be1f7b40..00000000000 +--- a/pkg/analysis_server/test/timing/timing_framework.dart ++++ /dev/null +@@ -1,312 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +-import 'dart:math'; +- +-import 'package:path/path.dart'; +- +-import '../integration/support/integration_test_methods.dart'; +-import '../integration/support/integration_tests.dart'; +- +-/** +- * Instances of the class [TimingResult] represent the timing information +- * gathered while executing a given timing test. +- */ +-class TimingResult { +- /** +- * The number of nanoseconds in a millisecond. +- */ +- static int NANOSECONDS_PER_MILLISECOND =3D 1000000; +- +- /** +- * The amount of time spent executing each test, in nanoseconds. +- */ +- List times; +- +- /** +- * Initialize a newly created timing result. +- */ +- TimingResult(this.times); +- +- /** +- * The average amount of time spent executing a single iteration, in +- * milliseconds. +- */ +- int get averageTime { +- return totalTime ~/ times.length; +- } +- +- /** +- * The maximum amount of time spent executing a single iteration, in +- * milliseconds. +- */ +- int get maxTime { +- int maxTime =3D 0; +- int count =3D times.length; +- for (int i =3D 0; i < count; i++) { +- maxTime =3D max(maxTime, times[i]); +- } +- return maxTime ~/ NANOSECONDS_PER_MILLISECOND; +- } +- +- /** +- * The minimum amount of time spent executing a single iteration, in +- * milliseconds. +- */ +- int get minTime { +- int minTime =3D times[0]; +- int count =3D times.length; +- for (int i =3D 1; i < count; i++) { +- minTime =3D min(minTime, times[i]); +- } +- return minTime ~/ NANOSECONDS_PER_MILLISECOND; +- } +- +- /** +- * The standard deviation of the times. +- */ +- double get standardDeviation { +- return computeStandardDeviation(toMilliseconds(times)); +- } +- +- /** +- * The total amount of time spent executing the test, in milliseconds. +- */ +- int get totalTime { +- int totalTime =3D 0; +- int count =3D times.length; +- for (int i =3D 0; i < count; i++) { +- totalTime +=3D times[i]; +- } +- return totalTime ~/ NANOSECONDS_PER_MILLISECOND; +- } +- +- /** +- * Compute the standard deviation of the given set of [values]. +- */ +- double computeStandardDeviation(List values) { +- int count =3D values.length; +- double sumOfValues =3D 0.0; +- for (int i =3D 0; i < count; i++) { +- sumOfValues +=3D values[i]; +- } +- double average =3D sumOfValues / count; +- double sumOfDiffSquared =3D 0.0; +- for (int i =3D 0; i < count; i++) { +- double diff =3D values[i] - average; +- sumOfDiffSquared +=3D diff * diff; +- } +- return sqrt((sumOfDiffSquared / (count - 1))); +- } +- +- /** +- * Convert the given [times], expressed in nanoseconds, to times expres= sed in +- * milliseconds. +- */ +- List toMilliseconds(List times) { +- int count =3D times.length; +- List convertedValues =3D new List(); +- for (int i =3D 0; i < count; i++) { +- convertedValues.add(times[i] ~/ NANOSECONDS_PER_MILLISECOND); +- } +- return convertedValues; +- } +-} +- +-/** +- * The abstract class [TimingTest] defines the behavior of objects that m= easure +- * the time required to perform some sequence of server operations. +- */ +-abstract class TimingTest extends IntegrationTestMixin { +- /** +- * The number of times the test will be performed in order to warm up t= he VM. +- */ +- static final int DEFAULT_WARMUP_COUNT =3D 10; +- +- /** +- * The number of times the test will be performed in order to compute a= time. +- */ +- static final int DEFAULT_TIMING_COUNT =3D 10; +- +- /** +- * The file suffix used to identify Dart files. +- */ +- static final String DART_SUFFIX =3D '.dart'; +- +- /** +- * The file suffix used to identify HTML files. +- */ +- static final String HTML_SUFFIX =3D '.html'; +- +- /** +- * The amount of time to give the server to respond to a shutdown reque= st +- * before forcibly terminating it. +- */ +- static const Duration SHUTDOWN_TIMEOUT =3D const Duration(seconds: 5); +- +- /** +- * The connection to the analysis server. +- */ +- Server server; +- +- /** +- * The temporary directory in which source files can be stored. +- */ +- Directory sourceDirectory; +- +- /** +- * A flag indicating whether the teardown process should skip sending a +- * "server.shutdown" request because the server is known to have already +- * shutdown. +- */ +- bool skipShutdown =3D false; +- +- /** +- * Initialize a newly created test. +- */ +- TimingTest(); +- +- /** +- * Return the number of iterations that should be performed in order to +- * compute a time. +- */ +- int get timingCount =3D> DEFAULT_TIMING_COUNT; +- +- /** +- * Return the number of iterations that should be performed in order to= warm +- * up the VM. +- */ +- int get warmupCount =3D> DEFAULT_WARMUP_COUNT; +- +- /** +- * Perform any operations that need to be performed once before any ite= rations. +- */ +- Future oneTimeSetUp() { +- initializeInttestMixin(); +- server =3D new Server(); +- sourceDirectory =3D Directory.systemTemp.createTempSync('analysisServ= er'); +- Completer serverConnected =3D new Completer(); +- onServerConnected.listen((_) { +- serverConnected.complete(); +- }); +- skipShutdown =3D true; +- return server.start(/*profileServer: true*/).then((_) { +- server.listenToOutput(dispatchNotification); +- server.exitCode.then((_) { +- skipShutdown =3D true; +- }); +- return serverConnected.future; +- }); +- } +- +- /** +- * Perform any operations that need to be performed once after all iter= ations. +- */ +- Future oneTimeTearDown() { +- return _shutdownIfNeeded().then((_) { +- sourceDirectory.deleteSync(recursive: true); +- }); +- } +- +- /** +- * Perform any operations that part of a single iteration. It is the ex= ecution +- * of this method that will be measured. +- */ +- Future perform(); +- +- /** +- * Return a future that will complete with a timing result representing= the +- * number of milliseconds required to perform the operation the specifi= ed +- * number of times. +- */ +- Future run() async { +- List times =3D new List(); +- await oneTimeSetUp(); +- await _repeat(warmupCount, null); +- await _repeat(timingCount, times); +- await oneTimeTearDown(); +- return new Future.value(new TimingResult(times)); +- } +- +- /** +- * Perform any operations that need to be performed before each iterati= on. +- */ +- Future setUp(); +- +- /** +- * Convert the given [relativePath] to an absolute path, by interpretin= g it +- * relative to [sourceDirectory]. On Windows any forward slashes in +- * [relativePath] are converted to backslashes. +- */ +- String sourcePath(String relativePath) { +- return join(sourceDirectory.path, relativePath.replaceAll('/', separa= tor)); +- } +- +- /** +- * Perform any operations that need to be performed after each iteratio= n. +- */ +- Future tearDown(); +- +- /** +- * Write a source file with the given absolute [pathname] and [contents= ]. +- * +- * If the file didn't previously exist, it is created. If it did, it is +- * overwritten. +- * +- * Parent directories are created as necessary. +- */ +- void writeFile(String pathname, String contents) { +- new Directory(dirname(pathname)).createSync(recursive: true); +- new File(pathname).writeAsStringSync(contents); +- } +- +- /** +- * Return the number of nanoseconds that have elapsed since the given +- * [stopwatch] was last stopped. +- */ +- int _elapsedNanoseconds(Stopwatch stopwatch) { +- return (stopwatch.elapsedTicks * 1000000000) ~/ stopwatch.frequency; +- } +- +- /** +- * Repeatedly execute this test [count] times, adding timing informatio= n to +- * the given list of [times] if it is non-`null`. +- */ +- Future _repeat(int count, List times) { +- Stopwatch stopwatch =3D new Stopwatch(); +- return setUp().then((_) { +- stopwatch.start(); +- return perform().then((_) { +- stopwatch.stop(); +- if (times !=3D null) { +- times.add(_elapsedNanoseconds(stopwatch)); +- } +- return tearDown().then((_) { +- if (count > 0) { +- return _repeat(count - 1, times); +- } else { +- return new Future.value(); +- } +- }); +- }); +- }); +- } +- +- /** +- * Shut the server down unless [skipShutdown] is `true`. +- */ +- Future _shutdownIfNeeded() { +- if (skipShutdown) { +- return new Future.value(); +- } +- // Give the server a short time to comply with the shutdown request; = if it +- // doesn't exit, then forcibly terminate it. +- sendServerShutdown(); +- return server.exitCode.timeout(SHUTDOWN_TIMEOUT, onTimeout: () { +- return server.kill('server failed to exit'); +- }); +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/log/log.dart b/pkg/a= nalysis_server/tool/instrumentation/log/log.dart +deleted file mode 100644 +index 544013cd027..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/log/log.dart ++++ /dev/null +@@ -1,1195 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * A representation of the contents of an instrumentation log. +- */ +-import 'dart:convert'; +-import 'dart:math' as math; +- +-import 'package:analyzer/instrumentation/instrumentation.dart'; +-import 'package:path/path.dart' as path; +- +-/** +- * A boolean-valued function of one argument. +- */ +-typedef bool Predicate(T value); +- +-/** +- * A description of a group of log entries. +- */ +-class EntryGroup { +- /** +- * A list of all of the instances of this class. +- */ +- static final List groups =3D [ +- new EntryGroup._( +- 'nonTask', 'Non-task', (LogEntry entry) =3D> entry is! TaskEntry), +- new EntryGroup._( +- 'errors', +- 'Errors', +- (LogEntry entry) =3D> +- entry is ErrorEntry || +- entry is ExceptionEntry || +- (entry is NotificationEntry && entry.isServerError)), +- new EntryGroup._('malformed', 'Malformed', +- (LogEntry entry) =3D> entry is MalformedLogEntry), +- new EntryGroup._('all', 'All', (LogEntry entry) =3D> true), +- ]; +- +- /** +- * The unique id of the group. +- */ +- final String id; +- +- /** +- * The human-readable name of the group. +- */ +- final String name; +- +- /** +- * The filter used to determine which entries belong to the group. The = filter +- * should return `true` for members and `false` for non-members. +- */ +- final Predicate filter; +- +- /** +- * Initialize a newly created entry group with the given state. +- */ +- EntryGroup._(this.id, this.name, this.filter); +- +- /** +- * Given a list of [entries], return all of the entries in the list tha= t are +- * members of this group. +- */ +- List computeMembers(List entries) { +- return entries.where(filter).toList(); +- } +- +- /** +- * Return the entry group with the given [id], or `null` if there is no= group +- * with the given id. +- */ +- static EntryGroup withId(String id) { +- for (EntryGroup group in groups) { +- if (group.id =3D=3D id) { +- return group; +- } +- } +- return null; +- } +-} +- +-/** +- * A range of log entries, represented by the index of the first and last +- * entries in the range. +- */ +-class EntryRange { +- /** +- * The index of the first entry in the range. +- */ +- int firstIndex; +- +- /** +- * The index of the first entry in the range. +- */ +- int lastIndex; +- +- /** +- * Initialize a newly created range to represent the entries between the +- * [firstIndex] and the [lastIndex], inclusive. +- */ +- EntryRange(this.firstIndex, this.lastIndex); +-} +- +-/** +- * A log entry representing an Err entry. +- */ +-class ErrorEntry extends GenericEntry { +- /** +- * Initialize a newly created log entry. +- */ +- ErrorEntry( +- int index, int timeStamp, String entryKind, List components) +- : super(index, timeStamp, entryKind, components); +-} +- +-/** +- * A log entry representing an Ex entry. +- */ +-class ExceptionEntry extends GenericEntry { +- /** +- * Initialize a newly created log entry. +- */ +- ExceptionEntry( +- int index, int timeStamp, String entryKind, List components) +- : super(index, timeStamp, entryKind, components); +-} +- +-/** +- * A representation of a generic log entry. +- */ +-class GenericEntry extends LogEntry { +- /** +- * The kind of the log entry. +- */ +- String entryKind; +- +- /** +- * The components in the entry that follow the time stamp and entry kin= d. +- */ +- List components; +- +- /** +- * Initialize a newly created generic log entry to have the given [time= Stamp], +- * [entryKind] and list of [components] +- */ +- GenericEntry(int index, int timeStamp, this.entryKind, this.components) +- : super(index, timeStamp); +- +- @override +- String get kind =3D> entryKind; +- +- @override +- void _appendDetails(StringBuffer buffer) { +- super._appendDetails(buffer); +- for (String component in components) { +- buffer.write(component); +- buffer.write('
    '); +- } +- } +-} +- +-/** +- * A log entry representing an PluginErr entry. +- */ +-class GenericPluginEntry extends GenericEntry with PluginEntryMixin { +- /** +- * The components describing the plugin associated with this entry. +- */ +- final List pluginData; +- +- /** +- * Initialize a newly created log entry. +- */ +- GenericPluginEntry(int index, int timeStamp, String entryKind, +- List components, this.pluginData) +- : super(index, timeStamp, entryKind, components); +-} +- +-/** +- * A representation of an instrumentation log. +- */ +-class InstrumentationLog { +- /** +- * The paths of the log files containing the entries. +- */ +- List logFilePaths; +- +- /** +- * The entries in the instrumentation log. +- */ +- List logEntries; +- +- /** +- * A table mapping the entry groups that have been computed to the list= of +- * entries in that group. +- */ +- Map> entryGroups =3D >{}; +- +- /** +- * A table mapping entries that are paired with another entry to the en= try +- * with which they are paired. +- */ +- Map _pairedEntries =3D {}; +- +- /** +- * A table mapping the id's of requests to the entry representing the r= equest. +- */ +- Map _requestMap =3D {}; +- +- /** +- * A table mapping the id's of plugin requests to the entry representin= g the +- * request. +- */ +- Map _pluginRequestMap =3D +- {}; +- +- /** +- * A table mapping the id's of responses to the entry representing the +- * response. +- */ +- Map _responseMap =3D {}; +- +- /** +- * A table mapping the id's of plugin responses to the entry representi= ng the +- * response. +- */ +- Map _pluginResponseMap =3D +- {}; +- +- /** +- * A table mapping the ids of completion events to the events with thos= e ids. +- */ +- Map> _completionMap =3D +- >{}; +- +- /** +- * The ranges of entries that are between analysis start and analysis e= nd +- * notifications. +- */ +- List analysisRanges; +- +- /** +- * Initialize a newly created instrumentation log by parsing each of th= e lines +- * in the [logContent] into a separate entry. The log contents should b= e the +- * contents of the files whose paths are in the given list of [logFileP= aths]. +- */ +- InstrumentationLog(this.logFilePaths, List logContent) { +- _parseLogContent(logContent); +- } +- +- /** +- * Return a list of the completion events associated with the given [id= ]. +- */ +- List completionEventsWithId(String id) =3D> +- _completionMap[id]; +- +- /** +- * Return the log entries that are contained in the given [group]. +- */ +- List entriesInGroup(EntryGroup group) =3D> +- entryGroups.putIfAbsent(group, () =3D> group.computeMembers(logEntr= ies)); +- +- /** +- * Return the entry that is paired with the given [entry], or `null` if= there +- * is no entry paired with it. +- */ +- LogEntry pairedEntry(LogEntry entry) =3D> _pairedEntries[entry]; +- +- /** +- * Return the response that corresponds to the given plugin request. +- */ +- PluginRequestEntry pluginRequestFor(PluginResponseEntry entry) =3D> +- _pluginRequestMap[entry.id]; +- +- /** +- * Return the response that corresponds to the given request. +- */ +- PluginResponseEntry pluginResponseFor(PluginRequestEntry entry) =3D> +- _pluginResponseMap[entry.id]; +- +- /** +- * Return the response that corresponds to the given request. +- */ +- RequestEntry requestFor(ResponseEntry entry) =3D> _requestMap[entry.id]; +- +- /** +- * Return the response that corresponds to the given request. +- */ +- ResponseEntry responseFor(RequestEntry entry) =3D> _responseMap[entry.i= d]; +- +- /** +- * Return a list containing all of the task entries between the start of +- * analysis notification at the given [startIndex] and the matching end= of +- * analysis notification (or the end of the log if the log does not con= tain a +- * corresponding end notification. +- */ +- List taskEntriesFor(int startIndex) { +- List taskEntries =3D []; +- NotificationEntry startEntry =3D logEntries[startIndex]; +- LogEntry endEntry =3D pairedEntry(startEntry); +- int lastIndex =3D endEntry =3D=3D null ? logEntries.length : endEntry= .index; +- for (int i =3D startEntry.index + 1; i < lastIndex; i++) { +- LogEntry entry =3D logEntries[i]; +- if (entry is TaskEntry) { +- taskEntries.add(entry); +- } +- } +- return taskEntries; +- } +- +- /** +- * Return `true` if the given [logContent] appears to be from session d= ata. +- */ +- bool _isSessionData(List logContent) { +- if (logContent.length < 2) { +- return false; +- } +- String firstLine =3D logContent[0]; +- return firstLine.startsWith('-----') && logContent[1].startsWith('~')= || +- firstLine.startsWith('~'); +- } +- +- /** +- * Merge any multi-line entries into a single line so that every elemen= t in +- * the given [logContent] is a single entry. +- */ +- void _mergeEntries(List logContent) { +- bool isStartOfEntry(String line) { +- return line.startsWith(LogEntry.entryRegExp); +- } +- +- String merge(String line, List extraLines) { +- StringBuffer buffer =3D new StringBuffer(); +- buffer.writeln(line); +- for (String extraLine in extraLines) { +- buffer.writeln(extraLine); +- } +- return buffer.toString(); +- } +- +- List extraLines =3D []; +- for (int i =3D logContent.length - 1; i >=3D 0; i--) { +- String line =3D logContent[i]; +- if (isStartOfEntry(line)) { +- if (extraLines.isNotEmpty) { +- logContent[i] =3D merge(line, extraLines); +- } +- extraLines.clear(); +- } else { +- logContent.removeAt(i); +- extraLines.insert(0, line); +- } +- } +- if (extraLines.isNotEmpty) { +- int count =3D math.min(extraLines.length, 10); +- StringBuffer buffer =3D new StringBuffer(); +- buffer.writeln('${extraLines.length} non-entry lines before any ent= ry'); +- buffer.writeln('First $count lines:'); +- for (int i =3D 0; i < count; i++) { +- buffer.writeln(extraLines[i]); +- } +- throw new StateError(buffer.toString()); +- } +- } +- +- /** +- * Parse the given [logContent] into a list of log entries. +- */ +- void _parseLogContent(List logContent) { +- if (_isSessionData(logContent)) { +- if (logContent[0].startsWith('-----')) { +- logContent.removeAt(0); +- } +- int lastIndex =3D logContent.length - 1; +- if (logContent[lastIndex].startsWith('extraction complete')) { +- logContent.removeAt(lastIndex); +- } +- } else { +- _mergeEntries(logContent); +- } +- logEntries =3D []; +- analysisRanges =3D []; +- NotificationEntry analysisStartEntry =3D null; +- int analysisStartIndex =3D -1; +- NotificationEntry pubStartEntry =3D null; +- for (String line in logContent) { +- LogEntry entry =3D new LogEntry.from(logEntries.length, line); +- if (entry !=3D null) { +- logEntries.add(entry); +- if (entry is RequestEntry) { +- _requestMap[entry.id] =3D entry; +- } else if (entry is ResponseEntry) { +- _responseMap[entry.id] =3D entry; +- RequestEntry request =3D _requestMap[entry.id]; +- _pairedEntries[entry] =3D request; +- _pairedEntries[request] =3D entry; +- } else if (entry is NotificationEntry) { +- if (entry.isServerStatus) { +- var analysisStatus =3D entry.param('analysis'); +- if (analysisStatus is Map) { +- if (analysisStatus['isAnalyzing']) { +- if (analysisStartEntry !=3D null) { +- analysisStartEntry.recordProblem( +- 'Analysis started without being terminated.'); +- } +- analysisStartEntry =3D entry; +- analysisStartIndex =3D logEntries.length - 1; +- } else { +- if (analysisStartEntry =3D=3D null) { +- entry.recordProblem( +- 'Analysis terminated without being started.'); +- } else { +- int analysisEnd =3D logEntries.length - 1; +- analysisRanges +- .add(new EntryRange(analysisStartIndex, analysisEnd= )); +- _pairedEntries[entry] =3D analysisStartEntry; +- _pairedEntries[analysisStartEntry] =3D entry; +- analysisStartEntry =3D null; +- analysisStartIndex =3D -1; +- } +- } +- } +- var pubStatus =3D entry.param('pub'); +- if (pubStatus is Map) { +- if (pubStatus['isListingPackageDirs']) { +- if (pubStartEntry !=3D null) { +- pubStartEntry.recordProblem( +- 'Pub started without previous being terminated.'); +- } +- pubStartEntry =3D entry; +- } else { +- if (pubStartEntry =3D=3D null) { +- entry.recordProblem('Pub terminated without being start= ed.'); +- } else { +- _pairedEntries[entry] =3D pubStartEntry; +- _pairedEntries[pubStartEntry] =3D entry; +- pubStartEntry =3D null; +- } +- } +- } +- } else if (entry.event =3D=3D 'completion.results') { +- String id =3D entry.param('id'); +- if (id !=3D null) { +- _completionMap +- .putIfAbsent(id, () =3D> new List()) +- .add(entry); +- } +- } +- } else if (entry is PluginRequestEntry) { +- _pluginRequestMap[entry.id] =3D entry; +- } else if (entry is PluginResponseEntry) { +- _pluginResponseMap[entry.id] =3D entry; +- PluginRequestEntry request =3D _pluginRequestMap[entry.id]; +- _pairedEntries[entry] =3D request; +- _pairedEntries[request] =3D entry; +- } +- } +- } +- if (analysisStartEntry !=3D null) { +- analysisStartEntry +- .recordProblem('Analysis started without being terminated.'); +- } +- if (pubStartEntry !=3D null) { +- pubStartEntry +- .recordProblem('Pub started without previous being terminated.'= ); +- } +- } +-} +- +-/** +- * A log entry that has a single JSON encoded component following the tim= e stamp +- * and entry kind. +- */ +-abstract class JsonBasedEntry extends LogEntry { +- /** +- * The HTML string used to indent text when formatting the JSON [data]. +- */ +- static const String singleIndent =3D '   '; +- +- /** +- * The decoded form of the JSON encoded component. +- */ +- final Map data; +- +- /** +- * Initialize a newly created log entry to have the given [timeStamp] a= nd +- * [data]. +- */ +- JsonBasedEntry(int index, int timeStamp, this.data) : super(index, time= Stamp); +- +- @override +- void _appendDetails(StringBuffer buffer) { +- super._appendDetails(buffer); +- _format(buffer, '', data); +- } +- +- /** +- * Encode any character in the given [string] that would prevent source= code +- * from being displayed correctly: end of line markers and spaces. +- */ +- String _encodeSourceCode(String string) { +- // TODO(brianwilkerson) This method isn't working completely. Some so= urce +- // code produces an error of +- // "log?start=3D3175:261 Uncaught SyntaxError: missing ) after argume= nt list" +- // in the sample log I was using. +- StringBuffer buffer =3D new StringBuffer(); +- int length =3D string.length; +- int index =3D 0; +- while (index < length) { +- int char =3D string.codeUnitAt(index); +- index++; +- // TODO(brianwilkerson) Handle tabs and other special characters. +- if (char =3D=3D '\r'.codeUnitAt(0)) { +- if (index < length && string.codeUnitAt(index) =3D=3D '\n'.codeUn= itAt(0)) { +- index++; +- } +- buffer.write('
    '); +- } else if (char =3D=3D '\n'.codeUnitAt(0)) { +- buffer.write('
    '); +- } else if (char =3D=3D ' '.codeUnitAt(0)) { +- // Encode all spaces in order to accurately reproduce the original +- // source code when displaying it. +- buffer.write(' '); +- } else { +- buffer.writeCharCode(char); +- } +- } +- return buffer.toString(); +- } +- +- /** +- * Write an HTML representation the given JSON [object] to the given [b= uffer], +- * using the given [indent] to make the output more readable. +- */ +- void _format(StringBuffer buffer, String indent, Object object) { +- if (object is String) { +- buffer.write('"'); +- buffer.write(_encodeSourceCode(object)); +- buffer.write('"'); +- } else if (object is int || object is bool) { +- buffer.write(object); +- } else if (object is Map) { +- buffer.write('{
    '); +- object.forEach((Object key, Object value) { +- String newIndent =3D indent + singleIndent; +- buffer.write(newIndent); +- _format(buffer, newIndent, key); +- buffer.write(' : '); +- _format(buffer, newIndent, value); +- buffer.write('
    '); +- }); +- buffer.write(indent); +- buffer.write('}'); +- } else if (object is List) { +- buffer.write('[
    '); +- object.forEach((Object element) { +- String newIndent =3D indent + singleIndent; +- buffer.write(newIndent); +- _format(buffer, newIndent, element); +- buffer.write('
    '); +- }); +- buffer.write(indent); +- buffer.write(']'); +- } +- } +-} +- +-/** +- * A log entry representing a communication between the server and a plug= in. +- */ +-abstract class JsonBasedPluginEntry extends JsonBasedEntry +- with PluginEntryMixin { +- /** +- * The components describing the plugin associated with this entry. +- */ +- final List pluginData; +- +- /** +- * Initialize a newly created entry to have the given [timeStamp] and +- * [notificationData] and to be associated with the plugin with the giv= en +- * [pluginData]. +- */ +- JsonBasedPluginEntry( +- int index, int timeStamp, Map notificationData, this.pluginData) +- : super(index, timeStamp, notificationData); +-} +- +-/** +- * A single entry in an instrumentation log. +- */ +-abstract class LogEntry { +- /** +- * The character used to separate fields within an entry. +- */ +- static final int fieldSeparator =3D ':'.codeUnitAt(0); +- +- /** +- * A regular expression that will match the beginning of a valid log en= try. +- */ +- static final RegExp entryRegExp =3D new RegExp('[0-9]+\\:'); +- +- /** +- * A table mapping kinds to the names of those kinds. +- */ +- static final Map kindMap =3D { +- 'Err': 'Error', +- 'Ex': 'Exception', +- 'Log': 'Log message', +- 'Mal': 'Malformed entry', +- 'Noti': 'Notification', +- 'Read': 'Read file', +- 'Req': 'Request', +- 'Res': 'Response', +- 'Perf': 'Performance data', +- 'SPResult': 'Subprocess result', +- 'SPStart': 'Subprocess start', +- 'Task': 'Task', +- 'Ver': 'Version information', +- 'Watch': 'Watch event', +- }; +- +- /** +- * The index of this entry in the log file. +- */ +- final int index; +- +- /** +- * The time at which the entry occurred. +- */ +- final int timeStamp; +- +- /** +- * A list containing the descriptions of problems that were found while +- * processing the log file, or `null` if no problems were found. +- */ +- List _problems =3D null; +- +- /** +- * Initialize a newly created log entry with the given [timeStamp]. +- */ +- LogEntry(this.index, this.timeStamp); +- +- /** +- * Create a log entry from the given encoded form of the [entry]. +- */ +- factory LogEntry.from(int index, String entry) { +- if (entry.isEmpty) { +- return null; +- } +- try { +- List components =3D _parseComponents(entry); +- int timeStamp; +- String component =3D components[0]; +- if (component.startsWith('~')) { +- component =3D component.substring(1); +- } +- timeStamp =3D int.parse(component); +- String entryKind =3D components[1]; +- if (entryKind =3D=3D InstrumentationService.TAG_ANALYSIS_TASK) { +- return new TaskEntry(index, timeStamp, components[2], components[= 3]); +- } else if (entryKind =3D=3D InstrumentationService.TAG_ERROR) { +- return new ErrorEntry( +- index, timeStamp, entryKind, components.sublist(2)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_EXCEPTION) { +- return new ExceptionEntry( +- index, timeStamp, entryKind, components.sublist(2)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_FILE_READ) { +- // Fall through +- } else if (entryKind =3D=3D InstrumentationService.TAG_LOG_ENTRY) { +- // Fall through +- } else if (entryKind =3D=3D InstrumentationService.TAG_NOTIFICATION= ) { +- Map requestData =3D JSON.decode(components[2]); +- return new NotificationEntry(index, timeStamp, requestData); +- } else if (entryKind =3D=3D InstrumentationService.TAG_PERFORMANCE)= { +- // Fall through +- } else if (entryKind =3D=3D InstrumentationService.TAG_PLUGIN_ERROR= ) { +- return new PluginErrorEntry(index, timeStamp, entryKind, +- components.sublist(2, 4), components.sublist(4)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_PLUGIN_EXCEP= TION) { +- return new PluginExceptionEntry(index, timeStamp, entryKind, +- components.sublist(2, 5), components.sublist(5)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_PLUGIN_NOTIF= ICATION) { +- Map requestData =3D JSON.decode(components[2]); +- return new PluginNotificationEntry( +- index, timeStamp, requestData, components.sublist(3)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_PLUGIN_REQUE= ST) { +- Map requestData =3D JSON.decode(components[2]); +- return new PluginRequestEntry( +- index, timeStamp, requestData, components.sublist(3)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_PLUGIN_RESPO= NSE) { +- Map responseData =3D JSON.decode(components[2]); +- return new PluginResponseEntry( +- index, timeStamp, responseData, components.sublist(3)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_PLUGIN_TIMEO= UT) { +- return new PluginErrorEntry(index, timeStamp, entryKind, +- components.sublist(2, 3), components.sublist(3)); +- } else if (entryKind =3D=3D InstrumentationService.TAG_REQUEST) { +- Map requestData =3D JSON.decode(components[2]); +- return new RequestEntry(index, timeStamp, requestData); +- } else if (entryKind =3D=3D InstrumentationService.TAG_RESPONSE) { +- Map responseData =3D JSON.decode(components[2]); +- return new ResponseEntry(index, timeStamp, responseData); +- } else if (entryKind =3D=3D InstrumentationService.TAG_SUBPROCESS_S= TART) { +- // Fall through +- } else if (entryKind =3D=3D InstrumentationService.TAG_SUBPROCESS_R= ESULT) { +- // Fall through +- } else if (entryKind =3D=3D InstrumentationService.TAG_VERSION) { +- // Fall through +- } else if (entryKind =3D=3D InstrumentationService.TAG_WATCH_EVENT)= { +- // Fall through +- } +- return new GenericEntry( +- index, timeStamp, entryKind, components.sublist(2)); +- } catch (exception) { +- LogEntry logEntry =3D new MalformedLogEntry(index, entry); +- logEntry.recordProblem(exception.toString()); +- return logEntry; +- } +- } +- +- /** +- * Return `true` if any problems were found while processing the log fi= le. +- */ +- bool get hasProblems =3D> _problems !=3D null; +- +- /** +- * Return the value of the component used to indicate the kind of the e= ntry. +- * This is the abbreviation recorded in the entry. +- */ +- String get kind; +- +- /** +- * Return a human-readable representation of the kind of this entry. +- */ +- String get kindName =3D> kindMap[kind] ?? kind; +- +- /** +- * Return a list containing the descriptions of problems that were foun= d while +- * processing the log file, or `null` if no problems were found. +- */ +- List get problems =3D> _problems; +- +- /** +- * Return a date that is equivalent to the [timeStamp]. +- */ +- DateTime get toTime =3D> new DateTime.fromMillisecondsSinceEpoch(timeSt= amp); +- +- /** +- * Return an HTML representation of the details of the entry. +- */ +- String details() { +- StringBuffer buffer =3D new StringBuffer(); +- _appendDetails(buffer); +- return buffer.toString(); +- } +- +- /** +- * Record that the given [problem] was found while processing the log f= ile. +- */ +- void recordProblem(String problem) { +- _problems ??=3D []; +- _problems.add(problem); +- } +- +- /** +- * Append details related to this entry to the given [buffer]. +- */ +- void _appendDetails(StringBuffer buffer) { +- if (_problems !=3D null) { +- for (String problem in _problems) { +- buffer.write('

    $problem

    '); +- } +- } +- } +- +- /** +- * Parse the given encoded form of the [entry] into a list of component= s. The +- * first component is always the time stamp for when the entry was gene= rated. +- * The second component is always the kind of the entry. The remaining +- * components depend on the kind of the entry. Return the components th= at were +- * parsed. +- */ +- static List _parseComponents(String entry) { +- List components =3D []; +- StringBuffer component =3D new StringBuffer(); +- int length =3D entry.length; +- for (int i =3D 0; i < length; i++) { +- int char =3D entry.codeUnitAt(i); +- if (char =3D=3D fieldSeparator) { +- if (entry.codeUnitAt(i + 1) =3D=3D fieldSeparator) { +- component.write(':'); +- i++; +- } else { +- components.add(component.toString()); +- component.clear(); +- } +- } else { +- component.writeCharCode(char); +- } +- } +- components.add(component.toString()); +- return components; +- } +-} +- +-/** +- * A representation of a malformed log entry. +- */ +-class MalformedLogEntry extends LogEntry { +- final String entry; +- +- MalformedLogEntry(int index, this.entry) : super(index, -1); +- +- @override +- String get kind =3D> 'Mal'; +- +- @override +- void _appendDetails(StringBuffer buffer) { +- super._appendDetails(buffer); +- buffer.write(entry); +- buffer.write('
    '); +- } +-} +- +-/** +- * A log entry representing a notification that was sent from the server = to the +- * client. +- */ +-class NotificationEntry extends JsonBasedEntry { +- /** +- * Initialize a newly created response to have the given [timeStamp] and +- * [notificationData]. +- */ +- NotificationEntry(int index, int timeStamp, Map notificationData) +- : super(index, timeStamp, notificationData); +- +- /** +- * Return the event field of the request. +- */ +- String get event =3D> data['event']; +- +- /** +- * Return `true` if this is a server error notification. +- */ +- bool get isServerError =3D> event =3D=3D 'server.error'; +- +- /** +- * Return `true` if this is a server status notification. +- */ +- bool get isServerStatus =3D> event =3D=3D 'server.status'; +- +- @override +- String get kind =3D> 'Noti'; +- +- /** +- * Return the value of the parameter with the given [parameterName], or= `null` +- * if there is no such parameter. +- */ +- dynamic param(String parameterName) { +- var parameters =3D data['params']; +- if (parameters is Map) { +- return parameters[parameterName]; +- } +- return null; +- } +-} +- +-/** +- * A log entry representing a communication between the server and a plug= in. +- */ +-abstract class PluginEntryMixin { +- /** +- * The components describing the plugin associated with this entry. +- */ +- List get pluginData; +- +- /** +- * The id of the plugin associated with this entry. +- */ +- String get pluginId =3D> pluginData[0]; +- +- /** +- * The name of the plugin associated with this entry. +- */ +- String get pluginName =3D> pluginData[1]; +- +- /** +- * The version of the plugin associated with this entry. +- */ +- String get pluginVersion =3D> pluginData[2]; +- +- /** +- * Return a shortened version of the plugin id. +- */ +- String get shortPluginId { +- int index =3D pluginId.lastIndexOf(path.separator); +- if (index > 0) { +- return pluginId.substring(index + 1); +- } +- return pluginId; +- } +-} +- +-/** +- * A log entry representing an PluginErr entry. +- */ +-class PluginErrorEntry extends GenericPluginEntry { +- /** +- * Initialize a newly created log entry. +- */ +- PluginErrorEntry(int index, int timeStamp, String entryKind, +- List components, List pluginData) +- : super(index, timeStamp, entryKind, components, pluginData); +-} +- +-/** +- * A log entry representing an PluginEx entry. +- */ +-class PluginExceptionEntry extends GenericPluginEntry { +- /** +- * Initialize a newly created log entry. +- */ +- PluginExceptionEntry(int index, int timeStamp, String entryKind, +- List components, List pluginData) +- : super(index, timeStamp, entryKind, components, pluginData); +-} +- +-/** +- * A log entry representing a notification that was sent from a plugin to= the +- * server. +- */ +-class PluginNotificationEntry extends JsonBasedPluginEntry { +- /** +- * Initialize a newly created notification to have the given [timeStamp= ] and +- * [notificationData]. +- */ +- PluginNotificationEntry( +- int index, int timeStamp, Map notificationData, List plugin= Data) +- : super(index, timeStamp, notificationData, pluginData); +- +- /** +- * Return the event field of the notification. +- */ +- String get event =3D> data['event']; +- +- @override +- String get kind =3D> 'PluginNoti'; +- +- /** +- * Return the value of the parameter with the given [parameterName], or= `null` +- * if there is no such parameter. +- */ +- dynamic param(String parameterName) { +- var parameters =3D data['params']; +- if (parameters is Map) { +- return parameters[parameterName]; +- } +- return null; +- } +-} +- +-/** +- * A log entry representing a request that was sent from the server to a = plugin. +- */ +-class PluginRequestEntry extends JsonBasedPluginEntry { +- /** +- * Initialize a newly created response to have the given [timeStamp] and +- * [requestData]. +- */ +- PluginRequestEntry( +- int index, int timeStamp, Map requestData, List pluginData) +- : super(index, timeStamp, requestData, pluginData); +- +- /** +- * Return the id field of the request. +- */ +- String get id =3D> data['id']; +- +- @override +- String get kind =3D> 'PluginReq'; +- +- /** +- * Return the method field of the request. +- */ +- String get method =3D> data['method']; +- +- /** +- * Return the value of the parameter with the given [parameterName], or= `null` +- * if there is no such parameter. +- */ +- dynamic param(String parameterName) { +- var parameters =3D data['params']; +- if (parameters is Map) { +- return parameters[parameterName]; +- } +- return null; +- } +-} +- +-/** +- * A log entry representing a response that was sent from a plugin to the +- * server. +- */ +-class PluginResponseEntry extends JsonBasedPluginEntry { +- /** +- * Initialize a newly created response to have the given [timeStamp] and +- * [responseData]. +- */ +- PluginResponseEntry( +- int index, int timeStamp, Map responseData, List pluginData) +- : super(index, timeStamp, responseData, pluginData); +- +- /** +- * Return the id field of the response. +- */ +- String get id =3D> data['id']; +- +- @override +- String get kind =3D> 'PluginRes'; +- +- /** +- * Return the value of the result with the given [resultName], or `null= ` if +- * there is no such result. +- */ +- dynamic result(String resultName) { +- var results =3D data['result']; +- if (results is Map) { +- return results[resultName]; +- } +- return null; +- } +-} +- +-/** +- * A log entry representing a request that was sent from the client to the +- * server. +- */ +-class RequestEntry extends JsonBasedEntry { +- /** +- * Initialize a newly created response to have the given [timeStamp] and +- * [requestData]. +- */ +- RequestEntry(int index, int timeStamp, Map requestData) +- : super(index, timeStamp, requestData); +- +- /** +- * Return the clientRequestTime field of the request. +- */ +- int get clientRequestTime =3D> data['clientRequestTime']; +- +- /** +- * Return the id field of the request. +- */ +- String get id =3D> data['id']; +- +- @override +- String get kind =3D> 'Req'; +- +- /** +- * Return the method field of the request. +- */ +- String get method =3D> data['method']; +- +- /** +- * Return the value of the parameter with the given [parameterName], or= `null` +- * if there is no such parameter. +- */ +- dynamic param(String parameterName) { +- var parameters =3D data['params']; +- if (parameters is Map) { +- return parameters[parameterName]; +- } +- return null; +- } +-} +- +-/** +- * A log entry representing a response that was sent from the server to t= he +- * client. +- */ +-class ResponseEntry extends JsonBasedEntry { +- /** +- * Initialize a newly created response to have the given [timeStamp] and +- * [responseData]. +- */ +- ResponseEntry(int index, int timeStamp, Map responseData) +- : super(index, timeStamp, responseData); +- +- /** +- * Return the id field of the response. +- */ +- String get id =3D> data['id']; +- +- @override +- String get kind =3D> 'Res'; +- +- /** +- * Return the value of the result with the given [resultName], or `null= ` if +- * there is no such result. +- */ +- dynamic result(String resultName) { +- var results =3D data['result']; +- if (results is Map) { +- return results[resultName]; +- } +- return null; +- } +-} +- +-class TaskEntry extends LogEntry { +- /** +- * The path to the directory at the root of the context in which analys= is was +- * being performed. +- */ +- final String context; +- +- /** +- * A description of the task that was performed. +- */ +- final String description; +- +- /** +- * The name of the class implementing the task. +- */ +- String _taskName =3D null; +- +- /** +- * The description of the target of the task. +- */ +- String _target =3D null; +- +- /** +- * Initialize a newly created entry with the given [index] and [timeSta= mp] to +- * represent the execution of an analysis task in the given [context] t= hat is +- * described by the given [description]. +- */ +- TaskEntry(int index, int timeStamp, this.context, this.description) +- : super(index, timeStamp); +- +- @override +- String get kind =3D> 'Task'; +- +- /** +- * Return the description of the target of the task. +- */ +- String get target { +- if (_target =3D=3D null) { +- _splitDescription(); +- } +- return _target; +- } +- +- /** +- * Return the name of the class implementing the task. +- */ +- String get taskName { +- if (_taskName =3D=3D null) { +- _splitDescription(); +- } +- return _taskName; +- } +- +- @override +- void _appendDetails(StringBuffer buffer) { +- super._appendDetails(buffer); +- buffer.write('Context: '); +- buffer.write(context); +- buffer.write('
    Description: '); +- buffer.write(description); +- } +- +- /** +- * Split the description to get the task name and target description. +- */ +- void _splitDescription() { +- int index =3D description.indexOf(' '); +- if (index < 0) { +- _taskName =3D ''; +- } else { +- _taskName =3D description.substring(0, index); +- } +- index =3D description.lastIndexOf(' '); +- _target =3D description.substring(index + 1); +- int slash =3D context.lastIndexOf('/'); +- if (slash < 0) { +- slash =3D context.lastIndexOf('\\'); +- } +- if (slash >=3D 0) { +- String prefix =3D context.substring(0, slash); +- _target =3D _target.replaceAll(prefix, '...'); +- } +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/log_viewer.dart b/pk= g/analysis_server/tool/instrumentation/log_viewer.dart +deleted file mode 100644 +index 62d572236e7..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/log_viewer.dart ++++ /dev/null +@@ -1,129 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io' as io; +- +-import 'package:args/args.dart'; +- +-import 'log/log.dart'; +-import 'server.dart'; +- +-/** +- * Start a web server that will allow an instrumentation log to be viewed. +- */ +-void main(List args) { +- Driver driver =3D new Driver(); +- driver.start(args); +-} +- +-/** +- * The main driver that configures and starts the web server. +- */ +-class Driver { +- /** +- * The flag used to specify that the user wants to have help text print= ed but +- * that no other work should be done. +- */ +- static String helpFlag =3D 'help'; +- +- /** +- * The option used to specify the port on which the server should liste= n for +- * requests. +- */ +- static String portOption =3D 'port'; +- +- /** +- * The port that will be used if no port number is provided on the comm= and +- * line. +- */ +- static int defaultPortNumber =3D 11000; +- +- /** +- * Initialize a newly created driver. +- */ +- Driver(); +- +- /** +- * Create and return the parser used to parse the command-line argument= s. +- */ +- ArgParser createParser() { +- ArgParser parser =3D new ArgParser(); +- parser.addFlag(helpFlag, help: 'Print this help text', negatable: fal= se); +- parser.addOption(portOption, +- help: 'The port number on which the server should listen for requ= ests', +- defaultsTo: defaultPortNumber.toString()); +- return parser; +- } +- +- /** +- * Print usage information. +- */ +- void printUsage(ArgParser parser, +- {String error, Object exception, StackTrace stackTrace}) { +- if (error !=3D null) { +- print(error); +- print(''); +- } +- print('log_viewer [options] logFile'); +- print(''); +- print('Usage:'); +- print(''); +- print( +- 'The "logFile" is the file containing the content of the log that= is being viewed'); +- print(''); +- print('Options:'); +- print(parser.usage); +- if (exception !=3D null) { +- print(exception); +- } +- if (stackTrace !=3D null) { +- print(stackTrace); +- } +- } +- +- /** +- * Use the given command-line [args] to configure and start the web ser= ver. +- */ +- void start(List args) { +- ArgParser parser =3D createParser(); +- ArgResults options =3D parser.parse(args); +- if (options[helpFlag]) { +- printUsage(parser); +- return; +- } +- +- int port =3D defaultPortNumber; +- try { +- port =3D int.parse(options[portOption]); +- } catch (exception) { +- printUsage(parser, error: 'Invalid port number'); +- return; +- } +- +- List arguments =3D options.rest; +- if (arguments =3D=3D null || arguments.length !=3D 1) { +- printUsage(parser, error: 'Missing log file'); +- return; +- } +- String fileName =3D arguments[0]; +- io.File logFile =3D new io.File(fileName); +- List lines; +- try { +- lines =3D logFile.readAsLinesSync(); +- } catch (exception, stackTrace) { +- printUsage(parser, +- error: 'Could not read file "$fileName":', +- exception: exception, +- stackTrace: stackTrace); +- return; +- } +- print('Log file contains ${lines.length} lines'); +- +- InstrumentationLog log =3D +- new InstrumentationLog([logFile.path], lines); +- WebServer server =3D new WebServer(log); +- server.serveHttp(port); +- print('logViewer is listening on http://localhost:$port/log'); +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/page/log_page.dart b= /pkg/analysis_server/tool/instrumentation/page/log_page.dart +deleted file mode 100644 +index b53758015f5..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/page/log_page.dart ++++ /dev/null +@@ -1,331 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:math' as math; +- +-import '../log/log.dart'; +-import '../server.dart'; +-import 'page_writer.dart'; +- +-/** +- * A page writer that will produce the page containing access to the full +- * content of the log. +- */ +-class LogPage extends PageWriter { +- /** +- * The instrumentation log to be written. +- */ +- InstrumentationLog log; +- +- /** +- * The id of the entry groups to be displayed. +- */ +- EntryGroup selectedGroup; +- +- /** +- * The entries in the selected group. +- */ +- List entries; +- +- /** +- * The index of the first entry to be written. +- */ +- int pageStart =3D 0; +- +- /** +- * The number of entries to be written, or `null` if all of the entries= should +- * be written. +- */ +- int pageLength =3D null; +- +- /** +- * The number of digits in the event stamps that are the same for every= entry. +- */ +- int prefixLength; +- +- /** +- * A table mapping the ids of plugins to an index for the plugin. +- */ +- Map pluginIdMap =3D {}; +- +- /** +- * Initialize a newly created writer to write the content of the given +- * [instrumentationLog]. +- */ +- LogPage(this.log); +- +- /** +- * Return the encoding for the given [pluginId] that is used to build a= nchors. +- */ +- int getPluginId(String pluginId) { +- return pluginIdMap.putIfAbsent(pluginId, () =3D> pluginIdMap.length); +- } +- +- @override +- void writeBody(StringSink sink) { +- entries =3D log.entriesInGroup(selectedGroup); +- prefixLength =3D computePrefixLength(entries); +- +- writeMenu(sink); +- writeTwoColumns( +- sink, 'leftColumn', _writeLeftColumn, 'rightColumn', _writeRightC= olumn); +- } +- +- @override +- void writeScripts(StringSink sink) { +- super.writeScripts(sink); +- sink.writeln(r''' +-var highlightedRows =3D []; +-function clearHighlight() { +- for (i =3D 0; i < highlightedRows.length; i++) { +- setFontWeight(highlightedRows[i], "normal"); +- } +-} +-function highlight(requestId, responseId) { +- clearHighlight(); +- setFontWeight(requestId, "bold"); +- setFontWeight(responseId, "bold"); +- highlightedRows =3D [requestId, responseId]; +-} +-function setFontWeight(id, weight) { +- var element =3D document.getElementById(id); +- if (element !=3D null) { +- element.style.fontWeight =3D weight; +- } +-} +-function setDetails(detailsContent) { +- var element =3D document.getElementById("details"); +- if (element !=3D null) { +- element.innerHTML =3D detailsContent; +- } +-} +-function selectEntryGroup(pageStart) { +- var element =3D document.getElementById("entryGroup"); +- var url =3D "/log?group=3D" + element.value; +- window.location.assign(url); +-} +-'''); +- } +- +- /** +- * Write the content of the style sheet (without the 'script' tag) for = the +- * page to the given [sink]. +- */ +- void writeStyleSheet(StringSink sink) { +- super.writeStyleSheet(sink); +- writeTwoColumnStyles(sink, 'leftColumn', 'rightColumn'); +- } +- +- /** +- * Return the number of milliseconds elapsed between the [startEntry] a= nd the +- * [endEntry], or a question . +- */ +- String _getDuration(LogEntry startEntry, LogEntry endEntry) { +- if (startEntry !=3D null && endEntry !=3D null) { +- return (endEntry.timeStamp - startEntry.timeStamp).toString(); +- } +- return '?'; +- } +- +- /** +- * Write the given log [entry] to the given [sink]. +- */ +- void _writeEntry(StringSink sink, LogEntry entry) { +- String id =3D null; +- String clickHandler =3D 'clearHighlight()'; +- String icon =3D ''; +- String description =3D entry.kindName; +- if (entry is RequestEntry) { +- String entryId =3D entry.id; +- id =3D 'req$entryId'; +- clickHandler =3D 'highlight(\'req$entryId\', \'res$entryId\')'; +- icon =3D '→'; +- description =3D entry.method; +- } else if (entry is ResponseEntry) { +- String entryId =3D entry.id; +- RequestEntry request =3D log.requestFor(entry); +- id =3D 'res$entryId'; +- clickHandler =3D 'highlight(\'req$entryId\', \'res$entryId\')'; +- icon =3D '←'; +- if (request !=3D null) { +- int latency =3D entry.timeStamp - request.timeStamp; +- description =3D +- '${request.method} ($latency ms)'; +- } +- } else if (entry is NotificationEntry) { +- id =3D 'e${entry.index}'; +- LogEntry pairedEntry =3D log.pairedEntry(entry); +- if (pairedEntry !=3D null) { +- String pairedId =3D 'e${pairedEntry.index}'; +- clickHandler =3D 'highlight(\'$id\', \'$pairedId\')'; +- } +- icon =3D '←'; +- description =3D entry.event; +- if (entry.isServerStatus) { +- var analysisStatus =3D entry.param('analysis'); +- if (analysisStatus is Map) { +- if (analysisStatus['isAnalyzing']) { +- description =3D +- '$description (analysis) (
    tasks)'; +- } else { +- String duration =3D _getDuration(pairedEntry, entry); +- description =3D +- '$description (analysis - $duration = ms)'; +- } +- } +- var pubStatus =3D entry.param('pub'); +- if (pubStatus is Map) { +- if (pubStatus['isListingPackageDirs']) { +- description =3D '$description (pub)'; +- } else { +- String duration =3D _getDuration(pairedEntry, entry); +- description =3D +- '$description (pub - $duration ms)'; +- } +- } +- } +- } else if (entry is PluginRequestEntry) { +- String entryId =3D entry.id; +- int pluginId =3D getPluginId(entry.pluginId); +- id =3D 'req$pluginId.$entryId'; +- clickHandler =3D +- 'highlight(\'req$pluginId.$entryId\', \'res$pluginId.$entryId\'= )'; +- icon =3D '→'; +- description =3D '${entry.method} (${entry.shortPluginId})'; +- } else if (entry is PluginResponseEntry) { +- String entryId =3D entry.id; +- int pluginId =3D getPluginId(entry.pluginId); +- PluginRequestEntry request =3D log.pluginRequestFor(entry); +- id =3D 'res$pluginId.$entryId'; +- clickHandler =3D +- 'highlight(\'req$pluginId.$entryId\', \'res$pluginId.$entryId\'= )'; +- icon =3D '←'; +- if (request !=3D null) { +- int latency =3D entry.timeStamp - request.timeStamp; +- description =3D +- '${request.method} ($latency ms) = (${entry.shortPluginId})'; +- } +- } else if (entry is PluginNotificationEntry) { +- id =3D 'e${entry.index}'; +- LogEntry pairedEntry =3D log.pairedEntry(entry); +- if (pairedEntry !=3D null) { +- String pairedId =3D 'e${pairedEntry.index}'; +- clickHandler =3D 'highlight(\'$id\', \'$pairedId\')'; +- } +- icon =3D '←'; +- description =3D '${entry.event} (${entry.shortPluginId})'; +- } else if (entry is TaskEntry) { +- description =3D entry.description; +- } else if (entry is ErrorEntry) { +- description =3D '$description'; +- } else if (entry is PluginErrorEntry) { +- description =3D +- '$description (${entry.shortPlugin= Id})'; +- } else if (entry is ExceptionEntry) { +- description =3D '$description'; +- } else if (entry is MalformedLogEntry) { +- description =3D '$description'; +- } +- id =3D id =3D=3D null ? '' : 'id=3D"$id" '; +- clickHandler =3D '$clickHandler; setDetails(\'${escape(entry.details(= ))}\')'; +- String timeStamp =3D entry.timeStamp.toString(); +- if (prefixLength > 0) { +- timeStamp =3D timeStamp.substring(prefixLength); +- } +- +- sink.writeln(''); +- sink.writeln('$icon'); +- sink.writeln(''); +- sink.writeln(timeStamp); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(description); +- sink.writeln(''); +- sink.writeln(''); +- } +- +- /** +- * Write the entries in the instrumentation log to the given [sink]. +- */ +- void _writeLeftColumn(StringSink sink) { +- int length =3D entries.length; +- int pageEnd =3D +- pageLength =3D=3D null ? length : math.min(pageStart + pageLength= , length); +- // +- // Write the header of the column. +- // +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln(''); +- if (length =3D=3D 0) { +- sink.writeln('No matching events'); +- } else { +- sink.writeln('Events $pageStart - ${pageEnd - 1} of $length'); +- } +- sink.writeln('
    '); +- +- sink.writeln('
    '); +- if (pageStart =3D=3D 0) { +- sink.writeln('= '); +- } else { +- sink.write(''); +- } +- // TODO(brianwilkerson) Add a text field for selecting the start inde= x. +- if (pageEnd =3D=3D length) { +- sink.writeln('= '); +- } else { +- sink.write(''); +- } +- sink.writeln('
    '); +- sink.writeln('
    '); +- // +- // Write the main body of the column. +- // +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- for (int i =3D pageStart; i < pageEnd; i++) { +- LogEntry entry =3D entries[i]; +- _writeEntry(sink, entry); +- } +- sink.writeln('
    TimeKind
    '); +- } +- +- /** +- * Write a placeholder to the given [sink] where the details of a selec= ted +- * entry can be displayed. +- */ +- void _writeRightColumn(StringSink sink) { +- // +- // Write the header of the column. +- // +- sink.writeln('
    '); +- sink.writeln('

    Entry Details

    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/page/page_writer.dar= t b/pkg/analysis_server/tool/instrumentation/page/page_writer.dart +deleted file mode 100644 +index dca5673452b..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/page/page_writer.dart ++++ /dev/null +@@ -1,317 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import '../log/log.dart'; +-import '../server.dart'; +- +-typedef void Writer(StringSink sink); +- +-/** +- * A class used to write an HTML page. +- */ +-abstract class PageWriter { +- /** +- * The object used to escape special HTML characters. +- */ +- static final HtmlEscape htmlEscape =3D new HtmlEscape(); +- +- /** +- * Initialize a newly create page writer. +- */ +- PageWriter(); +- +- /** +- * Return the length of the common prefix for time stamps associated wi= th the +- * given log [entries]. +- */ +- int computePrefixLength(List entries) { +- int length =3D entries.length; +- if (length < 2) { +- return 0; +- } +- String firstTime =3D entries[0].timeStamp.toString(); +- String lastTime =3D entries[length - 1].timeStamp.toString(); +- int prefixLength =3D 0; +- int timeLength =3D firstTime.length; +- while (prefixLength < timeLength && +- firstTime.codeUnitAt(prefixLength) =3D=3D +- lastTime.codeUnitAt(prefixLength)) { +- prefixLength++; +- } +- return prefixLength; +- } +- +- /** +- * Return an escaped version of the given [unsafe] text. +- */ +- String escape(String unsafe) { +- // We double escape single quotes because the escaped characters are +- // processed as part of reading the HTML, which means that single quo= tes +- // end up terminating string literals too early when they appear in e= vent +- // handlers (which in turn leads to JavaScript syntax errors). +- return htmlEscape.convert(unsafe).replaceAll(''', '&#39;'); +- } +- +- /** +- * Write the body of the page (without the 'body' tag) to the given [si= nk]. +- */ +- void writeBody(StringSink sink); +- +- /** +- * Write the given [date] to the given [sink]. +- */ +- void writeDate(StringSink sink, DateTime date) { +- String isoString =3D date.toIso8601String(); +- int index =3D isoString.indexOf('T'); +- String dateString =3D isoString.substring(0, index); +- String timeString =3D isoString.substring(index + 1); +- sink.write(dateString); +- sink.write(' at '); +- sink.write(timeString); +- } +- +- /** +- * Write the body of the page (without the 'body' tag) to the given [si= nk]. +- */ +- void writeMenu(StringSink sink) { +- sink.writeln('
    '); +- sink.write('Log'); +- sink.write(' • '); +- sink.write('Sta= ts'); +- sink.writeln('
    '); +- } +- +- /** +- * Write the contents of the instrumentation log to the given [sink]. +- */ +- void writePage(StringSink sink) { +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln( +- ''); +- sink.writeln('Instrumentation Log'); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- writeBody(sink); +- sink.writeln(''); +- sink.writeln(''); +- } +- +- /** +- * Write the scripts for the page (without the 'script' tag) to the giv= en +- * [sink]. +- */ +- void writeScripts(StringSink sink) { +- // No common scripts. +- } +- +- /** +- * Write the content of the style sheet (without the 'script' tag) for = the +- * page to the given [sink]. +- */ +- void writeStyleSheet(StringSink sink) { +- sink.writeln(r''' +-a { +- color: #000000; +- text-decoration: none; +-} +-a.menuItem { +- font-weight: bold; +-} +-body { +- font-family: sans-serif; +- height: 100%; +- margin: 0px; +- overflow: hidden; +- padding: 0px; +- width: 100%; +-} +-div.columnHeader { +-} +-div.button { +- display: inline-block; +- border-radius: 4px; +- border: 1px solid; +- height: 16px; +- text-align: center; +- vertical-align: middle; +- width: 16px; +-} +-div.inset { +- padding: 10px; +-} +-div.menu { +- background-color: #cce6ff; +- padding: 5px; +-} +-html { +- height: 100%; +- width: 100%; +-} +-span.button { +- border-radius: 5px; +- border: 1px solid; +- height: 16px; +- width: 16px; +-} +-span.error { +- color: #ff0000; +-} +-span.gray { +- color: #777777; +-} +-span.label { +- font-weight: bold; +-} +-table.fullWidth { +- border: 0px; +- width: 100%; +-} +-td.halfWidth { +- width: 50%; +- vertical-align: top; +-} +-td.int { +- text-align: right; +-} +-th { +- text-align: left; +-} +-th.narrow { +- width: 16px; +-} +- +-#container { +- height: 100%; +- min-height: 100%; +- position: relative; +- width: 100%; +-} +-#content { +- height: 90%; +- width: 100%; +-} +-'''); +- } +- +- /** +- * Write to the given [sink] the HTML required to display content in two +- * columns. The content of the columns will be written by the functions +- * [writeLeftColumn], [writeCenterColumn] and [writeRightColumn] and wi= ll be +- * contained in 'div' elements with the id's [leftColumnId], [centerCol= umnId] +- * and [rightColumnId]. +- */ +- void writeThreeColumns( +- StringSink sink, +- String leftColumnId, +- Writer writeLeftColumn, +- String centerColumnId, +- Writer writeCenterColumn, +- String rightColumnId, +- Writer writeRightColumn) { +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- writeLeftColumn(sink); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- writeRightColumn(sink); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- writeCenterColumn(sink); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- } +- +- /** +- * Writeto the given [sink] the styles needed by a three column section= where +- * the columns have the ids [leftColumnId], [centerColumnId] and +- * [rightColumnId]. +- */ +- void writeThreeColumnStyles(StringSink sink, String leftColumnId, +- String centerColumnId, String rightColumnId) { +- sink.writeln(''' +-#$leftColumnId { +- float: left; +- height: 100%; +- overflow: auto; +- width: 33%; +-} +-#$centerColumnId { +- height: 100%; +- overflow: auto; +- width: 33%; +-} +-#$rightColumnId { +- float: right; +- height: 100%; +- overflow: auto; +- width: 33%; +-} +-'''); +- } +- +- /** +- * Write to the given [sink] the HTML required to display content in two +- * columns. The content of the columns will be written by the functions +- * [writeLeftColumn] and [writeRightColumn] and will be contained in 'd= iv' +- * elements with the id's [leftColumnId] and [rightColumnId]. +- */ +- void writeTwoColumns(StringSink sink, String leftColumnId, +- Writer writeLeftColumn, String rightColumnId, Writer writeRightColu= mn) { +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- writeLeftColumn(sink); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- writeRightColumn(sink); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- } +- +- /** +- * Writeto the given [sink] the styles needed by a two column section w= here +- * the columns have the ids [leftColumnId] and [rightColumnId]. +- */ +- void writeTwoColumnStyles( +- StringSink sink, String leftColumnId, String rightColumnId) { +- sink.writeln(''' +-#$leftColumnId { +- float: left; +- height: 100%; +- overflow: auto; +- width: 50%; +-} +-#$rightColumnId { +- float: right; +- height: 100%; +- overflow: auto; +- width: 50%; +-} +-'''); +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/page/stats_page.dart= b/pkg/analysis_server/tool/instrumentation/page/stats_page.dart +deleted file mode 100644 +index a8932a16920..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/page/stats_page.dart ++++ /dev/null +@@ -1,265 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import '../log/log.dart'; +-import 'page_writer.dart'; +- +-/** +- * A page writer that will produce the page containing statistics about an +- * instrumentation log. +- */ +-class StatsPage extends PageWriter { +- /** +- * The instrumentation log to be written. +- */ +- final InstrumentationLog log; +- +- /** +- * A table mapping the kinds of entries in the log to the number of eac= h kind. +- */ +- final Map entryCounts =3D {}; +- +- /** +- * The number of responses that returned an error. +- */ +- int errorCount =3D 0; +- +- /** +- * The number of responses from each plugin that returned an error. +- */ +- Map pluginErrorCount =3D {}; +- +- /** +- * A table mapping request method names to a list of the latencies asso= ciated +- * with those requests, where the latency is defined to be the time bet= ween +- * when the request was sent by the client and when the server started +- * processing the request. +- */ +- final Map> latencyData =3D >{}; +- +- /** +- * A table mapping request method names to a list of the latencies asso= ciated +- * with those requests, where the latency is defined to be the time bet= ween +- * when the request was sent by the server and when the plugin sent a r= esponse. +- */ +- final Map>> pluginResponseData =3D +- >>{}; +- +- /** +- * A list of the number of milliseconds between a completion request an= d the +- * first event for that request. +- */ +- final List completionResponseTimes =3D []; +- +- /** +- * Initialize a newly created page writer to write information about th= e given +- * instrumentation [log]. +- */ +- StatsPage(this.log) { +- _processEntries(log.logEntries); +- } +- +- @override +- void writeBody(StringSink sink) { +- writeMenu(sink); +- writeTwoColumns( +- sink, 'leftColumn', _writeLeftColumn, 'rightColumn', _writeRightC= olumn); +- } +- +- /** +- * Write the content of the style sheet (without the 'script' tag) for = the +- * page to the given [sink]. +- */ +- void writeStyleSheet(StringSink sink) { +- super.writeStyleSheet(sink); +- writeTwoColumnStyles(sink, 'leftColumn', 'rightColumn'); +- } +- +- /** +- * Return the mean of the values in the given list of [values]. +- */ +- int _mean(List values) { +- int sum =3D values.fold(0, (int sum, int latency) =3D> sum + latency); +- return sum ~/ values.length; +- } +- +- /** +- * Return a table mapping the kinds of the given [entries] to the numbe= r of +- * each kind. +- */ +- void _processEntries(List entries) { +- void increment(Map map, K key) { +- map[key] =3D (map[key] ?? 0) + 1; +- } +- +- for (LogEntry entry in entries) { +- String kind =3D entry.kind; +- increment(entryCounts, kind); +- if (entry is ResponseEntry) { +- if (entry.result('error') !=3D null) { +- errorCount++; +- } +- } else if (entry is RequestEntry) { +- String method =3D entry.method; +- int latency =3D entry.timeStamp - entry.clientRequestTime; +- latencyData.putIfAbsent(method, () =3D> new List()).add(late= ncy); +- if (method =3D=3D 'completion.getSuggestions') { +- ResponseEntry response =3D log.responseFor(entry); +- if (response !=3D null) { +- String id =3D response.result('id'); +- if (id !=3D null) { +- List events =3D log.completionEventsWith= Id(id); +- if (events !=3D null && events.length > 0) { +- completionResponseTimes +- .add(events[0].timeStamp - entry.timeStamp); +- } +- } +- } +- } +- } else if (entry is PluginResponseEntry) { +- if (entry.result('error') !=3D null) { +- int count =3D pluginErrorCount[entry.pluginId] ?? 0; +- pluginErrorCount[entry.pluginId] =3D count + 1; +- } +- } else if (entry is PluginRequestEntry) { +- PluginResponseEntry response =3D log.pluginResponseFor(entry); +- int responseTime =3D response.timeStamp - entry.timeStamp; +- var pluginData =3D pluginResponseData.putIfAbsent( +- entry.pluginId, () =3D> >{}); +- pluginData +- .putIfAbsent(entry.method, () =3D> new List()) +- .add(responseTime); +- } +- } +- } +- +- void _writeLeftColumn(StringSink sink) { +- List filePaths =3D log.logFilePaths; +- List entries =3D log.logEntries; +- DateTime startDate =3D entries[0].toTime; +- DateTime endDate =3D entries[entries.length - 1].toTime; +- Duration duration =3D endDate.difference(startDate); +- List entryKinds =3D entryCounts.keys.toList()..sort(); +- +- sink.writeln('

    General

    '); +- sink.writeln('

    '); +- if (filePaths.length =3D=3D 1) { +- sink.write('Log file: '); +- sink.write(filePaths[0]); +- } else { +- sink.write('Log files: '); +- bool needsSeparator =3D false; +- for (String path in filePaths) { +- if (needsSeparator) { +- sink.write(', '); +- } else { +- needsSeparator =3D true; +- } +- sink.write(path); +- } +- } +- sink.writeln('
    '); +- sink.write('Start time: '); +- writeDate(sink, startDate); +- sink.writeln('
    '); +- sink.write('End time: '); +- writeDate(sink, endDate); +- sink.writeln('
    '); +- sink.write('Duration: '); +- sink.write(duration.toString()); +- sink.writeln('

    '); +- +- sink.writeln('

    Entries

    '); +- sink.write('

    '); +- sink.write('Number of entries: '); +- sink.write(entries.length); +- sink.writeln('

    '); +- sink.write('

    '); +- sink.write('Error count: '); +- sink.write(errorCount); +- sink.writeln('

    '); +- pluginErrorCount.forEach((String pluginId, int count) { +- sink.write('

    '); +- sink.write('Errors from $pluginId: '); +- sink.write(count); +- sink.writeln('

    '); +- }); +- sink.writeln(''); +- sink.writeln(''); +- for (String kind in entryKinds) { +- sink.write(''); +- } +- sink.write(''); +- sink.writeln('
    countkind
    '); +- sink.write(entryCounts[kind]); +- sink.write(''); +- sink.write(kind); +- sink.writeln('
    '); +- sink.write(entries.length); +- sink.writeln('Total
    '); +- } +- +- void _writeRightColumn(StringSink sink) { +- completionResponseTimes.sort(); +- +- sink.writeln('

    Latency

    '); +- sink.write('

    '); +- sink.write('Latency by method'); +- sink.writeln('

    '); +- sink.writeln(''); +- sink.writeln( +- ''); +- List methodNames =3D latencyData.keys.toList()..sort(); +- for (String method in methodNames) { +- List latencies =3D latencyData[method]..sort(); +- // TODO(brianwilkerson) Add a spark-line distribution graph. +- sink.write(''); +- } +- sink.writeln('
    minmeanmaxmethod
    '); +- sink.write(latencies[0]); +- sink.write(''); +- sink.write(_mean(latencies)); +- sink.write(''); +- sink.write(latencies[latencies.length - 1]); +- sink.write(''); +- sink.write(method); +- sink.writeln('
    '); +- +- sink.writeln('

    Completion

    '); +- sink.write('

    '); +- sink.write('Time to first notification: = '); +- sink.write(completionResponseTimes[0]); +- sink.write(', '); +- sink.write(_mean(completionResponseTimes)); +- sink.write(', '); +- sink.write(completionResponseTimes[completionResponseTimes.length - 1= ]); +- sink.writeln('

    '); +- +- if (pluginResponseData.isNotEmpty) { +- sink.writeln('

    Plugin response times

    '); +- pluginResponseData +- .forEach((String pluginId, Map> responseData)= { +- sink.write('

    '); +- sink.write(pluginId); +- sink.writeln('

    '); +- sink.writeln(''); +- List methodNames =3D responseData.keys.toList()..sort(); +- for (String method in methodNames) { +- List responseTimes =3D responseData[method]..sort(); +- // TODO(brianwilkerson) Add a spark-line distribution graph. +- sink.write(''); +- } +- sink.writeln('
    '); +- sink.write(responseTimes[0]); +- sink.write(''); +- sink.write(_mean(responseTimes)); +- sink.write(''); +- sink.write(responseTimes[responseTimes.length - 1]); +- sink.write(''); +- sink.write(method); +- sink.writeln('
    '); +- }); +- } +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/page/task_page.dart = b/pkg/analysis_server/tool/instrumentation/page/task_page.dart +deleted file mode 100644 +index f5cd3124a72..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/page/task_page.dart ++++ /dev/null +@@ -1,168 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:math' as math; +- +-import '../log/log.dart'; +-import '../server.dart'; +-import 'page_writer.dart'; +- +-/** +- * A class used to write a human-readable version of the tasks executed w= ithin a +- * single analysis step. +- */ +-class TaskPage extends PageWriter { +- /** +- * The instrumentation log to be written. +- */ +- final InstrumentationLog log; +- +- /** +- * The index of the entry representing the start of an analysis session. +- */ +- int analysisStart =3D 0; +- +- /** +- * The index of the first task to be written. +- */ +- int pageStart =3D 0; +- +- /** +- * The number of tasks to be written, or `null` if all of the tasks sho= uld +- * be written. +- */ +- int pageLength =3D null; +- +- /** +- * The number of digits in the event stamps that are the same for every= task. +- */ +- int prefixLength; +- +- /** +- * Initialize a newly created page writer to write a single page worth = of +- * tasks. +- */ +- TaskPage(this.log); +- +- @override +- void writeBody(StringSink sink) { +- writeMenu(sink); +- writeTwoColumns( +- sink, 'leftColumn', _writeLeftColumn, 'rightColumn', _writeRightC= olumn); +- } +- +- @override +- void writeScripts(StringSink sink) { +- super.writeScripts(sink); +- sink.writeln(r''' +-function setDetails(detailsContent) { +- var element =3D document.getElementById("details"); +- if (element !=3D null) { +- element.innerHTML =3D detailsContent; +- } +-} +-'''); +- } +- +- /** +- * Write the content of the style sheet (without the 'script' tag) for = the +- * page to the given [sink]. +- */ +- void writeStyleSheet(StringSink sink) { +- super.writeStyleSheet(sink); +- writeTwoColumnStyles(sink, 'leftColumn', 'rightColumn'); +- } +- +- /** +- * Write the given log [entry] to the given [sink]. +- */ +- void _writeEntry(StringSink sink, TaskEntry entry) { +- String clickHandler =3D 'setDetails(\'${escape(entry.details())}\')'; +- String timeStamp =3D entry.timeStamp.toString(); +- if (prefixLength > 0) { +- timeStamp =3D timeStamp.substring(prefixLength); +- } +- +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(timeStamp); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(entry.taskName); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(entry.target); +- sink.writeln(''); +- sink.writeln(''); +- } +- +- /** +- * Write the entries in the instrumentation log to the given [sink]. +- */ +- void _writeLeftColumn(StringSink sink) { +- List entries =3D log.taskEntriesFor(analysisStart); +- prefixLength =3D computePrefixLength(entries); +- int length =3D entries.length; +- int pageEnd =3D +- pageLength =3D=3D null ? length : math.min(pageStart + pageLength= , length); +- // +- // Write the header of the column. +- // +- sink.writeln('
    '); +- sink.writeln('
    '); +- sink.writeln('Tasks $pageStart - ${pageEnd - 1} of ${length - 1}'); +- sink.writeln('
    '); +- +- sink.writeln('
    '); +- if (pageStart =3D=3D 0) { +- sink.writeln('= '); +- } else { +- sink.write(''); +- } +- // TODO(brianwilkerson) Add a text field for selecting the start inde= x. +- if (pageEnd =3D=3D length) { +- sink.writeln('= '); +- } else { +- sink.write(''); +- } +- sink.writeln('
    '); +- sink.writeln('
    '); +- // +- // Write the main body of the column. +- // +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- sink.writeln(''); +- for (int i =3D pageStart; i < pageEnd; i++) { +- LogEntry entry =3D entries[i]; +- _writeEntry(sink, entry); +- } +- sink.writeln('
    TimeTaskTarget
    '); +- } +- +- /** +- * Write a placeholder to the given [sink] where the details of a selec= ted +- * entry can be displayed. +- */ +- void _writeRightColumn(StringSink sink) { +- // +- // Write the header of the column. +- // +- sink.writeln('
    '); +- sink.writeln('

    Task Details

    '); +- sink.writeln('
    '); +- sink.writeln('
    '); +- } +-} +diff --git a/pkg/analysis_server/tool/instrumentation/server.dart b/pkg/an= alysis_server/tool/instrumentation/server.dart +deleted file mode 100644 +index 768c8b8fc6b..00000000000 +--- a/pkg/analysis_server/tool/instrumentation/server.dart ++++ /dev/null +@@ -1,238 +0,0 @@ +-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:collection'; +-import 'dart:io'; +- +-import 'log/log.dart'; +-import 'page/log_page.dart'; +-import 'page/stats_page.dart'; +-import 'page/task_page.dart'; +- +-/** +- * An exception that is thrown when a request is received that cannot be +- * handled. +- */ +-class UnknownRequest implements Exception {} +- +-/** +- * A simple web server. +- */ +-class WebServer { +- /** +- * The path to the page containing a single page from the instrumentati= on log. +- */ +- static final String logPath =3D '/log'; +- +- /** +- * The path to the page containing statistics about the instrumentation= log. +- */ +- static final String statsPath =3D '/stats'; +- +- /** +- * The path to the page containing statistics about the instrumentation= log. +- */ +- static final String taskPath =3D '/task'; +- +- /** +- * The content type for HTML responses. +- */ +- static final ContentType _htmlContent =3D +- new ContentType("text", "html", charset: "utf-8"); +- +- /** +- * The instrumentation log being served up. +- */ +- final InstrumentationLog log; +- +- /** +- * Future that is completed with the HTTP server once it is running. +- */ +- Future _server; +- +- /** +- * Initialize a newly created server. +- */ +- WebServer(this.log); +- +- Map getParameterMap(HttpRequest request) { +- Map parameterMap =3D new HashMap(); +- String query =3D request.uri.query; +- if (query !=3D null && query.isNotEmpty) { +- List pairs =3D query.split('&'); +- for (String pair in pairs) { +- List parts =3D pair.split('=3D'); +- String value =3D parts[1].trim(); +- value =3D value.replaceAll('+', ' '); +- parameterMap[parts[0].trim()] =3D value; +- } +- } +- return parameterMap; +- } +- +- /** +- * Return a table mapping the names of properties to the values of those +- * properties that is extracted from the given HTTP [request]. +- */ +- Future> getValueMap(HttpRequest request) async { +- StringBuffer buffer =3D new StringBuffer(); +- await request.forEach((List element) { +- for (int code in element) { +- buffer.writeCharCode(code); +- } +- }); +- Map valueMap =3D new HashMap(); +- String parameters =3D buffer.toString(); +- if (parameters.isNotEmpty) { +- List pairs =3D parameters.split('&'); +- for (String pair in pairs) { +- List parts =3D pair.split('=3D'); +- String value =3D parts[1].trim(); +- value =3D value.replaceAll('+', ' '); +- valueMap[parts[0].trim()] =3D value; +- } +- } +- return valueMap; +- } +- +- /** +- * Begin serving HTTP requests over the given [port]. +- */ +- void serveHttp(int port) { +- _server =3D HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, port); +- _server.then(_handleServer).catchError((_) {/* Ignore errors. */}); +- } +- +- /** +- * Handle a GET [request] received by the HTTP server. +- */ +- void _handleGetRequest(HttpRequest request) { +- StringBuffer buffer =3D new StringBuffer(); +- try { +- String path =3D request.uri.path; +- if (path =3D=3D logPath) { +- _writeLogPage(request, buffer); +- } else if (path =3D=3D statsPath) { +- _writeStatsPage(request, buffer); +- } else if (path =3D=3D taskPath) { +- _writeTaskPage(request, buffer); +- } else { +- _returnUnknownRequest(request); +- return; +- } +- } on UnknownRequest { +- _returnUnknownRequest(request); +- return; +- } catch (exception, stackTrace) { +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.OK; +- response.headers.contentType =3D _htmlContent; +- StringBuffer buffer =3D new StringBuffer(); +- buffer.write('

    Exception while composing page:

    '); +- buffer.write('

    $exception

    '); +- buffer.write('

    '); +- _writeStackTrace(buffer, stackTrace); +- buffer.write('

    '); +- response.write(buffer.toString()); +- response.close(); +- return; +- } +- +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.OK; +- response.headers.contentType =3D _htmlContent; +- response.write(buffer.toString()); +- response.close(); +- } +- +- /** +- * Handle a POST [request] received by the HTTP server. +- */ +- Future _handlePostRequest(HttpRequest request) async { +- _returnUnknownRequest(request); +- } +- +- /** +- * Attach a listener to a newly created HTTP server. +- */ +- void _handleServer(HttpServer httpServer) { +- httpServer.listen((HttpRequest request) { +- String method =3D request.method; +- if (method =3D=3D 'GET') { +- _handleGetRequest(request); +- } else if (method =3D=3D 'POST') { +- _handlePostRequest(request); +- } else { +- _returnUnknownRequest(request); +- } +- }); +- } +- +- /** +- * Return an error in response to an unrecognized request received by t= he HTTP +- * server. +- */ +- void _returnUnknownRequest(HttpRequest request) { +- HttpResponse response =3D request.response; +- response.statusCode =3D HttpStatus.NOT_FOUND; +- response.headers.contentType =3D +- new ContentType("text", "html", charset: "utf-8"); +- response.write( +- '

    Page not found: "${request.uri.path= }".

    '); +- response.close(); +- } +- +- void _writeLogPage(HttpRequest request, StringBuffer buffer) { +- Map parameterMap =3D getParameterMap(request); +- String groupId =3D parameterMap['group']; +- String startIndex =3D parameterMap['start']; +- LogPage page =3D new LogPage(log); +- page.selectedGroup =3D EntryGroup.withId(groupId ?? 'nonTask'); +- if (startIndex !=3D null) { +- page.pageStart =3D int.parse(startIndex); +- } else { +- page.pageStart =3D 0; +- } +- page.pageLength =3D 25; +- page.writePage(buffer); +- } +- +- /** +- * Write a representation of the given [stackTrace] to the given [sink]. +- */ +- void _writeStackTrace(StringSink sink, StackTrace stackTrace) { +- if (stackTrace !=3D null) { +- String trace =3D stackTrace.toString().replaceAll('#', '
    #'); +- if (trace.startsWith('
    #')) { +- trace =3D trace.substring(4); +- } +- sink.write('

    '); +- sink.write(trace); +- sink.write('

    '); +- } +- } +- +- void _writeStatsPage(HttpRequest request, StringBuffer buffer) { +- new StatsPage(log).writePage(buffer); +- } +- +- void _writeTaskPage(HttpRequest request, StringBuffer buffer) { +- Map parameterMap =3D getParameterMap(request); +- String analysisStart =3D parameterMap['analysisStart']; +- String start =3D parameterMap['start']; +- TaskPage page =3D new TaskPage(log); +- if (analysisStart =3D=3D null) { +- throw new UnknownRequest(); +- } +- page.analysisStart =3D int.parse(analysisStart); +- if (start !=3D null) { +- page.pageStart =3D int.parse(start); +- } else { +- page.pageStart =3D 0; +- } +- page.pageLength =3D 25; +- page.writePage(buffer); +- } +-} +diff --git a/pkg/analysis_server/tool/spec/api.dart b/pkg/analysis_server/= tool/spec/api.dart +deleted file mode 100644 +index 1fd0c67e649..00000000000 +--- a/pkg/analysis_server/tool/spec/api.dart ++++ /dev/null +@@ -1,528 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Data structures representing an API definition, and visitor base class= es +- * for visiting those data structures. +- */ +-import 'dart:collection'; +- +-import 'package:html/dom.dart' as dom; +- +-/** +- * Toplevel container for the API. +- */ +-class Api extends ApiNode { +- final String version; +- final List domains; +- final Types types; +- final Refactorings refactorings; +- +- Api(this.version, this.domains, this.types, this.refactorings, +- dom.Element html, +- {bool experimental}) +- : super(html, experimental, false); +-} +- +-/** +- * Base class for objects in the API model. +- */ +-class ApiNode { +- /** +- * A flag to indicate if this API is experimental. +- */ +- final bool experimental; +- +- /** +- * A flag to indicate if this API is deprecated. +- */ +- final bool deprecated; +- +- /** +- * Html element representing this part of the API. +- */ +- final dom.Element html; +- +- ApiNode(this.html, bool experimental, bool deprecated) +- : this.experimental =3D experimental ?? false, +- this.deprecated =3D deprecated ?? false; +-} +- +-/** +- * Base class for visiting the API definition. +- */ +-abstract class ApiVisitor { +- /** +- * Dispatch the given [type] to the visitor. +- */ +- T visitTypeDecl(TypeDecl type) =3D> type.accept(this) as T; +- T visitTypeEnum(TypeEnum typeEnum); +- T visitTypeList(TypeList typeList); +- T visitTypeMap(TypeMap typeMap); +- T visitTypeObject(TypeObject typeObject); +- T visitTypeReference(TypeReference typeReference); +- +- T visitTypeUnion(TypeUnion typeUnion); +-} +- +-/** +- * Definition of a single domain. +- */ +-class Domain extends ApiNode { +- final String name; +- final List requests; +- final List notifications; +- +- Domain(this.name, this.requests, this.notifications, dom.Element html, +- {bool experimental, bool deprecated}) +- : super(html, experimental, deprecated); +-} +- +-/** +- * API visitor that visits the entire API hierarchically by default. +- */ +-class HierarchicalApiVisitor extends ApiVisitor { +- /** +- * The API to visit. +- */ +- final Api api; +- +- HierarchicalApiVisitor(this.api); +- +- /** +- * If [type] is a [TypeReference] that is defined in the API, follow the +- * chain until a non-[TypeReference] is found, if possible. +- * +- * If it is not possible (because the chain ends with a [TypeReference]= that +- * is not defined in the API), then that final [TypeReference] is retur= ned. +- */ +- TypeDecl resolveTypeReferenceChain(TypeDecl type) { +- while (type is TypeReference && api.types.containsKey(type.typeName))= { +- type =3D api.types[(type as TypeReference).typeName].type; +- } +- return type; +- } +- +- void visitApi() { +- api.domains.forEach(visitDomain); +- visitTypes(api.types); +- visitRefactorings(api.refactorings); +- } +- +- void visitDomain(Domain domain) { +- domain.requests.forEach(visitRequest); +- domain.notifications.forEach(visitNotification); +- } +- +- void visitNotification(Notification notification) { +- if (notification.params !=3D null) { +- visitTypeDecl(notification.params); +- } +- } +- +- void visitRefactoring(Refactoring refactoring) { +- if (refactoring.feedback !=3D null) { +- visitTypeDecl(refactoring.feedback); +- } +- if (refactoring.options !=3D null) { +- visitTypeDecl(refactoring.options); +- } +- } +- +- void visitRefactorings(Refactorings refactorings) { +- refactorings?.forEach(visitRefactoring); +- } +- +- void visitRequest(Request request) { +- if (request.params !=3D null) { +- visitTypeDecl(request.params); +- } +- if (request.result !=3D null) { +- visitTypeDecl(request.result); +- } +- } +- +- void visitTypeDefinition(TypeDefinition typeDefinition) { +- visitTypeDecl(typeDefinition.type); +- } +- +- @override +- void visitTypeEnum(TypeEnum typeEnum) { +- typeEnum.values.forEach(visitTypeEnumValue); +- } +- +- void visitTypeEnumValue(TypeEnumValue typeEnumValue) {} +- +- @override +- void visitTypeList(TypeList typeList) { +- visitTypeDecl(typeList.itemType); +- } +- +- @override +- void visitTypeMap(TypeMap typeMap) { +- visitTypeDecl(typeMap.keyType); +- visitTypeDecl(typeMap.valueType); +- } +- +- @override +- void visitTypeObject(TypeObject typeObject) { +- typeObject.fields.forEach(visitTypeObjectField); +- } +- +- void visitTypeObjectField(TypeObjectField typeObjectField) { +- visitTypeDecl(typeObjectField.type); +- } +- +- @override +- void visitTypeReference(TypeReference typeReference) {} +- +- void visitTypes(Types types) { +- types.forEach(visitTypeDefinition); +- } +- +- @override +- void visitTypeUnion(TypeUnion typeUnion) { +- typeUnion.choices.forEach(visitTypeDecl); +- } +-} +- +-/** +- * Description of a notification method. +- */ +-class Notification extends ApiNode { +- /** +- * Name of the domain enclosing this request. +- */ +- final String domainName; +- +- /** +- * Name of the notification, without the domain prefix. +- */ +- final String event; +- +- /** +- * Type of the object associated with the "params" key in the notificat= ion +- * object, or null if the notification has no parameters. +- */ +- final TypeObject params; +- +- Notification(this.domainName, this.event, this.params, dom.Element html, +- {bool experimental}) +- : super(html, experimental, false); +- +- /** +- * Get the name of the notification, including the domain prefix. +- */ +- String get longEvent =3D> '$domainName.$event'; +- +- /** +- * Get the full type of the notification object, including the common "= id" +- * and "error" fields. +- */ +- TypeDecl get notificationType { +- List fields =3D [ +- new TypeObjectField('event', new TypeReference('String', null), nul= l, +- value: '$domainName.$event') +- ]; +- if (params !=3D null) { +- fields.add(new TypeObjectField('params', params, null)); +- } +- return new TypeObject(fields, null); +- } +-} +- +-/** +- * Description of a single refactoring. +- */ +-class Refactoring extends ApiNode { +- /** +- * Name of the refactoring. This should match one of the values allowe= d for +- * RefactoringKind. +- */ +- final String kind; +- +- /** +- * Type of the refactoring feedback, or null if the refactoring has no +- * feedback. +- */ +- final TypeObject feedback; +- +- /** +- * Type of the refactoring options, or null if the refactoring has no o= ptions. +- */ +- final TypeObject options; +- +- Refactoring(this.kind, this.feedback, this.options, dom.Element html, +- {bool experimental}) +- : super(html, experimental, false); +-} +- +-/** +- * A collection of refactoring definitions. +- */ +-class Refactorings extends ApiNode with IterableMixin { +- final List refactorings; +- +- Refactorings(this.refactorings, dom.Element html, {bool experimental}) +- : super(html, experimental, false); +- +- @override +- Iterator get iterator =3D> refactorings.iterator; +-} +- +-/** +- * Description of a request method. +- */ +-class Request extends ApiNode { +- /** +- * Name of the domain enclosing this request. +- */ +- final String domainName; +- +- /** +- * Name of the request, without the domain prefix. +- */ +- final String method; +- +- /** +- * Type of the object associated with the "params" key in the request o= bject, +- * or null if the request has no parameters. +- */ +- final TypeObject params; +- +- /** +- * Type of the object associated with the "result" key in the response = object, +- * or null if the response has no results. +- */ +- final TypeObject result; +- +- Request( +- this.domainName, this.method, this.params, this.result, dom.Element= html, +- {bool experimental, bool deprecated}) +- : super(html, experimental, deprecated); +- +- /** +- * Get the name of the request, including the domain prefix. +- */ +- String get longMethod =3D> '$domainName.$method'; +- +- /** +- * Get the full type of the request object, including the common "id" a= nd +- * "method" fields. +- */ +- TypeDecl get requestType { +- List fields =3D [ +- new TypeObjectField('id', new TypeReference('String', null), null), +- new TypeObjectField('method', new TypeReference('String', null), nu= ll, +- value: '$domainName.$method') +- ]; +- if (params !=3D null) { +- fields.add(new TypeObjectField('params', params, null)); +- } +- return new TypeObject(fields, null); +- } +- +- /** +- * Get the full type of the response object, including the common "id" = and +- * "error" fields. +- */ +- TypeDecl get responseType { +- List fields =3D [ +- new TypeObjectField('id', new TypeReference('String', null), null), +- new TypeObjectField( +- 'error', new TypeReference('RequestError', null), null, +- optional: true) +- ]; +- if (result !=3D null) { +- fields.add(new TypeObjectField('result', result, null)); +- } +- return new TypeObject(fields, null); +- } +-} +- +-/** +- * Base class for all possible types. +- */ +-abstract class TypeDecl extends ApiNode { +- TypeDecl(dom.Element html, bool experimental, bool deprecated) +- : super(html, experimental, deprecated); +- +- accept(ApiVisitor visitor); +-} +- +-/** +- * Description of a named type definition. +- */ +-class TypeDefinition extends ApiNode { +- final String name; +- final TypeDecl type; +- +- bool isExternal =3D false; +- +- TypeDefinition(this.name, this.type, dom.Element html, +- {bool experimental, bool deprecated}) +- : super(html, experimental, deprecated); +-} +- +-/** +- * Type of an enum. We represent enums in JSON as strings, so this type +- * declaration simply lists the allowed values. +- */ +-class TypeEnum extends TypeDecl { +- final List values; +- +- TypeEnum(this.values, dom.Element html, {bool experimental, bool deprec= ated}) +- : super(html, experimental, deprecated); +- +- @override +- accept(ApiVisitor visitor) =3D> visitor.visitTypeEnum(this); +-} +- +-/** +- * Description of a single allowed value for an enum. +- */ +-class TypeEnumValue extends ApiNode { +- final String value; +- +- TypeEnumValue(this.value, dom.Element html, +- {bool experimental, bool deprecated}) +- : super(html, experimental, deprecated); +-} +- +-/** +- * Type of a JSON list. +- */ +-class TypeList extends TypeDecl { +- final TypeDecl itemType; +- +- TypeList(this.itemType, dom.Element html, {bool experimental}) +- : super(html, experimental, false); +- +- @override +- accept(ApiVisitor visitor) =3D> visitor.visitTypeList(this); +-} +- +-/** +- * Type of a JSON map. +- */ +-class TypeMap extends TypeDecl { +- /** +- * Type of map keys. Note that since JSON map keys must always be stri= ngs, +- * this must either be a [TypeReference] for [String], or a [TypeRefere= nce] +- * to a type which is defined in the API as an enum or a synonym for [S= tring]. +- */ +- final TypeReference keyType; +- +- /** +- * Type of map values. +- */ +- final TypeDecl valueType; +- +- TypeMap(this.keyType, this.valueType, dom.Element html, {bool experimen= tal}) +- : super(html, experimental, false); +- +- @override +- accept(ApiVisitor visitor) =3D> visitor.visitTypeMap(this); +-} +- +-/** +- * Type of a JSON object with specified fields, some of which may be opti= onal. +- */ +-class TypeObject extends TypeDecl { +- final List fields; +- +- TypeObject(this.fields, dom.Element html, +- {bool experimental, bool deprecated}) +- : super(html, experimental, deprecated); +- +- @override +- accept(ApiVisitor visitor) =3D> visitor.visitTypeObject(this); +- +- /** +- * Return the field with the given [name], or null if there is no such = field. +- */ +- TypeObjectField getField(String name) { +- for (TypeObjectField field in fields) { +- if (field.name =3D=3D name) { +- return field; +- } +- } +- return null; +- } +-} +- +-/** +- * Description of a single field in a [TypeObject]. +- */ +-class TypeObjectField extends ApiNode { +- final String name; +- final TypeDecl type; +- final bool optional; +- +- /** +- * Value that the field is required to contain, or null if it may vary. +- */ +- final Object value; +- +- TypeObjectField(this.name, this.type, dom.Element html, +- {this.optional: false, this.value, bool experimental, bool deprecat= ed}) +- : super(html, experimental, deprecated); +-} +- +-/** +- * A reference to a type which is either defined elsewhere in the API or = which +- * is built-in ([String], [bool], or [int]). +- */ +-class TypeReference extends TypeDecl { +- final String typeName; +- +- TypeReference(this.typeName, dom.Element html, {bool experimental}) +- : super(html, experimental, false) { +- if (typeName.isEmpty) { +- throw new Exception('Empty type name'); +- } +- } +- +- @override +- accept(ApiVisitor visitor) =3D> visitor.visitTypeReference(this); +-} +- +-/** +- * A collection of type definitions. +- */ +-class Types extends ApiNode with IterableMixin { +- final Map types; +- +- List importUris =3D []; +- +- Types(this.types, dom.Element html, {bool experimental}) +- : super(html, experimental, false); +- +- @override +- Iterator get iterator =3D> types.values.iterator; +- +- Iterable get keys =3D> types.keys; +- +- TypeDefinition operator [](String typeName) =3D> types[typeName]; +- +- bool containsKey(String typeName) =3D> types.containsKey(typeName); +-} +- +-/** +- * Type which represents a union among multiple choices. +- */ +-class TypeUnion extends TypeDecl { +- final List choices; +- +- /** +- * The field that is used to disambiguate this union +- */ +- final String field; +- +- TypeUnion(this.choices, this.field, dom.Element html, {bool experimenta= l}) +- : super(html, experimental, false); +- +- @override +- accept(ApiVisitor visitor) =3D> visitor.visitTypeUnion(this); +-} +diff --git a/pkg/analysis_server/tool/spec/check_all_test.dart b/pkg/analy= sis_server/tool/spec/check_all_test.dart +deleted file mode 100644 +index a19596d7ad0..00000000000 +--- a/pkg/analysis_server/tool/spec/check_all_test.dart ++++ /dev/null +@@ -1,23 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:path/path.dart'; +- +-import 'generate_all.dart'; +- +-/** +- * Check that all targets have been code generated. If they haven't tell= the +- * user to run generate_all.dart. +- */ +-main() async { +- String script =3D Platform.script.toFilePath(windows: Platform.isWindow= s); +- List components =3D split(script); +- int index =3D components.indexOf('analysis_server'); +- String pkgPath =3D joinAll(components.sublist(0, index + 1)); +- await GeneratedContent.checkAll( +- pkgPath, join('tool', 'spec', 'generate_all.dart'), allTargets); +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_analysis_server.dart b/= pkg/analysis_server/tool/spec/codegen_analysis_server.dart +deleted file mode 100644 +index 307cf0727e4..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_analysis_server.dart ++++ /dev/null +@@ -1,137 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code generation for the file "AnalysisServer.java". +- */ +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +- +-import 'api.dart'; +-import 'codegen_java.dart'; +- +-final GeneratedFile target =3D javaGeneratedFile( +- 'tool/spec/generated/java/AnalysisServer.java', +- (Api api) =3D> new CodegenAnalysisServer(api)); +- +-class CodegenAnalysisServer extends CodegenJavaVisitor { +- CodegenAnalysisServer(Api api) : super(api); +- +- /** +- * Get the name of the consumer class for responses to this request. +- */ +- String consumerName(Request request) { +- return camelJoin([request.method, 'consumer'], doCapitalize: true); +- } +- +- @override +- void visitApi() { +- outputHeader(javaStyle: true); +- writeln('package com.google.dart.server.generated;'); +- writeln(); +- writeln('import com.google.dart.server.*;'); +- writeln('import org.dartlang.analysis.server.protocol.*;'); +- writeln(); +- writeln('import java.util.List;'); +- writeln('import java.util.Map;'); +- writeln(); +- writeln('''/** +- * The interface {@code AnalysisServer} defines the behavior of objects t= hat interface to an +- * analysis server. +- *=20 +- * @coverage dart.server +- */'''); +- makeClass('public interface AnalysisServer', () { +- // +- // addAnalysisServerListener(..) +- // +- publicMethod('addAnalysisServerListener', () { +- writeln('''/** +- * Add the given listener to the list of listeners that will receive noti= fication when new +- * analysis results become available. +- *=20 +- * @param listener the listener to be added +- */'''); +- writeln( +- 'public void addAnalysisServerListener(AnalysisServerListener= listener);'); +- }); +- +- // +- // removeAnalysisServerListener(..) +- // +- publicMethod('removeAnalysisServerListener', () { +- writeln('''/** +- * Remove the given listener from the list of listeners that will receive= notification when new +- * analysis results become available. +- *=20 +- * @param listener the listener to be removed +- */'''); +- writeln( +- 'public void removeAnalysisServerListener(AnalysisServerListe= ner listener);'); +- }); +- +- // +- // addStatusListener(..) +- // +- publicMethod('addStatusListener', () { +- writeln('''/** +- * Add the given listener to the list of listeners that will receive noti= fication when the server +- * is not active +- *=20 +- * @param listener the listener to be added +- */'''); +- writeln( +- 'public void addStatusListener(AnalysisServerStatusListener l= istener);'); +- }); +- +- // +- // isSocketOpen() +- // +- publicMethod('isSocketOpen', () { +- writeln('''/** +- * Return {@code true} if the socket is open. +- */'''); +- writeln('public boolean isSocketOpen();'); +- }); +- +- // +- // start(..) +- // +- publicMethod('start', () { +- writeln('''/** +- * Start the analysis server. +- */'''); +- writeln('public void start() throws Exception;'); +- }); +- super.visitApi(); +- }); +- } +- +- @override +- void visitRequest(Request request) { +- String methodName =3D '${request.domainName}_${request.method}'; +- publicMethod(methodName, () { +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.write('{@code ${request.longMethod }}'); +- toHtmlVisitor.translateHtml(request.html); +- toHtmlVisitor.javadocParams(request.params); +- if (request.deprecated) { +- toHtmlVisitor.p(() =3D> toHtmlVisitor.write('@deprecated')); +- } +- })); +- write('public void $methodName('); +- List arguments =3D []; +- if (request.params !=3D null) { +- for (TypeObjectField field in request.params.fields) { +- arguments.add('${javaType(field.type)} ${javaName(field.name)}'= ); +- } +- } +- if (request.result !=3D null) { +- arguments.add('${consumerName(request)} consumer'); +- } +- write(arguments.join(', ')); +- writeln(');'); +- }); +- } +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_dart.dart b/pkg/analysi= s_server/tool/spec/codegen_dart.dart +deleted file mode 100644 +index 8b736bbd257..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_dart.dart ++++ /dev/null +@@ -1,49 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'api.dart'; +- +-/** +- * Visitor specialized for generating Dart code. +- */ +-class DartCodegenVisitor extends HierarchicalApiVisitor { +- /** +- * Type references in the spec that are named something else in Dart. +- */ +- static const Map _typeRenames =3D const { +- 'long': 'int', +- 'object': 'Map', +- }; +- +- DartCodegenVisitor(Api api) : super(api); +- +- /** +- * Convert the given [TypeDecl] to a Dart type. +- */ +- String dartType(TypeDecl type) { +- if (type is TypeReference) { +- String typeName =3D type.typeName; +- TypeDefinition referencedDefinition =3D api.types[typeName]; +- if (_typeRenames.containsKey(typeName)) { +- return _typeRenames[typeName]; +- } +- if (referencedDefinition =3D=3D null) { +- return typeName; +- } +- TypeDecl referencedType =3D referencedDefinition.type; +- if (referencedType is TypeObject || referencedType is TypeEnum) { +- return typeName; +- } +- return dartType(referencedType); +- } else if (type is TypeList) { +- return 'List<${dartType(type.itemType)}>'; +- } else if (type is TypeMap) { +- return 'Map<${dartType(type.keyType)}, ${dartType(type.valueType)}>= '; +- } else if (type is TypeUnion) { +- return 'dynamic'; +- } else { +- throw new Exception("Can't convert to a dart type"); +- } +- } +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_dart_protocol.dart b/pk= g/analysis_server/tool/spec/codegen_dart_protocol.dart +deleted file mode 100644 +index 621da412ee2..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_dart_protocol.dart ++++ /dev/null +@@ -1,1326 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert'; +- +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:html/dom.dart' as dom; +-import 'package:path/path.dart' as path; +- +-import 'api.dart'; +-import 'codegen_dart.dart'; +-import 'from_html.dart'; +-import 'implied_types.dart'; +-import 'to_html.dart'; +- +-/** +- * Special flags that need to be inserted into the declaration of the Ele= ment +- * class. +- */ +-const Map specialElementFlags =3D const { +- 'abstract': '0x01', +- 'const': '0x02', +- 'final': '0x04', +- 'static': '0x08', +- 'private': '0x10', +- 'deprecated': '0x20' +-}; +- +-GeneratedFile target(bool responseRequiresRequestTime) { +- return new GeneratedFile('lib/protocol/protocol_generated.dart', +- (String pkgPath) async { +- CodegenProtocolVisitor visitor =3D new CodegenProtocolVisitor( +- path.basename(pkgPath), responseRequiresRequestTime, readApi(pkgP= ath)); +- return visitor.collectCode(visitor.visitApi); +- }); +-} +- +-/** +- * Callback type used to represent arbitrary code generation. +- */ +-typedef void CodegenCallback(); +- +-typedef String FromJsonSnippetCallback(String jsonPath, String json); +- +-typedef String ToJsonSnippetCallback(String value); +- +-/** +- * Visitor which produces Dart code representing the API. +- */ +-class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerato= r { +- /** +- * Class members for which the constructor argument should be optional,= even +- * if the member is not an optional part of the protocol. For list typ= es, +- * the constructor will default the member to the empty list. +- */ +- static const Map> _optionalConstructorArguments = =3D const { +- 'AnalysisErrorFixes': const ['fixes'], +- 'SourceChange': const ['edits', 'linkedEditGroups'], +- 'SourceFileEdit': const ['edits'], +- 'TypeHierarchyItem': const ['interfaces', 'mixins', 'subclasses'], +- }; +- +- /** +- * The disclaimer added to the documentation comment for each of the cl= asses +- * that are generated. +- */ +- static const String disclaimer =3D +- 'Clients may not extend, implement or mix-in this class.'; +- +- /** +- * The name of the package into which code is being generated. +- */ +- final String packageName; +- +- /** +- * A flag indicating whether the class [Response] requires a `requestTi= me` +- * parameter. +- */ +- final bool responseRequiresRequestTime; +- +- /** +- * Visitor used to produce doc comments. +- */ +- final ToHtmlVisitor toHtmlVisitor; +- +- /** +- * Types implied by the API. This includes types explicitly named in t= he +- * API as well as those implied by the definitions of requests, respons= es, +- * notifications, etc. +- */ +- final Map impliedTypes; +- +- CodegenProtocolVisitor( +- this.packageName, this.responseRequiresRequestTime, Api api) +- : toHtmlVisitor =3D new ToHtmlVisitor(api), +- impliedTypes =3D computeImpliedTypes(api), +- super(api) { +- codeGeneratorSettings.commentLineLength =3D 79; +- codeGeneratorSettings.languageName =3D 'dart'; +- } +- +- /** +- * Compute the code necessary to compare two objects for equality. +- */ +- String compareEqualsCode(TypeDecl type, String thisVar, String otherVar= ) { +- TypeDecl resolvedType =3D resolveTypeReferenceChain(type); +- if (resolvedType is TypeReference || +- resolvedType is TypeEnum || +- resolvedType is TypeObject || +- resolvedType is TypeUnion) { +- return '$thisVar =3D=3D $otherVar'; +- } else if (resolvedType is TypeList) { +- String itemTypeName =3D dartType(resolvedType.itemType); +- String subComparison =3D compareEqualsCode(resolvedType.itemType, '= a', 'b'); +- String closure =3D '($itemTypeName a, $itemTypeName b) =3D> $subCom= parison'; +- return 'listEqual($thisVar, $otherVar, $closure)'; +- } else if (resolvedType is TypeMap) { +- String valueTypeName =3D dartType(resolvedType.valueType); +- String subComparison =3D +- compareEqualsCode(resolvedType.valueType, 'a', 'b'); +- String closure =3D '($valueTypeName a, $valueTypeName b) =3D> $subC= omparison'; +- return 'mapEqual($thisVar, $otherVar, $closure)'; +- } +- throw new Exception( +- "Don't know how to compare for equality: $resolvedType"); +- } +- +- /** +- * Translate each of the given [types] implied by the API to a class. +- */ +- void emitClasses(List types) { +- for (ImpliedType impliedType in types) { +- TypeDecl type =3D impliedType.type; +- String dartTypeName =3D capitalize(impliedType.camelName); +- if (type =3D=3D null) { +- writeln(); +- emitEmptyObjectClass(dartTypeName, impliedType); +- } else if (type is TypeObject) { +- writeln(); +- emitObjectClass(dartTypeName, type, impliedType); +- } else if (type is TypeEnum) { +- writeln(); +- emitEnumClass(dartTypeName, type, impliedType); +- } +- } +- } +- +- /** +- * Emit a convenience constructor for decoding a piece of protocol, if +- * appropriate. Return true if a constructor was emitted. +- */ +- bool emitConvenienceConstructor(String className, ImpliedType impliedTy= pe) { +- // The type of object from which this piece of protocol should be dec= oded. +- String inputType; +- // The name of the input object. +- String inputName; +- // The field within the input object to decode. +- String fieldName; +- // Constructor call to create the JsonDecoder object. +- String makeDecoder; +- // Name of the constructor to create. +- String constructorName; +- // Extra arguments for the constructor. +- List extraArgs =3D []; +- switch (impliedType.kind) { +- case 'requestParams': +- inputType =3D 'Request'; +- inputName =3D 'request'; +- fieldName =3D 'params'; +- makeDecoder =3D 'new RequestDecoder(request)'; +- constructorName =3D 'fromRequest'; +- break; +- case 'requestResult': +- inputType =3D 'Response'; +- inputName =3D 'response'; +- fieldName =3D 'result'; +- makeDecoder =3D +- 'new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(resp= onse.id))'; +- constructorName =3D 'fromResponse'; +- break; +- case 'notificationParams': +- inputType =3D 'Notification'; +- inputName =3D 'notification'; +- fieldName =3D 'params'; +- makeDecoder =3D 'new ResponseDecoder(null)'; +- constructorName =3D 'fromNotification'; +- break; +- case 'refactoringOptions': +- inputType =3D 'EditGetRefactoringParams'; +- inputName =3D 'refactoringParams'; +- fieldName =3D 'options'; +- makeDecoder =3D 'new RequestDecoder(request)'; +- constructorName =3D 'fromRefactoringParams'; +- extraArgs.add('Request request'); +- break; +- default: +- return false; +- } +- List args =3D ['$inputType $inputName']; +- args.addAll(extraArgs); +- writeln('factory $className.$constructorName(${args.join(', ')}) {'); +- indent(() { +- String fieldNameString =3D +- literalString(fieldName.replaceFirst(new RegExp('^_'), '')); +- if (className =3D=3D 'EditGetRefactoringParams') { +- writeln('var params =3D new $className.fromJson('); +- writeln(' $makeDecoder, $fieldNameString, $inputName.$fieldNam= e);'); +- writeln('REQUEST_ID_REFACTORING_KINDS[request.id] =3D params.kind= ;'); +- writeln('return params;'); +- } else { +- writeln('return new $className.fromJson('); +- writeln(' $makeDecoder, $fieldNameString, $inputName.$fieldNam= e);'); +- } +- }); +- writeln('}'); +- return true; +- } +- +- /** +- * Emit a class representing an data structure that doesn't exist in the +- * protocol because it is empty (e.g. the "params" object for a request= that +- * doesn't have any parameters). +- */ +- void emitEmptyObjectClass(String className, ImpliedType impliedType) { +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(impliedType.humanReadableName); +- }); +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(disclaimer); +- }); +- })); +- write('class $className'); +- if (impliedType.kind =3D=3D 'refactoringFeedback') { +- writeln(' extends RefactoringFeedback implements HasToJson {'); +- } else if (impliedType.kind =3D=3D 'refactoringOptions') { +- writeln(' extends RefactoringOptions implements HasToJson {'); +- } else if (impliedType.kind =3D=3D 'requestParams') { +- writeln(' implements RequestParams {'); +- } else if (impliedType.kind =3D=3D 'requestResult') { +- writeln(' implements ResponseResult {'); +- } else { +- writeln(' {'); +- } +- indent(() { +- if (impliedType.kind =3D=3D 'requestResult' || +- impliedType.kind =3D=3D 'requestParams') { +- emitEmptyToJsonMember(); +- writeln(); +- } +- if (emitToRequestMember(impliedType)) { +- writeln(); +- } +- if (emitToResponseMember(impliedType)) { +- writeln(); +- } +- if (emitToNotificationMember(impliedType)) { +- writeln(); +- } +- emitObjectEqualsMember(null, className); +- writeln(); +- emitObjectHashCode(null, className); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the toJson() code for an empty class. +- */ +- void emitEmptyToJsonMember() { +- writeln('@override'); +- writeln('Map toJson() =3D> {};'); +- } +- +- /** +- * Emit a class to encapsulate an enum. +- */ +- void emitEnumClass(String className, TypeEnum type, ImpliedType implied= Type) { +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(impliedType.humanReadableName); +- }); +- if (impliedType.type !=3D null) { +- toHtmlVisitor.showType(null, impliedType.type); +- } +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(disclaimer); +- }); +- })); +- writeln('class $className implements Enum {'); +- indent(() { +- if (emitSpecialStaticMembers(className)) { +- writeln(); +- } +- for (TypeEnumValue value in type.values) { +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(value.html); +- })); +- String valueString =3D literalString(value.value); +- writeln( +- 'static const $className ${value.value} =3D const $className.= _($valueString);'); +- writeln(); +- } +- +- writeln('/**'); +- writeln(' * A list containing all of the enum values that are defin= ed.'); +- writeln(' */'); +- write('static const List<'); +- write(className); +- write('> VALUES =3D const <'); +- write(className); +- write('>['); +- bool first =3D true; +- for (TypeEnumValue value in type.values) { +- if (first) { +- first =3D false; +- } else { +- write(', '); +- } +- write(value.value); +- } +- writeln('];'); +- writeln(); +- +- writeln('@override'); +- writeln('final String name;'); +- writeln(); +- writeln('const $className._(this.name);'); +- writeln(); +- emitEnumClassConstructor(className, type); +- writeln(); +- emitEnumFromJsonConstructor(className, type, impliedType); +- writeln(); +- if (emitSpecialConstructors(className)) { +- writeln(); +- } +- if (emitSpecialGetters(className)) { +- writeln(); +- } +- if (emitSpecialMethods(className)) { +- writeln(); +- } +- writeln('@override'); +- writeln('String toString() =3D> "$className.\$name";'); +- writeln(); +- writeln('String toJson() =3D> name;'); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the constructor for an enum class. +- */ +- void emitEnumClassConstructor(String className, TypeEnum type) { +- writeln('factory $className(String name) {'); +- indent(() { +- writeln('switch (name) {'); +- indent(() { +- for (TypeEnumValue value in type.values) { +- String valueString =3D literalString(value.value); +- writeln('case $valueString:'); +- indent(() { +- writeln('return ${value.value};'); +- }); +- } +- }); +- writeln('}'); +- writeln(r"throw new Exception('Illegal enum value: $name');"); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the method for decoding an enum from JSON. +- */ +- void emitEnumFromJsonConstructor( +- String className, TypeEnum type, ImpliedType impliedType) { +- writeln( +- 'factory $className.fromJson(JsonDecoder jsonDecoder, String json= Path, Object json) {'); +- indent(() { +- writeln('if (json is String) {'); +- indent(() { +- writeln('try {'); +- indent(() { +- writeln('return new $className(json);'); +- }); +- writeln('} catch(_) {'); +- indent(() { +- writeln('// Fall through'); +- }); +- writeln('}'); +- }); +- writeln('}'); +- String humanReadableNameString =3D +- literalString(impliedType.humanReadableName); +- writeln( +- 'throw jsonDecoder.mismatch(jsonPath, $humanReadableNameString,= json);'); +- }); +- writeln('}'); +- } +- +- void emitImports() { +- writeln("import 'dart:convert' hide JsonDecoder;"); +- writeln(); +- writeln("import 'package:analyzer/src/generated/utilities_general.dar= t';"); +- writeln("import 'package:$packageName/protocol/protocol.dart';"); +- writeln( +- "import 'package:$packageName/src/protocol/protocol_internal.dart= ';"); +- for (String uri in api.types.importUris) { +- write("import '"); +- write(uri); +- writeln("';"); +- } +- } +- +- /** +- * Emit the class to encapsulate an object type. +- */ +- void emitObjectClass( +- String className, TypeObject type, ImpliedType impliedType) { +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(impliedType.humanReadableName); +- }); +- if (impliedType.type !=3D null) { +- toHtmlVisitor.showType(null, impliedType.type); +- } +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(disclaimer); +- }); +- })); +- write('class $className'); +- if (impliedType.kind =3D=3D 'refactoringFeedback') { +- writeln(' extends RefactoringFeedback {'); +- } else if (impliedType.kind =3D=3D 'refactoringOptions') { +- writeln(' extends RefactoringOptions {'); +- } else if (impliedType.kind =3D=3D 'requestParams') { +- writeln(' implements RequestParams {'); +- } else if (impliedType.kind =3D=3D 'requestResult') { +- writeln(' implements ResponseResult {'); +- } else { +- writeln(' implements HasToJson {'); +- } +- indent(() { +- if (emitSpecialStaticMembers(className)) { +- writeln(); +- } +- for (TypeObjectField field in type.fields) { +- if (field.value !=3D null) { +- continue; +- } +- writeln('${dartType(field.type)} _${field.name};'); +- writeln(); +- } +- for (TypeObjectField field in type.fields) { +- if (field.value !=3D null) { +- continue; +- } +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(field.html); +- })); +- writeln('${dartType(field.type)} get ${field.name} =3D> _${field.= name};'); +- writeln(); +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(field.html); +- })); +- writeln('void set ${field.name}(${dartType(field.type)} value) {'= ); +- indent(() { +- if (!field.optional) { +- writeln('assert(value !=3D null);'); +- } +- writeln('this._${field.name} =3D value;'); +- }); +- writeln('}'); +- writeln(); +- } +- emitObjectConstructor(type, className); +- writeln(); +- emitObjectFromJsonConstructor(className, type, impliedType); +- writeln(); +- if (emitConvenienceConstructor(className, impliedType)) { +- writeln(); +- } +- if (emitSpecialConstructors(className)) { +- writeln(); +- } +- if (emitSpecialGetters(className)) { +- writeln(); +- } +- emitToJsonMember(type); +- writeln(); +- if (emitToRequestMember(impliedType)) { +- writeln(); +- } +- if (emitToResponseMember(impliedType)) { +- writeln(); +- } +- if (emitToNotificationMember(impliedType)) { +- writeln(); +- } +- if (emitSpecialMethods(className)) { +- writeln(); +- } +- writeln('@override'); +- writeln('String toString() =3D> JSON.encode(toJson());'); +- writeln(); +- emitObjectEqualsMember(type, className); +- writeln(); +- emitObjectHashCode(type, className); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the constructor for an object class. +- */ +- void emitObjectConstructor(TypeObject type, String className) { +- List args =3D []; +- List optionalArgs =3D []; +- List extraInitCode =3D []; +- for (TypeObjectField field in type.fields) { +- if (field.value !=3D null) { +- continue; +- } +- String arg =3D '${dartType(field.type)} ${field.name}'; +- String setValueFromArg =3D 'this.${field.name} =3D ${field.name};'; +- if (isOptionalConstructorArg(className, field)) { +- optionalArgs.add(arg); +- if (!field.optional) { +- // Optional constructor arg, but non-optional field. If no arg= is +- // given, the constructor should populate with the empty list. +- TypeDecl fieldType =3D field.type; +- if (fieldType is TypeList) { +- extraInitCode.add(() { +- writeln('if (${field.name} =3D=3D null) {'); +- indent(() { +- writeln( +- 'this.${field.name} =3D <${dartType(fieldType.itemTyp= e)}>[];'); +- }); +- writeln('} else {'); +- indent(() { +- writeln(setValueFromArg); +- }); +- writeln('}'); +- }); +- } else { +- throw new Exception( +- "Don't know how to create default field value."); +- } +- } else { +- extraInitCode.add(() { +- writeln(setValueFromArg); +- }); +- } +- } else { +- args.add(arg); +- extraInitCode.add(() { +- writeln(setValueFromArg); +- }); +- } +- } +- if (optionalArgs.isNotEmpty) { +- args.add('{${optionalArgs.join(', ')}}'); +- } +- write('$className(${args.join(', ')})'); +- if (extraInitCode.isEmpty) { +- writeln(';'); +- } else { +- writeln(' {'); +- indent(() { +- for (CodegenCallback callback in extraInitCode) { +- callback(); +- } +- }); +- writeln('}'); +- } +- } +- +- /** +- * Emit the operator=3D=3D code for an object class. +- */ +- void emitObjectEqualsMember(TypeObject type, String className) { +- writeln('@override'); +- writeln('bool operator =3D=3D(other) {'); +- indent(() { +- writeln('if (other is $className) {'); +- indent(() { +- var comparisons =3D []; +- if (type !=3D null) { +- for (TypeObjectField field in type.fields) { +- if (field.value !=3D null) { +- continue; +- } +- comparisons.add(compareEqualsCode( +- field.type, field.name, 'other.${field.name}')); +- } +- } +- if (comparisons.isEmpty) { +- writeln('return true;'); +- } else { +- String concatenated =3D comparisons.join(' &&\n '); +- writeln('return $concatenated;'); +- } +- }); +- writeln('}'); +- writeln('return false;'); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the method for decoding an object from JSON. +- */ +- void emitObjectFromJsonConstructor( +- String className, TypeObject type, ImpliedType impliedType) { +- String humanReadableNameString =3D +- literalString(impliedType.humanReadableName); +- if (className =3D=3D 'RefactoringFeedback') { +- writeln('factory RefactoringFeedback.fromJson(JsonDecoder jsonDecod= er, ' +- 'String jsonPath, Object json, Map responseJson) {'); +- indent(() { +- writeln('return refactoringFeedbackFromJson(jsonDecoder, jsonPath= , ' +- 'json, responseJson);'); +- }); +- writeln('}'); +- return; +- } +- if (className =3D=3D 'RefactoringOptions') { +- writeln('factory RefactoringOptions.fromJson(JsonDecoder jsonDecode= r, ' +- 'String jsonPath, Object json, RefactoringKind kind) {'); +- indent(() { +- writeln('return refactoringOptionsFromJson(jsonDecoder, jsonPath,= ' +- 'json, kind);'); +- }); +- writeln('}'); +- return; +- } +- writeln( +- 'factory $className.fromJson(JsonDecoder jsonDecoder, String json= Path, Object json) {'); +- indent(() { +- writeln('if (json =3D=3D null) {'); +- indent(() { +- writeln('json =3D {};'); +- }); +- writeln('}'); +- writeln('if (json is Map) {'); +- indent(() { +- List args =3D []; +- List optionalArgs =3D []; +- for (TypeObjectField field in type.fields) { +- String fieldNameString =3D literalString(field.name); +- String fieldAccessor =3D 'json[$fieldNameString]'; +- String jsonPath =3D 'jsonPath + ${literalString('.${field.name}= ')}'; +- if (field.value !=3D null) { +- String valueString =3D literalString(field.value); +- writeln('if ($fieldAccessor !=3D $valueString) {'); +- indent(() { +- writeln( +- 'throw jsonDecoder.mismatch(jsonPath, "equal " + $value= String, json);'); +- }); +- writeln('}'); +- continue; +- } +- if (isOptionalConstructorArg(className, field)) { +- optionalArgs.add('${field.name}: ${field.name}'); +- } else { +- args.add(field.name); +- } +- TypeDecl fieldType =3D field.type; +- String fieldDartType =3D dartType(fieldType); +- writeln('$fieldDartType ${field.name};'); +- writeln('if (json.containsKey($fieldNameString)) {'); +- indent(() { +- String fromJson =3D +- fromJsonCode(fieldType).asSnippet(jsonPath, fieldAccessor= ); +- writeln('${field.name} =3D $fromJson;'); +- }); +- write('}'); +- if (!field.optional) { +- writeln(' else {'); +- indent(() { +- writeln( +- "throw jsonDecoder.mismatch(jsonPath, $fieldNameString)= ;"); +- }); +- writeln('}'); +- } else { +- writeln(); +- } +- } +- args.addAll(optionalArgs); +- writeln('return new $className(${args.join(', ')});'); +- }); +- writeln('} else {'); +- indent(() { +- writeln( +- 'throw jsonDecoder.mismatch(jsonPath, $humanReadableNameStrin= g, json);'); +- }); +- writeln('}'); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the hashCode getter for an object class. +- */ +- void emitObjectHashCode(TypeObject type, String className) { +- writeln('@override'); +- writeln('int get hashCode {'); +- indent(() { +- if (type =3D=3D null) { +- writeln('return ${className.hashCode};'); +- } else { +- writeln('int hash =3D 0;'); +- for (TypeObjectField field in type.fields) { +- String valueToCombine; +- if (field.value !=3D null) { +- valueToCombine =3D field.value.hashCode.toString(); +- } else { +- valueToCombine =3D '${field.name}.hashCode'; +- } +- writeln('hash =3D JenkinsSmiHash.combine(hash, $valueToCombine)= ;'); +- } +- writeln('return JenkinsSmiHash.finish(hash);'); +- } +- }); +- writeln('}'); +- } +- +- /** +- * If the class named [className] requires special constructors, emit t= hem +- * and return true. +- */ +- bool emitSpecialConstructors(String className) { +- switch (className) { +- case 'LinkedEditGroup': +- docComment([new dom.Text('Construct an empty LinkedEditGroup.')]); +- writeln( +- 'LinkedEditGroup.empty() : this([], 0, []);'); +- return true; +- case 'RefactoringProblemSeverity': +- docComment([ +- new dom.Text( +- 'Returns the [RefactoringProblemSeverity] with the maximal = severity.') +- ]); +- writeln( +- 'static RefactoringProblemSeverity max(RefactoringProblemSeve= rity a, RefactoringProblemSeverity b) =3D>'); +- writeln(' maxRefactoringProblemSeverity(a, b);'); +- return true; +- default: +- return false; +- } +- } +- +- /** +- * If the class named [className] requires special getters, emit them a= nd +- * return true. +- */ +- bool emitSpecialGetters(String className) { +- switch (className) { +- case 'Element': +- for (String name in specialElementFlags.keys) { +- String flag =3D 'FLAG_${name.toUpperCase()}'; +- writeln( +- 'bool get ${camelJoin(['is', name])} =3D> (flags & $flag) != =3D 0;'); +- } +- return true; +- case 'SourceEdit': +- docComment([new dom.Text('The end of the region to be modified.')= ]); +- writeln('int get end =3D> offset + length;'); +- return true; +- default: +- return false; +- } +- } +- +- /** +- * If the class named [className] requires special methods, emit them a= nd +- * return true. +- */ +- bool emitSpecialMethods(String className) { +- switch (className) { +- case 'LinkedEditGroup': +- docComment([new dom.Text('Add a new position and change the lengt= h.')]); +- writeln('void addPosition(Position position, int length) {'); +- indent(() { +- writeln('positions.add(position);'); +- writeln('this.length =3D length;'); +- }); +- writeln('}'); +- writeln(); +- docComment([new dom.Text('Add a new suggestion.')]); +- writeln('void addSuggestion(LinkedEditSuggestion suggestion) {'); +- indent(() { +- writeln('suggestions.add(suggestion);'); +- }); +- writeln('}'); +- return true; +- case 'SourceChange': +- docComment([ +- new dom.Text('Adds [edit] to the [FileEdit] for the given [file= ].') +- ]); +- writeln('void addEdit(String file, int fileStamp, SourceEdit edit= ) =3D>'); +- writeln(' addEditToSourceChange(this, file, fileStamp, edit);'= ); +- writeln(); +- docComment([new dom.Text('Adds the given [FileEdit].')]); +- writeln('void addFileEdit(SourceFileEdit edit) {'); +- indent(() { +- writeln('edits.add(edit);'); +- }); +- writeln('}'); +- writeln(); +- docComment([new dom.Text('Adds the given [LinkedEditGroup].')]); +- writeln('void addLinkedEditGroup(LinkedEditGroup linkedEditGroup)= {'); +- indent(() { +- writeln('linkedEditGroups.add(linkedEditGroup);'); +- }); +- writeln('}'); +- writeln(); +- docComment([ +- new dom.Text( +- 'Returns the [FileEdit] for the given [file], maybe `null`.= ') +- ]); +- writeln('SourceFileEdit getFileEdit(String file) =3D>'); +- writeln(' getChangeFileEdit(this, file);'); +- return true; +- case 'SourceEdit': +- docComment([ +- new dom.Text( +- 'Get the result of applying the edit to the given [code].') +- ]); +- writeln('String apply(String code) =3D> applyEdit(code, this);'); +- return true; +- case 'SourceFileEdit': +- docComment([new dom.Text('Adds the given [Edit] to the list.')]); +- writeln('void add(SourceEdit edit) =3D> addEditForSource(this, ed= it);'); +- writeln(); +- docComment([new dom.Text('Adds the given [Edit]s.')]); +- writeln('void addAll(Iterable edits) =3D>'); +- writeln(' addAllEditsForSource(this, edits);'); +- return true; +- default: +- return false; +- } +- } +- +- /** +- * If the class named [className] requires special static members, emit= them +- * and return true. +- */ +- bool emitSpecialStaticMembers(String className) { +- switch (className) { +- case 'Element': +- List makeFlagsArgs =3D []; +- List makeFlagsStatements =3D []; +- specialElementFlags.forEach((String name, String value) { +- String flag =3D 'FLAG_${name.toUpperCase()}'; +- String camelName =3D camelJoin(['is', name]); +- writeln('static const int $flag =3D $value;'); +- makeFlagsArgs.add('$camelName: false'); +- makeFlagsStatements.add('if ($camelName) flags |=3D $flag;'); +- }); +- writeln(); +- writeln('static int makeFlags({${makeFlagsArgs.join(', ')}}) {'); +- indent(() { +- writeln('int flags =3D 0;'); +- for (String statement in makeFlagsStatements) { +- writeln(statement); +- } +- writeln('return flags;'); +- }); +- writeln('}'); +- return true; +- case 'SourceEdit': +- docComment([ +- new dom.Text('Get the result of applying a set of ' + +- '[edits] to the given [code]. Edits are applied in the ord= er ' + +- 'they appear in [edits].') +- ]); +- writeln( +- 'static String applySequence(String code, Iterable edits) =3D>'); +- writeln(' applySequenceOfEdits(code, edits);'); +- return true; +- default: +- return false; +- } +- } +- +- /** +- * Emit the toJson() code for an object class. +- */ +- void emitToJsonMember(TypeObject type) { +- writeln('@override'); +- writeln('Map toJson() {'); +- indent(() { +- writeln('Map result =3D {};'); +- for (TypeObjectField field in type.fields) { +- String fieldNameString =3D literalString(field.name); +- if (field.value !=3D null) { +- writeln('result[$fieldNameString] =3D ${literalString(field.val= ue)};'); +- continue; +- } +- String fieldToJson =3D toJsonCode(field.type).asSnippet(field.nam= e); +- String populateField =3D 'result[$fieldNameString] =3D $fieldToJs= on;'; +- if (field.optional) { +- writeln('if (${field.name} !=3D null) {'); +- indent(() { +- writeln(populateField); +- }); +- writeln('}'); +- } else { +- writeln(populateField); +- } +- } +- writeln('return result;'); +- }); +- writeln('}'); +- } +- +- /** +- * Emit the toNotification() code for a class, if appropriate. Returns= true +- * if code was emitted. +- */ +- bool emitToNotificationMember(ImpliedType impliedType) { +- if (impliedType.kind =3D=3D 'notificationParams') { +- writeln('Notification toNotification() {'); +- indent(() { +- String eventString =3D +- literalString((impliedType.apiNode as Notification).longEvent= ); +- String jsonPart =3D impliedType.type !=3D null ? 'toJson()' : 'nu= ll'; +- writeln('return new Notification($eventString, $jsonPart);'); +- }); +- writeln('}'); +- return true; +- } +- return false; +- } +- +- /** +- * Emit the toRequest() code for a class, if appropriate. Returns true= if +- * code was emitted. +- */ +- bool emitToRequestMember(ImpliedType impliedType) { +- if (impliedType.kind =3D=3D 'requestParams') { +- writeln('@override'); +- writeln('Request toRequest(String id) {'); +- indent(() { +- String methodString =3D +- literalString((impliedType.apiNode as Request).longMethod); +- String jsonPart =3D impliedType.type !=3D null ? 'toJson()' : 'nu= ll'; +- writeln('return new Request(id, $methodString, $jsonPart);'); +- }); +- writeln('}'); +- return true; +- } +- return false; +- } +- +- /** +- * Emit the toResponse() code for a class, if appropriate. Returns tru= e if +- * code was emitted. +- */ +- bool emitToResponseMember(ImpliedType impliedType) { +- if (impliedType.kind =3D=3D 'requestResult') { +- writeln('@override'); +- if (responseRequiresRequestTime) { +- writeln('Response toResponse(String id, int requestTime) {'); +- } else { +- writeln('Response toResponse(String id) {'); +- } +- indent(() { +- String jsonPart =3D impliedType.type !=3D null ? 'toJson()' : 'nu= ll'; +- if (responseRequiresRequestTime) { +- writeln('return new Response(id, requestTime, result: $jsonPart= );'); +- } else { +- writeln('return new Response(id, result: $jsonPart);'); +- } +- }); +- writeln('}'); +- return true; +- } +- return false; +- } +- +- /** +- * Compute the code necessary to translate [type] from JSON. +- */ +- FromJsonCode fromJsonCode(TypeDecl type) { +- if (type is TypeReference) { +- TypeDefinition referencedDefinition =3D api.types[type.typeName]; +- if (referencedDefinition !=3D null) { +- TypeDecl referencedType =3D referencedDefinition.type; +- if (referencedType is TypeObject || referencedType is TypeEnum) { +- return new FromJsonSnippet((String jsonPath, String json) { +- String typeName =3D dartType(type); +- if (typeName =3D=3D 'RefactoringFeedback') { +- return 'new $typeName.fromJson(jsonDecoder, $jsonPath, $jso= n, json)'; +- } else if (typeName =3D=3D 'RefactoringOptions') { +- return 'new $typeName.fromJson(jsonDecoder, $jsonPath, $jso= n, kind)'; +- } else { +- return 'new $typeName.fromJson(jsonDecoder, $jsonPath, $jso= n)'; +- } +- }); +- } else { +- return fromJsonCode(referencedType); +- } +- } else { +- switch (type.typeName) { +- case 'String': +- return new FromJsonFunction('jsonDecoder.decodeString'); +- case 'bool': +- return new FromJsonFunction('jsonDecoder.decodeBool'); +- case 'int': +- case 'long': +- return new FromJsonFunction('jsonDecoder.decodeInt'); +- case 'object': +- return new FromJsonIdentity(); +- default: +- throw new Exception('Unexpected type name ${type.typeName}'); +- } +- } +- } else if (type is TypeMap) { +- FromJsonCode keyCode; +- if (dartType(type.keyType) !=3D 'String') { +- keyCode =3D fromJsonCode(type.keyType); +- } else { +- keyCode =3D new FromJsonIdentity(); +- } +- FromJsonCode valueCode =3D fromJsonCode(type.valueType); +- if (keyCode.isIdentity && valueCode.isIdentity) { +- return new FromJsonFunction('jsonDecoder.decodeMap'); +- } else { +- return new FromJsonSnippet((String jsonPath, String json) { +- StringBuffer result =3D new StringBuffer(); +- result.write('jsonDecoder.decodeMap($jsonPath, $json'); +- if (!keyCode.isIdentity) { +- result.write(', keyDecoder: ${keyCode.asClosure}'); +- } +- if (!valueCode.isIdentity) { +- result.write(', valueDecoder: ${valueCode.asClosure}'); +- } +- result.write(')'); +- return result.toString(); +- }); +- } +- } else if (type is TypeList) { +- FromJsonCode itemCode =3D fromJsonCode(type.itemType); +- if (itemCode.isIdentity) { +- return new FromJsonFunction('jsonDecoder.decodeList'); +- } else { +- return new FromJsonSnippet((String jsonPath, String json) =3D> +- 'jsonDecoder.decodeList($jsonPath, $json, ${itemCode.asClosur= e})'); +- } +- } else if (type is TypeUnion) { +- List decoders =3D []; +- for (TypeDecl choice in type.choices) { +- TypeDecl resolvedChoice =3D resolveTypeReferenceChain(choice); +- if (resolvedChoice is TypeObject) { +- TypeObjectField field =3D resolvedChoice.getField(type.field); +- if (field =3D=3D null) { +- throw new Exception( +- 'Each choice in the union needs a field named ${type.fiel= d}'); +- } +- if (field.value =3D=3D null) { +- throw new Exception( +- 'Each choice in the union needs a constant value for the = field ${type.field}'); +- } +- String closure =3D fromJsonCode(choice).asClosure; +- decoders.add('${literalString(field.value)}: $closure'); +- } else { +- throw new Exception('Union types must be unions of objects.'); +- } +- } +- return new FromJsonSnippet((String jsonPath, String json) =3D> +- 'jsonDecoder.decodeUnion($jsonPath, $json, ${literalString(type= .field)}, {${decoders.join(', ')}})'); +- } else { +- throw new Exception("Can't convert $type from JSON"); +- } +- } +- +- /** +- * Return a list of the classes to be emitted. +- */ +- List getClassesToEmit() { +- List types =3D impliedTypes.values.where((ImpliedType ty= pe) { +- ApiNode node =3D type.apiNode; +- return !(node is TypeDefinition && node.isExternal); +- }).toList(); +- types.sort((first, second) =3D> +- capitalize(first.camelName).compareTo(capitalize(second.camelName= ))); +- return types; +- } +- +- /** +- * True if the constructor argument for the given field should be optio= nal. +- */ +- bool isOptionalConstructorArg(String className, TypeObjectField field) { +- if (field.optional) { +- return true; +- } +- List forceOptional =3D _optionalConstructorArguments[classNam= e]; +- if (forceOptional !=3D null && forceOptional.contains(field.name)) { +- return true; +- } +- return false; +- } +- +- /** +- * Create a string literal that evaluates to [s]. +- */ +- String literalString(String s) { +- return JSON.encode(s); +- } +- +- /** +- * Compute the code necessary to convert [type] to JSON. +- */ +- ToJsonCode toJsonCode(TypeDecl type) { +- TypeDecl resolvedType =3D resolveTypeReferenceChain(type); +- if (resolvedType is TypeReference) { +- return new ToJsonIdentity(dartType(type)); +- } else if (resolvedType is TypeList) { +- ToJsonCode itemCode =3D toJsonCode(resolvedType.itemType); +- if (itemCode.isIdentity) { +- return new ToJsonIdentity(dartType(type)); +- } else { +- return new ToJsonSnippet(dartType(type), +- (String value) =3D> '$value.map(${itemCode.asClosure}).toList= ()'); +- } +- } else if (resolvedType is TypeMap) { +- ToJsonCode keyCode; +- if (dartType(resolvedType.keyType) !=3D 'String') { +- keyCode =3D toJsonCode(resolvedType.keyType); +- } else { +- keyCode =3D new ToJsonIdentity(dartType(resolvedType.keyType)); +- } +- ToJsonCode valueCode =3D toJsonCode(resolvedType.valueType); +- if (keyCode.isIdentity && valueCode.isIdentity) { +- return new ToJsonIdentity(dartType(resolvedType)); +- } else { +- return new ToJsonSnippet(dartType(type), (String value) { +- StringBuffer result =3D new StringBuffer(); +- result.write('mapMap($value'); +- if (!keyCode.isIdentity) { +- result.write(', keyCallback: ${keyCode.asClosure}'); +- } +- if (!valueCode.isIdentity) { +- result.write(', valueCallback: ${valueCode.asClosure}'); +- } +- result.write(')'); +- return result.toString(); +- }); +- } +- } else if (resolvedType is TypeUnion) { +- for (TypeDecl choice in resolvedType.choices) { +- if (resolveTypeReferenceChain(choice) is! TypeObject) { +- throw new Exception('Union types must be unions of objects'); +- } +- } +- return new ToJsonSnippet( +- dartType(type), (String value) =3D> '$value.toJson()'); +- } else if (resolvedType is TypeObject || resolvedType is TypeEnum) { +- return new ToJsonSnippet( +- dartType(type), (String value) =3D> '$value.toJson()'); +- } else { +- throw new Exception("Can't convert $resolvedType from JSON"); +- } +- } +- +- @override +- visitApi() { +- outputHeader(year: '2017'); +- writeln(); +- emitImports(); +- emitClasses(getClassesToEmit()); +- } +-} +- +-/** +- * Container for code that can be used to translate a data type from JSON. +- */ +-abstract class FromJsonCode { +- /** +- * Get the translation code in the form of a closure. +- */ +- String get asClosure; +- +- /** +- * True if the data type is already in JSON form, so the translation is= the +- * identity function. +- */ +- bool get isIdentity; +- +- /** +- * Get the translation code in the form of a code snippet, where [jsonP= ath] +- * is the variable holding the JSON path, and [json] is the variable ho= lding +- * the raw JSON. +- */ +- String asSnippet(String jsonPath, String json); +-} +- +-/** +- * Representation of FromJsonCode for a function defined elsewhere. +- */ +-class FromJsonFunction extends FromJsonCode { +- @override +- final String asClosure; +- +- FromJsonFunction(this.asClosure); +- +- @override +- bool get isIdentity =3D> false; +- +- @override +- String asSnippet(String jsonPath, String json) =3D> +- '$asClosure($jsonPath, $json)'; +-} +- +-/** +- * Representation of FromJsonCode for the identity transformation. +- */ +-class FromJsonIdentity extends FromJsonSnippet { +- FromJsonIdentity() : super((String jsonPath, String json) =3D> json); +- +- @override +- bool get isIdentity =3D> true; +-} +- +-/** +- * Representation of FromJsonCode for a snippet of inline code. +- */ +-class FromJsonSnippet extends FromJsonCode { +- /** +- * Callback that can be used to generate the code snippet, once the nam= es +- * of the [jsonPath] and [json] variables are known. +- */ +- final FromJsonSnippetCallback callback; +- +- FromJsonSnippet(this.callback); +- +- @override +- String get asClosure =3D> +- '(String jsonPath, Object json) =3D> ${callback('jsonPath', 'json')= }'; +- +- @override +- bool get isIdentity =3D> false; +- +- @override +- String asSnippet(String jsonPath, String json) =3D> callback(jsonPath, = json); +-} +- +-/** +- * Container for code that can be used to translate a data type to JSON. +- */ +-abstract class ToJsonCode { +- /** +- * Get the translation code in the form of a closure. +- */ +- String get asClosure; +- +- /** +- * True if the data type is already in JSON form, so the translation is= the +- * identity function. +- */ +- bool get isIdentity; +- +- /** +- * Get the translation code in the form of a code snippet, where [value] +- * is the variable holding the object to be translated. +- */ +- String asSnippet(String value); +-} +- +-/** +- * Representation of ToJsonCode for a function defined elsewhere. +- */ +-class ToJsonFunction extends ToJsonCode { +- @override +- final String asClosure; +- +- ToJsonFunction(this.asClosure); +- +- @override +- bool get isIdentity =3D> false; +- +- @override +- String asSnippet(String value) =3D> '$asClosure($value)'; +-} +- +-/** +- * Representation of FromJsonCode for the identity transformation. +- */ +-class ToJsonIdentity extends ToJsonSnippet { +- ToJsonIdentity(String type) : super(type, (String value) =3D> value); +- +- @override +- bool get isIdentity =3D> true; +-} +- +-/** +- * Representation of ToJsonCode for a snippet of inline code. +- */ +-class ToJsonSnippet extends ToJsonCode { +- /** +- * Callback that can be used to generate the code snippet, once the name +- * of the [value] variable is known. +- */ +- final ToJsonSnippetCallback callback; +- +- /** +- * Dart type of the [value] variable. +- */ +- final String type; +- +- ToJsonSnippet(this.type, this.callback); +- +- @override +- String get asClosure =3D> '($type value) =3D> ${callback('value')}'; +- +- @override +- bool get isIdentity =3D> false; +- +- @override +- String asSnippet(String value) =3D> callback(value); +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_inttest_methods.dart b/= pkg/analysis_server/tool/spec/codegen_inttest_methods.dart +deleted file mode 100644 +index 06b26e688bb..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_inttest_methods.dart ++++ /dev/null +@@ -1,275 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code generation for the file "integration_test_methods.dart". +- */ +-import 'dart:convert'; +- +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:path/path.dart' as path; +- +-import 'api.dart'; +-import 'codegen_dart.dart'; +-import 'from_html.dart'; +-import 'to_html.dart'; +- +-final GeneratedFile target =3D +- new GeneratedFile('test/integration/support/integration_test_methods.= dart', +- (String pkgPath) async { +- CodegenInttestMethodsVisitor visitor =3D new CodegenInttestMethodsVisit= or( +- path.basename(pkgPath), readApi(pkgPath)); +- return visitor.collectCode(visitor.visitApi); +-}); +- +-/** +- * Visitor that generates the code for integration_test_methods.dart +- */ +-class CodegenInttestMethodsVisitor extends DartCodegenVisitor +- with CodeGenerator { +- /** +- * The name of the package into which code is being generated. +- */ +- final String packageName; +- +- /** +- * Visitor used to produce doc comments. +- */ +- final ToHtmlVisitor toHtmlVisitor; +- +- /** +- * Code snippets concatenated to initialize all of the class fields. +- */ +- List fieldInitializationCode =3D []; +- +- /** +- * Code snippets concatenated to produce the contents of the switch sta= tement +- * for dispatching notifications. +- */ +- List notificationSwitchContents =3D []; +- +- CodegenInttestMethodsVisitor(this.packageName, Api api) +- : toHtmlVisitor =3D new ToHtmlVisitor(api), +- super(api) { +- codeGeneratorSettings.commentLineLength =3D 79; +- codeGeneratorSettings.languageName =3D 'dart'; +- } +- +- /** +- * Generate a function argument for the given parameter field. +- */ +- String formatArgument(TypeObjectField field) =3D> +- '${dartType(field.type)} ${field.name}'; +- +- /** +- * Figure out the appropriate Dart type for data having the given API +- * protocol [type]. +- */ +- String jsonType(TypeDecl type) { +- type =3D resolveTypeReferenceChain(type); +- if (type is TypeEnum) { +- return 'String'; +- } else if (type is TypeList) { +- return 'List<${jsonType(type.itemType)}>'; +- } else if (type is TypeMap) { +- return 'Map'; +- } else if (type is TypeObject) { +- return 'Map'; +- } else if (type is TypeReference) { +- switch (type.typeName) { +- case 'String': +- case 'int': +- case 'bool': +- // These types correspond exactly to Dart types +- return type.typeName; +- case 'object': +- return 'Map'; +- default: +- throw new Exception(type.typeName); +- } +- } else if (type is TypeUnion) { +- return 'Object'; +- } else { +- throw new Exception('Unexpected kind of TypeDecl'); +- } +- } +- +- @override +- visitApi() { +- outputHeader(year: '2017'); +- writeln(); +- writeln('/**'); +- writeln(' * Convenience methods for running integration tests'); +- writeln(' */'); +- writeln("import 'dart:async';"); +- writeln(); +- writeln("import 'package:$packageName/protocol/protocol_generated.dar= t';"); +- writeln( +- "import 'package:$packageName/src/protocol/protocol_internal.dart= ';"); +- writeln("import 'package:test/test.dart';"); +- writeln(); +- writeln("import 'integration_tests.dart';"); +- writeln("import 'protocol_matchers.dart';"); +- for (String uri in api.types.importUris) { +- write("import '"); +- write(uri); +- writeln("';"); +- } +- writeln(); +- writeln('/**'); +- writeln(' * Convenience methods for running integration tests'); +- writeln(' */'); +- writeln('abstract class IntegrationTestMixin {'); +- indent(() { +- writeln('Server get server;'); +- super.visitApi(); +- writeln(); +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.writeln('Initialize the fields in InttestMixin, and= '); +- toHtmlVisitor.writeln('ensure that notifications will be handled.= '); +- })); +- writeln('void initializeInttestMixin() {'); +- indent(() { +- write(fieldInitializationCode.join()); +- }); +- writeln('}'); +- writeln(); +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.writeln('Dispatch the notification named [event], a= nd'); +- toHtmlVisitor.writeln('containing parameters [params], to the'); +- toHtmlVisitor.writeln('appropriate stream.'); +- })); +- writeln('void dispatchNotification(String event, params) {'); +- indent(() { +- writeln('ResponseDecoder decoder =3D new ResponseDecoder(null);'); +- writeln('switch (event) {'); +- indent(() { +- write(notificationSwitchContents.join()); +- writeln('default:'); +- indent(() { +- writeln("fail('Unexpected notification: \$event');"); +- writeln('break;'); +- }); +- }); +- writeln('}'); +- }); +- writeln('}'); +- }); +- writeln('}'); +- } +- +- @override +- visitNotification(Notification notification) { +- String streamName =3D +- camelJoin(['on', notification.domainName, notification.event]); +- String className =3D camelJoin( +- [notification.domainName, notification.event, 'params'], +- doCapitalize: true); +- writeln(); +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(notification.html); +- toHtmlVisitor.describePayload(notification.params, 'Parameters'); +- })); +- writeln('Stream<$className> $streamName;'); +- writeln(); +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.write('Stream controller for [$streamName].'); +- })); +- writeln('StreamController<$className> _$streamName;'); +- fieldInitializationCode.add(collectCode(() { +- writeln('_$streamName =3D new StreamController<$className>(sync: tr= ue);'); +- writeln('$streamName =3D _$streamName.stream.asBroadcastStream();'); +- })); +- notificationSwitchContents.add(collectCode(() { +- writeln('case ${JSON.encode(notification.longEvent)}:'); +- indent(() { +- String paramsValidator =3D camelJoin( +- ['is', notification.domainName, notification.event, 'params']= ); +- writeln('outOfTestExpect(params, $paramsValidator);'); +- String constructorCall; +- if (notification.params =3D=3D null) { +- constructorCall =3D 'new $className()'; +- } else { +- constructorCall =3D +- "new $className.fromJson(decoder, 'params', params)"; +- } +- writeln('_$streamName.add($constructorCall);'); +- writeln('break;'); +- }); +- })); +- } +- +- @override +- visitRequest(Request request) { +- String methodName =3D camelJoin(['send', request.domainName, request.= method]); +- List args =3D []; +- List optionalArgs =3D []; +- if (request.params !=3D null) { +- for (TypeObjectField field in request.params.fields) { +- if (field.optional) { +- optionalArgs.add(formatArgument(field)); +- } else { +- args.add(formatArgument(field)); +- } +- } +- } +- if (optionalArgs.isNotEmpty) { +- args.add('{${optionalArgs.join(', ')}}'); +- } +- writeln(); +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(request.html); +- toHtmlVisitor.describePayload(request.params, 'Parameters'); +- toHtmlVisitor.describePayload(request.result, 'Returns'); +- })); +- if (request.deprecated) { +- writeln('@deprecated'); +- } +- String resultClass; +- String futureClass; +- if (request.result =3D=3D null) { +- futureClass =3D 'Future'; +- } else { +- resultClass =3D camelJoin([request.domainName, request.method, 'res= ult'], +- doCapitalize: true); +- futureClass =3D 'Future<$resultClass>'; +- } +- writeln('$futureClass $methodName(${args.join(', ')}) async {'); +- indent(() { +- String requestClass =3D camelJoin( +- [request.domainName, request.method, 'params'], +- doCapitalize: true); +- String paramsVar =3D 'null'; +- if (request.params !=3D null) { +- paramsVar =3D 'params'; +- List args =3D []; +- List optionalArgs =3D []; +- for (TypeObjectField field in request.params.fields) { +- if (field.optional) { +- optionalArgs.add('${field.name}: ${field.name}'); +- } else { +- args.add(field.name); +- } +- } +- args.addAll(optionalArgs); +- writeln('var params =3D new $requestClass(${args.join(', ')}).toJ= son();'); +- } +- String methodJson =3D JSON.encode(request.longMethod); +- writeln('var result =3D await server.send($methodJson, $paramsVar);= '); +- if (request.result !=3D null) { +- String kind =3D 'null'; +- if (requestClass =3D=3D 'EditGetRefactoringParams') { +- kind =3D 'kind'; +- } +- writeln('ResponseDecoder decoder =3D new ResponseDecoder($kind);'= ); +- writeln("return new $resultClass.fromJson(decoder, 'result', resu= lt);"); +- } else { +- writeln('outOfTestExpect(result, isNull);'); +- writeln('return null;'); +- } +- }); +- writeln('}'); +- } +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_java.dart b/pkg/analysi= s_server/tool/spec/codegen_java.dart +deleted file mode 100644 +index 805d06a7895..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_java.dart ++++ /dev/null +@@ -1,301 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Tools for Java code generation. +- */ +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:html/dom.dart' as dom; +- +-import 'api.dart'; +-import 'from_html.dart'; +-import 'to_html.dart'; +- +-/** +- * Create a [GeneratedFile] that creates Java code and outputs it to [pat= h]. +- * [path] uses Posix-style path separators regardless of the OS. +- */ +-GeneratedFile javaGeneratedFile( +- String path, CodegenJavaVisitor createVisitor(Api api)) { +- return new GeneratedFile(path, (String pkgPath) async { +- CodegenJavaVisitor visitor =3D createVisitor(readApi(pkgPath)); +- return visitor.collectCode(visitor.visitApi); +- }); +-} +- +-/** +- * Iterate through the values in [map] in the order of increasing keys. +- */ +-Iterable _valuesSortedByKey(Map map) { +- List keys =3D map.keys.toList(); +- keys.sort(); +- return keys.map((String key) =3D> map[key]); +-} +- +-/** +- * Common code for all Java code generation. +- */ +-class CodegenJavaVisitor extends HierarchicalApiVisitor with CodeGenerato= r { +- /** +- * Variable names which must be changed in order to avoid conflict with +- * reserved words in Java. +- */ +- static const Map _variableRenames =3D const { +- 'default': 'defaultSdk' +- }; +- +- /** +- * Type references in the spec that are named something else in Java. +- */ +- static const Map _typeRenames =3D const { +- 'bool': 'boolean', +- 'int': 'int', +- 'ExecutionContextId': 'String', +- 'FilePath': 'String', +- 'DebugContextId': 'String', +- 'object': 'Object', +- 'Override': 'OverrideMember', +- }; +- +- _CodegenJavaState _state; +- +- /** +- * Visitor used to produce doc comments. +- */ +- final ToHtmlVisitor toHtmlVisitor; +- +- CodegenJavaVisitor(Api api) +- : toHtmlVisitor =3D new ToHtmlVisitor(api), +- super(api); +- +- /** +- * Create a constructor, using [callback] to create its contents. +- */ +- void constructor(String name, void callback()) { +- _state.constructors[name] =3D collectCode(callback); +- } +- +- /** +- * Return true iff the passed [TypeDecl] will represent an array in Jav= a. +- */ +- bool isArray(TypeDecl type) { +- return type is TypeList && isPrimitive(type.itemType); +- } +- +- /** +- * Return true iff the passed [TypeDecl] is a type declared in the spec= _input. +- */ +- bool isDeclaredInSpec(TypeDecl type) { +-// TypeReference resolvedType =3D super.resolveTypeReferenceChain(type= ); +-// if(resolvedType is TypeObject) { +-// return truye; +-// } +- if (type is TypeReference) { +- return api.types.containsKey(type.typeName) && javaType(type) !=3D = 'String'; +- } +- return false; +- } +- +- /** +- * Return true iff the passed [TypeDecl] will represent an array in Jav= a. +- */ +- bool isList(TypeDecl type) { +- return type is TypeList && !isPrimitive(type.itemType); +- } +- +- /** +- * Return true iff the passed [TypeDecl] will represent a Map in type. +- */ +- bool isMap(TypeDecl type) { +- return type is TypeMap; +- } +- +- /** +- * Return true iff the passed [TypeDecl] will be represented as Object = in Java. +- */ +- bool isObject(TypeDecl type) { +- String typeStr =3D javaType(type); +- return typeStr =3D=3D 'Object'; +- } +- +- /** +- * Return true iff the passed [TypeDecl] will represent a primitive Jav= a type. +- */ +- bool isPrimitive(TypeDecl type) { +- if (type is TypeReference) { +- String typeStr =3D javaType(type); +- return typeStr =3D=3D 'boolean' || typeStr =3D=3D 'int' || typeStr = =3D=3D 'long'; +- } +- return false; +- } +- +- /** +- * Convenience method for subclasses for calling docComment. +- */ +- void javadocComment(List docs) { +- docComment(docs); +- } +- +- /** +- * Return a Java type for the given [TypeObjectField]. +- */ +- String javaFieldType(TypeObjectField field) { +- return javaType(field.type, field.optional); +- } +- +- /** +- * Return a suitable representation of [name] as the name of a Java var= iable. +- */ +- String javaName(String name) { +- if (_variableRenames.containsKey(name)) { +- return _variableRenames[name]; +- } +- return name; +- } +- +- /** +- * Convert the given [TypeDecl] to a Java type. +- */ +- String javaType(TypeDecl type, [bool optional =3D false]) { +- if (type is TypeReference) { +- TypeReference resolvedType =3D resolveTypeReferenceChain(type); +- String typeName =3D resolvedType.typeName; +- if (_typeRenames.containsKey(typeName)) { +- typeName =3D _typeRenames[typeName]; +- if (optional) { +- if (typeName =3D=3D 'boolean') { +- typeName =3D 'Boolean'; +- } else if (typeName =3D=3D 'int') { +- typeName =3D 'Integer'; +- } +- } +- } +- return typeName; +- } else if (type is TypeList) { +- if (isPrimitive(type.itemType)) { +- return '${javaType(type.itemType)}[]'; +- } else { +- return 'List<${javaType(type.itemType)}>'; +- } +- } else if (type is TypeMap) { +- return 'Map<${javaType(type.keyType)}, ${javaType(type.valueType)}>= '; +- } else if (type is TypeUnion) { +- return 'Object'; +- } else { +- throw new Exception("Can't make type buildable"); +- } +- } +- +- /** +- * Execute [callback], collecting any methods that are output using +- * [privateMethod] or [publicMethod], and insert the class (with methods +- * sorted). [header] is the part of the class declaration before the +- * opening brace. +- */ +- void makeClass(String header, void callback()) { +- _CodegenJavaState oldState =3D _state; +- try { +- _state =3D new _CodegenJavaState(); +- callback(); +- writeln('$header {'); +- indent(() { +- // fields +- List allFields =3D _state.publicFields.values.toList(); +- allFields.addAll(_state.privateFields.values.toList()); +- for (String field in allFields) { +- writeln(); +- write(field); +- } +- +- // constructors +- List allConstructors =3D _state.constructors.values.toLis= t(); +- for (String constructor in allConstructors) { +- writeln(); +- write(constructor); +- } +- +- // methods (ordered by method name) +- List allMethods =3D +- _valuesSortedByKey(_state.publicMethods).toList(); +- allMethods.addAll(_valuesSortedByKey(_state.privateMethods)); +- for (String method in allMethods) { +- writeln(); +- write(method); +- } +- writeln(); +- }); +- writeln('}'); +- } finally { +- _state =3D oldState; +- } +- } +- +- /** +- * Create a private field, using [callback] to create its contents. +- */ +- void privateField(String fieldName, void callback()) { +- _state.privateFields[fieldName] =3D collectCode(callback); +- } +- +- /** +- * Create a private method, using [callback] to create its contents. +- */ +- void privateMethod(String methodName, void callback()) { +- _state.privateMethods[methodName] =3D collectCode(callback); +- } +- +- /** +- * Create a public field, using [callback] to create its contents. +- */ +- void publicField(String fieldName, void callback()) { +- _state.publicFields[fieldName] =3D collectCode(callback); +- } +- +- /** +- * Create a public method, using [callback] to create its contents. +- */ +- void publicMethod(String methodName, void callback()) { +- _state.publicMethods[methodName] =3D collectCode(callback); +- } +- +- @override +- TypeDecl resolveTypeReferenceChain(TypeDecl type) { +- TypeDecl typeDecl =3D super.resolveTypeReferenceChain(type); +- if (typeDecl is TypeEnum) { +- return new TypeReference('String', null); +- } +- return type; +- } +-} +- +-/** +- * State used by [CodegenJavaVisitor]. +- */ +-class _CodegenJavaState { +- /** +- * Temporary storage for public methods. +- */ +- Map publicMethods =3D {}; +- +- /** +- * Temporary storage for private methods. +- */ +- Map privateMethods =3D {}; +- +- /** +- * Temporary storage for public fields. +- */ +- Map publicFields =3D {}; +- +- /** +- * Temporary storage for private fields. +- */ +- Map privateFields =3D {}; +- +- /** +- * Temporary storage for constructors. +- */ +- Map constructors =3D {}; +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_java_types.dart b/pkg/a= nalysis_server/tool/spec/codegen_java_types.dart +deleted file mode 100644 +index 85d6a9a6dcb..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_java_types.dart ++++ /dev/null +@@ -1,744 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code generation for the file "AnalysisServer.java". +- */ +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:html/dom.dart' as dom; +- +-import 'api.dart'; +-import 'codegen_java.dart'; +-import 'from_html.dart'; +-import 'implied_types.dart'; +- +-/** +- * A map between the field names and values for the Element object such a= s: +- * +- * private static final int ABSTRACT =3D 0x01; +- */ +-const Map _extraFieldsOnElement =3D const { +- 'ABSTRACT': '0x01', +- 'CONST': '0x02', +- 'FINAL': '0x04', +- 'TOP_LEVEL_STATIC': '0x08', +- 'PRIVATE': '0x10', +- 'DEPRECATED': '0x20', +-}; +- +-/** +- * A map between the method names and field names to generate additional = methods on the Element object: +- * +- * public boolean isFinal() { +- * return (flags & FINAL) !=3D 0; +- * } +- */ +-const Map _extraMethodsOnElement =3D const { +- 'isAbstract': 'ABSTRACT', +- 'isConst': 'CONST', +- 'isDeprecated': 'DEPRECATED', +- 'isFinal': 'FINAL', +- 'isPrivate': 'PRIVATE', +- 'isTopLevelOrStatic': 'TOP_LEVEL_STATIC', +-}; +- +-/** +- * Type references in the spec that are named something else in Java. +- */ +-const Map _typeRenames =3D const { +- 'Override': 'OverrideMember', +-}; +- +-final String pathToGenTypes =3D 'tool/spec/generated/java/types'; +- +-final GeneratedDirectory targetDir =3D +- new GeneratedDirectory(pathToGenTypes, (String pkgPath) { +- Api api =3D readApi(pkgPath); +- Map impliedTypes =3D computeImpliedTypes(api); +- Map map =3D +- new Map(); +- for (ImpliedType impliedType in impliedTypes.values) { +- String typeNameInSpec =3D capitalize(impliedType.camelName); +- bool isRefactoringFeedback =3D impliedType.kind =3D=3D 'refactoringFe= edback'; +- bool isRefactoringOption =3D impliedType.kind =3D=3D 'refactoringOpti= ons'; +- if (impliedType.kind =3D=3D 'typeDefinition' || +- isRefactoringFeedback || +- isRefactoringOption) { +- TypeDecl type =3D impliedType.type; +- if (type is TypeObject || type is TypeEnum) { +- // This is for situations such as 'Override' where the name in th= e spec +- // doesn't match the java object that we generate: +- String typeNameInJava =3D typeNameInSpec; +- if (_typeRenames.containsKey(typeNameInSpec)) { +- typeNameInJava =3D _typeRenames[typeNameInSpec]; +- } +- map['$typeNameInJava.java'] =3D (String pkgPath) async { +- String superclassName =3D null; +- if (isRefactoringFeedback) { +- superclassName =3D 'RefactoringFeedback'; +- } +- if (isRefactoringOption) { +- superclassName =3D 'RefactoringOptions'; +- } +- // configure accessors +- bool generateGetters =3D true; +- bool generateSetters =3D false; +- if (isRefactoringOption || +- typeNameInSpec =3D=3D 'Outline' || +- typeNameInSpec =3D=3D 'RefactoringMethodParameter') { +- generateSetters =3D true; +- } +- // create the visitor +- CodegenJavaType visitor =3D new CodegenJavaType(api, typeNameIn= Java, +- superclassName, generateGetters, generateSetters); +- return visitor.collectCode(() { +- dom.Element doc =3D type.html; +- if (impliedType.apiNode is TypeDefinition) { +- doc =3D (impliedType.apiNode as TypeDefinition).html; +- } +- visitor.emitType(type, doc); +- }); +- }; +- } +- } +- } +- return map; +-}); +- +-class CodegenJavaType extends CodegenJavaVisitor { +- final String className; +- final String superclassName; +- final bool generateGetters; +- final bool generateSetters; +- +- CodegenJavaType(Api api, this.className, this.superclassName, +- this.generateGetters, this.generateSetters) +- : super(api); +- +- /** +- * Get the name of the consumer class for responses to this request. +- */ +- String consumerName(Request request) { +- return camelJoin([request.method, 'consumer'], doCapitalize: true); +- } +- +- void emitType(TypeDecl type, dom.Element html) { +- outputHeader(javaStyle: true); +- writeln('package org.dartlang.analysis.server.protocol;'); +- writeln(); +- if (type is TypeObject) { +- _writeTypeObject(type, html); +- } else if (type is TypeEnum) { +- _writeTypeEnum(type, html); +- } +- } +- +- String _getAsTypeMethodName(TypeDecl typeDecl) { +- String name =3D javaType(typeDecl, true); +- if (name =3D=3D 'String') { +- return 'getAsString'; +- } else if (name =3D=3D 'boolean' || name =3D=3D 'Boolean') { +- return 'getAsBoolean'; +- } else if (name =3D=3D 'int' || name =3D=3D 'Integer') { +- return 'getAsInt'; +- } else if (name =3D=3D 'long' || name =3D=3D 'Long') { +- return 'getAsLong'; +- } else if (name.startsWith('List')) { +- return 'getAsJsonArray'; +- } else { +- // TODO (jwren) cleanup +- return 'getAsJsonArray'; +- } +- } +- +- String _getEqualsLogicForField(TypeObjectField field, String other) { +- String name =3D javaName(field.name); +- if (isPrimitive(field.type) && !field.optional) { +- return '$other.$name =3D=3D $name'; +- } else if (isArray(field.type)) { +- return 'Arrays.equals(other.$name, $name)'; +- } else { +- return 'ObjectUtilities.equals($other.$name, $name)'; +- } +- } +- +- /** +- * For some [TypeObjectField] return the [String] source for the field = value +- * for the toString generation. +- */ +- String _getToStringForField(TypeObjectField field) { +- String name =3D javaName(field.name); +- if (isArray(field.type) || isList(field.type)) { +- return 'StringUtils.join($name, ", ")'; +- } else { +- return name; +- } +- } +- +- bool _isTypeFieldInUpdateContentUnionType( +- String className, String fieldName) { +- if ((className =3D=3D 'AddContentOverlay' || +- className =3D=3D 'ChangeContentOverlay' || +- className =3D=3D 'RemoveContentOverlay') && +- fieldName =3D=3D 'type') { +- return true; +- } else { +- return false; +- } +- } +- +- /** +- * This method writes extra fields and methods to the Element type. +- */ +- void _writeExtraContentInElementType() { +- // +- // Extra fields on the Element type such as: +- // private static final int ABSTRACT =3D 0x01; +- // +- _extraFieldsOnElement.forEach((String name, String value) { +- publicField(javaName(name), () { +- writeln('private static final int $name =3D $value;'); +- }); +- }); +- +- // +- // Extra methods for the Element type such as: +- // public boolean isFinal() { +- // return (flags & FINAL) !=3D 0; +- // } +- // +- _extraMethodsOnElement.forEach((String methodName, String fieldName) { +- publicMethod(methodName, () { +- writeln('public boolean $methodName() {'); +- writeln(' return (flags & $fieldName) !=3D 0;'); +- writeln('}'); +- }); +- }); +- } +- +- /** +- * For some [TypeObjectField] write out the source that adds the field +- * information to the 'jsonObject'. +- */ +- void _writeOutJsonObjectAddStatement(TypeObjectField field) { +- String name =3D javaName(field.name); +- if (isDeclaredInSpec(field.type)) { +- writeln('jsonObject.add("$name", $name.toJson());'); +- } else if (field.type is TypeList) { +- TypeDecl listItemType =3D (field.type as TypeList).itemType; +- String jsonArrayName =3D 'jsonArray${capitalize(name)}'; +- writeln('JsonArray $jsonArrayName =3D new JsonArray();'); +- writeln('for (${javaType(listItemType)} elt : $name) {'); +- indent(() { +- if (isDeclaredInSpec(listItemType)) { +- writeln('$jsonArrayName.add(elt.toJson());'); +- } else { +- writeln('$jsonArrayName.add(new JsonPrimitive(elt));'); +- } +- }); +- writeln('}'); +- writeln('jsonObject.add("$name", $jsonArrayName);'); +- } else { +- writeln('jsonObject.addProperty("$name", $name);'); +- } +- } +- +- void _writeTypeEnum(TypeDecl type, dom.Element html) { +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(html); +- toHtmlVisitor.br(); +- toHtmlVisitor.write('@coverage dart.server.generated.types'); +- })); +- makeClass('public class $className', () { +- TypeEnum typeEnum =3D type as TypeEnum; +- List values =3D typeEnum.values; +- // +- // enum fields +- // +- for (TypeEnumValue value in values) { +- privateField(javaName(value.value), () { +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(value.html); +- })); +- writeln( +- 'public static final String ${value.value} =3D \"${value.va= lue}\";'); +- }); +- } +- }); +- } +- +- void _writeTypeObject(TypeDecl type, dom.Element html) { +- writeln('import java.util.Arrays;'); +- writeln('import java.util.List;'); +- writeln('import java.util.Map;'); +- writeln('import com.google.common.collect.Lists;'); +- writeln('import com.google.dart.server.utilities.general.JsonUtilitie= s;'); +- writeln('import com.google.dart.server.utilities.general.ObjectUtilit= ies;'); +- writeln('import com.google.gson.JsonArray;'); +- writeln('import com.google.gson.JsonElement;'); +- writeln('import com.google.gson.JsonObject;'); +- writeln('import com.google.gson.JsonPrimitive;'); +- writeln('import org.apache.commons.lang3.builder.HashCodeBuilder;'); +- writeln('import java.util.ArrayList;'); +- writeln('import java.util.Iterator;'); +- writeln('import org.apache.commons.lang3.StringUtils;'); +- writeln(); +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(html); +- toHtmlVisitor.br(); +- toHtmlVisitor.write('@coverage dart.server.generated.types'); +- })); +- writeln('@SuppressWarnings("unused")'); +- String header =3D 'public class $className'; +- if (superclassName !=3D null) { +- header +=3D ' extends $superclassName'; +- } +- makeClass(header, () { +- // +- // fields +- // +- // +- // public static final "EMPTY_ARRAY" field +- // +- publicField(javaName("EMPTY_ARRAY"), () { +- writeln( +- 'public static final $className[] EMPTY_ARRAY =3D new $classN= ame[0];'); +- }); +- +- // +- // public static final "EMPTY_LIST" field +- // +- publicField(javaName("EMPTY_LIST"), () { +- writeln( +- 'public static final List<$className> EMPTY_LIST =3D Lists.ne= wArrayList();'); +- }); +- +- // +- // "private static String name;" fields: +- // +- TypeObject typeObject =3D type as TypeObject; +- List fields =3D typeObject.fields; +- for (TypeObjectField field in fields) { +- String type =3D javaFieldType(field); +- String name =3D javaName(field.name); +- if (!(className =3D=3D 'Outline' && name =3D=3D 'children')) { +- privateField(name, () { +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(field.html); +- })); +- if (generateSetters) { +- writeln('private $type $name;'); +- } else { +- writeln('private final $type $name;'); +- } +- }); +- } +- } +- if (className =3D=3D 'Outline') { +- privateField(javaName('parent'), () { +- writeln('private final Outline parent;'); +- }); +- privateField(javaName('children'), () { +- writeln('private List children;'); +- }); +- } +- if (className =3D=3D 'NavigationRegion') { +- privateField(javaName('targetObjects'), () { +- writeln( +- 'private final List targetObjects =3D Lis= ts.newArrayList();'); +- }); +- } +- if (className =3D=3D 'NavigationTarget') { +- privateField(javaName('file'), () { +- writeln('private String file;'); +- }); +- } +- +- // +- // constructor +- // +- constructor(className, () { +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.write('Constructor for {@link $className}.'); +- })); +- write('public $className('); +- // write out parameters to constructor +- List parameters =3D new List(); +- if (className =3D=3D 'Outline') { +- parameters.add('Outline parent'); +- } +- for (TypeObjectField field in fields) { +- String type =3D javaFieldType(field); +- String name =3D javaName(field.name); +- if (!_isTypeFieldInUpdateContentUnionType(className, field.name= ) && +- !(className =3D=3D 'Outline' && name =3D=3D 'children')) { +- parameters.add('$type $name'); +- } +- } +- write(parameters.join(', ')); +- writeln(') {'); +- // write out the assignments in the body of the constructor +- indent(() { +- if (className =3D=3D 'Outline') { +- writeln('this.parent =3D parent;'); +- } +- for (TypeObjectField field in fields) { +- String name =3D javaName(field.name); +- if (!_isTypeFieldInUpdateContentUnionType(className, field.na= me) && +- !(className =3D=3D 'Outline' && name =3D=3D 'children')) { +- writeln('this.$name =3D $name;'); +- } else if (className =3D=3D 'AddContentOverlay') { +- writeln('this.type =3D "add";'); +- } else if (className =3D=3D 'ChangeContentOverlay') { +- writeln('this.type =3D "change";'); +- } else if (className =3D=3D 'RemoveContentOverlay') { +- writeln('this.type =3D "remove";'); +- } +- } +- }); +- writeln('}'); +- }); +- +- // +- // getter methods +- // +- if (generateGetters) { +- for (TypeObjectField field in fields) { +- String type =3D javaFieldType(field); +- String name =3D javaName(field.name); +- publicMethod('get$name', () { +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(field.html); +- })); +- if (type =3D=3D 'boolean') { +- writeln('public $type $name() {'); +- } else { +- writeln('public $type get${capitalize(name)}() {'); +- } +- writeln(' return $name;'); +- writeln('}'); +- }); +- } +- } +- +- // +- // setter methods +- // +- if (generateSetters) { +- for (TypeObjectField field in fields) { +- String type =3D javaFieldType(field); +- String name =3D javaName(field.name); +- publicMethod('set$name', () { +- javadocComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.translateHtml(field.html); +- })); +- String setterName =3D 'set' + capitalize(name); +- writeln('public void $setterName($type $name) {'); +- writeln(' this.$name =3D $name;'); +- writeln('}'); +- }); +- } +- } +- +- if (className =3D=3D 'NavigationRegion') { +- publicMethod('lookupTargets', () { +- writeln( +- 'public void lookupTargets(List allTarget= s) {'); +- writeln(' for (int i =3D 0; i < targets.length; i++) {'); +- writeln(' int targetIndex =3D targets[i];'); +- writeln(' NavigationTarget target =3D allTargets.get(targetI= ndex);'); +- writeln(' targetObjects.add(target);'); +- writeln(' }'); +- writeln('}'); +- }); +- publicMethod('getTargetObjects', () { +- writeln('public List getTargetObjects() {'); +- writeln(' return targetObjects;'); +- writeln('}'); +- }); +- } +- if (className =3D=3D 'NavigationTarget') { +- publicMethod('lookupFile', () { +- writeln('public void lookupFile(String[] allTargetFiles) {'); +- writeln(' file =3D allTargetFiles[fileIndex];'); +- writeln('}'); +- }); +- publicMethod('getFile', () { +- writeln('public String getFile() {'); +- writeln(' return file;'); +- writeln('}'); +- }); +- } +- +- // +- // fromJson(JsonObject) factory constructor, example: +-// public JsonObject toJson(JsonObject jsonObject) { +-// String x =3D jsonObject.get("x").getAsString(); +-// return new Y(x); +-// } +- if (className !=3D 'Outline') { +- publicMethod('fromJson', () { +- writeln('public static $className fromJson(JsonObject jsonObjec= t) {'); +- indent(() { +- for (TypeObjectField field in fields) { +- write('${javaFieldType(field)} ${javaName(field.name)} =3D = '); +- if (field.optional) { +- write( +- 'jsonObject.get("${javaName(field.name)}") =3D=3D nul= l ? null : '); +- } +- if (isDeclaredInSpec(field.type)) { +- write('${javaFieldType(field)}.fromJson('); +- write( +- 'jsonObject.get("${javaName(field.name)}").getAsJsonO= bject())'); +- } else { +- if (isList(field.type)) { +- if (javaFieldType(field).endsWith('')) { +- write( +- 'JsonUtilities.decodeStringList(jsonObject.get("$= {javaName(field.name)}").${_getAsTypeMethodName(field.type)}())'); +- } else { +- write( +- '${javaType((field.type as TypeList).itemType)}.f= romJsonArray(jsonObject.get("${javaName(field.name)}").${_getAsTypeMethodNa= me(field.type)}())'); +- } +- } else if (isArray(field.type)) { +- if (javaFieldType(field).startsWith('int')) { +- write( +- 'JsonUtilities.decodeIntArray(jsonObject.get("${j= avaName(field.name)}").${_getAsTypeMethodName(field.type)}())'); +- } +- } else { +- write( +- 'jsonObject.get("${javaName(field.name)}").${_getAs= TypeMethodName(field.type)}()'); +- } +- } +- writeln(';'); +- } +- write('return new $className('); +- List parameters =3D new List(); +- for (TypeObjectField field in fields) { +- if (!_isTypeFieldInUpdateContentUnionType( +- className, field.name)) { +- parameters.add('${javaName(field.name)}'); +- } +- } +- write(parameters.join(', ')); +- writeln(');'); +- }); +- writeln('}'); +- }); +- } else { +- publicMethod('fromJson', () { +- writeln( +- '''public static Outline fromJson(Outline parent, JsonObjec= t outlineObject) { +- JsonObject elementObject =3D outlineObject.get("element").getAsJsonObje= ct(); +- Element element =3D Element.fromJson(elementObject); +- int offset =3D outlineObject.get("offset").getAsInt(); +- int length =3D outlineObject.get("length").getAsInt(); +- +- // create outline object +- Outline outline =3D new Outline(parent, element, offset, length); +- +- // compute children recursively +- List childrenList =3D Lists.newArrayList(); +- JsonElement childrenJsonArray =3D outlineObject.get("children"); +- if (childrenJsonArray instanceof JsonArray) { +- Iterator childrenElementIterator =3D ((JsonArray) childr= enJsonArray).iterator(); +- while (childrenElementIterator.hasNext()) { +- JsonObject childObject =3D childrenElementIterator.next().getAsJson= Object(); +- childrenList.add(fromJson(outline, childObject)); +- } +- } +- outline.setChildren(childrenList); +- return outline; +-}'''); +- }); +- publicMethod('getParent', () { +- writeln('''public Outline getParent() { +- return parent; +-}'''); +- }); +- } +- +- // +- // fromJson(JsonArray) factory constructor +- // +- if (className !=3D 'Outline' && +- className !=3D 'RefactoringFeedback' && +- className !=3D 'RefactoringOptions') { +- publicMethod('fromJsonArray', () { +- writeln( +- 'public static List<$className> fromJsonArray(JsonArray jso= nArray) {'); +- indent(() { +- writeln('if (jsonArray =3D=3D null) {'); +- writeln(' return EMPTY_LIST;'); +- writeln('}'); +- writeln( +- 'ArrayList<$className> list =3D new ArrayList<$className>= (jsonArray.size());'); +- writeln('Iterator iterator =3D jsonArray.iterato= r();'); +- writeln('while (iterator.hasNext()) {'); +- writeln(' list.add(fromJson(iterator.next().getAsJsonObject(= )));'); +- writeln('}'); +- writeln('return list;'); +- }); +- writeln('}'); +- }); +- } +- +- // +- // toJson() method, example: +-// public JsonObject toJson() { +-// JsonObject jsonObject =3D new JsonObject(); +-// jsonObject.addProperty("x", x); +-// jsonObject.addProperty("y", y); +-// return jsonObject; +-// } +- if (className !=3D 'Outline') { +- publicMethod('toJson', () { +- writeln('public JsonObject toJson() {'); +- indent(() { +- writeln('JsonObject jsonObject =3D new JsonObject();'); +- for (TypeObjectField field in fields) { +- if (!isObject(field.type)) { +- if (field.optional) { +- writeln('if (${javaName(field.name)} !=3D null) {'); +- indent(() { +- _writeOutJsonObjectAddStatement(field); +- }); +- writeln('}'); +- } else { +- _writeOutJsonObjectAddStatement(field); +- } +- } +- } +- writeln('return jsonObject;'); +- }); +- writeln('}'); +- }); +- } +- +- // +- // equals() method +- // +- publicMethod('equals', () { +- writeln('@Override'); +- writeln('public boolean equals(Object obj) {'); +- indent(() { +- writeln('if (obj instanceof $className) {'); +- indent(() { +- writeln('$className other =3D ($className) obj;'); +- writeln('return'); +- indent(() { +- List equalsForField =3D new List(); +- for (TypeObjectField field in fields) { +- equalsForField.add(_getEqualsLogicForField(field, 'other'= )); +- } +- if (equalsForField.isNotEmpty) { +- write(equalsForField.join(' && \n')); +- } else { +- write('true'); +- } +- }); +- writeln(';'); +- }); +- writeln('}'); +- writeln('return false;'); +- }); +- writeln('}'); +- }); +- +- // +- // containsInclusive(int x) +- // +- if (className =3D=3D 'HighlightRegion' || +- className =3D=3D 'NavigationRegion' || +- className =3D=3D 'Outline') { +- publicMethod('containsInclusive', () { +- writeln('public boolean containsInclusive(int x) {'); +- indent(() { +- writeln('return offset <=3D x && x <=3D offset + length;'); +- }); +- writeln('}'); +- }); +- } +- +- // +- // contains(int x) +- // +- if (className =3D=3D 'Occurrences') { +- publicMethod('containsInclusive', () { +- writeln('public boolean containsInclusive(int x) {'); +- indent(() { +- writeln('for (int offset : offsets) {'); +- writeln(' if (offset <=3D x && x <=3D offset + length) {'); +- writeln(' return true;'); +- writeln(' }'); +- writeln('}'); +- writeln('return false;'); +- }); +- writeln('}'); +- }); +- } +- +- // +- // hashCode +- // +- publicMethod('hashCode', () { +- writeln('@Override'); +- writeln('public int hashCode() {'); +- indent(() { +- writeln('HashCodeBuilder builder =3D new HashCodeBuilder();'); +- for (int i =3D 0; i < fields.length; i++) { +- writeln("builder.append(${javaName(fields[i].name)});"); +- } +- writeln('return builder.toHashCode();'); +- }); +- writeln('}'); +- }); +- +- // +- // toString +- // +- publicMethod('toString', () { +- writeln('@Override'); +- writeln('public String toString() {'); +- indent(() { +- writeln('StringBuilder builder =3D new StringBuilder();'); +- writeln('builder.append(\"[\");'); +- for (int i =3D 0; i < fields.length; i++) { +- writeln("builder.append(\"${javaName(fields[i].name)}=3D\");"= ); +- write("builder.append(${_getToStringForField(fields[i])}"); +- if (i + 1 !=3D fields.length) { +- // this is not the last field +- write(' + \", \"'); +- } +- writeln(');'); +- } +- writeln('builder.append(\"]\");'); +- writeln('return builder.toString();'); +- }); +- writeln('}'); +- }); +- +- if (className =3D=3D 'Element') { +- _writeExtraContentInElementType(); +- } +- +- // +- // getBestName() +- // +- if (className =3D=3D 'TypeHierarchyItem') { +- publicMethod('getBestName', () { +- writeln('public String getBestName() {'); +- indent(() { +- writeln('if (displayName =3D=3D null) {'); +- writeln(' return classElement.getName();'); +- writeln('} else {'); +- writeln(' return displayName;'); +- writeln('}'); +- }); +- writeln('}'); +- }); +- } +- }); +- } +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_matchers.dart b/pkg/ana= lysis_server/tool/spec/codegen_matchers.dart +deleted file mode 100644 +index a321ba07b14..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_matchers.dart ++++ /dev/null +@@ -1,191 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code generation for the file "matchers.dart". +- */ +-import 'dart:convert'; +- +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +- +-import 'api.dart'; +-import 'from_html.dart'; +-import 'implied_types.dart'; +-import 'to_html.dart'; +- +-final GeneratedFile target =3D new GeneratedFile( +- 'test/integration/support/protocol_matchers.dart', (String pkgPath) a= sync { +- CodegenMatchersVisitor visitor =3D new CodegenMatchersVisitor(readApi(p= kgPath)); +- return visitor.collectCode(visitor.visitApi); +-}); +- +-class CodegenMatchersVisitor extends HierarchicalApiVisitor with CodeGene= rator { +- /** +- * Visitor used to produce doc comments. +- */ +- final ToHtmlVisitor toHtmlVisitor; +- +- /** +- * Short human-readable string describing the context of the matcher be= ing +- * created. +- */ +- String context; +- +- CodegenMatchersVisitor(Api api) +- : toHtmlVisitor =3D new ToHtmlVisitor(api), +- super(api) { +- codeGeneratorSettings.commentLineLength =3D 79; +- codeGeneratorSettings.languageName =3D 'dart'; +- } +- +- /** +- * Create a matcher for the part of the API called [name], optionally +- * clarified by [nameSuffix]. The matcher should verify that its input +- * matches the given [type]. +- */ +- void makeMatcher(ImpliedType impliedType) { +- context =3D impliedType.humanReadableName; +- docComment(toHtmlVisitor.collectHtml(() { +- toHtmlVisitor.p(() { +- toHtmlVisitor.write(context); +- }); +- if (impliedType.type !=3D null) { +- toHtmlVisitor.showType(null, impliedType.type); +- } +- })); +- write('final Matcher ${camelJoin(['is', impliedType.camelName])} =3D = '); +- if (impliedType.type =3D=3D null) { +- write('isNull'); +- } else { +- visitTypeDecl(impliedType.type); +- } +- writeln(';'); +- writeln(); +- } +- +- /** +- * Generate a map describing the given set of fields, for use as the +- * 'requiredFields' or 'optionalFields' argument to the [MatchesJsonObj= ect] +- * constructor. +- */ +- void outputObjectFields(Iterable fields) { +- if (fields.isEmpty) { +- write('null'); +- return; +- } +- writeln('{'); +- indent(() { +- bool commaNeeded =3D false; +- for (TypeObjectField field in fields) { +- if (commaNeeded) { +- writeln(','); +- } +- write('${JSON.encode(field.name)}: '); +- if (field.value !=3D null) { +- write('equals(${JSON.encode(field.value)})'); +- } else { +- visitTypeDecl(field.type); +- } +- commaNeeded =3D true; +- } +- writeln(); +- }); +- write('}'); +- } +- +- @override +- visitApi() { +- outputHeader(year: '2017'); +- writeln(); +- writeln('/**'); +- writeln(' * Matchers for data types defined in the analysis server AP= I'); +- writeln(' */'); +- writeln("import 'package:test/test.dart';"); +- writeln(); +- writeln("import 'integration_tests.dart';"); +- writeln(); +- List impliedTypes =3D computeImpliedTypes(api).values.to= List(); +- impliedTypes.sort((ImpliedType first, ImpliedType second) =3D> +- first.camelName.compareTo(second.camelName)); +- for (ImpliedType impliedType in impliedTypes) { +- makeMatcher(impliedType); +- } +- } +- +- @override +- visitTypeEnum(TypeEnum typeEnum) { +- writeln('new MatchesEnum(${JSON.encode(context)}, ['); +- indent(() { +- bool commaNeeded =3D false; +- for (TypeEnumValue value in typeEnum.values) { +- if (commaNeeded) { +- writeln(','); +- } +- write('${JSON.encode(value.value)}'); +- commaNeeded =3D true; +- } +- writeln(); +- }); +- write('])'); +- } +- +- @override +- visitTypeList(TypeList typeList) { +- write('isListOf('); +- visitTypeDecl(typeList.itemType); +- write(')'); +- } +- +- @override +- visitTypeMap(TypeMap typeMap) { +- write('isMapOf('); +- visitTypeDecl(typeMap.keyType); +- write(', '); +- visitTypeDecl(typeMap.valueType); +- write(')'); +- } +- +- @override +- void visitTypeObject(TypeObject typeObject) { +- writeln('new LazyMatcher(() =3D> new MatchesJsonObject('); +- indent(() { +- write('${JSON.encode(context)}, '); +- Iterable requiredFields =3D +- typeObject.fields.where((TypeObjectField field) =3D> !field.opt= ional); +- outputObjectFields(requiredFields); +- List optionalFields =3D typeObject.fields +- .where((TypeObjectField field) =3D> field.optional) +- .toList(); +- if (optionalFields.isNotEmpty) { +- write(', optionalFields: '); +- outputObjectFields(optionalFields); +- } +- }); +- write('))'); +- } +- +- @override +- void visitTypeReference(TypeReference typeReference) { +- String typeName =3D typeReference.typeName; +- if (typeName =3D=3D 'long') { +- typeName =3D 'int'; +- } +- write(camelJoin(['is', typeName])); +- } +- +- @override +- void visitTypeUnion(TypeUnion typeUnion) { +- bool commaNeeded =3D false; +- write('isOneOf(['); +- for (TypeDecl choice in typeUnion.choices) { +- if (commaNeeded) { +- write(', '); +- } +- visitTypeDecl(choice); +- commaNeeded =3D true; +- } +- write('])'); +- } +-} +diff --git a/pkg/analysis_server/tool/spec/codegen_protocol_constants.dart= b/pkg/analysis_server/tool/spec/codegen_protocol_constants.dart +deleted file mode 100644 +index cdb7c6a2454..00000000000 +--- a/pkg/analysis_server/tool/spec/codegen_protocol_constants.dart ++++ /dev/null +@@ -1,170 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +- +-import 'api.dart'; +-import 'codegen_dart.dart'; +-import 'from_html.dart'; +- +-final GeneratedFile target =3D new GeneratedFile( +- 'lib/protocol/protocol_constants.dart', (String pkgPath) async { +- CodegenVisitor visitor =3D new CodegenVisitor(readApi(pkgPath)); +- return visitor.collectCode(visitor.visitApi); +-}); +- +-/** +- * A visitor that produces Dart code defining constants associated with t= he API. +- */ +-class CodegenVisitor extends DartCodegenVisitor with CodeGenerator { +- CodegenVisitor(Api api) : super(api) { +- codeGeneratorSettings.commentLineLength =3D 79; +- codeGeneratorSettings.languageName =3D 'dart'; +- } +- +- /** +- * Generate all of the constants associates with the [api]. +- */ +- void generateConstants() { +- _ConstantVisitor visitor =3D new _ConstantVisitor(api); +- visitor.visitApi(); +- List<_Constant> constants =3D visitor.constants; +- constants.sort((first, second) =3D> first.name.compareTo(second.name)= ); +- for (_Constant constant in constants) { +- generateContant(constant); +- } +- } +- +- /** +- * Generate the given [constant]. +- */ +- void generateContant(_Constant constant) { +- write('const String '); +- write(constant.name); +- write(' =3D '); +- write(constant.value); +- writeln(';'); +- } +- +- @override +- visitApi() { +- outputHeader(year: '2017'); +- writeln(); +- generateConstants(); +- } +-} +- +-/** +- * A representation of a constant that is to be generated. +- */ +-class _Constant { +- /** +- * The name of the constant. +- */ +- final String name; +- +- /** +- * The value of the constant. +- */ +- final String value; +- +- /** +- * Initialize a newly created constant. +- */ +- _Constant(this.name, this.value); +-} +- +-/** +- * A visitor that visits an API to compute a list of constants to be gene= rated. +- */ +-class _ConstantVisitor extends HierarchicalApiVisitor { +- /** +- * The list of constants to be generated. +- */ +- List<_Constant> constants =3D <_Constant>[]; +- +- /** +- * Initialize a newly created visitor to visit the given [api]. +- */ +- _ConstantVisitor(Api api) : super(api); +- +- @override +- void visitNotification(Notification notification) { +- String domainName =3D notification.domainName; +- String event =3D notification.event; +- +- String constantName =3D _generateName(domainName, 'notification', eve= nt); +- constants.add(new _Constant(constantName, "'$domainName.$event'")); +- _addFieldConstants(constantName, notification.params); +- } +- +- @override +- void visitRequest(Request request) { +- String domainName =3D request.domainName; +- String method =3D request.method; +- +- String requestConstantName =3D _generateName(domainName, 'request', m= ethod); +- constants.add(new _Constant(requestConstantName, "'$domainName.$metho= d'")); +- _addFieldConstants(requestConstantName, request.params); +- +- String responseConstantName =3D _generateName(domainName, 'response',= method); +- _addFieldConstants(responseConstantName, request.result); +- } +- +- /** +- * Generate a constant for each of the fields in the given [type], wher= e the +- * name of each constant will be composed from the [parentName] and the= name +- * of the field. +- */ +- void _addFieldConstants(String parentName, TypeObject type) { +- if (type =3D=3D null) { +- return; +- } +- type.fields.forEach((TypeObjectField field) { +- String name =3D field.name; +- List components =3D []; +- components.add(parentName); +- components.addAll(_split(name)); +- String fieldConstantName =3D _fromComponents(components); +- constants.add(new _Constant(fieldConstantName, "'$name'")); +- }); +- } +- +- /** +- * Return a name generated by converting each of the given [components]= to an +- * uppercase equivalent, then joining them with underscores. +- */ +- String _fromComponents(List components) =3D> +- components.map((String component) =3D> component.toUpperCase()).joi= n('_'); +- +- /** +- * Generate a name from the [domainName], [kind] and [name] components. +- */ +- String _generateName(String domainName, String kind, String name) { +- List components =3D []; +- components.addAll(_split(domainName)); +- components.add(kind); +- components.addAll(_split(name)); +- return _fromComponents(components); +- } +- +- /** +- * Return the components of the given [string] that are indicated by an= upper +- * case letter. +- */ +- Iterable _split(String first) { +- RegExp regExp =3D new RegExp('[A-Z]'); +- List components =3D []; +- int start =3D 1; +- int index =3D first.indexOf(regExp, start); +- while (index >=3D 0) { +- components.add(first.substring(start - 1, index)); +- start =3D index + 1; +- index =3D first.indexOf(regExp, start); +- } +- components.add(first.substring(start - 1)); +- return components; +- } +-} +diff --git a/pkg/analysis_server/tool/spec/from_html.dart b/pkg/analysis_s= erver/tool/spec/from_html.dart +deleted file mode 100644 +index 26c6eb9122d..00000000000 +--- a/pkg/analysis_server/tool/spec/from_html.dart ++++ /dev/null +@@ -1,609 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code for reading an HTML API description. +- */ +-import 'dart:io'; +- +-import 'package:analyzer/src/codegen/html.dart'; +-import 'package:html/dom.dart' as dom; +-import 'package:html/parser.dart' as parser; +-import 'package:path/path.dart'; +- +-import 'api.dart'; +- +-/** +- * Read the API description from the file 'plugin_spec.html'. [pkgPath] = is the +- * path to the current package. +- */ +-Api readApi(String pkgPath) { +- ApiReader reader =3D +- new ApiReader(join(pkgPath, 'tool', 'spec', 'spec_input.html')); +- return reader.readApi(); +-} +- +-typedef void ElementProcessor(dom.Element element); +- +-typedef void TextProcessor(dom.Text text); +- +-class ApiReader { +- static const List specialElements =3D const [ +- 'domain', +- 'feedback', +- 'object', +- 'refactorings', +- 'refactoring', +- 'type', +- 'types', +- 'request', +- 'notification', +- 'params', +- 'result', +- 'field', +- 'list', +- 'map', +- 'enum', +- 'key', +- 'value', +- 'options', +- 'ref', +- 'code', +- 'version', +- 'union', +- 'index', +- 'include' +- ]; +- +- /** +- * The absolute and normalized path to the file being read. +- */ +- final String filePath; +- +- /** +- * Initialize a newly created API reader to read from the file with the= given +- * [filePath]. +- */ +- ApiReader(this.filePath); +- +- /** +- * Create an [Api] object from an HTML representation such as: +- * +- * +- * ... +- * +- * ... 1.0 ... +- * ... +- * ... +- * ... +- * +- * +- * +- * Child elements of can occur in any order. +- */ +- Api apiFromHtml(dom.Element html) { +- Api api; +- List versions =3D []; +- List domains =3D []; +- Types types =3D null; +- Refactorings refactorings =3D null; +- recurse(html, 'api', { +- 'domain': (dom.Element element) { +- domains.add(domainFromHtml(element)); +- }, +- 'refactorings': (dom.Element element) { +- refactorings =3D refactoringsFromHtml(element); +- }, +- 'types': (dom.Element element) { +- types =3D typesFromHtml(element); +- }, +- 'version': (dom.Element element) { +- versions.add(innerText(element)); +- }, +- 'index': (dom.Element element) { +- /* Ignore; generated dynamically. */ +- } +- }); +- if (versions.length !=3D 1) { +- throw new Exception('The API must contain exactly one ele= ment'); +- } +- api =3D new Api(versions[0], domains, types, refactorings, html); +- return api; +- } +- +- /** +- * Check that the given [element] has all of the attributes in +- * [requiredAttributes], possibly some of the attributes in +- * [optionalAttributes], and no others. +- */ +- void checkAttributes( +- dom.Element element, List requiredAttributes, String contex= t, +- {List optionalAttributes: const []}) { +- Set attributesFound =3D new Set(); +- element.attributes.forEach((name, value) { +- if (!requiredAttributes.contains(name) && +- !optionalAttributes.contains(name)) { +- throw new Exception( +- '$context: Unexpected attribute in ${element.localName}: $nam= e'); +- } +- attributesFound.add(name); +- }); +- for (String expectedAttribute in requiredAttributes) { +- if (!attributesFound.contains(expectedAttribute)) { +- throw new Exception('$context: ${element +- .localName} must contain attribute $expectedAttribute'); +- } +- } +- } +- +- /** +- * Check that the given [element] has the given [expectedName]. +- */ +- void checkName(dom.Element element, String expectedName, [String contex= t]) { +- if (element.localName !=3D expectedName) { +- if (context =3D=3D null) { +- context =3D element.localName; +- } +- throw new Exception( +- '$context: Expected $expectedName, found ${element.localName}'); +- } +- } +- +- /** +- * Create a [Domain] object from an HTML representation such as: +- * +- * +- * ... +- * ... +- * +- * +- * Note that the event name should not include the domain name. +- * +- * has the same form as , as described in [typeDeclFro= mHtml]. +- * +- * Child elements can occur in any order. +- */ +- Notification notificationFromHtml(dom.Element html, String context) { +- String domainName =3D getAncestor(html, 'domain', context).attributes= ['name']; +- checkName(html, 'notification', context); +- String event =3D html.attributes['event']; +- context =3D '$context.${event !=3D null ? event : 'event'}'; +- checkAttributes(html, ['event'], context, +- optionalAttributes: ['experimental']); +- bool experimental =3D html.attributes['experimental'] =3D=3D 'true'; +- TypeDecl params; +- recurse(html, context, { +- 'params': (dom.Element child) { +- params =3D typeObjectFromHtml(child, '$context.params'); +- } +- }); +- return new Notification(domainName, event, params, html, +- experimental: experimental); +- } +- +- /** +- * Create a single of [TypeDecl] corresponding to the type defined insi= de the +- * given HTML element. +- */ +- TypeDecl processContentsAsType(dom.Element html, String context) { +- List types =3D processContentsAsTypes(html, context); +- if (types.length !=3D 1) { +- throw new Exception('$context: Exactly one type must be specified'); +- } +- return types[0]; +- } +- +- /** +- * Create a list of [TypeDecl]s corresponding to the types defined insi= de the +- * given HTML element. The following forms are supported. +- * +- * To refer to a type declared elsewhere (or a built-in type): +- * +- * typeName +- * +- * For a list: ItemType +- * +- * For a map: KeyTypeValueType +- * +- * For a JSON object: +- * +- * +- * ... +- * +- * +- * For an enum: +- * +- * +- * ... +- * +- * +- * For a union type: +- * +- * TYPE +- * +- */ +- List processContentsAsTypes(dom.Element html, String context)= { +- List types =3D []; +- recurse(html, context, { +- 'object': (dom.Element child) { +- types.add(typeObjectFromHtml(child, context)); +- }, +- 'list': (dom.Element child) { +- checkAttributes(child, [], context); +- types.add(new TypeList(processContentsAsType(child, context), chi= ld)); +- }, +- 'map': (dom.Element child) { +- checkAttributes(child, [], context); +- TypeDecl keyType; +- TypeDecl valueType; +- recurse(child, context, { +- 'key': (dom.Element child) { +- if (keyType !=3D null) { +- throw new Exception('$context: Key type already specified'); +- } +- keyType =3D processContentsAsType(child, '$context.key'); +- }, +- 'value': (dom.Element child) { +- if (valueType !=3D null) { +- throw new Exception('$context: Value type already specified= '); +- } +- valueType =3D processContentsAsType(child, '$context.value'); +- } +- }); +- if (keyType =3D=3D null) { +- throw new Exception('$context: Key type not specified'); +- } +- if (valueType =3D=3D null) { +- throw new Exception('$context: Value type not specified'); +- } +- types.add(new TypeMap(keyType, valueType, child)); +- }, +- 'enum': (dom.Element child) { +- types.add(typeEnumFromHtml(child, context)); +- }, +- 'ref': (dom.Element child) { +- checkAttributes(child, [], context); +- types.add(new TypeReference(innerText(child), child)); +- }, +- 'union': (dom.Element child) { +- checkAttributes(child, ['field'], context); +- String field =3D child.attributes['field']; +- types.add(new TypeUnion( +- processContentsAsTypes(child, context), field, child)); +- } +- }); +- return types; +- } +- +- /** +- * Read the API description from file with the given [filePath]. +- */ +- Api readApi() { +- String htmlContents =3D new File(filePath).readAsStringSync(); +- dom.Document document =3D parser.parse(htmlContents); +- dom.Element htmlElement =3D document.children +- .singleWhere((element) =3D> element.localName.toLowerCase() =3D= =3D 'html'); +- return apiFromHtml(htmlElement); +- } +- +- void recurse(dom.Element parent, String context, +- Map elementProcessors) { +- for (String key in elementProcessors.keys) { +- if (!specialElements.contains(key)) { +- throw new Exception('$context: $key is not a special element'); +- } +- } +- for (dom.Node node in parent.nodes) { +- if (node is dom.Element) { +- if (elementProcessors.containsKey(node.localName)) { +- elementProcessors[node.localName](node); +- } else if (specialElements.contains(node.localName)) { +- throw new Exception( +- '$context: Unexpected use of <${node.localName}>'); +- } else { +- recurse(node, context, elementProcessors); +- } +- } +- } +- } +- +- /** +- * Create a [Refactoring] object from an HTML representation such as: +- * +- * +- * ... +- * ... +- * +- * +- * and have the same form as , as describe= d in +- * [typeDeclFromHtml]. +- * +- * Child elements can occur in any order. +- */ +- Refactoring refactoringFromHtml(dom.Element html) { +- checkName(html, 'refactoring'); +- String kind =3D html.attributes['kind']; +- String context =3D kind !=3D null ? kind : 'refactoring'; +- checkAttributes(html, ['kind'], context); +- TypeDecl feedback; +- TypeDecl options; +- recurse(html, context, { +- 'feedback': (dom.Element child) { +- feedback =3D typeObjectFromHtml(child, '$context.feedback'); +- }, +- 'options': (dom.Element child) { +- options =3D typeObjectFromHtml(child, '$context.options'); +- } +- }); +- return new Refactoring(kind, feedback, options, html); +- } +- +- /** +- * Create a [Refactorings] object from an HTML representation such as: +- * +- * +- * ... +- * +- */ +- Refactorings refactoringsFromHtml(dom.Element html) { +- checkName(html, 'refactorings'); +- String context =3D 'refactorings'; +- checkAttributes(html, [], context); +- List refactorings =3D []; +- recurse(html, context, { +- 'refactoring': (dom.Element child) { +- refactorings.add(refactoringFromHtml(child)); +- } +- }); +- return new Refactorings(refactorings, html); +- } +- +- /** +- * Create a [Request] object from an HTML representation such as: +- * +- * +- * ... +- * ... +- * +- * +- * Note that the method name should not include the domain name. +- * +- * and have the same form as , as described in +- * [typeDeclFromHtml]. +- * +- * Child elements can occur in any order. +- */ +- Request requestFromHtml(dom.Element html, String context) { +- String domainName =3D getAncestor(html, 'domain', context).attributes= ['name']; +- checkName(html, 'request', context); +- String method =3D html.attributes['method']; +- context =3D '$context.${method !=3D null ? method : 'method'}'; +- checkAttributes(html, ['method'], context, +- optionalAttributes: ['experimental', 'deprecated']); +- bool experimental =3D html.attributes['experimental'] =3D=3D 'true'; +- bool deprecated =3D html.attributes['deprecated'] =3D=3D 'true'; +- TypeDecl params; +- TypeDecl result; +- recurse(html, context, { +- 'params': (dom.Element child) { +- params =3D typeObjectFromHtml(child, '$context.params'); +- }, +- 'result': (dom.Element child) { +- result =3D typeObjectFromHtml(child, '$context.result'); +- } +- }); +- return new Request(domainName, method, params, result, html, +- experimental: experimental, deprecated: deprecated); +- } +- +- /** +- * Create a [TypeDefinition] object from an HTML representation such as: +- * +- * +- * TYPE +- * +- * +- * Where TYPE is any HTML that can be parsed by [typeDeclFromHtml]. +- * +- * Child elements can occur in any order. +- */ +- TypeDefinition typeDefinitionFromHtml(dom.Element html) { +- checkName(html, 'type'); +- String name =3D html.attributes['name']; +- String context =3D name !=3D null ? name : 'type'; +- checkAttributes(html, ['name'], context, +- optionalAttributes: ['experimental', 'deprecated']); +- TypeDecl type =3D processContentsAsType(html, context); +- bool experimental =3D html.attributes['experimental'] =3D=3D 'true'; +- bool deprecated =3D html.attributes['deprecated'] =3D=3D 'true'; +- return new TypeDefinition(name, type, html, +- experimental: experimental, deprecated: deprecated); +- } +- +- /** +- * Create a [TypeEnum] from an HTML description. +- */ +- TypeEnum typeEnumFromHtml(dom.Element html, String context) { +- checkName(html, 'enum', context); +- checkAttributes(html, [], context); +- List values =3D []; +- recurse(html, context, { +- 'value': (dom.Element child) { +- values.add(typeEnumValueFromHtml(child, context)); +- } +- }); +- return new TypeEnum(values, html); +- } +- +- /** +- * Create a [TypeEnumValue] from an HTML description such as: +- * +- * +- * VALUE +- * +- * +- * Where VALUE is the text of the enumerated value. +- * +- * Child elements can occur in any order. +- */ +- TypeEnumValue typeEnumValueFromHtml(dom.Element html, String context) { +- checkName(html, 'value', context); +- checkAttributes(html, [], context, optionalAttributes: ['deprecated']= ); +- bool deprecated =3D html.attributes['deprecated'] =3D=3D 'true'; +- List values =3D []; +- recurse(html, context, { +- 'code': (dom.Element child) { +- String text =3D innerText(child).trim(); +- values.add(text); +- } +- }); +- if (values.length !=3D 1) { +- throw new Exception('$context: Exactly one value must be specified'= ); +- } +- return new TypeEnumValue(values[0], html, deprecated: deprecated); +- } +- +- /** +- * Create a [TypeObjectField] from an HTML description such as: +- * +- * +- * TYPE +- * +- * +- * Where TYPE is any HTML that can be parsed by [typeDeclFromHtml]. +- * +- * In addition, the attribute optional=3D"true" may be used to specify = that the +- * field is optional, and the attribute value=3D"..." may be used to sp= ecify that +- * the field is required to have a certain value. +- * +- * Child elements can occur in any order. +- */ +- TypeObjectField typeObjectFieldFromHtml(dom.Element html, String contex= t) { +- checkName(html, 'field', context); +- String name =3D html.attributes['name']; +- context =3D '$context.${name !=3D null ? name : 'field'}'; +- checkAttributes(html, ['name'], context, +- optionalAttributes: ['optional', 'value', 'deprecated']); +- bool deprecated =3D html.attributes['deprecated'] =3D=3D 'true'; +- bool optional =3D false; +- String optionalString =3D html.attributes['optional']; +- if (optionalString !=3D null) { +- switch (optionalString) { +- case 'true': +- optional =3D true; +- break; +- case 'false': +- optional =3D false; +- break; +- default: +- throw new Exception( +- '$context: field contains invalid "optional" attribute: "$o= ptionalString"'); +- } +- } +- String value =3D html.attributes['value']; +- TypeDecl type =3D processContentsAsType(html, context); +- return new TypeObjectField(name, type, html, +- optional: optional, value: value, deprecated: deprecated); +- } +- +- /** +- * Create a [TypeObject] from an HTML description. +- */ +- TypeObject typeObjectFromHtml(dom.Element html, String context) { +- checkAttributes(html, [], context, optionalAttributes: ['experimental= ']); +- List fields =3D []; +- recurse(html, context, { +- 'field': (dom.Element child) { +- fields.add(typeObjectFieldFromHtml(child, context)); +- } +- }); +- bool experimental =3D html.attributes['experimental'] =3D=3D 'true'; +- return new TypeObject(fields, html, experimental: experimental); +- } +- +- /** +- * Create a [Types] object from an HTML representation such as: +- * +- * +- * ... +- * +- */ +- Types typesFromHtml(dom.Element html) { +- checkName(html, 'types'); +- String context =3D 'types'; +- checkAttributes(html, [], context); +- List importUris =3D []; +- Map typeMap =3D {}; +- List childElements =3D []; +- recurse(html, context, { +- 'include': (dom.Element child) { +- String importUri =3D child.attributes['import']; +- if (importUri !=3D null) { +- importUris.add(importUri); +- } +- String relativePath =3D child.attributes['path']; +- String path =3D normalize(join(dirname(filePath), relativePath)); +- ApiReader reader =3D new ApiReader(path); +- Api api =3D reader.readApi(); +- for (TypeDefinition typeDefinition in api.types) { +- typeDefinition.isExternal =3D true; +- childElements.add(typeDefinition.html); +- typeMap[typeDefinition.name] =3D typeDefinition; +- } +- }, +- 'type': (dom.Element child) { +- TypeDefinition typeDefinition =3D typeDefinitionFromHtml(child); +- typeMap[typeDefinition.name] =3D typeDefinition; +- } +- }); +- for (dom.Element element in childElements) { +- html.append(element); +- } +- Types types =3D new Types(typeMap, html); +- types.importUris.addAll(importUris); +- return types; +- } +-} +diff --git a/pkg/analysis_server/tool/spec/generate_all.dart b/pkg/analysi= s_server/tool/spec/generate_all.dart +deleted file mode 100644 +index c5dd126c01e..00000000000 +--- a/pkg/analysis_server/tool/spec/generate_all.dart ++++ /dev/null +@@ -1,40 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:path/path.dart'; +- +-import 'codegen_analysis_server.dart' as codegen_analysis_server; +-import 'codegen_dart_protocol.dart' as codegen_dart_protocol; +-import 'codegen_inttest_methods.dart' as codegen_inttest_methods; +-import 'codegen_java_types.dart' as codegen_java_types; +-import 'codegen_matchers.dart' as codegen_matchers; +-import 'codegen_protocol_constants.dart' as codegen_protocol_constants; +-import 'to_html.dart' as to_html; +- +-/** +- * Generate all targets. +- */ +-main() async { +- String script =3D Platform.script.toFilePath(windows: Platform.isWindow= s); +- String pkgPath =3D normalize(join(dirname(script), '..', '..')); +- await GeneratedContent.generateAll(pkgPath, allTargets); +-} +- +-/** +- * Get a list of all generated targets. +- */ +-List get allTargets { +- List targets =3D []; +- targets.add(codegen_analysis_server.target); +- targets.add(codegen_dart_protocol.target(false)); +- targets.add(codegen_java_types.targetDir); +- targets.add(codegen_inttest_methods.target); +- targets.add(codegen_matchers.target); +- targets.add(codegen_protocol_constants.target); +- targets.add(to_html.target); +- return targets; +-} +diff --git a/pkg/analysis_server/tool/spec/generate_files b/pkg/analysis_s= erver/tool/spec/generate_files +deleted file mode 100755 +index df2802d1f82..00000000000 +--- a/pkg/analysis_server/tool/spec/generate_files ++++ /dev/null +@@ -1,61 +0,0 @@ +-#!/usr/bin/env bash +-# Copyright (c) 2014, the Dart project authors. Please see the AUTHORS f= ile +-# for details. All rights reserved. Use of this source code is governed b= y a +-# BSD-style license that can be found in the LICENSE file. +-# +-# This script generates the following files, based on the contents of +-# spec_input.html: +-# +-# - ../../doc/api.html: The human-readable API spec. +-# +-# - ../../test/integration/protocol_matchers.dart: matchers to be used by +-# integration tests. +-# +-# - ../../test/integration/integration_test_methods.dart: convenience met= hods +-# to be used by integration tests. +- +-set -e +- +-function follow_links() { +- file=3D"$1" +- while [ -h "$file" ]; do +- # On Mac OS, readlink -f doesn't work. +- file=3D"$(readlink "$file")" +- done +- echo "$file" +-} +- +-# Unlike $0, $BASH_SOURCE points to the absolute path of this file. +-PROG_NAME=3D"$(follow_links "$BASH_SOURCE")" +- +-SCRIPT_DIR=3D"$(cd "${PROG_NAME%/*}" ; pwd -P)" +- +-ROOT_DIR=3D"$(cd "${SCRIPT_DIR}/../../../.." ; pwd -P)" +- +-if [[ $1 =3D=3D '--arch' && $2 =3D=3D 'x64' ]]; +-then +- DART_CONFIGURATION=3D"ReleaseX64" +-elif [ -z "$DART_CONFIGURATION" ]; +-then +- DART_CONFIGURATION=3D"ReleaseIA32" +-fi +- +-if [[ `uname` =3D=3D 'Darwin' ]]; +-then +- BUILD_DIR=3D"${ROOT_DIR}/xcodebuild/$DART_CONFIGURATION" +-fi +- +-PKG_FILE=3D"${ROOT_DIR}/.packages" +-if [[ !(-e $PKG_FILE) ]]; +-then +- PKG_FILE=3D"${ROOT_DIR}/.packages" +-fi +- +-DART=3D"${BUILD_DIR}/dart-sdk/bin/dart" +- +-declare -a VM_OPTIONS +-VM_OPTIONS+=3D("--checked") +-VM_OPTIONS+=3D("--packages=3D${PKG_FILE}") +- +-cd "${SCRIPT_DIR}" +-"${DART}" "${VM_OPTIONS[@]}" "generate_all.dart" +diff --git a/pkg/analysis_server/tool/spec/generated/java/AnalysisServer.j= ava b/pkg/analysis_server/tool/spec/generated/java/AnalysisServer.java +deleted file mode 100644 +index 24ff37d8cc5..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/AnalysisServer.java ++++ /dev/null +@@ -1,757 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package com.google.dart.server.generated; +- +-import com.google.dart.server.*; +-import org.dartlang.analysis.server.protocol.*; +- +-import java.util.List; +-import java.util.Map; +- +-/** +- * The interface {@code AnalysisServer} defines the behavior of objects t= hat interface to an +- * analysis server. +- * +- * @coverage dart.server +- */ +-public interface AnalysisServer { +- +- /** +- * Add the given listener to the list of listeners that will receive no= tification when new +- * analysis results become available. +- * +- * @param listener the listener to be added +- */ +- public void addAnalysisServerListener(AnalysisServerListener listener); +- +- /** +- * Add the given listener to the list of listeners that will receive no= tification when the server +- * is not active +- * +- * @param listener the listener to be added +- */ +- public void addStatusListener(AnalysisServerStatusListener listener); +- +- /** +- * {@code analysis.getErrors} +- * +- * Return the errors associated with the given file. If the errors for = the given file have not yet +- * been computed, or the most recently computed errors for the given fi= le are out of date, then the +- * response for this request will be delayed until they have been compu= ted. If some or all of the +- * errors for the file cannot be computed, then the subset of the error= s that can be computed will +- * be returned and the response will contain an error to indicate why t= he errors could not be +- * computed. If the content of the file changes after this request was = received but before a +- * response could be sent, then an error of type CONTENT_MODIFIED will = be generated. +- * +- * This request is intended to be used by clients that cannot asynchron= ously apply updated error +- * information. Clients that can apply error information as it becomes = available should use the +- * information provided by the 'analysis.errors' notification. +- * +- * If a request is made for a file which does not exist, or which is no= t currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified to +- * analysis.setAnalysisRoots), an error of type GET_ERRORS_INVALID_FILE= will be generated. +- * +- * @param file The file for which errors are being requested. +- */ +- public void analysis_getErrors(String file, GetErrorsConsumer consumer); +- +- /** +- * {@code analysis.getHover} +- * +- * Return the hover information associate with the given location. If s= ome or all of the hover +- * information is not available at the time this request is processed t= he information will be +- * omitted from the response. +- * +- * @param file The file in which hover information is being requested. +- * @param offset The offset for which hover information is being reques= ted. +- */ +- public void analysis_getHover(String file, int offset, GetHoverConsumer= consumer); +- +- /** +- * {@code analysis.getImportedElements} +- * +- * Return a description of all of the elements referenced in a given re= gion of a given file that +- * come from imported libraries. +- * +- * If a request is made for a file that does not exist, or that is not = currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified via +- * analysis.setAnalysisRoots), an error of type GET_IMPORTED_ELEMENTS_I= NVALID_FILE will be +- * generated. +- * +- * @param file The file in which import information is being requested. +- * @param offset The offset of the region for which import information = is being requested. +- * @param length The length of the region for which import information = is being requested. +- */ +- public void analysis_getImportedElements(String file, int offset, int l= ength, GetImportedElementsConsumer consumer); +- +- /** +- * {@code analysis.getLibraryDependencies} +- * +- * Return library dependency information for use in client-side indexin= g and package URI +- * resolution. +- * +- * Clients that are only using the libraries field should consider usin= g the analyzedFiles +- * notification instead. +- */ +- public void analysis_getLibraryDependencies(GetLibraryDependenciesConsu= mer consumer); +- +- /** +- * {@code analysis.getNavigation} +- * +- * Return the navigation information associated with the given region o= f the given file. If the +- * navigation information for the given file has not yet been computed,= or the most recently +- * computed navigation information for the given file is out of date, t= hen the response for this +- * request will be delayed until it has been computed. If the content o= f the file changes after +- * this request was received but before a response could be sent, then = an error of type +- * CONTENT_MODIFIED will be generated. +- * +- * If a navigation region overlaps (but extends either before or after)= the given region of the +- * file it will be included in the result. This means that it is theore= tically possible to get the +- * same navigation region in response to multiple requests. Clients can= avoid this by always +- * choosing a region that starts at the beginning of a line and ends at= the end of a (possibly +- * different) line in the file. +- * +- * If a request is made for a file which does not exist, or which is no= t currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified to +- * analysis.setAnalysisRoots), an error of type GET_NAVIGATION_INVALID_= FILE will be generated. +- * +- * @param file The file in which navigation information is being reques= ted. +- * @param offset The offset of the region for which navigation informat= ion is being requested. +- * @param length The length of the region for which navigation informat= ion is being requested. +- */ +- public void analysis_getNavigation(String file, int offset, int length,= GetNavigationConsumer consumer); +- +- /** +- * {@code analysis.getReachableSources} +- * +- * Return the transitive closure of reachable sources for a given file. +- * +- * If a request is made for a file which does not exist, or which is no= t currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified to +- * analysis.setAnalysisRoots), an error of type GET_REACHABLE_SOURCES_I= NVALID_FILE will be +- * generated. +- * +- * @param file The file for which reachable source information is being= requested. +- */ +- public void analysis_getReachableSources(String file, GetReachableSourc= esConsumer consumer); +- +- /** +- * {@code analysis.reanalyze} +- * +- * Force the re-analysis of everything contained in the specified analy= sis roots. This will cause +- * all previously computed analysis results to be discarded and recompu= ted, and will cause all +- * subscribed notifications to be re-sent. +- * +- * If no analysis roots are provided, then all current analysis roots w= ill be re-analyzed. If an +- * empty list of analysis roots is provided, then nothing will be re-an= alyzed. If the list contains +- * one or more paths that are not currently analysis roots, then an err= or of type +- * INVALID_ANALYSIS_ROOT will be generated. +- * +- * @param roots A list of the analysis roots that are to be re-analyzed. +- */ +- public void analysis_reanalyze(List roots); +- +- /** +- * {@code analysis.setAnalysisRoots} +- * +- * Sets the root paths used to determine which files to analyze. The se= t of files to be analyzed +- * are all of the files in one of the root paths that are not either ex= plicitly or implicitly +- * excluded. A file is explicitly excluded if it is in one of the exclu= ded paths. A file is +- * implicitly excluded if it is in a subdirectory of one of the root pa= ths where the name of the +- * subdirectory starts with a period (that is, a hidden directory). +- * +- * Note that this request determines the set of requested analysis root= s. The actual set of +- * analysis roots at any given time is the intersection of this set wit= h the set of files and +- * directories actually present on the filesystem. When the filesystem = changes, the actual set of +- * analysis roots is automatically updated, but the set of requested an= alysis roots is unchanged. +- * This means that if the client sets an analysis root before the root = becomes visible to server in +- * the filesystem, there is no error; once the server sees the root in = the filesystem it will start +- * analyzing it. Similarly, server will stop analyzing files that are r= emoved from the file system +- * but they will remain in the set of requested roots. +- * +- * If an included path represents a file, then server will look in the = directory containing the +- * file for a pubspec.yaml file. If none is found, then the parents of = the directory will be +- * searched until such a file is found or the root of the file system i= s reached. If such a file is +- * found, it will be used to resolve package: URI=E2=80=99s within the = file. +- * +- * @param included A list of the files and directories that should be a= nalyzed. +- * @param excluded A list of the files and directories within the inclu= ded directories that should +- * not be analyzed. +- * @param packageRoots A mapping from source directories to package roo= ts that should override the +- * normal package: URI resolution mechanism. If a package root = is a directory, then the +- * analyzer will behave as though the associated source directo= ry in the map contains a +- * special pubspec.yaml file which resolves any package: URI to= the corresponding path +- * within that package root directory. The effect is the same a= s specifying the package +- * root directory as a "--package_root" parameter to the Dart V= M when executing any Dart +- * file inside the source directory. If a package root is a fil= e, then the analyzer will +- * behave as though that file is a ".packages" file in the sour= ce directory. The effect is +- * the same as specifying the file as a "--packages" parameter = to the Dart VM when +- * executing any Dart file inside the source directory. Files i= n any directories that are +- * not overridden by this mapping have their package: URI's res= olved using the normal +- * pubspec.yaml mechanism. If this field is absent, or the empt= y map is specified, that +- * indicates that the normal pubspec.yaml mechanism should alwa= ys be used. +- */ +- public void analysis_setAnalysisRoots(List included, List excluded, Map packageRoots); +- +- /** +- * {@code analysis.setGeneralSubscriptions} +- * +- * Subscribe for general services (that is, services that are not speci= fic to individual files). +- * All previous subscriptions are replaced by the given set of services. +- * +- * It is an error if any of the elements in the list are not valid serv= ices. If there is an error, +- * then the current subscriptions will remain unchanged. +- * +- * @param subscriptions A list of the services being subscribed to. +- */ +- public void analysis_setGeneralSubscriptions(List subscriptions= ); +- +- /** +- * {@code analysis.setPriorityFiles} +- * +- * Set the priority files to the files in the given list. A priority fi= le is a file that is given +- * priority when scheduling which analysis work to do first. The list t= ypically contains those +- * files that are visible to the user and those for which analysis resu= lts will have the biggest +- * impact on the user experience. The order of the files within the lis= t is significant: the first +- * file will be given higher priority than the second, the second highe= r priority than the third, +- * and so on. +- * +- * Note that this request determines the set of requested priority file= s. The actual set of +- * priority files is the intersection of the requested set of priority = files with the set of files +- * currently subject to analysis. (See analysis.setSubscriptions for a = description of files that +- * are subject to analysis.) +- * +- * If a requested priority file is a directory it is ignored, but remai= ns in the set of requested +- * priority files so that if it later becomes a file it can be included= in the set of actual +- * priority files. +- * +- * @param files The files that are to be a priority for analysis. +- */ +- public void analysis_setPriorityFiles(List files); +- +- /** +- * {@code analysis.setSubscriptions} +- * +- * Subscribe for services that are specific to individual files. All pr= evious subscriptions are +- * replaced by the current set of subscriptions. If a given service is = not included as a key in the +- * map then no files will be subscribed to the service, exactly as if t= he service had been included +- * in the map with an explicit empty list of files. +- * +- * Note that this request determines the set of requested subscriptions= . The actual set of +- * subscriptions at any given time is the intersection of this set with= the set of files currently +- * subject to analysis. The files currently subject to analysis are the= set of files contained +- * within an actual analysis root but not excluded, plus all of the fil= es transitively reachable +- * from those files via import, export and part directives. (See analys= is.setAnalysisRoots for an +- * explanation of how the actual analysis roots are determined.) When t= he actual analysis roots +- * change, the actual set of subscriptions is automatically updated, bu= t the set of requested +- * subscriptions is unchanged. +- * +- * If a requested subscription is a directory it is ignored, but remain= s in the set of requested +- * subscriptions so that if it later becomes a file it can be included = in the set of actual +- * subscriptions. +- * +- * It is an error if any of the keys in the map are not valid services.= If there is an error, then +- * the existing subscriptions will remain unchanged. +- * +- * @param subscriptions A table mapping services to a list of the files= being subscribed to the +- * service. +- */ +- public void analysis_setSubscriptions(Map> subscri= ptions); +- +- /** +- * {@code analysis.updateContent} +- * +- * Update the content of one or more files. Files that were previously = updated but not included in +- * this update remain unchanged. This effectively represents an overlay= of the filesystem. The +- * files whose content is overridden are therefore seen by server as be= ing files with the given +- * content, even if the files do not exist on the filesystem or if the = file path represents the +- * path to a directory on the filesystem. +- * +- * @param files A table mapping the files whose content has changed to = a description of the content +- * change. +- */ +- public void analysis_updateContent(Map files, UpdateCon= tentConsumer consumer); +- +- /** +- * {@code analysis.updateOptions} +- * +- * Deprecated: all of the options can be set by users in an analysis op= tions file. +- * +- * Update the options controlling analysis based on the given set of op= tions. Any options that are +- * not included in the analysis options will not be changed. If there a= re options in the analysis +- * options that are not valid, they will be silently ignored. +- * +- * @param options The options that are to be used to control analysis. +- * +- * @deprecated +- */ +- public void analysis_updateOptions(AnalysisOptions options); +- +- /** +- * {@code analytics.enable} +- * +- * Enable or disable the sending of analytics data. Note that there are= other ways for users to +- * change this setting, so clients cannot assume that they have complet= e control over this setting. +- * In particular, there is no guarantee that the result returned by the= isEnabled request will +- * match the last value set via this request. +- * +- * @param value Enable or disable analytics. +- */ +- public void analytics_enable(boolean value); +- +- /** +- * {@code analytics.isEnabled} +- * +- * Query whether analytics is enabled. +- * +- * This flag controls whether the analysis server sends any analytics d= ata to the cloud. If +- * disabled, the analysis server does not send any analytics data, and = any data sent to it by +- * clients (from sendEvent and sendTiming) will be ignored. +- * +- * The value of this flag can be changed by other tools outside of the = analysis server's process. +- * When you query the flag, you get the value of the flag at a given mo= ment. Clients should not use +- * the value returned to decide whether or not to send the sendEvent an= d sendTiming requests. Those +- * requests should be used unconditionally and server will determine wh= ether or not it is +- * appropriate to forward the information to the cloud at the time each= request is received. +- */ +- public void analytics_isEnabled(IsEnabledConsumer consumer); +- +- /** +- * {@code analytics.sendEvent} +- * +- * Send information about client events. +- * +- * Ask the analysis server to include the fact that an action was perfo= rmed in the client as part +- * of the analytics data being sent. The data will only be included if = the sending of analytics +- * data is enabled at the time the request is processed. The action tha= t was performed is indicated +- * by the value of the action field. +- * +- * The value of the action field should not include the identity of the= client. The analytics data +- * sent by server will include the client id passed in using the --clie= nt-id command-line argument. +- * The request will be ignored if the client id was not provided when s= erver was started. +- * +- * @param action The value used to indicate which action was performed. +- */ +- public void analytics_sendEvent(String action); +- +- /** +- * {@code analytics.sendTiming} +- * +- * Send timing information for client events (e.g. code completions). +- * +- * Ask the analysis server to include the fact that a timed event occur= red as part of the analytics +- * data being sent. The data will only be included if the sending of an= alytics data is enabled at +- * the time the request is processed. +- * +- * The value of the event field should not include the identity of the = client. The analytics data +- * sent by server will include the client id passed in using the --clie= nt-id command-line argument. +- * The request will be ignored if the client id was not provided when s= erver was started. +- * +- * @param event The name of the event. +- * @param millis The duration of the event in milliseconds. +- */ +- public void analytics_sendTiming(String event, int millis); +- +- /** +- * {@code completion.getSuggestions} +- * +- * Request that completion suggestions for the given offset in the give= n file be returned. +- * +- * @param file The file containing the point at which suggestions are t= o be made. +- * @param offset The offset within the file at which suggestions are to= be made. +- */ +- public void completion_getSuggestions(String file, int offset, GetSugge= stionsConsumer consumer); +- +- /** +- * {@code diagnostic.getDiagnostics} +- * +- * Return server diagnostics. +- */ +- public void diagnostic_getDiagnostics(GetDiagnosticsConsumer consumer); +- +- /** +- * {@code diagnostic.getServerPort} +- * +- * Return the port of the diagnostic web server. If the server is not r= unning this call will start +- * the server. If unable to start the diagnostic web server, this call = will return an error of +- * DEBUG_PORT_COULD_NOT_BE_OPENED. +- */ +- public void diagnostic_getServerPort(GetServerPortConsumer consumer); +- +- /** +- * {@code edit.format} +- * +- * Format the contents of a single file. The currently selected region = of text is passed in so that +- * the selection can be preserved across the formatting operation. The = updated selection will be as +- * close to matching the original as possible, but whitespace at the be= ginning or end of the +- * selected region will be ignored. If preserving selection information= is not required, zero (0) +- * can be specified for both the selection offset and selection length. +- * +- * If a request is made for a file which does not exist, or which is no= t currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified to +- * analysis.setAnalysisRoots), an error of type FORMAT_INVALID_FILE wil= l be generated. If the +- * source contains syntax errors, an error of type FORMAT_WITH_ERRORS w= ill be generated. +- * +- * @param file The file containing the code to be formatted. +- * @param selectionOffset The offset of the current selection in the fi= le. +- * @param selectionLength The length of the current selection in the fi= le. +- * @param lineLength The line length to be used by the formatter. +- */ +- public void edit_format(String file, int selectionOffset, int selection= Length, int lineLength, FormatConsumer consumer); +- +- /** +- * {@code edit.getAssists} +- * +- * Return the set of assists that are available at the given location. = An assist is distinguished +- * from a refactoring primarily by the fact that it affects a single fi= le and does not require user +- * input in order to be performed. +- * +- * @param file The file containing the code for which assists are being= requested. +- * @param offset The offset of the code for which assists are being req= uested. +- * @param length The length of the code for which assists are being req= uested. +- */ +- public void edit_getAssists(String file, int offset, int length, GetAss= istsConsumer consumer); +- +- /** +- * {@code edit.getAvailableRefactorings} +- * +- * Get a list of the kinds of refactorings that are valid for the given= selection in the given +- * file. +- * +- * @param file The file containing the code on which the refactoring wo= uld be based. +- * @param offset The offset of the code on which the refactoring would = be based. +- * @param length The length of the code on which the refactoring would = be based. +- */ +- public void edit_getAvailableRefactorings(String file, int offset, int = length, GetAvailableRefactoringsConsumer consumer); +- +- /** +- * {@code edit.getFixes} +- * +- * Return the set of fixes that are available for the errors at a given= offset in a given file. +- * +- * @param file The file containing the errors for which fixes are being= requested. +- * @param offset The offset used to select the errors for which fixes w= ill be returned. +- */ +- public void edit_getFixes(String file, int offset, GetFixesConsumer con= sumer); +- +- /** +- * {@code edit.getPostfixCompletion} +- * +- * Get the changes required to convert the postfix template at the give= n location into the +- * template's expanded form. +- * +- * @param file The file containing the postfix template to be expanded. +- * @param key The unique name that identifies the template in use. +- * @param offset The offset used to identify the code to which the temp= late will be applied. +- */ +- public void edit_getPostfixCompletion(String file, String key, int offs= et, GetPostfixCompletionConsumer consumer); +- +- /** +- * {@code edit.getRefactoring} +- * +- * Get the changes required to perform a refactoring. +- * +- * If another refactoring request is received during the processing of = this one, an error of type +- * REFACTORING_REQUEST_CANCELLED will be generated. +- * +- * @param kind The kind of refactoring to be performed. +- * @param file The file containing the code involved in the refactoring. +- * @param offset The offset of the region involved in the refactoring. +- * @param length The length of the region involved in the refactoring. +- * @param validateOnly True if the client is only requesting that the v= alues of the options be +- * validated and no change be generated. +- * @param options Data used to provide values provided by the user. The= structure of the data is +- * dependent on the kind of refactoring being performed. The da= ta that is expected is +- * documented in the section titled Refactorings, labeled as "O= ptions". This field can be +- * omitted if the refactoring does not require any options or i= f the values of those +- * options are not known. +- */ +- public void edit_getRefactoring(String kind, String file, int offset, i= nt length, boolean validateOnly, RefactoringOptions options, GetRefactoring= Consumer consumer); +- +- /** +- * {@code edit.getStatementCompletion} +- * +- * Get the changes required to convert the partial statement at the giv= en location into a +- * syntactically valid statement. If the current statement is already v= alid the change will insert +- * a newline plus appropriate indentation at the end of the line contai= ning the offset. If a change +- * that makes the statement valid cannot be determined (perhaps because= it has not yet been +- * implemented) the statement will be considered already valid and the = appropriate change returned. +- * +- * @param file The file containing the statement to be completed. +- * @param offset The offset used to identify the statement to be comple= ted. +- */ +- public void edit_getStatementCompletion(String file, int offset, GetSta= tementCompletionConsumer consumer); +- +- /** +- * {@code edit.importElements} +- * +- * Return a list of edits that would need to be applied in order to ens= ure that all of the elements +- * in the specified list of imported elements are accessible within the= library. +- * +- * If a request is made for a file that does not exist, or that is not = currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified via +- * analysis.setAnalysisRoots), an error of type IMPORT_ELEMENTS_INVALID= _FILE will be generated. +- * +- * @param file The file in which the specified elements are to be made = accessible. +- * @param elements The elements to be made accessible in the specified = file. +- */ +- public void edit_importElements(String file, List ele= ments, ImportElementsConsumer consumer); +- +- /** +- * {@code edit.isPostfixCompletionApplicable} +- * +- * Determine if the request postfix completion template is applicable a= t the given location in the +- * given file. +- * +- * @param file The file containing the postfix template to be expanded. +- * @param key The unique name that identifies the template in use. +- * @param offset The offset used to identify the code to which the temp= late will be applied. +- */ +- public void edit_isPostfixCompletionApplicable(String file, String key,= int offset, IsPostfixCompletionApplicableConsumer consumer); +- +- /** +- * {@code edit.listPostfixCompletionTemplates} +- * +- * Return a list of all postfix templates currently available. +- */ +- public void edit_listPostfixCompletionTemplates(ListPostfixCompletionTe= mplatesConsumer consumer); +- +- /** +- * {@code edit.organizeDirectives} +- * +- * Organizes all of the directives - removes unused imports and sorts d= irectives of the given Dart +- * file according to the Dart Style Guide. +- * +- * If a request is made for a file that does not exist, does not belong= to an analysis root or is +- * not a Dart file, FILE_NOT_ANALYZED will be generated. +- * +- * If directives of the Dart file cannot be organized, for example beca= use it has scan or parse +- * errors, or by other reasons, ORGANIZE_DIRECTIVES_ERROR will be gener= ated. The message will +- * provide details about the reason. +- * +- * @param file The Dart file to organize directives in. +- */ +- public void edit_organizeDirectives(String file, OrganizeDirectivesCons= umer consumer); +- +- /** +- * {@code edit.sortMembers} +- * +- * Sort all of the directives, unit and class members of the given Dart= file. +- * +- * If a request is made for a file that does not exist, does not belong= to an analysis root or is +- * not a Dart file, SORT_MEMBERS_INVALID_FILE will be generated. +- * +- * If the Dart file has scan or parse errors, SORT_MEMBERS_PARSE_ERRORS= will be generated. +- * +- * @param file The Dart file to sort. +- */ +- public void edit_sortMembers(String file, SortMembersConsumer consumer); +- +- /** +- * {@code execution.createContext} +- * +- * Create an execution context for the executable file with the given p= ath. The context that is +- * created will persist until execution.deleteContext is used to delete= it. Clients, therefore, are +- * responsible for managing the lifetime of execution contexts. +- * +- * @param contextRoot The path of the Dart or HTML file that will be la= unched, or the path of the +- * directory containing the file. +- */ +- public void execution_createContext(String contextRoot, CreateContextCo= nsumer consumer); +- +- /** +- * {@code execution.deleteContext} +- * +- * Delete the execution context with the given identifier. The context = id is no longer valid after +- * this command. The server is allowed to re-use ids when they are no l= onger valid. +- * +- * @param id The identifier of the execution context that is to be dele= ted. +- */ +- public void execution_deleteContext(String id); +- +- /** +- * {@code execution.mapUri} +- * +- * Map a URI from the execution context to the file that it corresponds= to, or map a file to the +- * URI that it corresponds to in the execution context. +- * +- * Exactly one of the file and uri fields must be provided. If both fie= lds are provided, then an +- * error of type INVALID_PARAMETER will be generated. Similarly, if nei= ther field is provided, then +- * an error of type INVALID_PARAMETER will be generated. +- * +- * If the file field is provided and the value is not the path of a fil= e (either the file does not +- * exist or the path references something other than a file), then an e= rror of type +- * INVALID_PARAMETER will be generated. +- * +- * If the uri field is provided and the value is not a valid URI or if = the URI references something +- * that is not a file (either a file that does not exist or something o= ther than a file), then an +- * error of type INVALID_PARAMETER will be generated. +- * +- * If the contextRoot used to create the execution context does not exi= st, then an error of type +- * INVALID_EXECUTION_CONTEXT will be generated. +- * +- * @param id The identifier of the execution context in which the URI i= s to be mapped. +- * @param file The path of the file to be mapped into a URI. +- * @param uri The URI to be mapped into a file path. +- */ +- public void execution_mapUri(String id, String file, String uri, MapUri= Consumer consumer); +- +- /** +- * {@code execution.setSubscriptions} +- * +- * Deprecated: the analysis server no longer fires LAUNCH_DATA events. +- * +- * Subscribe for services. All previous subscriptions are replaced by t= he given set of services. +- * +- * It is an error if any of the elements in the list are not valid serv= ices. If there is an error, +- * then the current subscriptions will remain unchanged. +- * +- * @param subscriptions A list of the services being subscribed to. +- * +- * @deprecated +- */ +- public void execution_setSubscriptions(List subscriptions); +- +- /** +- * Return {@code true} if the socket is open. +- */ +- public boolean isSocketOpen(); +- +- /** +- * {@code kythe.getKytheEntries} +- * +- * Return the list of KytheEntry objects for some file, given the curre= nt state of the file system +- * populated by "analysis.updateContent". +- * +- * If a request is made for a file that does not exist, or that is not = currently subject to +- * analysis (e.g. because it is not associated with any analysis root s= pecified to +- * analysis.setAnalysisRoots), an error of type GET_KYTHE_ENTRIES_INVAL= ID_FILE will be generated. +- * +- * @param file The file containing the code for which the Kythe Entry o= bjects are being requested. +- */ +- public void kythe_getKytheEntries(String file, GetKytheEntriesConsumer = consumer); +- +- /** +- * Remove the given listener from the list of listeners that will recei= ve notification when new +- * analysis results become available. +- * +- * @param listener the listener to be removed +- */ +- public void removeAnalysisServerListener(AnalysisServerListener listene= r); +- +- /** +- * {@code search.findElementReferences} +- * +- * Perform a search for references to the element defined or referenced= at the given offset in the +- * given file. +- * +- * An identifier is returned immediately, and individual results will b= e returned via the +- * search.results notification as they become available. +- * +- * @param file The file containing the declaration of or reference to t= he element used to define +- * the search. +- * @param offset The offset within the file of the declaration of or re= ference to the element. +- * @param includePotential True if potential matches are to be included= in the results. +- */ +- public void search_findElementReferences(String file, int offset, boole= an includePotential, FindElementReferencesConsumer consumer); +- +- /** +- * {@code search.findMemberDeclarations} +- * +- * Perform a search for declarations of members whose name is equal to = the given name. +- * +- * An identifier is returned immediately, and individual results will b= e returned via the +- * search.results notification as they become available. +- * +- * @param name The name of the declarations to be found. +- */ +- public void search_findMemberDeclarations(String name, FindMemberDeclar= ationsConsumer consumer); +- +- /** +- * {@code search.findMemberReferences} +- * +- * Perform a search for references to members whose name is equal to th= e given name. This search +- * does not check to see that there is a member defined with the given = name, so it is able to find +- * references to undefined members as well. +- * +- * An identifier is returned immediately, and individual results will b= e returned via the +- * search.results notification as they become available. +- * +- * @param name The name of the references to be found. +- */ +- public void search_findMemberReferences(String name, FindMemberReferenc= esConsumer consumer); +- +- /** +- * {@code search.findTopLevelDeclarations} +- * +- * Perform a search for declarations of top-level elements (classes, ty= pedefs, getters, setters, +- * functions and fields) whose name matches the given pattern. +- * +- * An identifier is returned immediately, and individual results will b= e returned via the +- * search.results notification as they become available. +- * +- * @param pattern The regular expression used to match the names of the= declarations to be found. +- */ +- public void search_findTopLevelDeclarations(String pattern, FindTopLeve= lDeclarationsConsumer consumer); +- +- /** +- * {@code search.getTypeHierarchy} +- * +- * Return the type hierarchy of the class declared or referenced at the= given location. +- * +- * @param file The file containing the declaration or reference to the = type for which a hierarchy +- * is being requested. +- * @param offset The offset of the name of the type within the file. +- * @param superOnly True if the client is only requesting superclasses = and interfaces hierarchy. +- */ +- public void search_getTypeHierarchy(String file, int offset, boolean su= perOnly, GetTypeHierarchyConsumer consumer); +- +- /** +- * {@code server.getVersion} +- * +- * Return the version number of the analysis server. +- */ +- public void server_getVersion(GetVersionConsumer consumer); +- +- /** +- * {@code server.setSubscriptions} +- * +- * Subscribe for services. All previous subscriptions are replaced by t= he given set of services. +- * +- * It is an error if any of the elements in the list are not valid serv= ices. If there is an error, +- * then the current subscriptions will remain unchanged. +- * +- * @param subscriptions A list of the services being subscribed to. +- */ +- public void server_setSubscriptions(List subscriptions); +- +- /** +- * {@code server.shutdown} +- * +- * Cleanly shutdown the analysis server. Requests that are received aft= er this request will not be +- * processed. Requests that were received before this request, but for = which a response has not yet +- * been sent, will not be responded to. No further responses or notific= ations will be sent after +- * the response to this request has been sent. +- */ +- public void server_shutdown(); +- +- /** +- * Start the analysis server. +- */ +- public void start() throws Exception; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AddContent= Overlay.java b/pkg/analysis_server/tool/spec/generated/java/types/AddConten= tOverlay.java +deleted file mode 100644 +index 74249cad5b0..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AddContentOverlay= .java ++++ /dev/null +@@ -1,132 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A directive to begin overlaying the contents of a file. The supplied c= ontent will be used for +- * analysis in place of the file contents in the filesystem. +- * +- * If this directive is used on a file that already has a file content ov= erlay, the old overlay is +- * discarded and replaced with the new one. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class AddContentOverlay { +- +- public static final AddContentOverlay[] EMPTY_ARRAY =3D new AddContentO= verlay[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArr= ayList(); +- +- private final String type; +- +- /** +- * The new content of the file. +- */ +- private final String content; +- +- /** +- * Constructor for {@link AddContentOverlay}. +- */ +- public AddContentOverlay(String content) { +- this.type =3D "add"; +- this.content =3D content; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof AddContentOverlay) { +- AddContentOverlay other =3D (AddContentOverlay) obj; +- return +- ObjectUtilities.equals(other.type, type) && +- ObjectUtilities.equals(other.content, content); +- } +- return false; +- } +- +- public static AddContentOverlay fromJson(JsonObject jsonObject) { +- String type =3D jsonObject.get("type").getAsString(); +- String content =3D jsonObject.get("content").getAsString(); +- return new AddContentOverlay(content); +- } +- +- public static List fromJsonArray(JsonArray jsonArray= ) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The new content of the file. +- */ +- public String getContent() { +- return content; +- } +- +- public String getType() { +- return type; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(type); +- builder.append(content); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("type", type); +- jsonObject.addProperty("content", content); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("type=3D"); +- builder.append(type + ", "); +- builder.append("content=3D"); +- builder.append(content); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisEr= ror.java b/pkg/analysis_server/tool/spec/generated/java/types/AnalysisError= .java +deleted file mode 100644 +index 00c44959aed..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisError.java ++++ /dev/null +@@ -1,251 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An indication of an error, warning, or hint that was produced by the a= nalysis. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class AnalysisError { +- +- public static final AnalysisError[] EMPTY_ARRAY =3D new AnalysisError[0= ]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLi= st(); +- +- /** +- * The severity of the error. +- */ +- private final String severity; +- +- /** +- * The type of the error. +- */ +- private final String type; +- +- /** +- * The location associated with the error. +- */ +- private final Location location; +- +- /** +- * The message to be displayed for this error. The message should indic= ate what is wrong with the +- * code and why it is wrong. +- */ +- private final String message; +- +- /** +- * The correction message to be displayed for this error. The correctio= n message should indicate +- * how the user can fix the error. The field is omitted if there is no = correction message +- * associated with the error code. +- */ +- private final String correction; +- +- /** +- * The name, as a string, of the error code associated with this error. +- */ +- private final String code; +- +- /** +- * A hint to indicate to interested clients that this error has an asso= ciated fix (or fixes). The +- * absence of this field implies there are not known to be fixes. Note = that since the operation to +- * calculate whether fixes apply needs to be performant it is possible = that complicated tests will +- * be skipped and a false negative returned. For this reason, this attr= ibute should be treated as a +- * "hint". Despite the possibility of false negatives, no false positiv= es should be returned. If a +- * client sees this flag set they can proceed with the confidence that = there are in fact associated +- * fixes. +- */ +- private final Boolean hasFix; +- +- /** +- * Constructor for {@link AnalysisError}. +- */ +- public AnalysisError(String severity, String type, Location location, S= tring message, String correction, String code, Boolean hasFix) { +- this.severity =3D severity; +- this.type =3D type; +- this.location =3D location; +- this.message =3D message; +- this.correction =3D correction; +- this.code =3D code; +- this.hasFix =3D hasFix; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof AnalysisError) { +- AnalysisError other =3D (AnalysisError) obj; +- return +- ObjectUtilities.equals(other.severity, severity) && +- ObjectUtilities.equals(other.type, type) && +- ObjectUtilities.equals(other.location, location) && +- ObjectUtilities.equals(other.message, message) && +- ObjectUtilities.equals(other.correction, correction) && +- ObjectUtilities.equals(other.code, code) && +- ObjectUtilities.equals(other.hasFix, hasFix); +- } +- return false; +- } +- +- public static AnalysisError fromJson(JsonObject jsonObject) { +- String severity =3D jsonObject.get("severity").getAsString(); +- String type =3D jsonObject.get("type").getAsString(); +- Location location =3D Location.fromJson(jsonObject.get("location").ge= tAsJsonObject()); +- String message =3D jsonObject.get("message").getAsString(); +- String correction =3D jsonObject.get("correction") =3D=3D null ? null= : jsonObject.get("correction").getAsString(); +- String code =3D jsonObject.get("code").getAsString(); +- Boolean hasFix =3D jsonObject.get("hasFix") =3D=3D null ? null : json= Object.get("hasFix").getAsBoolean(); +- return new AnalysisError(severity, type, location, message, correctio= n, code, hasFix); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonAr= ray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The name, as a string, of the error code associated with this error. +- */ +- public String getCode() { +- return code; +- } +- +- /** +- * The correction message to be displayed for this error. The correctio= n message should indicate +- * how the user can fix the error. The field is omitted if there is no = correction message +- * associated with the error code. +- */ +- public String getCorrection() { +- return correction; +- } +- +- /** +- * A hint to indicate to interested clients that this error has an asso= ciated fix (or fixes). The +- * absence of this field implies there are not known to be fixes. Note = that since the operation to +- * calculate whether fixes apply needs to be performant it is possible = that complicated tests will +- * be skipped and a false negative returned. For this reason, this attr= ibute should be treated as a +- * "hint". Despite the possibility of false negatives, no false positiv= es should be returned. If a +- * client sees this flag set they can proceed with the confidence that = there are in fact associated +- * fixes. +- */ +- public Boolean getHasFix() { +- return hasFix; +- } +- +- /** +- * The location associated with the error. +- */ +- public Location getLocation() { +- return location; +- } +- +- /** +- * The message to be displayed for this error. The message should indic= ate what is wrong with the +- * code and why it is wrong. +- */ +- public String getMessage() { +- return message; +- } +- +- /** +- * The severity of the error. +- */ +- public String getSeverity() { +- return severity; +- } +- +- /** +- * The type of the error. +- */ +- public String getType() { +- return type; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(severity); +- builder.append(type); +- builder.append(location); +- builder.append(message); +- builder.append(correction); +- builder.append(code); +- builder.append(hasFix); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("severity", severity); +- jsonObject.addProperty("type", type); +- jsonObject.add("location", location.toJson()); +- jsonObject.addProperty("message", message); +- if (correction !=3D null) { +- jsonObject.addProperty("correction", correction); +- } +- jsonObject.addProperty("code", code); +- if (hasFix !=3D null) { +- jsonObject.addProperty("hasFix", hasFix); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("severity=3D"); +- builder.append(severity + ", "); +- builder.append("type=3D"); +- builder.append(type + ", "); +- builder.append("location=3D"); +- builder.append(location + ", "); +- builder.append("message=3D"); +- builder.append(message + ", "); +- builder.append("correction=3D"); +- builder.append(correction + ", "); +- builder.append("code=3D"); +- builder.append(code + ", "); +- builder.append("hasFix=3D"); +- builder.append(hasFix); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisEr= rorFixes.java b/pkg/analysis_server/tool/spec/generated/java/types/Analysis= ErrorFixes.java +deleted file mode 100644 +index a45caa1a2ce..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisErrorFixe= s.java ++++ /dev/null +@@ -1,138 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A list of fixes associated with a specific error. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class AnalysisErrorFixes { +- +- public static final AnalysisErrorFixes[] EMPTY_ARRAY =3D new AnalysisEr= rorFixes[0]; +- +- public static final List EMPTY_LIST =3D Lists.newAr= rayList(); +- +- /** +- * The error with which the fixes are associated. +- */ +- private final AnalysisError error; +- +- /** +- * The fixes associated with the error. +- */ +- private final List fixes; +- +- /** +- * Constructor for {@link AnalysisErrorFixes}. +- */ +- public AnalysisErrorFixes(AnalysisError error, List fixes= ) { +- this.error =3D error; +- this.fixes =3D fixes; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof AnalysisErrorFixes) { +- AnalysisErrorFixes other =3D (AnalysisErrorFixes) obj; +- return +- ObjectUtilities.equals(other.error, error) && +- ObjectUtilities.equals(other.fixes, fixes); +- } +- return false; +- } +- +- public static AnalysisErrorFixes fromJson(JsonObject jsonObject) { +- AnalysisError error =3D AnalysisError.fromJson(jsonObject.get("error"= ).getAsJsonObject()); +- List fixes =3D SourceChange.fromJsonArray(jsonObject.ge= t("fixes").getAsJsonArray()); +- return new AnalysisErrorFixes(error, fixes); +- } +- +- public static List fromJsonArray(JsonArray jsonArra= y) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The error with which the fixes are associated. +- */ +- public AnalysisError getError() { +- return error; +- } +- +- /** +- * The fixes associated with the error. +- */ +- public List getFixes() { +- return fixes; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(error); +- builder.append(fixes); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.add("error", error.toJson()); +- JsonArray jsonArrayFixes =3D new JsonArray(); +- for (SourceChange elt : fixes) { +- jsonArrayFixes.add(elt.toJson()); +- } +- jsonObject.add("fixes", jsonArrayFixes); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("error=3D"); +- builder.append(error + ", "); +- builder.append("fixes=3D"); +- builder.append(StringUtils.join(fixes, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisEr= rorSeverity.java b/pkg/analysis_server/tool/spec/generated/java/types/Analy= sisErrorSeverity.java +deleted file mode 100644 +index e07df408f3b..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisErrorSeve= rity.java ++++ /dev/null +@@ -1,32 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the possible severities of analysis errors. +- * +- * @coverage dart.server.generated.types +- */ +-public class AnalysisErrorSeverity { +- +- public static final String INFO =3D "INFO"; +- +- public static final String WARNING =3D "WARNING"; +- +- public static final String ERROR =3D "ERROR"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisEr= rorType.java b/pkg/analysis_server/tool/spec/generated/java/types/AnalysisE= rrorType.java +deleted file mode 100644 +index db6fe7669de..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisErrorType= .java ++++ /dev/null +@@ -1,42 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the possible types of analysis errors. +- * +- * @coverage dart.server.generated.types +- */ +-public class AnalysisErrorType { +- +- public static final String CHECKED_MODE_COMPILE_TIME_ERROR =3D "CHECKED= _MODE_COMPILE_TIME_ERROR"; +- +- public static final String COMPILE_TIME_ERROR =3D "COMPILE_TIME_ERROR"; +- +- public static final String HINT =3D "HINT"; +- +- public static final String LINT =3D "LINT"; +- +- public static final String STATIC_TYPE_WARNING =3D "STATIC_TYPE_WARNING= "; +- +- public static final String STATIC_WARNING =3D "STATIC_WARNING"; +- +- public static final String SYNTACTIC_ERROR =3D "SYNTACTIC_ERROR"; +- +- public static final String TODO =3D "TODO"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisOp= tions.java b/pkg/analysis_server/tool/spec/generated/java/types/AnalysisOpt= ions.java +deleted file mode 100644 +index 12f2cbc0cb2..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisOptions.j= ava ++++ /dev/null +@@ -1,287 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * Deprecated: the only reference to this type has been deprecated. +- * +- * A set of options controlling what kind of analysis is to be performed.= If the value of a field +- * is omitted the value of the option will not be changed. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class AnalysisOptions { +- +- public static final AnalysisOptions[] EMPTY_ARRAY =3D new AnalysisOptio= ns[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArray= List(); +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed async fe= ature. +- */ +- private final Boolean enableAsync; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed deferred= loading feature. +- */ +- private final Boolean enableDeferredLoading; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed enum fea= ture. +- */ +- private final Boolean enableEnums; +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed "null aw= are operators" feature. +- */ +- private final Boolean enableNullAwareOperators; +- +- /** +- * True if the client wants to enable support for the proposed "less re= stricted mixins" proposal +- * (DEP 34). +- */ +- private final Boolean enableSuperMixins; +- +- /** +- * True if hints that are specific to dart2js should be generated. This= option is ignored if +- * generateHints is false. +- */ +- private final Boolean generateDart2jsHints; +- +- /** +- * True if hints should be generated as part of generating errors and w= arnings. +- */ +- private final Boolean generateHints; +- +- /** +- * True if lints should be generated as part of generating errors and w= arnings. +- */ +- private final Boolean generateLints; +- +- /** +- * Constructor for {@link AnalysisOptions}. +- */ +- public AnalysisOptions(Boolean enableAsync, Boolean enableDeferredLoadi= ng, Boolean enableEnums, Boolean enableNullAwareOperators, Boolean enableSu= perMixins, Boolean generateDart2jsHints, Boolean generateHints, Boolean gen= erateLints) { +- this.enableAsync =3D enableAsync; +- this.enableDeferredLoading =3D enableDeferredLoading; +- this.enableEnums =3D enableEnums; +- this.enableNullAwareOperators =3D enableNullAwareOperators; +- this.enableSuperMixins =3D enableSuperMixins; +- this.generateDart2jsHints =3D generateDart2jsHints; +- this.generateHints =3D generateHints; +- this.generateLints =3D generateLints; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof AnalysisOptions) { +- AnalysisOptions other =3D (AnalysisOptions) obj; +- return +- ObjectUtilities.equals(other.enableAsync, enableAsync) && +- ObjectUtilities.equals(other.enableDeferredLoading, enableDeferre= dLoading) && +- ObjectUtilities.equals(other.enableEnums, enableEnums) && +- ObjectUtilities.equals(other.enableNullAwareOperators, enableNull= AwareOperators) && +- ObjectUtilities.equals(other.enableSuperMixins, enableSuperMixins= ) && +- ObjectUtilities.equals(other.generateDart2jsHints, generateDart2j= sHints) && +- ObjectUtilities.equals(other.generateHints, generateHints) && +- ObjectUtilities.equals(other.generateLints, generateLints); +- } +- return false; +- } +- +- public static AnalysisOptions fromJson(JsonObject jsonObject) { +- Boolean enableAsync =3D jsonObject.get("enableAsync") =3D=3D null ? n= ull : jsonObject.get("enableAsync").getAsBoolean(); +- Boolean enableDeferredLoading =3D jsonObject.get("enableDeferredLoadi= ng") =3D=3D null ? null : jsonObject.get("enableDeferredLoading").getAsBool= ean(); +- Boolean enableEnums =3D jsonObject.get("enableEnums") =3D=3D null ? n= ull : jsonObject.get("enableEnums").getAsBoolean(); +- Boolean enableNullAwareOperators =3D jsonObject.get("enableNullAwareO= perators") =3D=3D null ? null : jsonObject.get("enableNullAwareOperators").= getAsBoolean(); +- Boolean enableSuperMixins =3D jsonObject.get("enableSuperMixins") =3D= =3D null ? null : jsonObject.get("enableSuperMixins").getAsBoolean(); +- Boolean generateDart2jsHints =3D jsonObject.get("generateDart2jsHints= ") =3D=3D null ? null : jsonObject.get("generateDart2jsHints").getAsBoolean= (); +- Boolean generateHints =3D jsonObject.get("generateHints") =3D=3D null= ? null : jsonObject.get("generateHints").getAsBoolean(); +- Boolean generateLints =3D jsonObject.get("generateLints") =3D=3D null= ? null : jsonObject.get("generateLints").getAsBoolean(); +- return new AnalysisOptions(enableAsync, enableDeferredLoading, enable= Enums, enableNullAwareOperators, enableSuperMixins, generateDart2jsHints, g= enerateHints, generateLints); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(js= onArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed async fe= ature. +- */ +- public Boolean getEnableAsync() { +- return enableAsync; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed deferred= loading feature. +- */ +- public Boolean getEnableDeferredLoading() { +- return enableDeferredLoading; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed enum fea= ture. +- */ +- public Boolean getEnableEnums() { +- return enableEnums; +- } +- +- /** +- * Deprecated: this feature is always enabled. +- * +- * True if the client wants to enable support for the proposed "null aw= are operators" feature. +- */ +- public Boolean getEnableNullAwareOperators() { +- return enableNullAwareOperators; +- } +- +- /** +- * True if the client wants to enable support for the proposed "less re= stricted mixins" proposal +- * (DEP 34). +- */ +- public Boolean getEnableSuperMixins() { +- return enableSuperMixins; +- } +- +- /** +- * True if hints that are specific to dart2js should be generated. This= option is ignored if +- * generateHints is false. +- */ +- public Boolean getGenerateDart2jsHints() { +- return generateDart2jsHints; +- } +- +- /** +- * True if hints should be generated as part of generating errors and w= arnings. +- */ +- public Boolean getGenerateHints() { +- return generateHints; +- } +- +- /** +- * True if lints should be generated as part of generating errors and w= arnings. +- */ +- public Boolean getGenerateLints() { +- return generateLints; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(enableAsync); +- builder.append(enableDeferredLoading); +- builder.append(enableEnums); +- builder.append(enableNullAwareOperators); +- builder.append(enableSuperMixins); +- builder.append(generateDart2jsHints); +- builder.append(generateHints); +- builder.append(generateLints); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- if (enableAsync !=3D null) { +- jsonObject.addProperty("enableAsync", enableAsync); +- } +- if (enableDeferredLoading !=3D null) { +- jsonObject.addProperty("enableDeferredLoading", enableDeferredLoadi= ng); +- } +- if (enableEnums !=3D null) { +- jsonObject.addProperty("enableEnums", enableEnums); +- } +- if (enableNullAwareOperators !=3D null) { +- jsonObject.addProperty("enableNullAwareOperators", enableNullAwareO= perators); +- } +- if (enableSuperMixins !=3D null) { +- jsonObject.addProperty("enableSuperMixins", enableSuperMixins); +- } +- if (generateDart2jsHints !=3D null) { +- jsonObject.addProperty("generateDart2jsHints", generateDart2jsHints= ); +- } +- if (generateHints !=3D null) { +- jsonObject.addProperty("generateHints", generateHints); +- } +- if (generateLints !=3D null) { +- jsonObject.addProperty("generateLints", generateLints); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("enableAsync=3D"); +- builder.append(enableAsync + ", "); +- builder.append("enableDeferredLoading=3D"); +- builder.append(enableDeferredLoading + ", "); +- builder.append("enableEnums=3D"); +- builder.append(enableEnums + ", "); +- builder.append("enableNullAwareOperators=3D"); +- builder.append(enableNullAwareOperators + ", "); +- builder.append("enableSuperMixins=3D"); +- builder.append(enableSuperMixins + ", "); +- builder.append("generateDart2jsHints=3D"); +- builder.append(generateDart2jsHints + ", "); +- builder.append("generateHints=3D"); +- builder.append(generateHints + ", "); +- builder.append("generateLints=3D"); +- builder.append(generateLints); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisSe= rvice.java b/pkg/analysis_server/tool/spec/generated/java/types/AnalysisSer= vice.java +deleted file mode 100644 +index bd8579170a3..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisService.j= ava ++++ /dev/null +@@ -1,49 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the services provided by the analysis domain that ar= e related to a specific +- * list of files. +- * +- * @coverage dart.server.generated.types +- */ +-public class AnalysisService { +- +- public static final String CLOSING_LABELS =3D "CLOSING_LABELS"; +- +- public static final String FOLDING =3D "FOLDING"; +- +- public static final String HIGHLIGHTS =3D "HIGHLIGHTS"; +- +- public static final String IMPLEMENTED =3D "IMPLEMENTED"; +- +- /** +- * This service is not currently implemented and will become a GeneralA= nalysisService in a future +- * release. +- */ +- public static final String INVALIDATE =3D "INVALIDATE"; +- +- public static final String NAVIGATION =3D "NAVIGATION"; +- +- public static final String OCCURRENCES =3D "OCCURRENCES"; +- +- public static final String OUTLINE =3D "OUTLINE"; +- +- public static final String OVERRIDES =3D "OVERRIDES"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisSt= atus.java b/pkg/analysis_server/tool/spec/generated/java/types/AnalysisStat= us.java +deleted file mode 100644 +index 1a0cb7fa56f..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/AnalysisStatus.ja= va ++++ /dev/null +@@ -1,136 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An indication of the current state of analysis. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class AnalysisStatus { +- +- public static final AnalysisStatus[] EMPTY_ARRAY =3D new AnalysisStatus= [0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayL= ist(); +- +- /** +- * True if analysis is currently being performed. +- */ +- private final boolean isAnalyzing; +- +- /** +- * The name of the current target of analysis. This field is omitted if= analyzing is false. +- */ +- private final String analysisTarget; +- +- /** +- * Constructor for {@link AnalysisStatus}. +- */ +- public AnalysisStatus(boolean isAnalyzing, String analysisTarget) { +- this.isAnalyzing =3D isAnalyzing; +- this.analysisTarget =3D analysisTarget; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof AnalysisStatus) { +- AnalysisStatus other =3D (AnalysisStatus) obj; +- return +- other.isAnalyzing =3D=3D isAnalyzing && +- ObjectUtilities.equals(other.analysisTarget, analysisTarget); +- } +- return false; +- } +- +- public static AnalysisStatus fromJson(JsonObject jsonObject) { +- boolean isAnalyzing =3D jsonObject.get("isAnalyzing").getAsBoolean(); +- String analysisTarget =3D jsonObject.get("analysisTarget") =3D=3D nul= l ? null : jsonObject.get("analysisTarget").getAsString(); +- return new AnalysisStatus(isAnalyzing, analysisTarget); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(json= Array.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The name of the current target of analysis. This field is omitted if= analyzing is false. +- */ +- public String getAnalysisTarget() { +- return analysisTarget; +- } +- +- /** +- * True if analysis is currently being performed. +- */ +- public boolean isAnalyzing() { +- return isAnalyzing; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(isAnalyzing); +- builder.append(analysisTarget); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("isAnalyzing", isAnalyzing); +- if (analysisTarget !=3D null) { +- jsonObject.addProperty("analysisTarget", analysisTarget); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("isAnalyzing=3D"); +- builder.append(isAnalyzing + ", "); +- builder.append("analysisTarget=3D"); +- builder.append(analysisTarget); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ChangeCont= entOverlay.java b/pkg/analysis_server/tool/spec/generated/java/types/Change= ContentOverlay.java +deleted file mode 100644 +index e7b4062b3bd..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ChangeContentOver= lay.java ++++ /dev/null +@@ -1,142 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A directive to modify an existing file content overlay. One or more ra= nges of text are deleted +- * from the old file content overlay and replaced with new text. +- * +- * The edits are applied in the order in which they occur in the list. Th= is means that the offset +- * of each edit must be correct under the assumption that all previous ed= its have been applied. +- * +- * It is an error to use this overlay on a file that does not yet have a = file content overlay or +- * that has had its overlay removed via RemoveContentOverlay. +- * +- * If any of the edits cannot be applied due to its offset or length bein= g out of range, an +- * INVALID_OVERLAY_CHANGE error will be reported. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ChangeContentOverlay { +- +- public static final ChangeContentOverlay[] EMPTY_ARRAY =3D new ChangeCo= ntentOverlay[0]; +- +- public static final List EMPTY_LIST =3D Lists.new= ArrayList(); +- +- private final String type; +- +- /** +- * The edits to be applied to the file. +- */ +- private final List edits; +- +- /** +- * Constructor for {@link ChangeContentOverlay}. +- */ +- public ChangeContentOverlay(List edits) { +- this.type =3D "change"; +- this.edits =3D edits; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ChangeContentOverlay) { +- ChangeContentOverlay other =3D (ChangeContentOverlay) obj; +- return +- ObjectUtilities.equals(other.type, type) && +- ObjectUtilities.equals(other.edits, edits); +- } +- return false; +- } +- +- public static ChangeContentOverlay fromJson(JsonObject jsonObject) { +- String type =3D jsonObject.get("type").getAsString(); +- List edits =3D SourceEdit.fromJsonArray(jsonObject.get("e= dits").getAsJsonArray()); +- return new ChangeContentOverlay(edits); +- } +- +- public static List fromJsonArray(JsonArray jsonAr= ray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The edits to be applied to the file. +- */ +- public List getEdits() { +- return edits; +- } +- +- public String getType() { +- return type; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(type); +- builder.append(edits); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("type", type); +- JsonArray jsonArrayEdits =3D new JsonArray(); +- for (SourceEdit elt : edits) { +- jsonArrayEdits.add(elt.toJson()); +- } +- jsonObject.add("edits", jsonArrayEdits); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("type=3D"); +- builder.append(type + ", "); +- builder.append("edits=3D"); +- builder.append(StringUtils.join(edits, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ClosingLab= el.java b/pkg/analysis_server/tool/spec/generated/java/types/ClosingLabel.j= ava +deleted file mode 100644 +index 4cf5979bbd9..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ClosingLabel.java ++++ /dev/null +@@ -1,156 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A label that is associated with a range of code that may be useful to = render at the end of the +- * range to aid code readability. For example, a constructor call that sp= ans multiple lines may +- * result in a closing label to allow the constructor type/name to be ren= dered alongside the +- * closing parenthesis. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ClosingLabel { +- +- public static final ClosingLabel[] EMPTY_ARRAY =3D new ClosingLabel[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLis= t(); +- +- /** +- * The offset of the construct being labelled. +- */ +- private final int offset; +- +- /** +- * The length of the whole construct to be labelled. +- */ +- private final int length; +- +- /** +- * The label associated with this range that should be displayed to the= user. +- */ +- private final String label; +- +- /** +- * Constructor for {@link ClosingLabel}. +- */ +- public ClosingLabel(int offset, int length, String label) { +- this.offset =3D offset; +- this.length =3D length; +- this.label =3D label; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ClosingLabel) { +- ClosingLabel other =3D (ClosingLabel) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.label, label); +- } +- return false; +- } +- +- public static ClosingLabel fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- String label =3D jsonObject.get("label").getAsString(); +- return new ClosingLabel(offset, length, label); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArra= y.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The label associated with this range that should be displayed to the= user. +- */ +- public String getLabel() { +- return label; +- } +- +- /** +- * The length of the whole construct to be labelled. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the construct being labelled. +- */ +- public int getOffset() { +- return offset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(label); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- jsonObject.addProperty("label", label); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("label=3D"); +- builder.append(label); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Completion= Suggestion.java b/pkg/analysis_server/tool/spec/generated/java/types/Comple= tionSuggestion.java +deleted file mode 100644 +index 125322ccf71..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/CompletionSuggest= ion.java ++++ /dev/null +@@ -1,574 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A suggestion for how to complete partially entered text. Many of the f= ields are optional, +- * depending on the kind of element being suggested. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class CompletionSuggestion { +- +- public static final CompletionSuggestion[] EMPTY_ARRAY =3D new Completi= onSuggestion[0]; +- +- public static final List EMPTY_LIST =3D Lists.new= ArrayList(); +- +- /** +- * The kind of element being suggested. +- */ +- private final String kind; +- +- /** +- * The relevance of this completion suggestion where a higher number in= dicates a higher relevance. +- */ +- private final int relevance; +- +- /** +- * The identifier to be inserted if the suggestion is selected. If the = suggestion is for a method +- * or function, the client might want to additionally insert a template= for the parameters. The +- * information required in order to do so is contained in other fields. +- */ +- private final String completion; +- +- /** +- * The offset, relative to the beginning of the completion, of where th= e selection should be placed +- * after insertion. +- */ +- private final int selectionOffset; +- +- /** +- * The number of characters that should be selected after insertion. +- */ +- private final int selectionLength; +- +- /** +- * True if the suggested element is deprecated. +- */ +- private final boolean isDeprecated; +- +- /** +- * True if the element is not known to be valid for the target. This ha= ppens if the type of the +- * target is dynamic. +- */ +- private final boolean isPotential; +- +- /** +- * An abbreviated version of the Dartdoc associated with the element be= ing suggested, This field is +- * omitted if there is no Dartdoc associated with the element. +- */ +- private final String docSummary; +- +- /** +- * The Dartdoc associated with the element being suggested. This field = is omitted if there is no +- * Dartdoc associated with the element. +- */ +- private final String docComplete; +- +- /** +- * The class that declares the element being suggested. This field is o= mitted if the suggested +- * element is not a member of a class. +- */ +- private final String declaringType; +- +- /** +- * A default String for use in generating argument list source contents= on the client side. +- */ +- private final String defaultArgumentListString; +- +- /** +- * Pairs of offsets and lengths describing 'defaultArgumentListString' = text ranges suitable for use +- * by clients to set up linked edits of default argument source content= s. For example, given an +- * argument list string 'x, y', the corresponding text range [0, 1, 3, = 1], indicates two text +- * ranges of length 1, starting at offsets 0 and 3. Clients can use the= se ranges to treat the 'x' +- * and 'y' values specially for linked edits. +- */ +- private final int[] defaultArgumentListTextRanges; +- +- /** +- * Information about the element reference being suggested. +- */ +- private final Element element; +- +- /** +- * The return type of the getter, function or method or the type of the= field being suggested. This +- * field is omitted if the suggested element is not a getter, function = or method. +- */ +- private final String returnType; +- +- /** +- * The names of the parameters of the function or method being suggeste= d. This field is omitted if +- * the suggested element is not a setter, function or method. +- */ +- private final List parameterNames; +- +- /** +- * The types of the parameters of the function or method being suggeste= d. This field is omitted if +- * the parameterNames field is omitted. +- */ +- private final List parameterTypes; +- +- /** +- * The number of required parameters for the function or method being s= uggested. This field is +- * omitted if the parameterNames field is omitted. +- */ +- private final Integer requiredParameterCount; +- +- /** +- * True if the function or method being suggested has at least one name= d parameter. This field is +- * omitted if the parameterNames field is omitted. +- */ +- private final Boolean hasNamedParameters; +- +- /** +- * The name of the optional parameter being suggested. This field is om= itted if the suggestion is +- * not the addition of an optional argument within an argument list. +- */ +- private final String parameterName; +- +- /** +- * The type of the options parameter being suggested. This field is omi= tted if the parameterName +- * field is omitted. +- */ +- private final String parameterType; +- +- /** +- * The import to be added if the suggestion is out of scope and needs a= n import to be added to be +- * in scope. +- */ +- private final String importUri; +- +- /** +- * Constructor for {@link CompletionSuggestion}. +- */ +- public CompletionSuggestion(String kind, int relevance, String completi= on, int selectionOffset, int selectionLength, boolean isDeprecated, boolean= isPotential, String docSummary, String docComplete, String declaringType, = String defaultArgumentListString, int[] defaultArgumentListTextRanges, Elem= ent element, String returnType, List parameterNames, List p= arameterTypes, Integer requiredParameterCount, Boolean hasNamedParameters, = String parameterName, String parameterType, String importUri) { +- this.kind =3D kind; +- this.relevance =3D relevance; +- this.completion =3D completion; +- this.selectionOffset =3D selectionOffset; +- this.selectionLength =3D selectionLength; +- this.isDeprecated =3D isDeprecated; +- this.isPotential =3D isPotential; +- this.docSummary =3D docSummary; +- this.docComplete =3D docComplete; +- this.declaringType =3D declaringType; +- this.defaultArgumentListString =3D defaultArgumentListString; +- this.defaultArgumentListTextRanges =3D defaultArgumentListTextRanges; +- this.element =3D element; +- this.returnType =3D returnType; +- this.parameterNames =3D parameterNames; +- this.parameterTypes =3D parameterTypes; +- this.requiredParameterCount =3D requiredParameterCount; +- this.hasNamedParameters =3D hasNamedParameters; +- this.parameterName =3D parameterName; +- this.parameterType =3D parameterType; +- this.importUri =3D importUri; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof CompletionSuggestion) { +- CompletionSuggestion other =3D (CompletionSuggestion) obj; +- return +- ObjectUtilities.equals(other.kind, kind) && +- other.relevance =3D=3D relevance && +- ObjectUtilities.equals(other.completion, completion) && +- other.selectionOffset =3D=3D selectionOffset && +- other.selectionLength =3D=3D selectionLength && +- other.isDeprecated =3D=3D isDeprecated && +- other.isPotential =3D=3D isPotential && +- ObjectUtilities.equals(other.docSummary, docSummary) && +- ObjectUtilities.equals(other.docComplete, docComplete) && +- ObjectUtilities.equals(other.declaringType, declaringType) && +- ObjectUtilities.equals(other.defaultArgumentListString, defaultAr= gumentListString) && +- Arrays.equals(other.defaultArgumentListTextRanges, defaultArgumen= tListTextRanges) && +- ObjectUtilities.equals(other.element, element) && +- ObjectUtilities.equals(other.returnType, returnType) && +- ObjectUtilities.equals(other.parameterNames, parameterNames) && +- ObjectUtilities.equals(other.parameterTypes, parameterTypes) && +- ObjectUtilities.equals(other.requiredParameterCount, requiredPara= meterCount) && +- ObjectUtilities.equals(other.hasNamedParameters, hasNamedParamete= rs) && +- ObjectUtilities.equals(other.parameterName, parameterName) && +- ObjectUtilities.equals(other.parameterType, parameterType) && +- ObjectUtilities.equals(other.importUri, importUri); +- } +- return false; +- } +- +- public static CompletionSuggestion fromJson(JsonObject jsonObject) { +- String kind =3D jsonObject.get("kind").getAsString(); +- int relevance =3D jsonObject.get("relevance").getAsInt(); +- String completion =3D jsonObject.get("completion").getAsString(); +- int selectionOffset =3D jsonObject.get("selectionOffset").getAsInt(); +- int selectionLength =3D jsonObject.get("selectionLength").getAsInt(); +- boolean isDeprecated =3D jsonObject.get("isDeprecated").getAsBoolean(= ); +- boolean isPotential =3D jsonObject.get("isPotential").getAsBoolean(); +- String docSummary =3D jsonObject.get("docSummary") =3D=3D null ? null= : jsonObject.get("docSummary").getAsString(); +- String docComplete =3D jsonObject.get("docComplete") =3D=3D null ? nu= ll : jsonObject.get("docComplete").getAsString(); +- String declaringType =3D jsonObject.get("declaringType") =3D=3D null = ? null : jsonObject.get("declaringType").getAsString(); +- String defaultArgumentListString =3D jsonObject.get("defaultArgumentL= istString") =3D=3D null ? null : jsonObject.get("defaultArgumentListString"= ).getAsString(); +- int[] defaultArgumentListTextRanges =3D jsonObject.get("defaultArgume= ntListTextRanges") =3D=3D null ? null : JsonUtilities.decodeIntArray(jsonOb= ject.get("defaultArgumentListTextRanges").getAsJsonArray()); +- Element element =3D jsonObject.get("element") =3D=3D null ? null : El= ement.fromJson(jsonObject.get("element").getAsJsonObject()); +- String returnType =3D jsonObject.get("returnType") =3D=3D null ? null= : jsonObject.get("returnType").getAsString(); +- List parameterNames =3D jsonObject.get("parameterNames") =3D= =3D null ? null : JsonUtilities.decodeStringList(jsonObject.get("parameterN= ames").getAsJsonArray()); +- List parameterTypes =3D jsonObject.get("parameterTypes") =3D= =3D null ? null : JsonUtilities.decodeStringList(jsonObject.get("parameterT= ypes").getAsJsonArray()); +- Integer requiredParameterCount =3D jsonObject.get("requiredParameterC= ount") =3D=3D null ? null : jsonObject.get("requiredParameterCount").getAsI= nt(); +- Boolean hasNamedParameters =3D jsonObject.get("hasNamedParameters") = =3D=3D null ? null : jsonObject.get("hasNamedParameters").getAsBoolean(); +- String parameterName =3D jsonObject.get("parameterName") =3D=3D null = ? null : jsonObject.get("parameterName").getAsString(); +- String parameterType =3D jsonObject.get("parameterType") =3D=3D null = ? null : jsonObject.get("parameterType").getAsString(); +- String importUri =3D jsonObject.get("importUri") =3D=3D null ? null := jsonObject.get("importUri").getAsString(); +- return new CompletionSuggestion(kind, relevance, completion, selectio= nOffset, selectionLength, isDeprecated, isPotential, docSummary, docComplet= e, declaringType, defaultArgumentListString, defaultArgumentListTextRanges,= element, returnType, parameterNames, parameterTypes, requiredParameterCoun= t, hasNamedParameters, parameterName, parameterType, importUri); +- } +- +- public static List fromJsonArray(JsonArray jsonAr= ray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The identifier to be inserted if the suggestion is selected. If the = suggestion is for a method +- * or function, the client might want to additionally insert a template= for the parameters. The +- * information required in order to do so is contained in other fields. +- */ +- public String getCompletion() { +- return completion; +- } +- +- /** +- * The class that declares the element being suggested. This field is o= mitted if the suggested +- * element is not a member of a class. +- */ +- public String getDeclaringType() { +- return declaringType; +- } +- +- /** +- * A default String for use in generating argument list source contents= on the client side. +- */ +- public String getDefaultArgumentListString() { +- return defaultArgumentListString; +- } +- +- /** +- * Pairs of offsets and lengths describing 'defaultArgumentListString' = text ranges suitable for use +- * by clients to set up linked edits of default argument source content= s. For example, given an +- * argument list string 'x, y', the corresponding text range [0, 1, 3, = 1], indicates two text +- * ranges of length 1, starting at offsets 0 and 3. Clients can use the= se ranges to treat the 'x' +- * and 'y' values specially for linked edits. +- */ +- public int[] getDefaultArgumentListTextRanges() { +- return defaultArgumentListTextRanges; +- } +- +- /** +- * The Dartdoc associated with the element being suggested. This field = is omitted if there is no +- * Dartdoc associated with the element. +- */ +- public String getDocComplete() { +- return docComplete; +- } +- +- /** +- * An abbreviated version of the Dartdoc associated with the element be= ing suggested, This field is +- * omitted if there is no Dartdoc associated with the element. +- */ +- public String getDocSummary() { +- return docSummary; +- } +- +- /** +- * Information about the element reference being suggested. +- */ +- public Element getElement() { +- return element; +- } +- +- /** +- * True if the function or method being suggested has at least one name= d parameter. This field is +- * omitted if the parameterNames field is omitted. +- */ +- public Boolean getHasNamedParameters() { +- return hasNamedParameters; +- } +- +- /** +- * The import to be added if the suggestion is out of scope and needs a= n import to be added to be +- * in scope. +- */ +- public String getImportUri() { +- return importUri; +- } +- +- /** +- * True if the suggested element is deprecated. +- */ +- public boolean isDeprecated() { +- return isDeprecated; +- } +- +- /** +- * True if the element is not known to be valid for the target. This ha= ppens if the type of the +- * target is dynamic. +- */ +- public boolean isPotential() { +- return isPotential; +- } +- +- /** +- * The kind of element being suggested. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The name of the optional parameter being suggested. This field is om= itted if the suggestion is +- * not the addition of an optional argument within an argument list. +- */ +- public String getParameterName() { +- return parameterName; +- } +- +- /** +- * The names of the parameters of the function or method being suggeste= d. This field is omitted if +- * the suggested element is not a setter, function or method. +- */ +- public List getParameterNames() { +- return parameterNames; +- } +- +- /** +- * The type of the options parameter being suggested. This field is omi= tted if the parameterName +- * field is omitted. +- */ +- public String getParameterType() { +- return parameterType; +- } +- +- /** +- * The types of the parameters of the function or method being suggeste= d. This field is omitted if +- * the parameterNames field is omitted. +- */ +- public List getParameterTypes() { +- return parameterTypes; +- } +- +- /** +- * The relevance of this completion suggestion where a higher number in= dicates a higher relevance. +- */ +- public int getRelevance() { +- return relevance; +- } +- +- /** +- * The number of required parameters for the function or method being s= uggested. This field is +- * omitted if the parameterNames field is omitted. +- */ +- public Integer getRequiredParameterCount() { +- return requiredParameterCount; +- } +- +- /** +- * The return type of the getter, function or method or the type of the= field being suggested. This +- * field is omitted if the suggested element is not a getter, function = or method. +- */ +- public String getReturnType() { +- return returnType; +- } +- +- /** +- * The number of characters that should be selected after insertion. +- */ +- public int getSelectionLength() { +- return selectionLength; +- } +- +- /** +- * The offset, relative to the beginning of the completion, of where th= e selection should be placed +- * after insertion. +- */ +- public int getSelectionOffset() { +- return selectionOffset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(kind); +- builder.append(relevance); +- builder.append(completion); +- builder.append(selectionOffset); +- builder.append(selectionLength); +- builder.append(isDeprecated); +- builder.append(isPotential); +- builder.append(docSummary); +- builder.append(docComplete); +- builder.append(declaringType); +- builder.append(defaultArgumentListString); +- builder.append(defaultArgumentListTextRanges); +- builder.append(element); +- builder.append(returnType); +- builder.append(parameterNames); +- builder.append(parameterTypes); +- builder.append(requiredParameterCount); +- builder.append(hasNamedParameters); +- builder.append(parameterName); +- builder.append(parameterType); +- builder.append(importUri); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("kind", kind); +- jsonObject.addProperty("relevance", relevance); +- jsonObject.addProperty("completion", completion); +- jsonObject.addProperty("selectionOffset", selectionOffset); +- jsonObject.addProperty("selectionLength", selectionLength); +- jsonObject.addProperty("isDeprecated", isDeprecated); +- jsonObject.addProperty("isPotential", isPotential); +- if (docSummary !=3D null) { +- jsonObject.addProperty("docSummary", docSummary); +- } +- if (docComplete !=3D null) { +- jsonObject.addProperty("docComplete", docComplete); +- } +- if (declaringType !=3D null) { +- jsonObject.addProperty("declaringType", declaringType); +- } +- if (defaultArgumentListString !=3D null) { +- jsonObject.addProperty("defaultArgumentListString", defaultArgument= ListString); +- } +- if (defaultArgumentListTextRanges !=3D null) { +- JsonArray jsonArrayDefaultArgumentListTextRanges =3D new JsonArray(= ); +- for (int elt : defaultArgumentListTextRanges) { +- jsonArrayDefaultArgumentListTextRanges.add(new JsonPrimitive(elt)= ); +- } +- jsonObject.add("defaultArgumentListTextRanges", jsonArrayDefaultArg= umentListTextRanges); +- } +- if (element !=3D null) { +- jsonObject.add("element", element.toJson()); +- } +- if (returnType !=3D null) { +- jsonObject.addProperty("returnType", returnType); +- } +- if (parameterNames !=3D null) { +- JsonArray jsonArrayParameterNames =3D new JsonArray(); +- for (String elt : parameterNames) { +- jsonArrayParameterNames.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("parameterNames", jsonArrayParameterNames); +- } +- if (parameterTypes !=3D null) { +- JsonArray jsonArrayParameterTypes =3D new JsonArray(); +- for (String elt : parameterTypes) { +- jsonArrayParameterTypes.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("parameterTypes", jsonArrayParameterTypes); +- } +- if (requiredParameterCount !=3D null) { +- jsonObject.addProperty("requiredParameterCount", requiredParameterC= ount); +- } +- if (hasNamedParameters !=3D null) { +- jsonObject.addProperty("hasNamedParameters", hasNamedParameters); +- } +- if (parameterName !=3D null) { +- jsonObject.addProperty("parameterName", parameterName); +- } +- if (parameterType !=3D null) { +- jsonObject.addProperty("parameterType", parameterType); +- } +- if (importUri !=3D null) { +- jsonObject.addProperty("importUri", importUri); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("relevance=3D"); +- builder.append(relevance + ", "); +- builder.append("completion=3D"); +- builder.append(completion + ", "); +- builder.append("selectionOffset=3D"); +- builder.append(selectionOffset + ", "); +- builder.append("selectionLength=3D"); +- builder.append(selectionLength + ", "); +- builder.append("isDeprecated=3D"); +- builder.append(isDeprecated + ", "); +- builder.append("isPotential=3D"); +- builder.append(isPotential + ", "); +- builder.append("docSummary=3D"); +- builder.append(docSummary + ", "); +- builder.append("docComplete=3D"); +- builder.append(docComplete + ", "); +- builder.append("declaringType=3D"); +- builder.append(declaringType + ", "); +- builder.append("defaultArgumentListString=3D"); +- builder.append(defaultArgumentListString + ", "); +- builder.append("defaultArgumentListTextRanges=3D"); +- builder.append(StringUtils.join(defaultArgumentListTextRanges, ", ") = + ", "); +- builder.append("element=3D"); +- builder.append(element + ", "); +- builder.append("returnType=3D"); +- builder.append(returnType + ", "); +- builder.append("parameterNames=3D"); +- builder.append(StringUtils.join(parameterNames, ", ") + ", "); +- builder.append("parameterTypes=3D"); +- builder.append(StringUtils.join(parameterTypes, ", ") + ", "); +- builder.append("requiredParameterCount=3D"); +- builder.append(requiredParameterCount + ", "); +- builder.append("hasNamedParameters=3D"); +- builder.append(hasNamedParameters + ", "); +- builder.append("parameterName=3D"); +- builder.append(parameterName + ", "); +- builder.append("parameterType=3D"); +- builder.append(parameterType + ", "); +- builder.append("importUri=3D"); +- builder.append(importUri); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Completion= SuggestionKind.java b/pkg/analysis_server/tool/spec/generated/java/types/Co= mpletionSuggestionKind.java +deleted file mode 100644 +index 8216ce95b0e..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/CompletionSuggest= ionKind.java ++++ /dev/null +@@ -1,64 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of elements that can be included in a comp= letion suggestion. +- * +- * @coverage dart.server.generated.types +- */ +-public class CompletionSuggestionKind { +- +- /** +- * A list of arguments for the method or function that is being invoked= . For this suggestion kind, +- * the completion field is a textual representation of the invocation a= nd the parameterNames, +- * parameterTypes, and requiredParameterCount attributes are defined. +- */ +- public static final String ARGUMENT_LIST =3D "ARGUMENT_LIST"; +- +- public static final String IMPORT =3D "IMPORT"; +- +- /** +- * The element identifier should be inserted at the completion location= . For example "someMethod" +- * in import 'myLib.dart' show someMethod;. For suggestions of this kin= d, the element attribute is +- * defined and the completion field is the element's identifier. +- */ +- public static final String IDENTIFIER =3D "IDENTIFIER"; +- +- /** +- * The element is being invoked at the completion location. For example= , 'someMethod' in +- * x.someMethod();. For suggestions of this kind, the element attribute= is defined and the +- * completion field is the element's identifier. +- */ +- public static final String INVOCATION =3D "INVOCATION"; +- +- /** +- * A keyword is being suggested. For suggestions of this kind, the comp= letion is the keyword. +- */ +- public static final String KEYWORD =3D "KEYWORD"; +- +- /** +- * A named argument for the current call site is being suggested. For s= uggestions of this kind, the +- * completion is the named argument identifier including a trailing ':'= and a space. +- */ +- public static final String NAMED_ARGUMENT =3D "NAMED_ARGUMENT"; +- +- public static final String OPTIONAL_ARGUMENT =3D "OPTIONAL_ARGUMENT"; +- +- public static final String PARAMETER =3D "PARAMETER"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ContextDat= a.java b/pkg/analysis_server/tool/spec/generated/java/types/ContextData.java +deleted file mode 100644 +index ab4020c02af..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ContextData.java ++++ /dev/null +@@ -1,195 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * Information about an analysis context. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ContextData { +- +- public static final ContextData[] EMPTY_ARRAY =3D new ContextData[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList= (); +- +- /** +- * The name of the context. +- */ +- private final String name; +- +- /** +- * Explicitly analyzed files. +- */ +- private final int explicitFileCount; +- +- /** +- * Implicitly analyzed files. +- */ +- private final int implicitFileCount; +- +- /** +- * The number of work items in the queue. +- */ +- private final int workItemQueueLength; +- +- /** +- * Exceptions associated with cache entries. +- */ +- private final List cacheEntryExceptions; +- +- /** +- * Constructor for {@link ContextData}. +- */ +- public ContextData(String name, int explicitFileCount, int implicitFile= Count, int workItemQueueLength, List cacheEntryExceptions) { +- this.name =3D name; +- this.explicitFileCount =3D explicitFileCount; +- this.implicitFileCount =3D implicitFileCount; +- this.workItemQueueLength =3D workItemQueueLength; +- this.cacheEntryExceptions =3D cacheEntryExceptions; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ContextData) { +- ContextData other =3D (ContextData) obj; +- return +- ObjectUtilities.equals(other.name, name) && +- other.explicitFileCount =3D=3D explicitFileCount && +- other.implicitFileCount =3D=3D implicitFileCount && +- other.workItemQueueLength =3D=3D workItemQueueLength && +- ObjectUtilities.equals(other.cacheEntryExceptions, cacheEntryExce= ptions); +- } +- return false; +- } +- +- public static ContextData fromJson(JsonObject jsonObject) { +- String name =3D jsonObject.get("name").getAsString(); +- int explicitFileCount =3D jsonObject.get("explicitFileCount").getAsIn= t(); +- int implicitFileCount =3D jsonObject.get("implicitFileCount").getAsIn= t(); +- int workItemQueueLength =3D jsonObject.get("workItemQueueLength").get= AsInt(); +- List cacheEntryExceptions =3D JsonUtilities.decodeStringList(= jsonObject.get("cacheEntryExceptions").getAsJsonArray()); +- return new ContextData(name, explicitFileCount, implicitFileCount, wo= rkItemQueueLength, cacheEntryExceptions); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.= size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * Exceptions associated with cache entries. +- */ +- public List getCacheEntryExceptions() { +- return cacheEntryExceptions; +- } +- +- /** +- * Explicitly analyzed files. +- */ +- public int getExplicitFileCount() { +- return explicitFileCount; +- } +- +- /** +- * Implicitly analyzed files. +- */ +- public int getImplicitFileCount() { +- return implicitFileCount; +- } +- +- /** +- * The name of the context. +- */ +- public String getName() { +- return name; +- } +- +- /** +- * The number of work items in the queue. +- */ +- public int getWorkItemQueueLength() { +- return workItemQueueLength; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(name); +- builder.append(explicitFileCount); +- builder.append(implicitFileCount); +- builder.append(workItemQueueLength); +- builder.append(cacheEntryExceptions); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("name", name); +- jsonObject.addProperty("explicitFileCount", explicitFileCount); +- jsonObject.addProperty("implicitFileCount", implicitFileCount); +- jsonObject.addProperty("workItemQueueLength", workItemQueueLength); +- JsonArray jsonArrayCacheEntryExceptions =3D new JsonArray(); +- for (String elt : cacheEntryExceptions) { +- jsonArrayCacheEntryExceptions.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("cacheEntryExceptions", jsonArrayCacheEntryExceptions); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("explicitFileCount=3D"); +- builder.append(explicitFileCount + ", "); +- builder.append("implicitFileCount=3D"); +- builder.append(implicitFileCount + ", "); +- builder.append("workItemQueueLength=3D"); +- builder.append(workItemQueueLength + ", "); +- builder.append("cacheEntryExceptions=3D"); +- builder.append(StringUtils.join(cacheEntryExceptions, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Element.ja= va b/pkg/analysis_server/tool/spec/generated/java/types/Element.java +deleted file mode 100644 +index 579ef3f0e9a..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/Element.java ++++ /dev/null +@@ -1,297 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * Information about an element (something that can be declared in code). +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class Element { +- +- public static final Element[] EMPTY_ARRAY =3D new Element[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(); +- +- private static final int ABSTRACT =3D 0x01; +- +- private static final int CONST =3D 0x02; +- +- private static final int FINAL =3D 0x04; +- +- private static final int TOP_LEVEL_STATIC =3D 0x08; +- +- private static final int PRIVATE =3D 0x10; +- +- private static final int DEPRECATED =3D 0x20; +- +- /** +- * The kind of the element. +- */ +- private final String kind; +- +- /** +- * The name of the element. This is typically used as the label in the = outline. +- */ +- private final String name; +- +- /** +- * The location of the name in the declaration of the element. +- */ +- private final Location location; +- +- /** +- * A bit-map containing the following flags: +- * +- * - 0x01 - set if the element is explicitly or implicitly abstract +- * - 0x02 - set if the element was declared to be =E2=80=98const=E2=80= =99 +- * - 0x04 - set if the element was declared to be =E2=80=98final=E2=80= =99 +- * - 0x08 - set if the element is a static member of a class or is a to= p-level function or field +- * - 0x10 - set if the element is private +- * - 0x20 - set if the element is deprecated +- */ +- private final int flags; +- +- /** +- * The parameter list for the element. If the element is not a method o= r function this field will +- * not be defined. If the element doesn't have parameters (e.g. getter)= , this field will not be +- * defined. If the element has zero parameters, this field will have a = value of "()". +- */ +- private final String parameters; +- +- /** +- * The return type of the element. If the element is not a method or fu= nction this field will not +- * be defined. If the element does not have a declared return type, thi= s field will contain an +- * empty string. +- */ +- private final String returnType; +- +- /** +- * The type parameter list for the element. If the element doesn't have= type parameters, this field +- * will not be defined. +- */ +- private final String typeParameters; +- +- /** +- * Constructor for {@link Element}. +- */ +- public Element(String kind, String name, Location location, int flags, = String parameters, String returnType, String typeParameters) { +- this.kind =3D kind; +- this.name =3D name; +- this.location =3D location; +- this.flags =3D flags; +- this.parameters =3D parameters; +- this.returnType =3D returnType; +- this.typeParameters =3D typeParameters; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof Element) { +- Element other =3D (Element) obj; +- return +- ObjectUtilities.equals(other.kind, kind) && +- ObjectUtilities.equals(other.name, name) && +- ObjectUtilities.equals(other.location, location) && +- other.flags =3D=3D flags && +- ObjectUtilities.equals(other.parameters, parameters) && +- ObjectUtilities.equals(other.returnType, returnType) && +- ObjectUtilities.equals(other.typeParameters, typeParameters); +- } +- return false; +- } +- +- public static Element fromJson(JsonObject jsonObject) { +- String kind =3D jsonObject.get("kind").getAsString(); +- String name =3D jsonObject.get("name").getAsString(); +- Location location =3D jsonObject.get("location") =3D=3D null ? null := Location.fromJson(jsonObject.get("location").getAsJsonObject()); +- int flags =3D jsonObject.get("flags").getAsInt(); +- String parameters =3D jsonObject.get("parameters") =3D=3D null ? null= : jsonObject.get("parameters").getAsString(); +- String returnType =3D jsonObject.get("returnType") =3D=3D null ? null= : jsonObject.get("returnType").getAsString(); +- String typeParameters =3D jsonObject.get("typeParameters") =3D=3D nul= l ? null : jsonObject.get("typeParameters").getAsString(); +- return new Element(kind, name, location, flags, parameters, returnTyp= e, typeParameters); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A bit-map containing the following flags: +- * +- * - 0x01 - set if the element is explicitly or implicitly abstract +- * - 0x02 - set if the element was declared to be =E2=80=98const=E2=80= =99 +- * - 0x04 - set if the element was declared to be =E2=80=98final=E2=80= =99 +- * - 0x08 - set if the element is a static member of a class or is a to= p-level function or field +- * - 0x10 - set if the element is private +- * - 0x20 - set if the element is deprecated +- */ +- public int getFlags() { +- return flags; +- } +- +- /** +- * The kind of the element. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The location of the name in the declaration of the element. +- */ +- public Location getLocation() { +- return location; +- } +- +- /** +- * The name of the element. This is typically used as the label in the = outline. +- */ +- public String getName() { +- return name; +- } +- +- /** +- * The parameter list for the element. If the element is not a method o= r function this field will +- * not be defined. If the element doesn't have parameters (e.g. getter)= , this field will not be +- * defined. If the element has zero parameters, this field will have a = value of "()". +- */ +- public String getParameters() { +- return parameters; +- } +- +- /** +- * The return type of the element. If the element is not a method or fu= nction this field will not +- * be defined. If the element does not have a declared return type, thi= s field will contain an +- * empty string. +- */ +- public String getReturnType() { +- return returnType; +- } +- +- /** +- * The type parameter list for the element. If the element doesn't have= type parameters, this field +- * will not be defined. +- */ +- public String getTypeParameters() { +- return typeParameters; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(kind); +- builder.append(name); +- builder.append(location); +- builder.append(flags); +- builder.append(parameters); +- builder.append(returnType); +- builder.append(typeParameters); +- return builder.toHashCode(); +- } +- +- public boolean isAbstract() { +- return (flags & ABSTRACT) !=3D 0; +- } +- +- public boolean isConst() { +- return (flags & CONST) !=3D 0; +- } +- +- public boolean isDeprecated() { +- return (flags & DEPRECATED) !=3D 0; +- } +- +- public boolean isFinal() { +- return (flags & FINAL) !=3D 0; +- } +- +- public boolean isPrivate() { +- return (flags & PRIVATE) !=3D 0; +- } +- +- public boolean isTopLevelOrStatic() { +- return (flags & TOP_LEVEL_STATIC) !=3D 0; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("kind", kind); +- jsonObject.addProperty("name", name); +- if (location !=3D null) { +- jsonObject.add("location", location.toJson()); +- } +- jsonObject.addProperty("flags", flags); +- if (parameters !=3D null) { +- jsonObject.addProperty("parameters", parameters); +- } +- if (returnType !=3D null) { +- jsonObject.addProperty("returnType", returnType); +- } +- if (typeParameters !=3D null) { +- jsonObject.addProperty("typeParameters", typeParameters); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("location=3D"); +- builder.append(location + ", "); +- builder.append("flags=3D"); +- builder.append(flags + ", "); +- builder.append("parameters=3D"); +- builder.append(parameters + ", "); +- builder.append("returnType=3D"); +- builder.append(returnType + ", "); +- builder.append("typeParameters=3D"); +- builder.append(typeParameters); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ElementKin= d.java b/pkg/analysis_server/tool/spec/generated/java/types/ElementKind.java +deleted file mode 100644 +index 0b9f43894e2..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ElementKind.java ++++ /dev/null +@@ -1,76 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of elements. +- * +- * @coverage dart.server.generated.types +- */ +-public class ElementKind { +- +- public static final String CLASS =3D "CLASS"; +- +- public static final String CLASS_TYPE_ALIAS =3D "CLASS_TYPE_ALIAS"; +- +- public static final String COMPILATION_UNIT =3D "COMPILATION_UNIT"; +- +- public static final String CONSTRUCTOR =3D "CONSTRUCTOR"; +- +- public static final String CONSTRUCTOR_INVOCATION =3D "CONSTRUCTOR_INVO= CATION"; +- +- public static final String ENUM =3D "ENUM"; +- +- public static final String ENUM_CONSTANT =3D "ENUM_CONSTANT"; +- +- public static final String FIELD =3D "FIELD"; +- +- public static final String FILE =3D "FILE"; +- +- public static final String FUNCTION =3D "FUNCTION"; +- +- public static final String FUNCTION_INVOCATION =3D "FUNCTION_INVOCATION= "; +- +- public static final String FUNCTION_TYPE_ALIAS =3D "FUNCTION_TYPE_ALIAS= "; +- +- public static final String GETTER =3D "GETTER"; +- +- public static final String LABEL =3D "LABEL"; +- +- public static final String LIBRARY =3D "LIBRARY"; +- +- public static final String LOCAL_VARIABLE =3D "LOCAL_VARIABLE"; +- +- public static final String METHOD =3D "METHOD"; +- +- public static final String PARAMETER =3D "PARAMETER"; +- +- public static final String PREFIX =3D "PREFIX"; +- +- public static final String SETTER =3D "SETTER"; +- +- public static final String TOP_LEVEL_VARIABLE =3D "TOP_LEVEL_VARIABLE"; +- +- public static final String TYPE_PARAMETER =3D "TYPE_PARAMETER"; +- +- public static final String UNIT_TEST_GROUP =3D "UNIT_TEST_GROUP"; +- +- public static final String UNIT_TEST_TEST =3D "UNIT_TEST_TEST"; +- +- public static final String UNKNOWN =3D "UNKNOWN"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Executable= File.java b/pkg/analysis_server/tool/spec/generated/java/types/ExecutableFi= le.java +deleted file mode 100644 +index 52f0c9580f3..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExecutableFile.ja= va ++++ /dev/null +@@ -1,134 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of an executable file. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ExecutableFile { +- +- public static final ExecutableFile[] EMPTY_ARRAY =3D new ExecutableFile= [0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayL= ist(); +- +- /** +- * The path of the executable file. +- */ +- private final String file; +- +- /** +- * The kind of the executable file. +- */ +- private final String kind; +- +- /** +- * Constructor for {@link ExecutableFile}. +- */ +- public ExecutableFile(String file, String kind) { +- this.file =3D file; +- this.kind =3D kind; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ExecutableFile) { +- ExecutableFile other =3D (ExecutableFile) obj; +- return +- ObjectUtilities.equals(other.file, file) && +- ObjectUtilities.equals(other.kind, kind); +- } +- return false; +- } +- +- public static ExecutableFile fromJson(JsonObject jsonObject) { +- String file =3D jsonObject.get("file").getAsString(); +- String kind =3D jsonObject.get("kind").getAsString(); +- return new ExecutableFile(file, kind); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(json= Array.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The path of the executable file. +- */ +- public String getFile() { +- return file; +- } +- +- /** +- * The kind of the executable file. +- */ +- public String getKind() { +- return kind; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(file); +- builder.append(kind); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("file", file); +- jsonObject.addProperty("kind", kind); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("file=3D"); +- builder.append(file + ", "); +- builder.append("kind=3D"); +- builder.append(kind); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Executable= Kind.java b/pkg/analysis_server/tool/spec/generated/java/types/ExecutableKi= nd.java +deleted file mode 100644 +index 407f36824e1..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExecutableKind.ja= va ++++ /dev/null +@@ -1,34 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of executable files. +- * +- * @coverage dart.server.generated.types +- */ +-public class ExecutableKind { +- +- public static final String CLIENT =3D "CLIENT"; +- +- public static final String EITHER =3D "EITHER"; +- +- public static final String NOT_EXECUTABLE =3D "NOT_EXECUTABLE"; +- +- public static final String SERVER =3D "SERVER"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ExecutionS= ervice.java b/pkg/analysis_server/tool/spec/generated/java/types/ExecutionS= ervice.java +deleted file mode 100644 +index 0e1b005c09f..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExecutionService.= java ++++ /dev/null +@@ -1,28 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the services provided by the execution domain. +- * +- * @coverage dart.server.generated.types +- */ +-public class ExecutionService { +- +- public static final String LAUNCH_DATA =3D "LAUNCH_DATA"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ExtractLoc= alVariableFeedback.java b/pkg/analysis_server/tool/spec/generated/java/type= s/ExtractLocalVariableFeedback.java +deleted file mode 100644 +index 8058954986b..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExtractLocalVaria= bleFeedback.java ++++ /dev/null +@@ -1,221 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ExtractLocalVariableFeedback extends RefactoringFeedback { +- +- public static final ExtractLocalVariableFeedback[] EMPTY_ARRAY =3D new = ExtractLocalVariableFeedback[0]; +- +- public static final List EMPTY_LIST =3D L= ists.newArrayList(); +- +- /** +- * The offsets of the expressions that cover the specified selection, f= rom the down most to the up +- * most. +- */ +- private final int[] coveringExpressionOffsets; +- +- /** +- * The lengths of the expressions that cover the specified selection, f= rom the down most to the up +- * most. +- */ +- private final int[] coveringExpressionLengths; +- +- /** +- * The proposed names for the local variable. +- */ +- private final List names; +- +- /** +- * The offsets of the expressions that would be replaced by a reference= to the variable. +- */ +- private final int[] offsets; +- +- /** +- * The lengths of the expressions that would be replaced by a reference= to the variable. The +- * lengths correspond to the offsets. In other words, for a given expre= ssion, if the offset of that +- * expression is offsets[i], then the length of that expression is leng= ths[i]. +- */ +- private final int[] lengths; +- +- /** +- * Constructor for {@link ExtractLocalVariableFeedback}. +- */ +- public ExtractLocalVariableFeedback(int[] coveringExpressionOffsets, in= t[] coveringExpressionLengths, List names, int[] offsets, int[] len= gths) { +- this.coveringExpressionOffsets =3D coveringExpressionOffsets; +- this.coveringExpressionLengths =3D coveringExpressionLengths; +- this.names =3D names; +- this.offsets =3D offsets; +- this.lengths =3D lengths; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ExtractLocalVariableFeedback) { +- ExtractLocalVariableFeedback other =3D (ExtractLocalVariableFeedbac= k) obj; +- return +- Arrays.equals(other.coveringExpressionOffsets, coveringExpression= Offsets) && +- Arrays.equals(other.coveringExpressionLengths, coveringExpression= Lengths) && +- ObjectUtilities.equals(other.names, names) && +- Arrays.equals(other.offsets, offsets) && +- Arrays.equals(other.lengths, lengths); +- } +- return false; +- } +- +- public static ExtractLocalVariableFeedback fromJson(JsonObject jsonObje= ct) { +- int[] coveringExpressionOffsets =3D jsonObject.get("coveringExpressio= nOffsets") =3D=3D null ? null : JsonUtilities.decodeIntArray(jsonObject.get= ("coveringExpressionOffsets").getAsJsonArray()); +- int[] coveringExpressionLengths =3D jsonObject.get("coveringExpressio= nLengths") =3D=3D null ? null : JsonUtilities.decodeIntArray(jsonObject.get= ("coveringExpressionLengths").getAsJsonArray()); +- List names =3D JsonUtilities.decodeStringList(jsonObject.get(= "names").getAsJsonArray()); +- int[] offsets =3D JsonUtilities.decodeIntArray(jsonObject.get("offset= s").getAsJsonArray()); +- int[] lengths =3D JsonUtilities.decodeIntArray(jsonObject.get("length= s").getAsJsonArray()); +- return new ExtractLocalVariableFeedback(coveringExpressionOffsets, co= veringExpressionLengths, names, offsets, lengths); +- } +- +- public static List fromJsonArray(JsonArra= y jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The lengths of the expressions that cover the specified selection, f= rom the down most to the up +- * most. +- */ +- public int[] getCoveringExpressionLengths() { +- return coveringExpressionLengths; +- } +- +- /** +- * The offsets of the expressions that cover the specified selection, f= rom the down most to the up +- * most. +- */ +- public int[] getCoveringExpressionOffsets() { +- return coveringExpressionOffsets; +- } +- +- /** +- * The lengths of the expressions that would be replaced by a reference= to the variable. The +- * lengths correspond to the offsets. In other words, for a given expre= ssion, if the offset of that +- * expression is offsets[i], then the length of that expression is leng= ths[i]. +- */ +- public int[] getLengths() { +- return lengths; +- } +- +- /** +- * The proposed names for the local variable. +- */ +- public List getNames() { +- return names; +- } +- +- /** +- * The offsets of the expressions that would be replaced by a reference= to the variable. +- */ +- public int[] getOffsets() { +- return offsets; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(coveringExpressionOffsets); +- builder.append(coveringExpressionLengths); +- builder.append(names); +- builder.append(offsets); +- builder.append(lengths); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- if (coveringExpressionOffsets !=3D null) { +- JsonArray jsonArrayCoveringExpressionOffsets =3D new JsonArray(); +- for (int elt : coveringExpressionOffsets) { +- jsonArrayCoveringExpressionOffsets.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("coveringExpressionOffsets", jsonArrayCoveringExpres= sionOffsets); +- } +- if (coveringExpressionLengths !=3D null) { +- JsonArray jsonArrayCoveringExpressionLengths =3D new JsonArray(); +- for (int elt : coveringExpressionLengths) { +- jsonArrayCoveringExpressionLengths.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("coveringExpressionLengths", jsonArrayCoveringExpres= sionLengths); +- } +- JsonArray jsonArrayNames =3D new JsonArray(); +- for (String elt : names) { +- jsonArrayNames.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("names", jsonArrayNames); +- JsonArray jsonArrayOffsets =3D new JsonArray(); +- for (int elt : offsets) { +- jsonArrayOffsets.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("offsets", jsonArrayOffsets); +- JsonArray jsonArrayLengths =3D new JsonArray(); +- for (int elt : lengths) { +- jsonArrayLengths.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("lengths", jsonArrayLengths); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("coveringExpressionOffsets=3D"); +- builder.append(StringUtils.join(coveringExpressionOffsets, ", ") + ",= "); +- builder.append("coveringExpressionLengths=3D"); +- builder.append(StringUtils.join(coveringExpressionLengths, ", ") + ",= "); +- builder.append("names=3D"); +- builder.append(StringUtils.join(names, ", ") + ", "); +- builder.append("offsets=3D"); +- builder.append(StringUtils.join(offsets, ", ") + ", "); +- builder.append("lengths=3D"); +- builder.append(StringUtils.join(lengths, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ExtractLoc= alVariableOptions.java b/pkg/analysis_server/tool/spec/generated/java/types= /ExtractLocalVariableOptions.java +deleted file mode 100644 +index c0b9756aa3e..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExtractLocalVaria= bleOptions.java ++++ /dev/null +@@ -1,152 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ExtractLocalVariableOptions extends RefactoringOptions { +- +- public static final ExtractLocalVariableOptions[] EMPTY_ARRAY =3D new E= xtractLocalVariableOptions[0]; +- +- public static final List EMPTY_LIST =3D Li= sts.newArrayList(); +- +- /** +- * The name that the local variable should be given. +- */ +- private String name; +- +- /** +- * True if all occurrences of the expression within the scope in which = the variable will be defined +- * should be replaced by a reference to the local variable. The express= ion used to initiate the +- * refactoring will always be replaced. +- */ +- private boolean extractAll; +- +- /** +- * Constructor for {@link ExtractLocalVariableOptions}. +- */ +- public ExtractLocalVariableOptions(String name, boolean extractAll) { +- this.name =3D name; +- this.extractAll =3D extractAll; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ExtractLocalVariableOptions) { +- ExtractLocalVariableOptions other =3D (ExtractLocalVariableOptions)= obj; +- return +- ObjectUtilities.equals(other.name, name) && +- other.extractAll =3D=3D extractAll; +- } +- return false; +- } +- +- public static ExtractLocalVariableOptions fromJson(JsonObject jsonObjec= t) { +- String name =3D jsonObject.get("name").getAsString(); +- boolean extractAll =3D jsonObject.get("extractAll").getAsBoolean(); +- return new ExtractLocalVariableOptions(name, extractAll); +- } +- +- public static List fromJsonArray(JsonArray= jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * True if all occurrences of the expression within the scope in which = the variable will be defined +- * should be replaced by a reference to the local variable. The express= ion used to initiate the +- * refactoring will always be replaced. +- */ +- public boolean extractAll() { +- return extractAll; +- } +- +- /** +- * The name that the local variable should be given. +- */ +- public String getName() { +- return name; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(name); +- builder.append(extractAll); +- return builder.toHashCode(); +- } +- +- /** +- * True if all occurrences of the expression within the scope in which = the variable will be defined +- * should be replaced by a reference to the local variable. The express= ion used to initiate the +- * refactoring will always be replaced. +- */ +- public void setExtractAll(boolean extractAll) { +- this.extractAll =3D extractAll; +- } +- +- /** +- * The name that the local variable should be given. +- */ +- public void setName(String name) { +- this.name =3D name; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("name", name); +- jsonObject.addProperty("extractAll", extractAll); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("extractAll=3D"); +- builder.append(extractAll); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ExtractMet= hodFeedback.java b/pkg/analysis_server/tool/spec/generated/java/types/Extra= ctMethodFeedback.java +deleted file mode 100644 +index 6bb32fe8155..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExtractMethodFeed= back.java ++++ /dev/null +@@ -1,272 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ExtractMethodFeedback extends RefactoringFeedback { +- +- public static final ExtractMethodFeedback[] EMPTY_ARRAY =3D new Extract= MethodFeedback[0]; +- +- public static final List EMPTY_LIST =3D Lists.ne= wArrayList(); +- +- /** +- * The offset to the beginning of the expression or statements that wil= l be extracted. +- */ +- private final int offset; +- +- /** +- * The length of the expression or statements that will be extracted. +- */ +- private final int length; +- +- /** +- * The proposed return type for the method. If the returned element doe= s not have a declared return +- * type, this field will contain an empty string. +- */ +- private final String returnType; +- +- /** +- * The proposed names for the method. +- */ +- private final List names; +- +- /** +- * True if a getter could be created rather than a method. +- */ +- private final boolean canCreateGetter; +- +- /** +- * The proposed parameters for the method. +- */ +- private final List parameters; +- +- /** +- * The offsets of the expressions or statements that would be replaced = by an invocation of the +- * method. +- */ +- private final int[] offsets; +- +- /** +- * The lengths of the expressions or statements that would be replaced = by an invocation of the +- * method. The lengths correspond to the offsets. In other words, for a= given expression (or block +- * of statements), if the offset of that expression is offsets[i], then= the length of that +- * expression is lengths[i]. +- */ +- private final int[] lengths; +- +- /** +- * Constructor for {@link ExtractMethodFeedback}. +- */ +- public ExtractMethodFeedback(int offset, int length, String returnType,= List names, boolean canCreateGetter, List parameters, int[] offsets, int[] lengths) { +- this.offset =3D offset; +- this.length =3D length; +- this.returnType =3D returnType; +- this.names =3D names; +- this.canCreateGetter =3D canCreateGetter; +- this.parameters =3D parameters; +- this.offsets =3D offsets; +- this.lengths =3D lengths; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ExtractMethodFeedback) { +- ExtractMethodFeedback other =3D (ExtractMethodFeedback) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.returnType, returnType) && +- ObjectUtilities.equals(other.names, names) && +- other.canCreateGetter =3D=3D canCreateGetter && +- ObjectUtilities.equals(other.parameters, parameters) && +- Arrays.equals(other.offsets, offsets) && +- Arrays.equals(other.lengths, lengths); +- } +- return false; +- } +- +- public static ExtractMethodFeedback fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- String returnType =3D jsonObject.get("returnType").getAsString(); +- List names =3D JsonUtilities.decodeStringList(jsonObject.get(= "names").getAsJsonArray()); +- boolean canCreateGetter =3D jsonObject.get("canCreateGetter").getAsBo= olean(); +- List parameters =3D RefactoringMethodPara= meter.fromJsonArray(jsonObject.get("parameters").getAsJsonArray()); +- int[] offsets =3D JsonUtilities.decodeIntArray(jsonObject.get("offset= s").getAsJsonArray()); +- int[] lengths =3D JsonUtilities.decodeIntArray(jsonObject.get("length= s").getAsJsonArray()); +- return new ExtractMethodFeedback(offset, length, returnType, names, c= anCreateGetter, parameters, offsets, lengths); +- } +- +- public static List fromJsonArray(JsonArray jsonA= rray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * True if a getter could be created rather than a method. +- */ +- public boolean canCreateGetter() { +- return canCreateGetter; +- } +- +- /** +- * The length of the expression or statements that will be extracted. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The lengths of the expressions or statements that would be replaced = by an invocation of the +- * method. The lengths correspond to the offsets. In other words, for a= given expression (or block +- * of statements), if the offset of that expression is offsets[i], then= the length of that +- * expression is lengths[i]. +- */ +- public int[] getLengths() { +- return lengths; +- } +- +- /** +- * The proposed names for the method. +- */ +- public List getNames() { +- return names; +- } +- +- /** +- * The offset to the beginning of the expression or statements that wil= l be extracted. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The offsets of the expressions or statements that would be replaced = by an invocation of the +- * method. +- */ +- public int[] getOffsets() { +- return offsets; +- } +- +- /** +- * The proposed parameters for the method. +- */ +- public List getParameters() { +- return parameters; +- } +- +- /** +- * The proposed return type for the method. If the returned element doe= s not have a declared return +- * type, this field will contain an empty string. +- */ +- public String getReturnType() { +- return returnType; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(returnType); +- builder.append(names); +- builder.append(canCreateGetter); +- builder.append(parameters); +- builder.append(offsets); +- builder.append(lengths); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- jsonObject.addProperty("returnType", returnType); +- JsonArray jsonArrayNames =3D new JsonArray(); +- for (String elt : names) { +- jsonArrayNames.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("names", jsonArrayNames); +- jsonObject.addProperty("canCreateGetter", canCreateGetter); +- JsonArray jsonArrayParameters =3D new JsonArray(); +- for (RefactoringMethodParameter elt : parameters) { +- jsonArrayParameters.add(elt.toJson()); +- } +- jsonObject.add("parameters", jsonArrayParameters); +- JsonArray jsonArrayOffsets =3D new JsonArray(); +- for (int elt : offsets) { +- jsonArrayOffsets.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("offsets", jsonArrayOffsets); +- JsonArray jsonArrayLengths =3D new JsonArray(); +- for (int elt : lengths) { +- jsonArrayLengths.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("lengths", jsonArrayLengths); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("returnType=3D"); +- builder.append(returnType + ", "); +- builder.append("names=3D"); +- builder.append(StringUtils.join(names, ", ") + ", "); +- builder.append("canCreateGetter=3D"); +- builder.append(canCreateGetter + ", "); +- builder.append("parameters=3D"); +- builder.append(StringUtils.join(parameters, ", ") + ", "); +- builder.append("offsets=3D"); +- builder.append(StringUtils.join(offsets, ", ") + ", "); +- builder.append("lengths=3D"); +- builder.append(StringUtils.join(lengths, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ExtractMet= hodOptions.java b/pkg/analysis_server/tool/spec/generated/java/types/Extrac= tMethodOptions.java +deleted file mode 100644 +index 1e71e435763..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ExtractMethodOpti= ons.java ++++ /dev/null +@@ -1,261 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ExtractMethodOptions extends RefactoringOptions { +- +- public static final ExtractMethodOptions[] EMPTY_ARRAY =3D new ExtractM= ethodOptions[0]; +- +- public static final List EMPTY_LIST =3D Lists.new= ArrayList(); +- +- /** +- * The return type that should be defined for the method. +- */ +- private String returnType; +- +- /** +- * True if a getter should be created rather than a method. It is an er= ror if this field is true +- * and the list of parameters is non-empty. +- */ +- private boolean createGetter; +- +- /** +- * The name that the method should be given. +- */ +- private String name; +- +- /** +- * The parameters that should be defined for the method. +- * +- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL= parameter. It is an error +- * if a REQUIRED or POSITIONAL parameter follows a NAMED parameter. +- * +- * - To change the order and/or update proposed parameters, add paramet= ers with the same +- * identifiers as proposed. +- * - To add new parameters, omit their identifier. +- * - To remove some parameters, omit them in this list. +- */ +- private List parameters; +- +- /** +- * True if all occurrences of the expression or statements should be re= placed by an invocation of +- * the method. The expression or statements used to initiate the refact= oring will always be +- * replaced. +- */ +- private boolean extractAll; +- +- /** +- * Constructor for {@link ExtractMethodOptions}. +- */ +- public ExtractMethodOptions(String returnType, boolean createGetter, St= ring name, List parameters, boolean extractAll)= { +- this.returnType =3D returnType; +- this.createGetter =3D createGetter; +- this.name =3D name; +- this.parameters =3D parameters; +- this.extractAll =3D extractAll; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ExtractMethodOptions) { +- ExtractMethodOptions other =3D (ExtractMethodOptions) obj; +- return +- ObjectUtilities.equals(other.returnType, returnType) && +- other.createGetter =3D=3D createGetter && +- ObjectUtilities.equals(other.name, name) && +- ObjectUtilities.equals(other.parameters, parameters) && +- other.extractAll =3D=3D extractAll; +- } +- return false; +- } +- +- public static ExtractMethodOptions fromJson(JsonObject jsonObject) { +- String returnType =3D jsonObject.get("returnType").getAsString(); +- boolean createGetter =3D jsonObject.get("createGetter").getAsBoolean(= ); +- String name =3D jsonObject.get("name").getAsString(); +- List parameters =3D RefactoringMethodPara= meter.fromJsonArray(jsonObject.get("parameters").getAsJsonArray()); +- boolean extractAll =3D jsonObject.get("extractAll").getAsBoolean(); +- return new ExtractMethodOptions(returnType, createGetter, name, param= eters, extractAll); +- } +- +- public static List fromJsonArray(JsonArray jsonAr= ray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * True if a getter should be created rather than a method. It is an er= ror if this field is true +- * and the list of parameters is non-empty. +- */ +- public boolean createGetter() { +- return createGetter; +- } +- +- /** +- * True if all occurrences of the expression or statements should be re= placed by an invocation of +- * the method. The expression or statements used to initiate the refact= oring will always be +- * replaced. +- */ +- public boolean extractAll() { +- return extractAll; +- } +- +- /** +- * The name that the method should be given. +- */ +- public String getName() { +- return name; +- } +- +- /** +- * The parameters that should be defined for the method. +- * +- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL= parameter. It is an error +- * if a REQUIRED or POSITIONAL parameter follows a NAMED parameter. +- * +- * - To change the order and/or update proposed parameters, add paramet= ers with the same +- * identifiers as proposed. +- * - To add new parameters, omit their identifier. +- * - To remove some parameters, omit them in this list. +- */ +- public List getParameters() { +- return parameters; +- } +- +- /** +- * The return type that should be defined for the method. +- */ +- public String getReturnType() { +- return returnType; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(returnType); +- builder.append(createGetter); +- builder.append(name); +- builder.append(parameters); +- builder.append(extractAll); +- return builder.toHashCode(); +- } +- +- /** +- * True if a getter should be created rather than a method. It is an er= ror if this field is true +- * and the list of parameters is non-empty. +- */ +- public void setCreateGetter(boolean createGetter) { +- this.createGetter =3D createGetter; +- } +- +- /** +- * True if all occurrences of the expression or statements should be re= placed by an invocation of +- * the method. The expression or statements used to initiate the refact= oring will always be +- * replaced. +- */ +- public void setExtractAll(boolean extractAll) { +- this.extractAll =3D extractAll; +- } +- +- /** +- * The name that the method should be given. +- */ +- public void setName(String name) { +- this.name =3D name; +- } +- +- /** +- * The parameters that should be defined for the method. +- * +- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL= parameter. It is an error +- * if a REQUIRED or POSITIONAL parameter follows a NAMED parameter. +- * +- * - To change the order and/or update proposed parameters, add paramet= ers with the same +- * identifiers as proposed. +- * - To add new parameters, omit their identifier. +- * - To remove some parameters, omit them in this list. +- */ +- public void setParameters(List parameters) { +- this.parameters =3D parameters; +- } +- +- /** +- * The return type that should be defined for the method. +- */ +- public void setReturnType(String returnType) { +- this.returnType =3D returnType; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("returnType", returnType); +- jsonObject.addProperty("createGetter", createGetter); +- jsonObject.addProperty("name", name); +- JsonArray jsonArrayParameters =3D new JsonArray(); +- for (RefactoringMethodParameter elt : parameters) { +- jsonArrayParameters.add(elt.toJson()); +- } +- jsonObject.add("parameters", jsonArrayParameters); +- jsonObject.addProperty("extractAll", extractAll); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("returnType=3D"); +- builder.append(returnType + ", "); +- builder.append("createGetter=3D"); +- builder.append(createGetter + ", "); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("parameters=3D"); +- builder.append(StringUtils.join(parameters, ", ") + ", "); +- builder.append("extractAll=3D"); +- builder.append(extractAll); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/FileKind.j= ava b/pkg/analysis_server/tool/spec/generated/java/types/FileKind.java +deleted file mode 100644 +index 827531094da..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/FileKind.java ++++ /dev/null +@@ -1,30 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of files. +- * +- * @coverage dart.server.generated.types +- */ +-public class FileKind { +- +- public static final String LIBRARY =3D "LIBRARY"; +- +- public static final String PART =3D "PART"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/FoldingKin= d.java b/pkg/analysis_server/tool/spec/generated/java/types/FoldingKind.java +deleted file mode 100644 +index 4a281de9759..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/FoldingKind.java ++++ /dev/null +@@ -1,36 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of folding regions. +- * +- * @coverage dart.server.generated.types +- */ +-public class FoldingKind { +- +- public static final String COMMENT =3D "COMMENT"; +- +- public static final String CLASS_MEMBER =3D "CLASS_MEMBER"; +- +- public static final String DIRECTIVES =3D "DIRECTIVES"; +- +- public static final String DOCUMENTATION_COMMENT =3D "DOCUMENTATION_COM= MENT"; +- +- public static final String TOP_LEVEL_DECLARATION =3D "TOP_LEVEL_DECLARA= TION"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/FoldingReg= ion.java b/pkg/analysis_server/tool/spec/generated/java/types/FoldingRegion= .java +deleted file mode 100644 +index ebad0e79ca6..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/FoldingRegion.java ++++ /dev/null +@@ -1,153 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a region that can be folded. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class FoldingRegion { +- +- public static final FoldingRegion[] EMPTY_ARRAY =3D new FoldingRegion[0= ]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLi= st(); +- +- /** +- * The kind of the region. +- */ +- private final String kind; +- +- /** +- * The offset of the region to be folded. +- */ +- private final int offset; +- +- /** +- * The length of the region to be folded. +- */ +- private final int length; +- +- /** +- * Constructor for {@link FoldingRegion}. +- */ +- public FoldingRegion(String kind, int offset, int length) { +- this.kind =3D kind; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof FoldingRegion) { +- FoldingRegion other =3D (FoldingRegion) obj; +- return +- ObjectUtilities.equals(other.kind, kind) && +- other.offset =3D=3D offset && +- other.length =3D=3D length; +- } +- return false; +- } +- +- public static FoldingRegion fromJson(JsonObject jsonObject) { +- String kind =3D jsonObject.get("kind").getAsString(); +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- return new FoldingRegion(kind, offset, length); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonAr= ray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The kind of the region. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The length of the region to be folded. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the region to be folded. +- */ +- public int getOffset() { +- return offset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(kind); +- builder.append(offset); +- builder.append(length); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("kind", kind); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/GeneralAna= lysisService.java b/pkg/analysis_server/tool/spec/generated/java/types/Gene= ralAnalysisService.java +deleted file mode 100644 +index 80975fa5081..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/GeneralAnalysisSe= rvice.java ++++ /dev/null +@@ -1,29 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the services provided by the analysis domain that ar= e general in nature (that +- * is, are not specific to some list of files). +- * +- * @coverage dart.server.generated.types +- */ +-public class GeneralAnalysisService { +- +- public static final String ANALYZED_FILES =3D "ANALYZED_FILES"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/HighlightR= egion.java b/pkg/analysis_server/tool/spec/generated/java/types/HighlightRe= gion.java +deleted file mode 100644 +index ebbd41056bc..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/HighlightRegion.j= ava ++++ /dev/null +@@ -1,157 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a region that could have special highlighting associa= ted with it. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class HighlightRegion { +- +- public static final HighlightRegion[] EMPTY_ARRAY =3D new HighlightRegi= on[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArray= List(); +- +- /** +- * The type of highlight associated with the region. +- */ +- private final String type; +- +- /** +- * The offset of the region to be highlighted. +- */ +- private final int offset; +- +- /** +- * The length of the region to be highlighted. +- */ +- private final int length; +- +- /** +- * Constructor for {@link HighlightRegion}. +- */ +- public HighlightRegion(String type, int offset, int length) { +- this.type =3D type; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- public boolean containsInclusive(int x) { +- return offset <=3D x && x <=3D offset + length; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof HighlightRegion) { +- HighlightRegion other =3D (HighlightRegion) obj; +- return +- ObjectUtilities.equals(other.type, type) && +- other.offset =3D=3D offset && +- other.length =3D=3D length; +- } +- return false; +- } +- +- public static HighlightRegion fromJson(JsonObject jsonObject) { +- String type =3D jsonObject.get("type").getAsString(); +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- return new HighlightRegion(type, offset, length); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(js= onArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The length of the region to be highlighted. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the region to be highlighted. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The type of highlight associated with the region. +- */ +- public String getType() { +- return type; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(type); +- builder.append(offset); +- builder.append(length); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("type", type); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("type=3D"); +- builder.append(type + ", "); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/HighlightR= egionType.java b/pkg/analysis_server/tool/spec/generated/java/types/Highlig= htRegionType.java +deleted file mode 100644 +index 15d1373a801..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/HighlightRegionTy= pe.java ++++ /dev/null +@@ -1,319 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of highlighting that can be applied to fil= es. +- * +- * @coverage dart.server.generated.types +- */ +-public class HighlightRegionType { +- +- public static final String ANNOTATION =3D "ANNOTATION"; +- +- public static final String BUILT_IN =3D "BUILT_IN"; +- +- public static final String CLASS =3D "CLASS"; +- +- public static final String COMMENT_BLOCK =3D "COMMENT_BLOCK"; +- +- public static final String COMMENT_DOCUMENTATION =3D "COMMENT_DOCUMENTA= TION"; +- +- public static final String COMMENT_END_OF_LINE =3D "COMMENT_END_OF_LINE= "; +- +- public static final String CONSTRUCTOR =3D "CONSTRUCTOR"; +- +- public static final String DIRECTIVE =3D "DIRECTIVE"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String DYNAMIC_TYPE =3D "DYNAMIC_TYPE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String DYNAMIC_LOCAL_VARIABLE_DECLARATION =3D "DYNA= MIC_LOCAL_VARIABLE_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String DYNAMIC_LOCAL_VARIABLE_REFERENCE =3D "DYNAMI= C_LOCAL_VARIABLE_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String DYNAMIC_PARAMETER_DECLARATION =3D "DYNAMIC_P= ARAMETER_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String DYNAMIC_PARAMETER_REFERENCE =3D "DYNAMIC_PAR= AMETER_REFERENCE"; +- +- public static final String ENUM =3D "ENUM"; +- +- public static final String ENUM_CONSTANT =3D "ENUM_CONSTANT"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String FIELD =3D "FIELD"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String FIELD_STATIC =3D "FIELD_STATIC"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String FUNCTION =3D "FUNCTION"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String FUNCTION_DECLARATION =3D "FUNCTION_DECLARATI= ON"; +- +- public static final String FUNCTION_TYPE_ALIAS =3D "FUNCTION_TYPE_ALIAS= "; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String GETTER_DECLARATION =3D "GETTER_DECLARATION"; +- +- public static final String IDENTIFIER_DEFAULT =3D "IDENTIFIER_DEFAULT"; +- +- public static final String IMPORT_PREFIX =3D "IMPORT_PREFIX"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_FIELD_DECLARATION =3D "INSTANCE_FIE= LD_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_FIELD_REFERENCE =3D "INSTANCE_FIELD= _REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_GETTER_DECLARATION =3D "INSTANCE_GE= TTER_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_GETTER_REFERENCE =3D "INSTANCE_GETT= ER_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_METHOD_DECLARATION =3D "INSTANCE_ME= THOD_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_METHOD_REFERENCE =3D "INSTANCE_METH= OD_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_SETTER_DECLARATION =3D "INSTANCE_SE= TTER_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INSTANCE_SETTER_REFERENCE =3D "INSTANCE_SETT= ER_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String INVALID_STRING_ESCAPE =3D "INVALID_STRING_ES= CAPE"; +- +- public static final String KEYWORD =3D "KEYWORD"; +- +- public static final String LABEL =3D "LABEL"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String LIBRARY_NAME =3D "LIBRARY_NAME"; +- +- public static final String LITERAL_BOOLEAN =3D "LITERAL_BOOLEAN"; +- +- public static final String LITERAL_DOUBLE =3D "LITERAL_DOUBLE"; +- +- public static final String LITERAL_INTEGER =3D "LITERAL_INTEGER"; +- +- public static final String LITERAL_LIST =3D "LITERAL_LIST"; +- +- public static final String LITERAL_MAP =3D "LITERAL_MAP"; +- +- public static final String LITERAL_STRING =3D "LITERAL_STRING"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String LOCAL_FUNCTION_DECLARATION =3D "LOCAL_FUNCTI= ON_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String LOCAL_FUNCTION_REFERENCE =3D "LOCAL_FUNCTION= _REFERENCE"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String LOCAL_VARIABLE =3D "LOCAL_VARIABLE"; +- +- public static final String LOCAL_VARIABLE_DECLARATION =3D "LOCAL_VARIAB= LE_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String LOCAL_VARIABLE_REFERENCE =3D "LOCAL_VARIABLE= _REFERENCE"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String METHOD =3D "METHOD"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String METHOD_DECLARATION =3D "METHOD_DECLARATION"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String METHOD_DECLARATION_STATIC =3D "METHOD_DECLAR= ATION_STATIC"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String METHOD_STATIC =3D "METHOD_STATIC"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String PARAMETER =3D "PARAMETER"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String SETTER_DECLARATION =3D "SETTER_DECLARATION"; +- +- /** +- * Only for version 1 of highlight. +- */ +- public static final String TOP_LEVEL_VARIABLE =3D "TOP_LEVEL_VARIABLE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String PARAMETER_DECLARATION =3D "PARAMETER_DECLARA= TION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String PARAMETER_REFERENCE =3D "PARAMETER_REFERENCE= "; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_FIELD_DECLARATION =3D "STATIC_FIELD_D= ECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_GETTER_DECLARATION =3D "STATIC_GETTER= _DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_GETTER_REFERENCE =3D "STATIC_GETTER_R= EFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_METHOD_DECLARATION =3D "STATIC_METHOD= _DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_METHOD_REFERENCE =3D "STATIC_METHOD_R= EFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_SETTER_DECLARATION =3D "STATIC_SETTER= _DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String STATIC_SETTER_REFERENCE =3D "STATIC_SETTER_R= EFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_FUNCTION_DECLARATION =3D "TOP_LEVE= L_FUNCTION_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_FUNCTION_REFERENCE =3D "TOP_LEVEL_= FUNCTION_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_GETTER_DECLARATION =3D "TOP_LEVEL_= GETTER_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_GETTER_REFERENCE =3D "TOP_LEVEL_GE= TTER_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_SETTER_DECLARATION =3D "TOP_LEVEL_= SETTER_DECLARATION"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_SETTER_REFERENCE =3D "TOP_LEVEL_SE= TTER_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String TOP_LEVEL_VARIABLE_DECLARATION =3D "TOP_LEVE= L_VARIABLE_DECLARATION"; +- +- public static final String TYPE_NAME_DYNAMIC =3D "TYPE_NAME_DYNAMIC"; +- +- public static final String TYPE_PARAMETER =3D "TYPE_PARAMETER"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String UNRESOLVED_INSTANCE_MEMBER_REFERENCE =3D "UN= RESOLVED_INSTANCE_MEMBER_REFERENCE"; +- +- /** +- * Only for version 2 of highlight. +- */ +- public static final String VALID_STRING_ESCAPE =3D "VALID_STRING_ESCAPE= "; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/HoverInfor= mation.java b/pkg/analysis_server/tool/spec/generated/java/types/HoverInfor= mation.java +deleted file mode 100644 +index b9ca9819825..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/HoverInformation.= java ++++ /dev/null +@@ -1,372 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * The hover information associated with a specific location. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class HoverInformation { +- +- public static final HoverInformation[] EMPTY_ARRAY =3D new HoverInforma= tion[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArra= yList(); +- +- /** +- * The offset of the range of characters that encompasses the cursor po= sition and has the same +- * hover information as the cursor position. +- */ +- private final int offset; +- +- /** +- * The length of the range of characters that encompasses the cursor po= sition and has the same +- * hover information as the cursor position. +- */ +- private final int length; +- +- /** +- * The path to the defining compilation unit of the library in which th= e referenced element is +- * declared. This data is omitted if there is no referenced element, or= if the element is declared +- * inside an HTML file. +- */ +- private final String containingLibraryPath; +- +- /** +- * The name of the library in which the referenced element is declared.= This data is omitted if +- * there is no referenced element, or if the element is declared inside= an HTML file. +- */ +- private final String containingLibraryName; +- +- /** +- * A human-readable description of the class declaring the element bein= g referenced. This data is +- * omitted if there is no referenced element, or if the element is not = a class member. +- */ +- private final String containingClassDescription; +- +- /** +- * The dartdoc associated with the referenced element. Other than the r= emoval of the comment +- * delimiters, including leading asterisks in the case of a block comme= nt, the dartdoc is +- * unprocessed markdown. This data is omitted if there is no referenced= element, or if the element +- * has no dartdoc. +- */ +- private final String dartdoc; +- +- /** +- * A human-readable description of the element being referenced. This d= ata is omitted if there is +- * no referenced element. +- */ +- private final String elementDescription; +- +- /** +- * A human-readable description of the kind of element being referenced= (such as "class" or +- * "function type alias"). This data is omitted if there is no referenc= ed element. +- */ +- private final String elementKind; +- +- /** +- * True if the referenced element is deprecated. +- */ +- private final Boolean isDeprecated; +- +- /** +- * A human-readable description of the parameter corresponding to the e= xpression being hovered +- * over. This data is omitted if the location is not in an argument to = a function. +- */ +- private final String parameter; +- +- /** +- * The name of the propagated type of the expression. This data is omit= ted if the location does not +- * correspond to an expression or if there is no propagated type inform= ation. +- */ +- private final String propagatedType; +- +- /** +- * The name of the static type of the expression. This data is omitted = if the location does not +- * correspond to an expression. +- */ +- private final String staticType; +- +- /** +- * Constructor for {@link HoverInformation}. +- */ +- public HoverInformation(int offset, int length, String containingLibrar= yPath, String containingLibraryName, String containingClassDescription, Str= ing dartdoc, String elementDescription, String elementKind, Boolean isDepre= cated, String parameter, String propagatedType, String staticType) { +- this.offset =3D offset; +- this.length =3D length; +- this.containingLibraryPath =3D containingLibraryPath; +- this.containingLibraryName =3D containingLibraryName; +- this.containingClassDescription =3D containingClassDescription; +- this.dartdoc =3D dartdoc; +- this.elementDescription =3D elementDescription; +- this.elementKind =3D elementKind; +- this.isDeprecated =3D isDeprecated; +- this.parameter =3D parameter; +- this.propagatedType =3D propagatedType; +- this.staticType =3D staticType; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof HoverInformation) { +- HoverInformation other =3D (HoverInformation) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.containingLibraryPath, containingLib= raryPath) && +- ObjectUtilities.equals(other.containingLibraryName, containingLib= raryName) && +- ObjectUtilities.equals(other.containingClassDescription, containi= ngClassDescription) && +- ObjectUtilities.equals(other.dartdoc, dartdoc) && +- ObjectUtilities.equals(other.elementDescription, elementDescripti= on) && +- ObjectUtilities.equals(other.elementKind, elementKind) && +- ObjectUtilities.equals(other.isDeprecated, isDeprecated) && +- ObjectUtilities.equals(other.parameter, parameter) && +- ObjectUtilities.equals(other.propagatedType, propagatedType) && +- ObjectUtilities.equals(other.staticType, staticType); +- } +- return false; +- } +- +- public static HoverInformation fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- String containingLibraryPath =3D jsonObject.get("containingLibraryPat= h") =3D=3D null ? null : jsonObject.get("containingLibraryPath").getAsStrin= g(); +- String containingLibraryName =3D jsonObject.get("containingLibraryNam= e") =3D=3D null ? null : jsonObject.get("containingLibraryName").getAsStrin= g(); +- String containingClassDescription =3D jsonObject.get("containingClass= Description") =3D=3D null ? null : jsonObject.get("containingClassDescripti= on").getAsString(); +- String dartdoc =3D jsonObject.get("dartdoc") =3D=3D null ? null : jso= nObject.get("dartdoc").getAsString(); +- String elementDescription =3D jsonObject.get("elementDescription") = =3D=3D null ? null : jsonObject.get("elementDescription").getAsString(); +- String elementKind =3D jsonObject.get("elementKind") =3D=3D null ? nu= ll : jsonObject.get("elementKind").getAsString(); +- Boolean isDeprecated =3D jsonObject.get("isDeprecated") =3D=3D null ?= null : jsonObject.get("isDeprecated").getAsBoolean(); +- String parameter =3D jsonObject.get("parameter") =3D=3D null ? null := jsonObject.get("parameter").getAsString(); +- String propagatedType =3D jsonObject.get("propagatedType") =3D=3D nul= l ? null : jsonObject.get("propagatedType").getAsString(); +- String staticType =3D jsonObject.get("staticType") =3D=3D null ? null= : jsonObject.get("staticType").getAsString(); +- return new HoverInformation(offset, length, containingLibraryPath, co= ntainingLibraryName, containingClassDescription, dartdoc, elementDescriptio= n, elementKind, isDeprecated, parameter, propagatedType, staticType); +- } +- +- public static List fromJsonArray(JsonArray jsonArray)= { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(= jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A human-readable description of the class declaring the element bein= g referenced. This data is +- * omitted if there is no referenced element, or if the element is not = a class member. +- */ +- public String getContainingClassDescription() { +- return containingClassDescription; +- } +- +- /** +- * The name of the library in which the referenced element is declared.= This data is omitted if +- * there is no referenced element, or if the element is declared inside= an HTML file. +- */ +- public String getContainingLibraryName() { +- return containingLibraryName; +- } +- +- /** +- * The path to the defining compilation unit of the library in which th= e referenced element is +- * declared. This data is omitted if there is no referenced element, or= if the element is declared +- * inside an HTML file. +- */ +- public String getContainingLibraryPath() { +- return containingLibraryPath; +- } +- +- /** +- * The dartdoc associated with the referenced element. Other than the r= emoval of the comment +- * delimiters, including leading asterisks in the case of a block comme= nt, the dartdoc is +- * unprocessed markdown. This data is omitted if there is no referenced= element, or if the element +- * has no dartdoc. +- */ +- public String getDartdoc() { +- return dartdoc; +- } +- +- /** +- * A human-readable description of the element being referenced. This d= ata is omitted if there is +- * no referenced element. +- */ +- public String getElementDescription() { +- return elementDescription; +- } +- +- /** +- * A human-readable description of the kind of element being referenced= (such as "class" or +- * "function type alias"). This data is omitted if there is no referenc= ed element. +- */ +- public String getElementKind() { +- return elementKind; +- } +- +- /** +- * True if the referenced element is deprecated. +- */ +- public Boolean getIsDeprecated() { +- return isDeprecated; +- } +- +- /** +- * The length of the range of characters that encompasses the cursor po= sition and has the same +- * hover information as the cursor position. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the range of characters that encompasses the cursor po= sition and has the same +- * hover information as the cursor position. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * A human-readable description of the parameter corresponding to the e= xpression being hovered +- * over. This data is omitted if the location is not in an argument to = a function. +- */ +- public String getParameter() { +- return parameter; +- } +- +- /** +- * The name of the propagated type of the expression. This data is omit= ted if the location does not +- * correspond to an expression or if there is no propagated type inform= ation. +- */ +- public String getPropagatedType() { +- return propagatedType; +- } +- +- /** +- * The name of the static type of the expression. This data is omitted = if the location does not +- * correspond to an expression. +- */ +- public String getStaticType() { +- return staticType; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(containingLibraryPath); +- builder.append(containingLibraryName); +- builder.append(containingClassDescription); +- builder.append(dartdoc); +- builder.append(elementDescription); +- builder.append(elementKind); +- builder.append(isDeprecated); +- builder.append(parameter); +- builder.append(propagatedType); +- builder.append(staticType); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- if (containingLibraryPath !=3D null) { +- jsonObject.addProperty("containingLibraryPath", containingLibraryPa= th); +- } +- if (containingLibraryName !=3D null) { +- jsonObject.addProperty("containingLibraryName", containingLibraryNa= me); +- } +- if (containingClassDescription !=3D null) { +- jsonObject.addProperty("containingClassDescription", containingClas= sDescription); +- } +- if (dartdoc !=3D null) { +- jsonObject.addProperty("dartdoc", dartdoc); +- } +- if (elementDescription !=3D null) { +- jsonObject.addProperty("elementDescription", elementDescription); +- } +- if (elementKind !=3D null) { +- jsonObject.addProperty("elementKind", elementKind); +- } +- if (isDeprecated !=3D null) { +- jsonObject.addProperty("isDeprecated", isDeprecated); +- } +- if (parameter !=3D null) { +- jsonObject.addProperty("parameter", parameter); +- } +- if (propagatedType !=3D null) { +- jsonObject.addProperty("propagatedType", propagatedType); +- } +- if (staticType !=3D null) { +- jsonObject.addProperty("staticType", staticType); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("containingLibraryPath=3D"); +- builder.append(containingLibraryPath + ", "); +- builder.append("containingLibraryName=3D"); +- builder.append(containingLibraryName + ", "); +- builder.append("containingClassDescription=3D"); +- builder.append(containingClassDescription + ", "); +- builder.append("dartdoc=3D"); +- builder.append(dartdoc + ", "); +- builder.append("elementDescription=3D"); +- builder.append(elementDescription + ", "); +- builder.append("elementKind=3D"); +- builder.append(elementKind + ", "); +- builder.append("isDeprecated=3D"); +- builder.append(isDeprecated + ", "); +- builder.append("parameter=3D"); +- builder.append(parameter + ", "); +- builder.append("propagatedType=3D"); +- builder.append(propagatedType + ", "); +- builder.append("staticType=3D"); +- builder.append(staticType); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Implemente= dClass.java b/pkg/analysis_server/tool/spec/generated/java/types/Implemente= dClass.java +deleted file mode 100644 +index 5c08f6b2acf..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ImplementedClass.= java ++++ /dev/null +@@ -1,134 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a class that is implemented or extended. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ImplementedClass { +- +- public static final ImplementedClass[] EMPTY_ARRAY =3D new ImplementedC= lass[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArra= yList(); +- +- /** +- * The offset of the name of the implemented class. +- */ +- private final int offset; +- +- /** +- * The length of the name of the implemented class. +- */ +- private final int length; +- +- /** +- * Constructor for {@link ImplementedClass}. +- */ +- public ImplementedClass(int offset, int length) { +- this.offset =3D offset; +- this.length =3D length; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ImplementedClass) { +- ImplementedClass other =3D (ImplementedClass) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length; +- } +- return false; +- } +- +- public static ImplementedClass fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- return new ImplementedClass(offset, length); +- } +- +- public static List fromJsonArray(JsonArray jsonArray)= { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(= jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The length of the name of the implemented class. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the name of the implemented class. +- */ +- public int getOffset() { +- return offset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Implemente= dMember.java b/pkg/analysis_server/tool/spec/generated/java/types/Implement= edMember.java +deleted file mode 100644 +index a18d6a4ae57..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ImplementedMember= .java ++++ /dev/null +@@ -1,134 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a class member that is implemented or overridden. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ImplementedMember { +- +- public static final ImplementedMember[] EMPTY_ARRAY =3D new Implemented= Member[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArr= ayList(); +- +- /** +- * The offset of the name of the implemented member. +- */ +- private final int offset; +- +- /** +- * The length of the name of the implemented member. +- */ +- private final int length; +- +- /** +- * Constructor for {@link ImplementedMember}. +- */ +- public ImplementedMember(int offset, int length) { +- this.offset =3D offset; +- this.length =3D length; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ImplementedMember) { +- ImplementedMember other =3D (ImplementedMember) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length; +- } +- return false; +- } +- +- public static ImplementedMember fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- return new ImplementedMember(offset, length); +- } +- +- public static List fromJsonArray(JsonArray jsonArray= ) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The length of the name of the implemented member. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the name of the implemented member. +- */ +- public int getOffset() { +- return offset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ImportedEl= ements.java b/pkg/analysis_server/tool/spec/generated/java/types/ImportedEl= ements.java +deleted file mode 100644 +index 7f5b0e73ffd..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ImportedElements.= java ++++ /dev/null +@@ -1,158 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of the elements that are referenced in a region of a fil= e that come from a single +- * imported library. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class ImportedElements { +- +- public static final ImportedElements[] EMPTY_ARRAY =3D new ImportedElem= ents[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArra= yList(); +- +- /** +- * The absolute and normalized path of the file containing the library. +- */ +- private final String path; +- +- /** +- * The prefix that was used when importing the library into the origina= l source. +- */ +- private final String prefix; +- +- /** +- * The names of the elements imported from the library. +- */ +- private final List elements; +- +- /** +- * Constructor for {@link ImportedElements}. +- */ +- public ImportedElements(String path, String prefix, List elemen= ts) { +- this.path =3D path; +- this.prefix =3D prefix; +- this.elements =3D elements; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof ImportedElements) { +- ImportedElements other =3D (ImportedElements) obj; +- return +- ObjectUtilities.equals(other.path, path) && +- ObjectUtilities.equals(other.prefix, prefix) && +- ObjectUtilities.equals(other.elements, elements); +- } +- return false; +- } +- +- public static ImportedElements fromJson(JsonObject jsonObject) { +- String path =3D jsonObject.get("path").getAsString(); +- String prefix =3D jsonObject.get("prefix").getAsString(); +- List elements =3D JsonUtilities.decodeStringList(jsonObject.g= et("elements").getAsJsonArray()); +- return new ImportedElements(path, prefix, elements); +- } +- +- public static List fromJsonArray(JsonArray jsonArray)= { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(= jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The names of the elements imported from the library. +- */ +- public List getElements() { +- return elements; +- } +- +- /** +- * The absolute and normalized path of the file containing the library. +- */ +- public String getPath() { +- return path; +- } +- +- /** +- * The prefix that was used when importing the library into the origina= l source. +- */ +- public String getPrefix() { +- return prefix; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(path); +- builder.append(prefix); +- builder.append(elements); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("path", path); +- jsonObject.addProperty("prefix", prefix); +- JsonArray jsonArrayElements =3D new JsonArray(); +- for (String elt : elements) { +- jsonArrayElements.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("elements", jsonArrayElements); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("path=3D"); +- builder.append(path + ", "); +- builder.append("prefix=3D"); +- builder.append(prefix + ", "); +- builder.append("elements=3D"); +- builder.append(StringUtils.join(elements, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/InlineLoca= lVariableFeedback.java b/pkg/analysis_server/tool/spec/generated/java/types= /InlineLocalVariableFeedback.java +deleted file mode 100644 +index 65e4a869f41..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/InlineLocalVariab= leFeedback.java ++++ /dev/null +@@ -1,132 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class InlineLocalVariableFeedback extends RefactoringFeedback { +- +- public static final InlineLocalVariableFeedback[] EMPTY_ARRAY =3D new I= nlineLocalVariableFeedback[0]; +- +- public static final List EMPTY_LIST =3D Li= sts.newArrayList(); +- +- /** +- * The name of the variable being inlined. +- */ +- private final String name; +- +- /** +- * The number of times the variable occurs. +- */ +- private final int occurrences; +- +- /** +- * Constructor for {@link InlineLocalVariableFeedback}. +- */ +- public InlineLocalVariableFeedback(String name, int occurrences) { +- this.name =3D name; +- this.occurrences =3D occurrences; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof InlineLocalVariableFeedback) { +- InlineLocalVariableFeedback other =3D (InlineLocalVariableFeedback)= obj; +- return +- ObjectUtilities.equals(other.name, name) && +- other.occurrences =3D=3D occurrences; +- } +- return false; +- } +- +- public static InlineLocalVariableFeedback fromJson(JsonObject jsonObjec= t) { +- String name =3D jsonObject.get("name").getAsString(); +- int occurrences =3D jsonObject.get("occurrences").getAsInt(); +- return new InlineLocalVariableFeedback(name, occurrences); +- } +- +- public static List fromJsonArray(JsonArray= jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The name of the variable being inlined. +- */ +- public String getName() { +- return name; +- } +- +- /** +- * The number of times the variable occurs. +- */ +- public int getOccurrences() { +- return occurrences; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(name); +- builder.append(occurrences); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("name", name); +- jsonObject.addProperty("occurrences", occurrences); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("occurrences=3D"); +- builder.append(occurrences); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/InlineMeth= odFeedback.java b/pkg/analysis_server/tool/spec/generated/java/types/Inline= MethodFeedback.java +deleted file mode 100644 +index 6d80cfa5fbe..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/InlineMethodFeedb= ack.java ++++ /dev/null +@@ -1,155 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class InlineMethodFeedback extends RefactoringFeedback { +- +- public static final InlineMethodFeedback[] EMPTY_ARRAY =3D new InlineMe= thodFeedback[0]; +- +- public static final List EMPTY_LIST =3D Lists.new= ArrayList(); +- +- /** +- * The name of the class enclosing the method being inlined. If not a c= lass member is being +- * inlined, this field will be absent. +- */ +- private final String className; +- +- /** +- * The name of the method (or function) being inlined. +- */ +- private final String methodName; +- +- /** +- * True if the declaration of the method is selected. So all references= should be inlined. +- */ +- private final boolean isDeclaration; +- +- /** +- * Constructor for {@link InlineMethodFeedback}. +- */ +- public InlineMethodFeedback(String className, String methodName, boolea= n isDeclaration) { +- this.className =3D className; +- this.methodName =3D methodName; +- this.isDeclaration =3D isDeclaration; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof InlineMethodFeedback) { +- InlineMethodFeedback other =3D (InlineMethodFeedback) obj; +- return +- ObjectUtilities.equals(other.className, className) && +- ObjectUtilities.equals(other.methodName, methodName) && +- other.isDeclaration =3D=3D isDeclaration; +- } +- return false; +- } +- +- public static InlineMethodFeedback fromJson(JsonObject jsonObject) { +- String className =3D jsonObject.get("className") =3D=3D null ? null := jsonObject.get("className").getAsString(); +- String methodName =3D jsonObject.get("methodName").getAsString(); +- boolean isDeclaration =3D jsonObject.get("isDeclaration").getAsBoolea= n(); +- return new InlineMethodFeedback(className, methodName, isDeclaration); +- } +- +- public static List fromJsonArray(JsonArray jsonAr= ray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The name of the class enclosing the method being inlined. If not a c= lass member is being +- * inlined, this field will be absent. +- */ +- public String getClassName() { +- return className; +- } +- +- /** +- * True if the declaration of the method is selected. So all references= should be inlined. +- */ +- public boolean isDeclaration() { +- return isDeclaration; +- } +- +- /** +- * The name of the method (or function) being inlined. +- */ +- public String getMethodName() { +- return methodName; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(className); +- builder.append(methodName); +- builder.append(isDeclaration); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- if (className !=3D null) { +- jsonObject.addProperty("className", className); +- } +- jsonObject.addProperty("methodName", methodName); +- jsonObject.addProperty("isDeclaration", isDeclaration); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("className=3D"); +- builder.append(className + ", "); +- builder.append("methodName=3D"); +- builder.append(methodName + ", "); +- builder.append("isDeclaration=3D"); +- builder.append(isDeclaration); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/InlineMeth= odOptions.java b/pkg/analysis_server/tool/spec/generated/java/types/InlineM= ethodOptions.java +deleted file mode 100644 +index c13daa7de97..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/InlineMethodOptio= ns.java ++++ /dev/null +@@ -1,152 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class InlineMethodOptions extends RefactoringOptions { +- +- public static final InlineMethodOptions[] EMPTY_ARRAY =3D new InlineMet= hodOptions[0]; +- +- public static final List EMPTY_LIST =3D Lists.newA= rrayList(); +- +- /** +- * True if the method being inlined should be removed. It is an error i= f this field is true and +- * inlineAll is false. +- */ +- private boolean deleteSource; +- +- /** +- * True if all invocations of the method should be inlined, or false if= only the invocation site +- * used to create this refactoring should be inlined. +- */ +- private boolean inlineAll; +- +- /** +- * Constructor for {@link InlineMethodOptions}. +- */ +- public InlineMethodOptions(boolean deleteSource, boolean inlineAll) { +- this.deleteSource =3D deleteSource; +- this.inlineAll =3D inlineAll; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof InlineMethodOptions) { +- InlineMethodOptions other =3D (InlineMethodOptions) obj; +- return +- other.deleteSource =3D=3D deleteSource && +- other.inlineAll =3D=3D inlineAll; +- } +- return false; +- } +- +- public static InlineMethodOptions fromJson(JsonObject jsonObject) { +- boolean deleteSource =3D jsonObject.get("deleteSource").getAsBoolean(= ); +- boolean inlineAll =3D jsonObject.get("inlineAll").getAsBoolean(); +- return new InlineMethodOptions(deleteSource, inlineAll); +- } +- +- public static List fromJsonArray(JsonArray jsonArr= ay) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * True if the method being inlined should be removed. It is an error i= f this field is true and +- * inlineAll is false. +- */ +- public boolean deleteSource() { +- return deleteSource; +- } +- +- /** +- * True if all invocations of the method should be inlined, or false if= only the invocation site +- * used to create this refactoring should be inlined. +- */ +- public boolean inlineAll() { +- return inlineAll; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(deleteSource); +- builder.append(inlineAll); +- return builder.toHashCode(); +- } +- +- /** +- * True if the method being inlined should be removed. It is an error i= f this field is true and +- * inlineAll is false. +- */ +- public void setDeleteSource(boolean deleteSource) { +- this.deleteSource =3D deleteSource; +- } +- +- /** +- * True if all invocations of the method should be inlined, or false if= only the invocation site +- * used to create this refactoring should be inlined. +- */ +- public void setInlineAll(boolean inlineAll) { +- this.inlineAll =3D inlineAll; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("deleteSource", deleteSource); +- jsonObject.addProperty("inlineAll", inlineAll); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("deleteSource=3D"); +- builder.append(deleteSource + ", "); +- builder.append("inlineAll=3D"); +- builder.append(inlineAll); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/KytheEntry= .java b/pkg/analysis_server/tool/spec/generated/java/types/KytheEntry.java +deleted file mode 100644 +index 92fabffc587..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/KytheEntry.java ++++ /dev/null +@@ -1,202 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * This object matches the format and documentation of the Entry object d= ocumented in the Kythe +- * Storage Model. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class KytheEntry { +- +- public static final KytheEntry[] EMPTY_ARRAY =3D new KytheEntry[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(= ); +- +- /** +- * The ticket of the source node. +- */ +- private final KytheVName source; +- +- /** +- * An edge label. The schema defines which labels are meaningful. +- */ +- private final String kind; +- +- /** +- * The ticket of the target node. +- */ +- private final KytheVName target; +- +- /** +- * A fact label. The schema defines which fact labels are meaningful. +- */ +- private final String fact; +- +- /** +- * The String value of the fact. +- */ +- private final int[] value; +- +- /** +- * Constructor for {@link KytheEntry}. +- */ +- public KytheEntry(KytheVName source, String kind, KytheVName target, St= ring fact, int[] value) { +- this.source =3D source; +- this.kind =3D kind; +- this.target =3D target; +- this.fact =3D fact; +- this.value =3D value; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof KytheEntry) { +- KytheEntry other =3D (KytheEntry) obj; +- return +- ObjectUtilities.equals(other.source, source) && +- ObjectUtilities.equals(other.kind, kind) && +- ObjectUtilities.equals(other.target, target) && +- ObjectUtilities.equals(other.fact, fact) && +- Arrays.equals(other.value, value); +- } +- return false; +- } +- +- public static KytheEntry fromJson(JsonObject jsonObject) { +- KytheVName source =3D KytheVName.fromJson(jsonObject.get("source").ge= tAsJsonObject()); +- String kind =3D jsonObject.get("kind") =3D=3D null ? null : jsonObjec= t.get("kind").getAsString(); +- KytheVName target =3D jsonObject.get("target") =3D=3D null ? null : K= ytheVName.fromJson(jsonObject.get("target").getAsJsonObject()); +- String fact =3D jsonObject.get("fact").getAsString(); +- int[] value =3D jsonObject.get("value") =3D=3D null ? null : JsonUtil= ities.decodeIntArray(jsonObject.get("value").getAsJsonArray()); +- return new KytheEntry(source, kind, target, fact, value); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.si= ze()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A fact label. The schema defines which fact labels are meaningful. +- */ +- public String getFact() { +- return fact; +- } +- +- /** +- * An edge label. The schema defines which labels are meaningful. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The ticket of the source node. +- */ +- public KytheVName getSource() { +- return source; +- } +- +- /** +- * The ticket of the target node. +- */ +- public KytheVName getTarget() { +- return target; +- } +- +- /** +- * The String value of the fact. +- */ +- public int[] getValue() { +- return value; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(source); +- builder.append(kind); +- builder.append(target); +- builder.append(fact); +- builder.append(value); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.add("source", source.toJson()); +- if (kind !=3D null) { +- jsonObject.addProperty("kind", kind); +- } +- if (target !=3D null) { +- jsonObject.add("target", target.toJson()); +- } +- jsonObject.addProperty("fact", fact); +- if (value !=3D null) { +- JsonArray jsonArrayValue =3D new JsonArray(); +- for (int elt : value) { +- jsonArrayValue.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("value", jsonArrayValue); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("source=3D"); +- builder.append(source + ", "); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("target=3D"); +- builder.append(target + ", "); +- builder.append("fact=3D"); +- builder.append(fact + ", "); +- builder.append("value=3D"); +- builder.append(StringUtils.join(value, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/KytheVName= .java b/pkg/analysis_server/tool/spec/generated/java/types/KytheVName.java +deleted file mode 100644 +index 2c56a72d888..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/KytheVName.java ++++ /dev/null +@@ -1,200 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * This object matches the format and documentation of the Vector-Name ob= ject documented in the +- * Kythe Storage Model. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class KytheVName { +- +- public static final KytheVName[] EMPTY_ARRAY =3D new KytheVName[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(= ); +- +- /** +- * An opaque signature generated by the analyzer. +- */ +- private final String signature; +- +- /** +- * The corpus of source code this KytheVName belongs to. Loosely, a cor= pus is a collection of +- * related files, such as the contents of a given source repository. +- */ +- private final String corpus; +- +- /** +- * A corpus-specific root label, typically a directory path or project = identifier, denoting a +- * distinct subset of the corpus. This may also be used to designate vi= rtual collections like +- * generated files. +- */ +- private final String root; +- +- /** +- * A path-structured label describing the =E2=80=9Clocation=E2=80=9D of= the named object relative to the corpus and +- * the root. +- */ +- private final String path; +- +- /** +- * The language this name belongs to. +- */ +- private final String language; +- +- /** +- * Constructor for {@link KytheVName}. +- */ +- public KytheVName(String signature, String corpus, String root, String = path, String language) { +- this.signature =3D signature; +- this.corpus =3D corpus; +- this.root =3D root; +- this.path =3D path; +- this.language =3D language; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof KytheVName) { +- KytheVName other =3D (KytheVName) obj; +- return +- ObjectUtilities.equals(other.signature, signature) && +- ObjectUtilities.equals(other.corpus, corpus) && +- ObjectUtilities.equals(other.root, root) && +- ObjectUtilities.equals(other.path, path) && +- ObjectUtilities.equals(other.language, language); +- } +- return false; +- } +- +- public static KytheVName fromJson(JsonObject jsonObject) { +- String signature =3D jsonObject.get("signature").getAsString(); +- String corpus =3D jsonObject.get("corpus").getAsString(); +- String root =3D jsonObject.get("root").getAsString(); +- String path =3D jsonObject.get("path").getAsString(); +- String language =3D jsonObject.get("language").getAsString(); +- return new KytheVName(signature, corpus, root, path, language); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.si= ze()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The corpus of source code this KytheVName belongs to. Loosely, a cor= pus is a collection of +- * related files, such as the contents of a given source repository. +- */ +- public String getCorpus() { +- return corpus; +- } +- +- /** +- * The language this name belongs to. +- */ +- public String getLanguage() { +- return language; +- } +- +- /** +- * A path-structured label describing the =E2=80=9Clocation=E2=80=9D of= the named object relative to the corpus and +- * the root. +- */ +- public String getPath() { +- return path; +- } +- +- /** +- * A corpus-specific root label, typically a directory path or project = identifier, denoting a +- * distinct subset of the corpus. This may also be used to designate vi= rtual collections like +- * generated files. +- */ +- public String getRoot() { +- return root; +- } +- +- /** +- * An opaque signature generated by the analyzer. +- */ +- public String getSignature() { +- return signature; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(signature); +- builder.append(corpus); +- builder.append(root); +- builder.append(path); +- builder.append(language); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("signature", signature); +- jsonObject.addProperty("corpus", corpus); +- jsonObject.addProperty("root", root); +- jsonObject.addProperty("path", path); +- jsonObject.addProperty("language", language); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("signature=3D"); +- builder.append(signature + ", "); +- builder.append("corpus=3D"); +- builder.append(corpus + ", "); +- builder.append("root=3D"); +- builder.append(root + ", "); +- builder.append("path=3D"); +- builder.append(path + ", "); +- builder.append("language=3D"); +- builder.append(language); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/LinkedEdit= Group.java b/pkg/analysis_server/tool/spec/generated/java/types/LinkedEditG= roup.java +deleted file mode 100644 +index b83f30447ce..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/LinkedEditGroup.j= ava ++++ /dev/null +@@ -1,165 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A collection of positions that should be linked (edited simultaneously= ) for the purposes of +- * updating code after a source change. For example, if a set of edits in= troduced a new variable +- * name, the group would contain all of the positions of the variable nam= e so that if the client +- * wanted to let the user edit the variable name after the operation, all= occurrences of the name +- * could be edited simultaneously. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class LinkedEditGroup { +- +- public static final LinkedEditGroup[] EMPTY_ARRAY =3D new LinkedEditGro= up[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArray= List(); +- +- /** +- * The positions of the regions that should be edited simultaneously. +- */ +- private final List positions; +- +- /** +- * The length of the regions that should be edited simultaneously. +- */ +- private final int length; +- +- /** +- * Pre-computed suggestions for what every region might want to be chan= ged to. +- */ +- private final List suggestions; +- +- /** +- * Constructor for {@link LinkedEditGroup}. +- */ +- public LinkedEditGroup(List positions, int length, List suggestions) { +- this.positions =3D positions; +- this.length =3D length; +- this.suggestions =3D suggestions; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof LinkedEditGroup) { +- LinkedEditGroup other =3D (LinkedEditGroup) obj; +- return +- ObjectUtilities.equals(other.positions, positions) && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.suggestions, suggestions); +- } +- return false; +- } +- +- public static LinkedEditGroup fromJson(JsonObject jsonObject) { +- List positions =3D Position.fromJsonArray(jsonObject.get("p= ositions").getAsJsonArray()); +- int length =3D jsonObject.get("length").getAsInt(); +- List suggestions =3D LinkedEditSuggestion.fromJ= sonArray(jsonObject.get("suggestions").getAsJsonArray()); +- return new LinkedEditGroup(positions, length, suggestions); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(js= onArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The length of the regions that should be edited simultaneously. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The positions of the regions that should be edited simultaneously. +- */ +- public List getPositions() { +- return positions; +- } +- +- /** +- * Pre-computed suggestions for what every region might want to be chan= ged to. +- */ +- public List getSuggestions() { +- return suggestions; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(positions); +- builder.append(length); +- builder.append(suggestions); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- JsonArray jsonArrayPositions =3D new JsonArray(); +- for (Position elt : positions) { +- jsonArrayPositions.add(elt.toJson()); +- } +- jsonObject.add("positions", jsonArrayPositions); +- jsonObject.addProperty("length", length); +- JsonArray jsonArraySuggestions =3D new JsonArray(); +- for (LinkedEditSuggestion elt : suggestions) { +- jsonArraySuggestions.add(elt.toJson()); +- } +- jsonObject.add("suggestions", jsonArraySuggestions); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("positions=3D"); +- builder.append(StringUtils.join(positions, ", ") + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("suggestions=3D"); +- builder.append(StringUtils.join(suggestions, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/LinkedEdit= Suggestion.java b/pkg/analysis_server/tool/spec/generated/java/types/Linked= EditSuggestion.java +deleted file mode 100644 +index 2537bc50c24..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/LinkedEditSuggest= ion.java ++++ /dev/null +@@ -1,135 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A suggestion of a value that could be used to replace all of the linke= d edit regions in a +- * LinkedEditGroup. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class LinkedEditSuggestion { +- +- public static final LinkedEditSuggestion[] EMPTY_ARRAY =3D new LinkedEd= itSuggestion[0]; +- +- public static final List EMPTY_LIST =3D Lists.new= ArrayList(); +- +- /** +- * The value that could be used to replace all of the linked edit regio= ns. +- */ +- private final String value; +- +- /** +- * The kind of value being proposed. +- */ +- private final String kind; +- +- /** +- * Constructor for {@link LinkedEditSuggestion}. +- */ +- public LinkedEditSuggestion(String value, String kind) { +- this.value =3D value; +- this.kind =3D kind; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof LinkedEditSuggestion) { +- LinkedEditSuggestion other =3D (LinkedEditSuggestion) obj; +- return +- ObjectUtilities.equals(other.value, value) && +- ObjectUtilities.equals(other.kind, kind); +- } +- return false; +- } +- +- public static LinkedEditSuggestion fromJson(JsonObject jsonObject) { +- String value =3D jsonObject.get("value").getAsString(); +- String kind =3D jsonObject.get("kind").getAsString(); +- return new LinkedEditSuggestion(value, kind); +- } +- +- public static List fromJsonArray(JsonArray jsonAr= ray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The kind of value being proposed. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The value that could be used to replace all of the linked edit regio= ns. +- */ +- public String getValue() { +- return value; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(value); +- builder.append(kind); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("value", value); +- jsonObject.addProperty("kind", kind); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("value=3D"); +- builder.append(value + ", "); +- builder.append("kind=3D"); +- builder.append(kind); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/LinkedEdit= SuggestionKind.java b/pkg/analysis_server/tool/spec/generated/java/types/Li= nkedEditSuggestionKind.java +deleted file mode 100644 +index be193e0b6fe..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/LinkedEditSuggest= ionKind.java ++++ /dev/null +@@ -1,34 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kind of values that can be suggested for a linke= d edit. +- * +- * @coverage dart.server.generated.types +- */ +-public class LinkedEditSuggestionKind { +- +- public static final String METHOD =3D "METHOD"; +- +- public static final String PARAMETER =3D "PARAMETER"; +- +- public static final String TYPE =3D "TYPE"; +- +- public static final String VARIABLE =3D "VARIABLE"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Location.j= ava b/pkg/analysis_server/tool/spec/generated/java/types/Location.java +deleted file mode 100644 +index d9f8ae0d6f5..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/Location.java ++++ /dev/null +@@ -1,191 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A location (character range) within a file. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class Location { +- +- public static final Location[] EMPTY_ARRAY =3D new Location[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(); +- +- /** +- * The file containing the range. +- */ +- private final String file; +- +- /** +- * The offset of the range. +- */ +- private final int offset; +- +- /** +- * The length of the range. +- */ +- private final int length; +- +- /** +- * The one-based index of the line containing the first character of th= e range. +- */ +- private final int startLine; +- +- /** +- * The one-based index of the column containing the first character of = the range. +- */ +- private final int startColumn; +- +- /** +- * Constructor for {@link Location}. +- */ +- public Location(String file, int offset, int length, int startLine, int= startColumn) { +- this.file =3D file; +- this.offset =3D offset; +- this.length =3D length; +- this.startLine =3D startLine; +- this.startColumn =3D startColumn; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof Location) { +- Location other =3D (Location) obj; +- return +- ObjectUtilities.equals(other.file, file) && +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- other.startLine =3D=3D startLine && +- other.startColumn =3D=3D startColumn; +- } +- return false; +- } +- +- public static Location fromJson(JsonObject jsonObject) { +- String file =3D jsonObject.get("file").getAsString(); +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- int startLine =3D jsonObject.get("startLine").getAsInt(); +- int startColumn =3D jsonObject.get("startColumn").getAsInt(); +- return new Location(file, offset, length, startLine, startColumn); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()= ); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The file containing the range. +- */ +- public String getFile() { +- return file; +- } +- +- /** +- * The length of the range. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the range. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The one-based index of the column containing the first character of = the range. +- */ +- public int getStartColumn() { +- return startColumn; +- } +- +- /** +- * The one-based index of the line containing the first character of th= e range. +- */ +- public int getStartLine() { +- return startLine; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(file); +- builder.append(offset); +- builder.append(length); +- builder.append(startLine); +- builder.append(startColumn); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("file", file); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- jsonObject.addProperty("startLine", startLine); +- jsonObject.addProperty("startColumn", startColumn); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("file=3D"); +- builder.append(file + ", "); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("startLine=3D"); +- builder.append(startLine + ", "); +- builder.append("startColumn=3D"); +- builder.append(startColumn); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/MoveFileOp= tions.java b/pkg/analysis_server/tool/spec/generated/java/types/MoveFileOpt= ions.java +deleted file mode 100644 +index 4f04962be3b..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/MoveFileOptions.j= ava ++++ /dev/null +@@ -1,120 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class MoveFileOptions extends RefactoringOptions { +- +- public static final MoveFileOptions[] EMPTY_ARRAY =3D new MoveFileOptio= ns[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArray= List(); +- +- /** +- * The new file path to which the given file is being moved. +- */ +- private String newFile; +- +- /** +- * Constructor for {@link MoveFileOptions}. +- */ +- public MoveFileOptions(String newFile) { +- this.newFile =3D newFile; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof MoveFileOptions) { +- MoveFileOptions other =3D (MoveFileOptions) obj; +- return +- ObjectUtilities.equals(other.newFile, newFile); +- } +- return false; +- } +- +- public static MoveFileOptions fromJson(JsonObject jsonObject) { +- String newFile =3D jsonObject.get("newFile").getAsString(); +- return new MoveFileOptions(newFile); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(js= onArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The new file path to which the given file is being moved. +- */ +- public String getNewFile() { +- return newFile; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(newFile); +- return builder.toHashCode(); +- } +- +- /** +- * The new file path to which the given file is being moved. +- */ +- public void setNewFile(String newFile) { +- this.newFile =3D newFile; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("newFile", newFile); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("newFile=3D"); +- builder.append(newFile); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Navigation= Region.java b/pkg/analysis_server/tool/spec/generated/java/types/Navigation= Region.java +deleted file mode 100644 +index 80565a9f9ce..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/NavigationRegion.= java ++++ /dev/null +@@ -1,179 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a region from which the user can navigate to the decl= aration of an element. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class NavigationRegion { +- +- public static final NavigationRegion[] EMPTY_ARRAY =3D new NavigationRe= gion[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArra= yList(); +- +- /** +- * The offset of the region from which the user can navigate. +- */ +- private final int offset; +- +- /** +- * The length of the region from which the user can navigate. +- */ +- private final int length; +- +- /** +- * The indexes of the targets (in the enclosing navigation response) to= which the given region is +- * bound. By opening the target, clients can implement one form of navi= gation. This list cannot be +- * empty. +- */ +- private final int[] targets; +- +- private final List targetObjects =3D Lists.newArrayLi= st(); +- +- /** +- * Constructor for {@link NavigationRegion}. +- */ +- public NavigationRegion(int offset, int length, int[] targets) { +- this.offset =3D offset; +- this.length =3D length; +- this.targets =3D targets; +- } +- +- public boolean containsInclusive(int x) { +- return offset <=3D x && x <=3D offset + length; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof NavigationRegion) { +- NavigationRegion other =3D (NavigationRegion) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- Arrays.equals(other.targets, targets); +- } +- return false; +- } +- +- public static NavigationRegion fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- int[] targets =3D JsonUtilities.decodeIntArray(jsonObject.get("target= s").getAsJsonArray()); +- return new NavigationRegion(offset, length, targets); +- } +- +- public static List fromJsonArray(JsonArray jsonArray)= { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(= jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- public List getTargetObjects() { +- return targetObjects; +- } +- +- /** +- * The length of the region from which the user can navigate. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the region from which the user can navigate. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The indexes of the targets (in the enclosing navigation response) to= which the given region is +- * bound. By opening the target, clients can implement one form of navi= gation. This list cannot be +- * empty. +- */ +- public int[] getTargets() { +- return targets; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(targets); +- return builder.toHashCode(); +- } +- +- public void lookupTargets(List allTargets) { +- for (int i =3D 0; i < targets.length; i++) { +- int targetIndex =3D targets[i]; +- NavigationTarget target =3D allTargets.get(targetIndex); +- targetObjects.add(target); +- } +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- JsonArray jsonArrayTargets =3D new JsonArray(); +- for (int elt : targets) { +- jsonArrayTargets.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("targets", jsonArrayTargets); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("targets=3D"); +- builder.append(StringUtils.join(targets, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Navigation= Target.java b/pkg/analysis_server/tool/spec/generated/java/types/Navigation= Target.java +deleted file mode 100644 +index d1ef09fd094..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/NavigationTarget.= java ++++ /dev/null +@@ -1,220 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a target to which the user can navigate. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class NavigationTarget { +- +- public static final NavigationTarget[] EMPTY_ARRAY =3D new NavigationTa= rget[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArra= yList(); +- +- /** +- * The kind of the element. +- */ +- private final String kind; +- +- /** +- * The index of the file (in the enclosing navigation response) to navi= gate to. +- */ +- private final int fileIndex; +- +- /** +- * The offset of the region to which the user can navigate. +- */ +- private final int offset; +- +- /** +- * The length of the region to which the user can navigate. +- */ +- private final int length; +- +- /** +- * The one-based index of the line containing the first character of th= e region. +- */ +- private final int startLine; +- +- /** +- * The one-based index of the column containing the first character of = the region. +- */ +- private final int startColumn; +- +- private String file; +- +- /** +- * Constructor for {@link NavigationTarget}. +- */ +- public NavigationTarget(String kind, int fileIndex, int offset, int len= gth, int startLine, int startColumn) { +- this.kind =3D kind; +- this.fileIndex =3D fileIndex; +- this.offset =3D offset; +- this.length =3D length; +- this.startLine =3D startLine; +- this.startColumn =3D startColumn; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof NavigationTarget) { +- NavigationTarget other =3D (NavigationTarget) obj; +- return +- ObjectUtilities.equals(other.kind, kind) && +- other.fileIndex =3D=3D fileIndex && +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- other.startLine =3D=3D startLine && +- other.startColumn =3D=3D startColumn; +- } +- return false; +- } +- +- public static NavigationTarget fromJson(JsonObject jsonObject) { +- String kind =3D jsonObject.get("kind").getAsString(); +- int fileIndex =3D jsonObject.get("fileIndex").getAsInt(); +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- int startLine =3D jsonObject.get("startLine").getAsInt(); +- int startColumn =3D jsonObject.get("startColumn").getAsInt(); +- return new NavigationTarget(kind, fileIndex, offset, length, startLin= e, startColumn); +- } +- +- public static List fromJsonArray(JsonArray jsonArray)= { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(= jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- public String getFile() { +- return file; +- } +- +- /** +- * The index of the file (in the enclosing navigation response) to navi= gate to. +- */ +- public int getFileIndex() { +- return fileIndex; +- } +- +- /** +- * The kind of the element. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The length of the region to which the user can navigate. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the region to which the user can navigate. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The one-based index of the column containing the first character of = the region. +- */ +- public int getStartColumn() { +- return startColumn; +- } +- +- /** +- * The one-based index of the line containing the first character of th= e region. +- */ +- public int getStartLine() { +- return startLine; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(kind); +- builder.append(fileIndex); +- builder.append(offset); +- builder.append(length); +- builder.append(startLine); +- builder.append(startColumn); +- return builder.toHashCode(); +- } +- +- public void lookupFile(String[] allTargetFiles) { +- file =3D allTargetFiles[fileIndex]; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("kind", kind); +- jsonObject.addProperty("fileIndex", fileIndex); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- jsonObject.addProperty("startLine", startLine); +- jsonObject.addProperty("startColumn", startColumn); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("fileIndex=3D"); +- builder.append(fileIndex + ", "); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("startLine=3D"); +- builder.append(startLine + ", "); +- builder.append("startColumn=3D"); +- builder.append(startColumn); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Occurrence= s.java b/pkg/analysis_server/tool/spec/generated/java/types/Occurrences.java +deleted file mode 100644 +index 2f84e5595a0..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/Occurrences.java ++++ /dev/null +@@ -1,166 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of the references to a single element within a single fi= le. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class Occurrences { +- +- public static final Occurrences[] EMPTY_ARRAY =3D new Occurrences[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList= (); +- +- /** +- * The element that was referenced. +- */ +- private final Element element; +- +- /** +- * The offsets of the name of the referenced element within the file. +- */ +- private final int[] offsets; +- +- /** +- * The length of the name of the referenced element. +- */ +- private final int length; +- +- /** +- * Constructor for {@link Occurrences}. +- */ +- public Occurrences(Element element, int[] offsets, int length) { +- this.element =3D element; +- this.offsets =3D offsets; +- this.length =3D length; +- } +- +- public boolean containsInclusive(int x) { +- for (int offset : offsets) { +- if (offset <=3D x && x <=3D offset + length) { +- return true; +- } +- } +- return false; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof Occurrences) { +- Occurrences other =3D (Occurrences) obj; +- return +- ObjectUtilities.equals(other.element, element) && +- Arrays.equals(other.offsets, offsets) && +- other.length =3D=3D length; +- } +- return false; +- } +- +- public static Occurrences fromJson(JsonObject jsonObject) { +- Element element =3D Element.fromJson(jsonObject.get("element").getAsJ= sonObject()); +- int[] offsets =3D JsonUtilities.decodeIntArray(jsonObject.get("offset= s").getAsJsonArray()); +- int length =3D jsonObject.get("length").getAsInt(); +- return new Occurrences(element, offsets, length); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.= size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The element that was referenced. +- */ +- public Element getElement() { +- return element; +- } +- +- /** +- * The length of the name of the referenced element. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offsets of the name of the referenced element within the file. +- */ +- public int[] getOffsets() { +- return offsets; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(element); +- builder.append(offsets); +- builder.append(length); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.add("element", element.toJson()); +- JsonArray jsonArrayOffsets =3D new JsonArray(); +- for (int elt : offsets) { +- jsonArrayOffsets.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("offsets", jsonArrayOffsets); +- jsonObject.addProperty("length", length); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("element=3D"); +- builder.append(element + ", "); +- builder.append("offsets=3D"); +- builder.append(StringUtils.join(offsets, ", ") + ", "); +- builder.append("length=3D"); +- builder.append(length); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Outline.ja= va b/pkg/analysis_server/tool/spec/generated/java/types/Outline.java +deleted file mode 100644 +index 142671f25a2..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/Outline.java ++++ /dev/null +@@ -1,207 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An node in the outline structure of a file. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class Outline { +- +- public static final Outline[] EMPTY_ARRAY =3D new Outline[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(); +- +- /** +- * A description of the element represented by this node. +- */ +- private Element element; +- +- /** +- * The offset of the first character of the element. This is different = than the offset in the +- * Element, which is the offset of the name of the element. It can be u= sed, for example, to map +- * locations in the file back to an outline. +- */ +- private int offset; +- +- /** +- * The length of the element. +- */ +- private int length; +- +- private final Outline parent; +- +- private List children; +- +- /** +- * Constructor for {@link Outline}. +- */ +- public Outline(Outline parent, Element element, int offset, int length)= { +- this.parent =3D parent; +- this.element =3D element; +- this.offset =3D offset; +- this.length =3D length; +- } +- +- public boolean containsInclusive(int x) { +- return offset <=3D x && x <=3D offset + length; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof Outline) { +- Outline other =3D (Outline) obj; +- return +- ObjectUtilities.equals(other.element, element) && +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.children, children); +- } +- return false; +- } +- +- public static Outline fromJson(Outline parent, JsonObject outlineObject= ) { +- JsonObject elementObject =3D outlineObject.get("element").getAsJsonOb= ject(); +- Element element =3D Element.fromJson(elementObject); +- int offset =3D outlineObject.get("offset").getAsInt(); +- int length =3D outlineObject.get("length").getAsInt(); +- +- // create outline object +- Outline outline =3D new Outline(parent, element, offset, length); +- +- // compute children recursively +- List childrenList =3D Lists.newArrayList(); +- JsonElement childrenJsonArray =3D outlineObject.get("children"); +- if (childrenJsonArray instanceof JsonArray) { +- Iterator childrenElementIterator =3D ((JsonArray) chil= drenJsonArray).iterator(); +- while (childrenElementIterator.hasNext()) { +- JsonObject childObject =3D childrenElementIterator.next().getAsJs= onObject(); +- childrenList.add(fromJson(outline, childObject)); +- } +- } +- outline.setChildren(childrenList); +- return outline; +- } +- +- public Outline getParent() { +- return parent; +- } +- +- /** +- * The children of the node. The field will be omitted if the node has = no children. +- */ +- public List getChildren() { +- return children; +- } +- +- /** +- * A description of the element represented by this node. +- */ +- public Element getElement() { +- return element; +- } +- +- /** +- * The length of the element. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the first character of the element. This is different = than the offset in the +- * Element, which is the offset of the name of the element. It can be u= sed, for example, to map +- * locations in the file back to an outline. +- */ +- public int getOffset() { +- return offset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(element); +- builder.append(offset); +- builder.append(length); +- builder.append(children); +- return builder.toHashCode(); +- } +- +- /** +- * The children of the node. The field will be omitted if the node has = no children. +- */ +- public void setChildren(List children) { +- this.children =3D children; +- } +- +- /** +- * A description of the element represented by this node. +- */ +- public void setElement(Element element) { +- this.element =3D element; +- } +- +- /** +- * The length of the element. +- */ +- public void setLength(int length) { +- this.length =3D length; +- } +- +- /** +- * The offset of the first character of the element. This is different = than the offset in the +- * Element, which is the offset of the name of the element. It can be u= sed, for example, to map +- * locations in the file back to an outline. +- */ +- public void setOffset(int offset) { +- this.offset =3D offset; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("element=3D"); +- builder.append(element + ", "); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("children=3D"); +- builder.append(StringUtils.join(children, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Overridden= Member.java b/pkg/analysis_server/tool/spec/generated/java/types/Overridden= Member.java +deleted file mode 100644 +index 6054c5583dc..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/OverriddenMember.= java ++++ /dev/null +@@ -1,134 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a member that is being overridden. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class OverriddenMember { +- +- public static final OverriddenMember[] EMPTY_ARRAY =3D new OverriddenMe= mber[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArra= yList(); +- +- /** +- * The element that is being overridden. +- */ +- private final Element element; +- +- /** +- * The name of the class in which the member is defined. +- */ +- private final String className; +- +- /** +- * Constructor for {@link OverriddenMember}. +- */ +- public OverriddenMember(Element element, String className) { +- this.element =3D element; +- this.className =3D className; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof OverriddenMember) { +- OverriddenMember other =3D (OverriddenMember) obj; +- return +- ObjectUtilities.equals(other.element, element) && +- ObjectUtilities.equals(other.className, className); +- } +- return false; +- } +- +- public static OverriddenMember fromJson(JsonObject jsonObject) { +- Element element =3D Element.fromJson(jsonObject.get("element").getAsJ= sonObject()); +- String className =3D jsonObject.get("className").getAsString(); +- return new OverriddenMember(element, className); +- } +- +- public static List fromJsonArray(JsonArray jsonArray)= { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(= jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The name of the class in which the member is defined. +- */ +- public String getClassName() { +- return className; +- } +- +- /** +- * The element that is being overridden. +- */ +- public Element getElement() { +- return element; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(element); +- builder.append(className); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.add("element", element.toJson()); +- jsonObject.addProperty("className", className); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("element=3D"); +- builder.append(element + ", "); +- builder.append("className=3D"); +- builder.append(className); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/OverrideMe= mber.java b/pkg/analysis_server/tool/spec/generated/java/types/OverrideMemb= er.java +deleted file mode 100644 +index 6f5936eefbb..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/OverrideMember.ja= va ++++ /dev/null +@@ -1,186 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a member that overrides an inherited member. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class OverrideMember { +- +- public static final OverrideMember[] EMPTY_ARRAY =3D new OverrideMember= [0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayL= ist(); +- +- /** +- * The offset of the name of the overriding member. +- */ +- private final int offset; +- +- /** +- * The length of the name of the overriding member. +- */ +- private final int length; +- +- /** +- * The member inherited from a superclass that is overridden by the ove= rriding member. The field is +- * omitted if there is no superclass member, in which case there must b= e at least one interface +- * member. +- */ +- private final OverriddenMember superclassMember; +- +- /** +- * The members inherited from interfaces that are overridden by the ove= rriding member. The field is +- * omitted if there are no interface members, in which case there must = be a superclass member. +- */ +- private final List interfaceMembers; +- +- /** +- * Constructor for {@link OverrideMember}. +- */ +- public OverrideMember(int offset, int length, OverriddenMember supercla= ssMember, List interfaceMembers) { +- this.offset =3D offset; +- this.length =3D length; +- this.superclassMember =3D superclassMember; +- this.interfaceMembers =3D interfaceMembers; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof OverrideMember) { +- OverrideMember other =3D (OverrideMember) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.superclassMember, superclassMember) = && +- ObjectUtilities.equals(other.interfaceMembers, interfaceMembers); +- } +- return false; +- } +- +- public static OverrideMember fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- OverriddenMember superclassMember =3D jsonObject.get("superclassMembe= r") =3D=3D null ? null : OverriddenMember.fromJson(jsonObject.get("supercla= ssMember").getAsJsonObject()); +- List interfaceMembers =3D jsonObject.get("interface= Members") =3D=3D null ? null : OverriddenMember.fromJsonArray(jsonObject.ge= t("interfaceMembers").getAsJsonArray()); +- return new OverrideMember(offset, length, superclassMember, interface= Members); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(json= Array.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The members inherited from interfaces that are overridden by the ove= rriding member. The field is +- * omitted if there are no interface members, in which case there must = be a superclass member. +- */ +- public List getInterfaceMembers() { +- return interfaceMembers; +- } +- +- /** +- * The length of the name of the overriding member. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the name of the overriding member. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The member inherited from a superclass that is overridden by the ove= rriding member. The field is +- * omitted if there is no superclass member, in which case there must b= e at least one interface +- * member. +- */ +- public OverriddenMember getSuperclassMember() { +- return superclassMember; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(superclassMember); +- builder.append(interfaceMembers); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- if (superclassMember !=3D null) { +- jsonObject.add("superclassMember", superclassMember.toJson()); +- } +- if (interfaceMembers !=3D null) { +- JsonArray jsonArrayInterfaceMembers =3D new JsonArray(); +- for (OverriddenMember elt : interfaceMembers) { +- jsonArrayInterfaceMembers.add(elt.toJson()); +- } +- jsonObject.add("interfaceMembers", jsonArrayInterfaceMembers); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("superclassMember=3D"); +- builder.append(superclassMember + ", "); +- builder.append("interfaceMembers=3D"); +- builder.append(StringUtils.join(interfaceMembers, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Position.j= ava b/pkg/analysis_server/tool/spec/generated/java/types/Position.java +deleted file mode 100644 +index d9e36366d1b..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/Position.java ++++ /dev/null +@@ -1,134 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A position within a file. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class Position { +- +- public static final Position[] EMPTY_ARRAY =3D new Position[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(); +- +- /** +- * The file containing the position. +- */ +- private final String file; +- +- /** +- * The offset of the position. +- */ +- private final int offset; +- +- /** +- * Constructor for {@link Position}. +- */ +- public Position(String file, int offset) { +- this.file =3D file; +- this.offset =3D offset; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof Position) { +- Position other =3D (Position) obj; +- return +- ObjectUtilities.equals(other.file, file) && +- other.offset =3D=3D offset; +- } +- return false; +- } +- +- public static Position fromJson(JsonObject jsonObject) { +- String file =3D jsonObject.get("file").getAsString(); +- int offset =3D jsonObject.get("offset").getAsInt(); +- return new Position(file, offset); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()= ); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The file containing the position. +- */ +- public String getFile() { +- return file; +- } +- +- /** +- * The offset of the position. +- */ +- public int getOffset() { +- return offset; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(file); +- builder.append(offset); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("file", file); +- jsonObject.addProperty("offset", offset); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("file=3D"); +- builder.append(file + ", "); +- builder.append("offset=3D"); +- builder.append(offset); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/PostfixTem= plateDescriptor.java b/pkg/analysis_server/tool/spec/generated/java/types/P= ostfixTemplateDescriptor.java +deleted file mode 100644 +index 8358f363390..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/PostfixTemplateDe= scriptor.java ++++ /dev/null +@@ -1,153 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * The description of a postfix completion template. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class PostfixTemplateDescriptor { +- +- public static final PostfixTemplateDescriptor[] EMPTY_ARRAY =3D new Pos= tfixTemplateDescriptor[0]; +- +- public static final List EMPTY_LIST =3D List= s.newArrayList(); +- +- /** +- * The template name, shown in the UI. +- */ +- private final String name; +- +- /** +- * The unique template key, not shown in the UI. +- */ +- private final String key; +- +- /** +- * A short example of the transformation performed when the template is= applied. +- */ +- private final String example; +- +- /** +- * Constructor for {@link PostfixTemplateDescriptor}. +- */ +- public PostfixTemplateDescriptor(String name, String key, String exampl= e) { +- this.name =3D name; +- this.key =3D key; +- this.example =3D example; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof PostfixTemplateDescriptor) { +- PostfixTemplateDescriptor other =3D (PostfixTemplateDescriptor) obj; +- return +- ObjectUtilities.equals(other.name, name) && +- ObjectUtilities.equals(other.key, key) && +- ObjectUtilities.equals(other.example, example); +- } +- return false; +- } +- +- public static PostfixTemplateDescriptor fromJson(JsonObject jsonObject)= { +- String name =3D jsonObject.get("name").getAsString(); +- String key =3D jsonObject.get("key").getAsString(); +- String example =3D jsonObject.get("example").getAsString(); +- return new PostfixTemplateDescriptor(name, key, example); +- } +- +- public static List fromJsonArray(JsonArray j= sonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A short example of the transformation performed when the template is= applied. +- */ +- public String getExample() { +- return example; +- } +- +- /** +- * The unique template key, not shown in the UI. +- */ +- public String getKey() { +- return key; +- } +- +- /** +- * The template name, shown in the UI. +- */ +- public String getName() { +- return name; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(name); +- builder.append(key); +- builder.append(example); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("name", name); +- jsonObject.addProperty("key", key); +- jsonObject.addProperty("example", example); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("key=3D"); +- builder.append(key + ", "); +- builder.append("example=3D"); +- builder.append(example); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/PubStatus.= java b/pkg/analysis_server/tool/spec/generated/java/types/PubStatus.java +deleted file mode 100644 +index 9d45a192ec8..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/PubStatus.java ++++ /dev/null +@@ -1,115 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An indication of the current state of pub execution. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class PubStatus { +- +- public static final PubStatus[] EMPTY_ARRAY =3D new PubStatus[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(); +- +- /** +- * True if the server is currently running pub to produce a list of pac= kage directories. +- */ +- private final boolean isListingPackageDirs; +- +- /** +- * Constructor for {@link PubStatus}. +- */ +- public PubStatus(boolean isListingPackageDirs) { +- this.isListingPackageDirs =3D isListingPackageDirs; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof PubStatus) { +- PubStatus other =3D (PubStatus) obj; +- return +- other.isListingPackageDirs =3D=3D isListingPackageDirs; +- } +- return false; +- } +- +- public static PubStatus fromJson(JsonObject jsonObject) { +- boolean isListingPackageDirs =3D jsonObject.get("isListingPackageDirs= ").getAsBoolean(); +- return new PubStatus(isListingPackageDirs); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size= ()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * True if the server is currently running pub to produce a list of pac= kage directories. +- */ +- public boolean isListingPackageDirs() { +- return isListingPackageDirs; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(isListingPackageDirs); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("isListingPackageDirs", isListingPackageDirs); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("isListingPackageDirs=3D"); +- builder.append(isListingPackageDirs); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gFeedback.java b/pkg/analysis_server/tool/spec/generated/java/types/Refacto= ringFeedback.java +deleted file mode 100644 +index d3cfa25c7e0..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringFeedba= ck.java ++++ /dev/null +@@ -1,85 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An abstract superclass of all refactoring feedbacks. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RefactoringFeedback { +- +- public static final RefactoringFeedback[] EMPTY_ARRAY =3D new Refactori= ngFeedback[0]; +- +- public static final List EMPTY_LIST =3D Lists.newA= rrayList(); +- +- /** +- * Constructor for {@link RefactoringFeedback}. +- */ +- public RefactoringFeedback() { +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RefactoringFeedback) { +- RefactoringFeedback other =3D (RefactoringFeedback) obj; +- return +- true; +- } +- return false; +- } +- +- public static RefactoringFeedback fromJson(JsonObject jsonObject) { +- return new RefactoringFeedback(); +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gKind.java b/pkg/analysis_server/tool/spec/generated/java/types/Refactoring= Kind.java +deleted file mode 100644 +index b4eb166b6e9..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringKind.j= ava ++++ /dev/null +@@ -1,44 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of refactorings that can be created. +- * +- * @coverage dart.server.generated.types +- */ +-public class RefactoringKind { +- +- public static final String CONVERT_GETTER_TO_METHOD =3D "CONVERT_GETTER= _TO_METHOD"; +- +- public static final String CONVERT_METHOD_TO_GETTER =3D "CONVERT_METHOD= _TO_GETTER"; +- +- public static final String EXTRACT_LOCAL_VARIABLE =3D "EXTRACT_LOCAL_VA= RIABLE"; +- +- public static final String EXTRACT_METHOD =3D "EXTRACT_METHOD"; +- +- public static final String INLINE_LOCAL_VARIABLE =3D "INLINE_LOCAL_VARI= ABLE"; +- +- public static final String INLINE_METHOD =3D "INLINE_METHOD"; +- +- public static final String MOVE_FILE =3D "MOVE_FILE"; +- +- public static final String RENAME =3D "RENAME"; +- +- public static final String SORT_MEMBERS =3D "SORT_MEMBERS"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gMethodParameter.java b/pkg/analysis_server/tool/spec/generated/java/types/= RefactoringMethodParameter.java +deleted file mode 100644 +index ddad03276f8..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringMethod= Parameter.java ++++ /dev/null +@@ -1,242 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a parameter in a method refactoring. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RefactoringMethodParameter { +- +- public static final RefactoringMethodParameter[] EMPTY_ARRAY =3D new Re= factoringMethodParameter[0]; +- +- public static final List EMPTY_LIST =3D Lis= ts.newArrayList(); +- +- /** +- * The unique identifier of the parameter. Clients may omit this field = for the parameters they want +- * to add. +- */ +- private String id; +- +- /** +- * The kind of the parameter. +- */ +- private String kind; +- +- /** +- * The type that should be given to the parameter, or the return type o= f the parameter's function +- * type. +- */ +- private String type; +- +- /** +- * The name that should be given to the parameter. +- */ +- private String name; +- +- /** +- * The parameter list of the parameter's function type. If the paramete= r is not of a function type, +- * this field will not be defined. If the function type has zero parame= ters, this field will have a +- * value of '()'. +- */ +- private String parameters; +- +- /** +- * Constructor for {@link RefactoringMethodParameter}. +- */ +- public RefactoringMethodParameter(String id, String kind, String type, = String name, String parameters) { +- this.id =3D id; +- this.kind =3D kind; +- this.type =3D type; +- this.name =3D name; +- this.parameters =3D parameters; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RefactoringMethodParameter) { +- RefactoringMethodParameter other =3D (RefactoringMethodParameter) o= bj; +- return +- ObjectUtilities.equals(other.id, id) && +- ObjectUtilities.equals(other.kind, kind) && +- ObjectUtilities.equals(other.type, type) && +- ObjectUtilities.equals(other.name, name) && +- ObjectUtilities.equals(other.parameters, parameters); +- } +- return false; +- } +- +- public static RefactoringMethodParameter fromJson(JsonObject jsonObject= ) { +- String id =3D jsonObject.get("id") =3D=3D null ? null : jsonObject.ge= t("id").getAsString(); +- String kind =3D jsonObject.get("kind").getAsString(); +- String type =3D jsonObject.get("type").getAsString(); +- String name =3D jsonObject.get("name").getAsString(); +- String parameters =3D jsonObject.get("parameters") =3D=3D null ? null= : jsonObject.get("parameters").getAsString(); +- return new RefactoringMethodParameter(id, kind, type, name, parameter= s); +- } +- +- public static List fromJsonArray(JsonArray = jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The unique identifier of the parameter. Clients may omit this field = for the parameters they want +- * to add. +- */ +- public String getId() { +- return id; +- } +- +- /** +- * The kind of the parameter. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The name that should be given to the parameter. +- */ +- public String getName() { +- return name; +- } +- +- /** +- * The parameter list of the parameter's function type. If the paramete= r is not of a function type, +- * this field will not be defined. If the function type has zero parame= ters, this field will have a +- * value of '()'. +- */ +- public String getParameters() { +- return parameters; +- } +- +- /** +- * The type that should be given to the parameter, or the return type o= f the parameter's function +- * type. +- */ +- public String getType() { +- return type; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(id); +- builder.append(kind); +- builder.append(type); +- builder.append(name); +- builder.append(parameters); +- return builder.toHashCode(); +- } +- +- /** +- * The unique identifier of the parameter. Clients may omit this field = for the parameters they want +- * to add. +- */ +- public void setId(String id) { +- this.id =3D id; +- } +- +- /** +- * The kind of the parameter. +- */ +- public void setKind(String kind) { +- this.kind =3D kind; +- } +- +- /** +- * The name that should be given to the parameter. +- */ +- public void setName(String name) { +- this.name =3D name; +- } +- +- /** +- * The parameter list of the parameter's function type. If the paramete= r is not of a function type, +- * this field will not be defined. If the function type has zero parame= ters, this field will have a +- * value of '()'. +- */ +- public void setParameters(String parameters) { +- this.parameters =3D parameters; +- } +- +- /** +- * The type that should be given to the parameter, or the return type o= f the parameter's function +- * type. +- */ +- public void setType(String type) { +- this.type =3D type; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- if (id !=3D null) { +- jsonObject.addProperty("id", id); +- } +- jsonObject.addProperty("kind", kind); +- jsonObject.addProperty("type", type); +- jsonObject.addProperty("name", name); +- if (parameters !=3D null) { +- jsonObject.addProperty("parameters", parameters); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("id=3D"); +- builder.append(id + ", "); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("type=3D"); +- builder.append(type + ", "); +- builder.append("name=3D"); +- builder.append(name + ", "); +- builder.append("parameters=3D"); +- builder.append(parameters); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gMethodParameterKind.java b/pkg/analysis_server/tool/spec/generated/java/ty= pes/RefactoringMethodParameterKind.java +deleted file mode 100644 +index c71d8bbdcb1..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringMethod= ParameterKind.java ++++ /dev/null +@@ -1,32 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of parameters. +- * +- * @coverage dart.server.generated.types +- */ +-public class RefactoringMethodParameterKind { +- +- public static final String REQUIRED =3D "REQUIRED"; +- +- public static final String POSITIONAL =3D "POSITIONAL"; +- +- public static final String NAMED =3D "NAMED"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gOptions.java b/pkg/analysis_server/tool/spec/generated/java/types/Refactor= ingOptions.java +deleted file mode 100644 +index 67abd4bb1ba..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringOption= s.java ++++ /dev/null +@@ -1,85 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An abstract superclass of all refactoring options. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RefactoringOptions { +- +- public static final RefactoringOptions[] EMPTY_ARRAY =3D new Refactorin= gOptions[0]; +- +- public static final List EMPTY_LIST =3D Lists.newAr= rayList(); +- +- /** +- * Constructor for {@link RefactoringOptions}. +- */ +- public RefactoringOptions() { +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RefactoringOptions) { +- RefactoringOptions other =3D (RefactoringOptions) obj; +- return +- true; +- } +- return false; +- } +- +- public static RefactoringOptions fromJson(JsonObject jsonObject) { +- return new RefactoringOptions(); +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gProblem.java b/pkg/analysis_server/tool/spec/generated/java/types/Refactor= ingProblem.java +deleted file mode 100644 +index 1b82e4a158a..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringProble= m.java ++++ /dev/null +@@ -1,159 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a problem related to a refactoring. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RefactoringProblem { +- +- public static final RefactoringProblem[] EMPTY_ARRAY =3D new Refactorin= gProblem[0]; +- +- public static final List EMPTY_LIST =3D Lists.newAr= rayList(); +- +- /** +- * The severity of the problem being represented. +- */ +- private final String severity; +- +- /** +- * A human-readable description of the problem being represented. +- */ +- private final String message; +- +- /** +- * The location of the problem being represented. This field is omitted= unless there is a specific +- * location associated with the problem (such as a location where an el= ement being renamed will be +- * shadowed). +- */ +- private final Location location; +- +- /** +- * Constructor for {@link RefactoringProblem}. +- */ +- public RefactoringProblem(String severity, String message, Location loc= ation) { +- this.severity =3D severity; +- this.message =3D message; +- this.location =3D location; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RefactoringProblem) { +- RefactoringProblem other =3D (RefactoringProblem) obj; +- return +- ObjectUtilities.equals(other.severity, severity) && +- ObjectUtilities.equals(other.message, message) && +- ObjectUtilities.equals(other.location, location); +- } +- return false; +- } +- +- public static RefactoringProblem fromJson(JsonObject jsonObject) { +- String severity =3D jsonObject.get("severity").getAsString(); +- String message =3D jsonObject.get("message").getAsString(); +- Location location =3D jsonObject.get("location") =3D=3D null ? null := Location.fromJson(jsonObject.get("location").getAsJsonObject()); +- return new RefactoringProblem(severity, message, location); +- } +- +- public static List fromJsonArray(JsonArray jsonArra= y) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The location of the problem being represented. This field is omitted= unless there is a specific +- * location associated with the problem (such as a location where an el= ement being renamed will be +- * shadowed). +- */ +- public Location getLocation() { +- return location; +- } +- +- /** +- * A human-readable description of the problem being represented. +- */ +- public String getMessage() { +- return message; +- } +- +- /** +- * The severity of the problem being represented. +- */ +- public String getSeverity() { +- return severity; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(severity); +- builder.append(message); +- builder.append(location); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("severity", severity); +- jsonObject.addProperty("message", message); +- if (location !=3D null) { +- jsonObject.add("location", location.toJson()); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("severity=3D"); +- builder.append(severity + ", "); +- builder.append("message=3D"); +- builder.append(message + ", "); +- builder.append("location=3D"); +- builder.append(location); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/Refactorin= gProblemSeverity.java b/pkg/analysis_server/tool/spec/generated/java/types/= RefactoringProblemSeverity.java +deleted file mode 100644 +index 6befcd6ec96..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringProble= mSeverity.java ++++ /dev/null +@@ -1,55 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the severities of problems that can be returned by t= he refactoring requests. +- * +- * @coverage dart.server.generated.types +- */ +-public class RefactoringProblemSeverity { +- +- /** +- * A minor code problem. No example, because it is not used yet. +- */ +- public static final String INFO =3D "INFO"; +- +- /** +- * A minor code problem. For example names of local variables should be= camel case and start with a +- * lower case letter. Staring the name of a variable with an upper case= is OK from the language +- * point of view, but it is nice to warn the user. +- */ +- public static final String WARNING =3D "WARNING"; +- +- /** +- * The refactoring technically can be performed, but there is a logical= problem. For example the +- * name of a local variable being extracted conflicts with another name= in the scope, or duplicate +- * parameter names in the method being extracted, or a conflict between= a parameter name and a +- * local variable, etc. In some cases the location of the problem is al= so provided, so the IDE can +- * show user the location and the problem, and let the user decide whet= her they want to perform the +- * refactoring. For example the name conflict might be expected, and th= e user wants to fix it +- * afterwards. +- */ +- public static final String ERROR =3D "ERROR"; +- +- /** +- * A fatal error, which prevents performing the refactoring. For exampl= e the name of a local +- * variable being extracted is not a valid identifier, or selection is = not a valid expression. +- */ +- public static final String FATAL =3D "FATAL"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/RemoveCont= entOverlay.java b/pkg/analysis_server/tool/spec/generated/java/types/Remove= ContentOverlay.java +deleted file mode 100644 +index c9e14a401aa..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RemoveContentOver= lay.java ++++ /dev/null +@@ -1,113 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A directive to remove an existing file content overlay. After processi= ng this directive, the +- * file contents will once again be read from the file system. +- * +- * If this directive is used on a file that doesn't currently have a cont= ent overlay, it has no +- * effect. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RemoveContentOverlay { +- +- public static final RemoveContentOverlay[] EMPTY_ARRAY =3D new RemoveCo= ntentOverlay[0]; +- +- public static final List EMPTY_LIST =3D Lists.new= ArrayList(); +- +- private final String type; +- +- /** +- * Constructor for {@link RemoveContentOverlay}. +- */ +- public RemoveContentOverlay() { +- this.type =3D "remove"; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RemoveContentOverlay) { +- RemoveContentOverlay other =3D (RemoveContentOverlay) obj; +- return +- ObjectUtilities.equals(other.type, type); +- } +- return false; +- } +- +- public static RemoveContentOverlay fromJson(JsonObject jsonObject) { +- String type =3D jsonObject.get("type").getAsString(); +- return new RemoveContentOverlay(); +- } +- +- public static List fromJsonArray(JsonArray jsonAr= ray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- public String getType() { +- return type; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(type); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("type", type); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("type=3D"); +- builder.append(type); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/RenameFeed= back.java b/pkg/analysis_server/tool/spec/generated/java/types/RenameFeedba= ck.java +deleted file mode 100644 +index c10021ff74e..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RenameFeedback.ja= va ++++ /dev/null +@@ -1,172 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RenameFeedback extends RefactoringFeedback { +- +- public static final RenameFeedback[] EMPTY_ARRAY =3D new RenameFeedback= [0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayL= ist(); +- +- /** +- * The offset to the beginning of the name selected to be renamed. +- */ +- private final int offset; +- +- /** +- * The length of the name selected to be renamed. +- */ +- private final int length; +- +- /** +- * The human-readable description of the kind of element being renamed = (such as "class" or +- * "function type alias"). +- */ +- private final String elementKindName; +- +- /** +- * The old name of the element before the refactoring. +- */ +- private final String oldName; +- +- /** +- * Constructor for {@link RenameFeedback}. +- */ +- public RenameFeedback(int offset, int length, String elementKindName, S= tring oldName) { +- this.offset =3D offset; +- this.length =3D length; +- this.elementKindName =3D elementKindName; +- this.oldName =3D oldName; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RenameFeedback) { +- RenameFeedback other =3D (RenameFeedback) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.elementKindName, elementKindName) && +- ObjectUtilities.equals(other.oldName, oldName); +- } +- return false; +- } +- +- public static RenameFeedback fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- String elementKindName =3D jsonObject.get("elementKindName").getAsStr= ing(); +- String oldName =3D jsonObject.get("oldName").getAsString(); +- return new RenameFeedback(offset, length, elementKindName, oldName); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(json= Array.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The human-readable description of the kind of element being renamed = (such as "class" or +- * "function type alias"). +- */ +- public String getElementKindName() { +- return elementKindName; +- } +- +- /** +- * The length of the name selected to be renamed. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset to the beginning of the name selected to be renamed. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The old name of the element before the refactoring. +- */ +- public String getOldName() { +- return oldName; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(elementKindName); +- builder.append(oldName); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- jsonObject.addProperty("elementKindName", elementKindName); +- jsonObject.addProperty("oldName", oldName); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("elementKindName=3D"); +- builder.append(elementKindName + ", "); +- builder.append("oldName=3D"); +- builder.append(oldName); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/RenameOpti= ons.java b/pkg/analysis_server/tool/spec/generated/java/types/RenameOptions= .java +deleted file mode 100644 +index 18b80e019d5..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RenameOptions.java ++++ /dev/null +@@ -1,120 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RenameOptions extends RefactoringOptions { +- +- public static final RenameOptions[] EMPTY_ARRAY =3D new RenameOptions[0= ]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLi= st(); +- +- /** +- * The name that the element should have after the refactoring. +- */ +- private String newName; +- +- /** +- * Constructor for {@link RenameOptions}. +- */ +- public RenameOptions(String newName) { +- this.newName =3D newName; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RenameOptions) { +- RenameOptions other =3D (RenameOptions) obj; +- return +- ObjectUtilities.equals(other.newName, newName); +- } +- return false; +- } +- +- public static RenameOptions fromJson(JsonObject jsonObject) { +- String newName =3D jsonObject.get("newName").getAsString(); +- return new RenameOptions(newName); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonAr= ray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * The name that the element should have after the refactoring. +- */ +- public String getNewName() { +- return newName; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(newName); +- return builder.toHashCode(); +- } +- +- /** +- * The name that the element should have after the refactoring. +- */ +- public void setNewName(String newName) { +- this.newName =3D newName; +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("newName", newName); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("newName=3D"); +- builder.append(newName); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/RequestErr= or.java b/pkg/analysis_server/tool/spec/generated/java/types/RequestError.j= ava +deleted file mode 100644 +index 34c6b317988..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RequestError.java ++++ /dev/null +@@ -1,155 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * An indication of a problem with the execution of the server, typically= in response to a request. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class RequestError { +- +- public static final RequestError[] EMPTY_ARRAY =3D new RequestError[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLis= t(); +- +- /** +- * A code that uniquely identifies the error that occurred. +- */ +- private final String code; +- +- /** +- * A short description of the error. +- */ +- private final String message; +- +- /** +- * The stack trace associated with processing the request, used for deb= ugging the server. +- */ +- private final String stackTrace; +- +- /** +- * Constructor for {@link RequestError}. +- */ +- public RequestError(String code, String message, String stackTrace) { +- this.code =3D code; +- this.message =3D message; +- this.stackTrace =3D stackTrace; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof RequestError) { +- RequestError other =3D (RequestError) obj; +- return +- ObjectUtilities.equals(other.code, code) && +- ObjectUtilities.equals(other.message, message) && +- ObjectUtilities.equals(other.stackTrace, stackTrace); +- } +- return false; +- } +- +- public static RequestError fromJson(JsonObject jsonObject) { +- String code =3D jsonObject.get("code").getAsString(); +- String message =3D jsonObject.get("message").getAsString(); +- String stackTrace =3D jsonObject.get("stackTrace") =3D=3D null ? null= : jsonObject.get("stackTrace").getAsString(); +- return new RequestError(code, message, stackTrace); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArra= y.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A code that uniquely identifies the error that occurred. +- */ +- public String getCode() { +- return code; +- } +- +- /** +- * A short description of the error. +- */ +- public String getMessage() { +- return message; +- } +- +- /** +- * The stack trace associated with processing the request, used for deb= ugging the server. +- */ +- public String getStackTrace() { +- return stackTrace; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(code); +- builder.append(message); +- builder.append(stackTrace); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("code", code); +- jsonObject.addProperty("message", message); +- if (stackTrace !=3D null) { +- jsonObject.addProperty("stackTrace", stackTrace); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("code=3D"); +- builder.append(code + ", "); +- builder.append("message=3D"); +- builder.append(message + ", "); +- builder.append("stackTrace=3D"); +- builder.append(stackTrace); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/RequestErr= orCode.java b/pkg/analysis_server/tool/spec/generated/java/types/RequestErr= orCode.java +deleted file mode 100644 +index a389b5bfd2c..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/RequestErrorCode.= java ++++ /dev/null +@@ -1,182 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the types of errors that can occur in the execution = of the server. +- * +- * @coverage dart.server.generated.types +- */ +-public class RequestErrorCode { +- +- /** +- * An "analysis.getErrors" or "analysis.getNavigation" request could no= t be satisfied because the +- * content of the file changed before the requested results could be co= mputed. +- */ +- public static final String CONTENT_MODIFIED =3D "CONTENT_MODIFIED"; +- +- /** +- * The server was unable to open a port for the diagnostic server. +- */ +- public static final String DEBUG_PORT_COULD_NOT_BE_OPENED =3D "DEBUG_PO= RT_COULD_NOT_BE_OPENED"; +- +- /** +- * A request specified a FilePath which does not match a file in an ana= lysis root, or the requested +- * operation is not available for the file. +- */ +- public static final String FILE_NOT_ANALYZED =3D "FILE_NOT_ANALYZED"; +- +- /** +- * An "edit.format" request specified a FilePath which does not match a= Dart file in an analysis +- * root. +- */ +- public static final String FORMAT_INVALID_FILE =3D "FORMAT_INVALID_FILE= "; +- +- /** +- * An "edit.format" request specified a file that contains syntax error= s. +- */ +- public static final String FORMAT_WITH_ERRORS =3D "FORMAT_WITH_ERRORS"; +- +- /** +- * An "analysis.getErrors" request specified a FilePath which does not = match a file currently +- * subject to analysis. +- */ +- public static final String GET_ERRORS_INVALID_FILE =3D "GET_ERRORS_INVA= LID_FILE"; +- +- /** +- * An "analysis.getImportedElements" request specified a FilePath that = does not match a file +- * currently subject to analysis. +- */ +- public static final String GET_IMPORTED_ELEMENTS_INVALID_FILE =3D "GET_= IMPORTED_ELEMENTS_INVALID_FILE"; +- +- /** +- * An "analysis.getKytheEntries" request specified a FilePath that does= not match a file that is +- * currently subject to analysis. +- */ +- public static final String GET_KYTHE_ENTRIES_INVALID_FILE =3D "GET_KYTH= E_ENTRIES_INVALID_FILE"; +- +- /** +- * An "analysis.getNavigation" request specified a FilePath which does = not match a file currently +- * subject to analysis. +- */ +- public static final String GET_NAVIGATION_INVALID_FILE =3D "GET_NAVIGAT= ION_INVALID_FILE"; +- +- /** +- * An "analysis.getReachableSources" request specified a FilePath which= does not match a file +- * currently subject to analysis. +- */ +- public static final String GET_REACHABLE_SOURCES_INVALID_FILE =3D "GET_= REACHABLE_SOURCES_INVALID_FILE"; +- +- /** +- * An "edit.importElements" request specified a FilePath that does not = match a file currently +- * subject to analysis. +- */ +- public static final String IMPORT_ELEMENTS_INVALID_FILE =3D "IMPORT_ELE= MENTS_INVALID_FILE"; +- +- /** +- * A path passed as an argument to a request (such as analysis.reanalyz= e) is required to be an +- * analysis root, but isn't. +- */ +- public static final String INVALID_ANALYSIS_ROOT =3D "INVALID_ANALYSIS_= ROOT"; +- +- /** +- * The context root used to create an execution context does not exist. +- */ +- public static final String INVALID_EXECUTION_CONTEXT =3D "INVALID_EXECU= TION_CONTEXT"; +- +- /** +- * The format of the given file path is invalid, e.g. is not absolute a= nd normalized. +- */ +- public static final String INVALID_FILE_PATH_FORMAT =3D "INVALID_FILE_P= ATH_FORMAT"; +- +- /** +- * An "analysis.updateContent" request contained a ChangeContentOverlay= object which can't be +- * applied, due to an edit having an offset or length that is out of ra= nge. +- */ +- public static final String INVALID_OVERLAY_CHANGE =3D "INVALID_OVERLAY_= CHANGE"; +- +- /** +- * One of the method parameters was invalid. +- */ +- public static final String INVALID_PARAMETER =3D "INVALID_PARAMETER"; +- +- /** +- * A malformed request was received. +- */ +- public static final String INVALID_REQUEST =3D "INVALID_REQUEST"; +- +- /** +- * An "edit.organizeDirectives" request specified a Dart file that cann= ot be analyzed. The reason +- * is described in the message. +- */ +- public static final String ORGANIZE_DIRECTIVES_ERROR =3D "ORGANIZE_DIRE= CTIVES_ERROR"; +- +- /** +- * Another refactoring request was received during processing of this o= ne. +- */ +- public static final String REFACTORING_REQUEST_CANCELLED =3D "REFACTORI= NG_REQUEST_CANCELLED"; +- +- /** +- * The analysis server has already been started (and hence won't accept= new connections). +- * +- * This error is included for future expansion; at present the analysis= server can only speak to +- * one client at a time so this error will never occur. +- */ +- public static final String SERVER_ALREADY_STARTED =3D "SERVER_ALREADY_S= TARTED"; +- +- /** +- * An internal error occurred in the analysis server. Also see the serv= er.error notification. +- */ +- public static final String SERVER_ERROR =3D "SERVER_ERROR"; +- +- /** +- * An "edit.sortMembers" request specified a FilePath which does not ma= tch a Dart file in an +- * analysis root. +- */ +- public static final String SORT_MEMBERS_INVALID_FILE =3D "SORT_MEMBERS_= INVALID_FILE"; +- +- /** +- * An "edit.sortMembers" request specified a Dart file that has scan or= parse errors. +- */ +- public static final String SORT_MEMBERS_PARSE_ERRORS =3D "SORT_MEMBERS_= PARSE_ERRORS"; +- +- /** +- * An "analysis.setPriorityFiles" request includes one or more files th= at are not being analyzed. +- * +- * This is a legacy error; it will be removed before the API reaches ve= rsion 1.0. +- */ +- public static final String UNANALYZED_PRIORITY_FILES =3D "UNANALYZED_PR= IORITY_FILES"; +- +- /** +- * A request was received which the analysis server does not recognize,= or cannot handle in its +- * current configuration. +- */ +- public static final String UNKNOWN_REQUEST =3D "UNKNOWN_REQUEST"; +- +- /** +- * The analysis server was requested to perform an action on a source t= hat does not exist. +- */ +- public static final String UNKNOWN_SOURCE =3D "UNKNOWN_SOURCE"; +- +- /** +- * The analysis server was requested to perform an action which is not = supported. +- * +- * This is a legacy error; it will be removed before the API reaches ve= rsion 1.0. +- */ +- public static final String UNSUPPORTED_FEATURE =3D "UNSUPPORTED_FEATURE= "; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/SearchResu= lt.java b/pkg/analysis_server/tool/spec/generated/java/types/SearchResult.j= ava +deleted file mode 100644 +index 299aba0c1cc..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/SearchResult.java ++++ /dev/null +@@ -1,182 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A single result from a search request. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class SearchResult { +- +- public static final SearchResult[] EMPTY_ARRAY =3D new SearchResult[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLis= t(); +- +- /** +- * The location of the code that matched the search criteria. +- */ +- private final Location location; +- +- /** +- * The kind of element that was found or the kind of reference that was= found. +- */ +- private final String kind; +- +- /** +- * True if the result is a potential match but cannot be confirmed to b= e a match. For example, if +- * all references to a method m defined in some class were requested, a= nd a reference to a method m +- * from an unknown class were found, it would be marked as being a pote= ntial match. +- */ +- private final boolean isPotential; +- +- /** +- * The elements that contain the result, starting with the most immedia= tely enclosing ancestor and +- * ending with the library. +- */ +- private final List path; +- +- /** +- * Constructor for {@link SearchResult}. +- */ +- public SearchResult(Location location, String kind, boolean isPotential= , List path) { +- this.location =3D location; +- this.kind =3D kind; +- this.isPotential =3D isPotential; +- this.path =3D path; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof SearchResult) { +- SearchResult other =3D (SearchResult) obj; +- return +- ObjectUtilities.equals(other.location, location) && +- ObjectUtilities.equals(other.kind, kind) && +- other.isPotential =3D=3D isPotential && +- ObjectUtilities.equals(other.path, path); +- } +- return false; +- } +- +- public static SearchResult fromJson(JsonObject jsonObject) { +- Location location =3D Location.fromJson(jsonObject.get("location").ge= tAsJsonObject()); +- String kind =3D jsonObject.get("kind").getAsString(); +- boolean isPotential =3D jsonObject.get("isPotential").getAsBoolean(); +- List path =3D Element.fromJsonArray(jsonObject.get("path").g= etAsJsonArray()); +- return new SearchResult(location, kind, isPotential, path); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArra= y.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * True if the result is a potential match but cannot be confirmed to b= e a match. For example, if +- * all references to a method m defined in some class were requested, a= nd a reference to a method m +- * from an unknown class were found, it would be marked as being a pote= ntial match. +- */ +- public boolean isPotential() { +- return isPotential; +- } +- +- /** +- * The kind of element that was found or the kind of reference that was= found. +- */ +- public String getKind() { +- return kind; +- } +- +- /** +- * The location of the code that matched the search criteria. +- */ +- public Location getLocation() { +- return location; +- } +- +- /** +- * The elements that contain the result, starting with the most immedia= tely enclosing ancestor and +- * ending with the library. +- */ +- public List getPath() { +- return path; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(location); +- builder.append(kind); +- builder.append(isPotential); +- builder.append(path); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.add("location", location.toJson()); +- jsonObject.addProperty("kind", kind); +- jsonObject.addProperty("isPotential", isPotential); +- JsonArray jsonArrayPath =3D new JsonArray(); +- for (Element elt : path) { +- jsonArrayPath.add(elt.toJson()); +- } +- jsonObject.add("path", jsonArrayPath); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("location=3D"); +- builder.append(location + ", "); +- builder.append("kind=3D"); +- builder.append(kind + ", "); +- builder.append("isPotential=3D"); +- builder.append(isPotential + ", "); +- builder.append("path=3D"); +- builder.append(StringUtils.join(path, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/SearchResu= ltKind.java b/pkg/analysis_server/tool/spec/generated/java/types/SearchResu= ltKind.java +deleted file mode 100644 +index e5562728a9e..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/SearchResultKind.= java ++++ /dev/null +@@ -1,61 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the kinds of search results returned by the search d= omain. +- * +- * @coverage dart.server.generated.types +- */ +-public class SearchResultKind { +- +- /** +- * The declaration of an element. +- */ +- public static final String DECLARATION =3D "DECLARATION"; +- +- /** +- * The invocation of a function or method. +- */ +- public static final String INVOCATION =3D "INVOCATION"; +- +- /** +- * A reference to a field, parameter or variable where it is being read. +- */ +- public static final String READ =3D "READ"; +- +- /** +- * A reference to a field, parameter or variable where it is being read= and written. +- */ +- public static final String READ_WRITE =3D "READ_WRITE"; +- +- /** +- * A reference to an element. +- */ +- public static final String REFERENCE =3D "REFERENCE"; +- +- /** +- * Some other kind of search result. +- */ +- public static final String UNKNOWN =3D "UNKNOWN"; +- +- /** +- * A reference to a field, parameter or variable where it is being writ= ten. +- */ +- public static final String WRITE =3D "WRITE"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ServerServ= ice.java b/pkg/analysis_server/tool/spec/generated/java/types/ServerService= .java +deleted file mode 100644 +index 6846e6ec066..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/ServerService.java ++++ /dev/null +@@ -1,28 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-/** +- * An enumeration of the services provided by the server domain. +- * +- * @coverage dart.server.generated.types +- */ +-public class ServerService { +- +- public static final String STATUS =3D "STATUS"; +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/SourceChan= ge.java b/pkg/analysis_server/tool/spec/generated/java/types/SourceChange.j= ava +deleted file mode 100644 +index 6842e2fedf6..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/SourceChange.java ++++ /dev/null +@@ -1,182 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a set of edits that implement a single conceptual cha= nge. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class SourceChange { +- +- public static final SourceChange[] EMPTY_ARRAY =3D new SourceChange[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayLis= t(); +- +- /** +- * A human-readable description of the change to be applied. +- */ +- private final String message; +- +- /** +- * A list of the edits used to effect the change, grouped by file. +- */ +- private final List edits; +- +- /** +- * A list of the linked editing groups used to customize the changes th= at were made. +- */ +- private final List linkedEditGroups; +- +- /** +- * The position that should be selected after the edits have been appli= ed. +- */ +- private final Position selection; +- +- /** +- * Constructor for {@link SourceChange}. +- */ +- public SourceChange(String message, List edits, List linkedEditGroups, Position selection) { +- this.message =3D message; +- this.edits =3D edits; +- this.linkedEditGroups =3D linkedEditGroups; +- this.selection =3D selection; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof SourceChange) { +- SourceChange other =3D (SourceChange) obj; +- return +- ObjectUtilities.equals(other.message, message) && +- ObjectUtilities.equals(other.edits, edits) && +- ObjectUtilities.equals(other.linkedEditGroups, linkedEditGroups) = && +- ObjectUtilities.equals(other.selection, selection); +- } +- return false; +- } +- +- public static SourceChange fromJson(JsonObject jsonObject) { +- String message =3D jsonObject.get("message").getAsString(); +- List edits =3D SourceFileEdit.fromJsonArray(jsonObjec= t.get("edits").getAsJsonArray()); +- List linkedEditGroups =3D LinkedEditGroup.fromJsonAr= ray(jsonObject.get("linkedEditGroups").getAsJsonArray()); +- Position selection =3D jsonObject.get("selection") =3D=3D null ? null= : Position.fromJson(jsonObject.get("selection").getAsJsonObject()); +- return new SourceChange(message, edits, linkedEditGroups, selection); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArra= y.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A list of the edits used to effect the change, grouped by file. +- */ +- public List getEdits() { +- return edits; +- } +- +- /** +- * A list of the linked editing groups used to customize the changes th= at were made. +- */ +- public List getLinkedEditGroups() { +- return linkedEditGroups; +- } +- +- /** +- * A human-readable description of the change to be applied. +- */ +- public String getMessage() { +- return message; +- } +- +- /** +- * The position that should be selected after the edits have been appli= ed. +- */ +- public Position getSelection() { +- return selection; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(message); +- builder.append(edits); +- builder.append(linkedEditGroups); +- builder.append(selection); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("message", message); +- JsonArray jsonArrayEdits =3D new JsonArray(); +- for (SourceFileEdit elt : edits) { +- jsonArrayEdits.add(elt.toJson()); +- } +- jsonObject.add("edits", jsonArrayEdits); +- JsonArray jsonArrayLinkedEditGroups =3D new JsonArray(); +- for (LinkedEditGroup elt : linkedEditGroups) { +- jsonArrayLinkedEditGroups.add(elt.toJson()); +- } +- jsonObject.add("linkedEditGroups", jsonArrayLinkedEditGroups); +- if (selection !=3D null) { +- jsonObject.add("selection", selection.toJson()); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("message=3D"); +- builder.append(message + ", "); +- builder.append("edits=3D"); +- builder.append(StringUtils.join(edits, ", ") + ", "); +- builder.append("linkedEditGroups=3D"); +- builder.append(StringUtils.join(linkedEditGroups, ", ") + ", "); +- builder.append("selection=3D"); +- builder.append(selection); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/SourceEdit= .java b/pkg/analysis_server/tool/spec/generated/java/types/SourceEdit.java +deleted file mode 100644 +index 1d54802df1b..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/SourceEdit.java ++++ /dev/null +@@ -1,186 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a single change to a single file. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class SourceEdit { +- +- public static final SourceEdit[] EMPTY_ARRAY =3D new SourceEdit[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayList(= ); +- +- /** +- * The offset of the region to be modified. +- */ +- private final int offset; +- +- /** +- * The length of the region to be modified. +- */ +- private final int length; +- +- /** +- * The code that is to replace the specified region in the original cod= e. +- */ +- private final String replacement; +- +- /** +- * An identifier that uniquely identifies this source edit from other e= dits in the same response. +- * This field is omitted unless a containing structure needs to be able= to identify the edit for +- * some reason. +- * +- * For example, some refactoring operations can produce edits that migh= t not be appropriate +- * (referred to as potential edits). Such edits will have an id so that= they can be referenced. +- * Edits in the same response that do not need to be referenced will no= t have an id. +- */ +- private final String id; +- +- /** +- * Constructor for {@link SourceEdit}. +- */ +- public SourceEdit(int offset, int length, String replacement, String id= ) { +- this.offset =3D offset; +- this.length =3D length; +- this.replacement =3D replacement; +- this.id =3D id; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof SourceEdit) { +- SourceEdit other =3D (SourceEdit) obj; +- return +- other.offset =3D=3D offset && +- other.length =3D=3D length && +- ObjectUtilities.equals(other.replacement, replacement) && +- ObjectUtilities.equals(other.id, id); +- } +- return false; +- } +- +- public static SourceEdit fromJson(JsonObject jsonObject) { +- int offset =3D jsonObject.get("offset").getAsInt(); +- int length =3D jsonObject.get("length").getAsInt(); +- String replacement =3D jsonObject.get("replacement").getAsString(); +- String id =3D jsonObject.get("id") =3D=3D null ? null : jsonObject.ge= t("id").getAsString(); +- return new SourceEdit(offset, length, replacement, id); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.si= ze()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * An identifier that uniquely identifies this source edit from other e= dits in the same response. +- * This field is omitted unless a containing structure needs to be able= to identify the edit for +- * some reason. +- * +- * For example, some refactoring operations can produce edits that migh= t not be appropriate +- * (referred to as potential edits). Such edits will have an id so that= they can be referenced. +- * Edits in the same response that do not need to be referenced will no= t have an id. +- */ +- public String getId() { +- return id; +- } +- +- /** +- * The length of the region to be modified. +- */ +- public int getLength() { +- return length; +- } +- +- /** +- * The offset of the region to be modified. +- */ +- public int getOffset() { +- return offset; +- } +- +- /** +- * The code that is to replace the specified region in the original cod= e. +- */ +- public String getReplacement() { +- return replacement; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(offset); +- builder.append(length); +- builder.append(replacement); +- builder.append(id); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("offset", offset); +- jsonObject.addProperty("length", length); +- jsonObject.addProperty("replacement", replacement); +- if (id !=3D null) { +- jsonObject.addProperty("id", id); +- } +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("offset=3D"); +- builder.append(offset + ", "); +- builder.append("length=3D"); +- builder.append(length + ", "); +- builder.append("replacement=3D"); +- builder.append(replacement + ", "); +- builder.append("id=3D"); +- builder.append(id); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/SourceFile= Edit.java b/pkg/analysis_server/tool/spec/generated/java/types/SourceFileEd= it.java +deleted file mode 100644 +index 18fab9bd18f..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/SourceFileEdit.ja= va ++++ /dev/null +@@ -1,163 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A description of a set of changes to a single file. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class SourceFileEdit { +- +- public static final SourceFileEdit[] EMPTY_ARRAY =3D new SourceFileEdit= [0]; +- +- public static final List EMPTY_LIST =3D Lists.newArrayL= ist(); +- +- /** +- * The file containing the code to be modified. +- */ +- private final String file; +- +- /** +- * The modification stamp of the file at the moment when the change was= created, in milliseconds +- * since the "Unix epoch". Will be -1 if the file did not exist and sho= uld be created. The client +- * may use this field to make sure that the file was not changed since = then, so it is safe to apply +- * the change. +- */ +- private final long fileStamp; +- +- /** +- * A list of the edits used to effect the change. +- */ +- private final List edits; +- +- /** +- * Constructor for {@link SourceFileEdit}. +- */ +- public SourceFileEdit(String file, long fileStamp, List edi= ts) { +- this.file =3D file; +- this.fileStamp =3D fileStamp; +- this.edits =3D edits; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof SourceFileEdit) { +- SourceFileEdit other =3D (SourceFileEdit) obj; +- return +- ObjectUtilities.equals(other.file, file) && +- other.fileStamp =3D=3D fileStamp && +- ObjectUtilities.equals(other.edits, edits); +- } +- return false; +- } +- +- public static SourceFileEdit fromJson(JsonObject jsonObject) { +- String file =3D jsonObject.get("file").getAsString(); +- long fileStamp =3D jsonObject.get("fileStamp").getAsLong(); +- List edits =3D SourceEdit.fromJsonArray(jsonObject.get("e= dits").getAsJsonArray()); +- return new SourceFileEdit(file, fileStamp, edits); +- } +- +- public static List fromJsonArray(JsonArray jsonArray) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(json= Array.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- /** +- * A list of the edits used to effect the change. +- */ +- public List getEdits() { +- return edits; +- } +- +- /** +- * The file containing the code to be modified. +- */ +- public String getFile() { +- return file; +- } +- +- /** +- * The modification stamp of the file at the moment when the change was= created, in milliseconds +- * since the "Unix epoch". Will be -1 if the file did not exist and sho= uld be created. The client +- * may use this field to make sure that the file was not changed since = then, so it is safe to apply +- * the change. +- */ +- public long getFileStamp() { +- return fileStamp; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(file); +- builder.append(fileStamp); +- builder.append(edits); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.addProperty("file", file); +- jsonObject.addProperty("fileStamp", fileStamp); +- JsonArray jsonArrayEdits =3D new JsonArray(); +- for (SourceEdit elt : edits) { +- jsonArrayEdits.add(elt.toJson()); +- } +- jsonObject.add("edits", jsonArrayEdits); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("file=3D"); +- builder.append(file + ", "); +- builder.append("fileStamp=3D"); +- builder.append(fileStamp + ", "); +- builder.append("edits=3D"); +- builder.append(StringUtils.join(edits, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/generated/java/types/TypeHierar= chyItem.java b/pkg/analysis_server/tool/spec/generated/java/types/TypeHiera= rchyItem.java +deleted file mode 100644 +index b6420a2a21c..00000000000 +--- a/pkg/analysis_server/tool/spec/generated/java/types/TypeHierarchyItem= .java ++++ /dev/null +@@ -1,271 +0,0 @@ +-/* +- * Copyright (c) 2015, the Dart project authors. +- * +- * Licensed under the Eclipse Public License v1.0 (the "License"); you ma= y not use this file except +- * in compliance with the License. You may obtain a copy of the License at +- * +- * http://www.eclipse.org/legal/epl-v10.html +- * +- * Unless required by applicable law or agreed to in writing, software di= stributed under the License +- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS O= F ANY KIND, either express +- * or implied. See the License for the specific language governing permis= sions and limitations under +- * the License. +- * +- * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". +- */ +-package org.dartlang.analysis.server.protocol; +- +-import java.util.Arrays; +-import java.util.List; +-import java.util.Map; +-import com.google.common.collect.Lists; +-import com.google.dart.server.utilities.general.JsonUtilities; +-import com.google.dart.server.utilities.general.ObjectUtilities; +-import com.google.gson.JsonArray; +-import com.google.gson.JsonElement; +-import com.google.gson.JsonObject; +-import com.google.gson.JsonPrimitive; +-import org.apache.commons.lang3.builder.HashCodeBuilder; +-import java.util.ArrayList; +-import java.util.Iterator; +-import org.apache.commons.lang3.StringUtils; +- +-/** +- * A representation of a class in a type hierarchy. +- * +- * @coverage dart.server.generated.types +- */ +-@SuppressWarnings("unused") +-public class TypeHierarchyItem { +- +- public static final TypeHierarchyItem[] EMPTY_ARRAY =3D new TypeHierarc= hyItem[0]; +- +- public static final List EMPTY_LIST =3D Lists.newArr= ayList(); +- +- /** +- * The class element represented by this item. +- */ +- private final Element classElement; +- +- /** +- * The name to be displayed for the class. This field will be omitted i= f the display name is the +- * same as the name of the element. The display name is different if th= ere is additional type +- * information to be displayed, such as type arguments. +- */ +- private final String displayName; +- +- /** +- * The member in the class corresponding to the member on which the hie= rarchy was requested. This +- * field will be omitted if the hierarchy was not requested for a membe= r or if the class does not +- * have a corresponding member. +- */ +- private final Element memberElement; +- +- /** +- * The index of the item representing the superclass of this class. Thi= s field will be omitted if +- * this item represents the class Object. +- */ +- private final Integer superclass; +- +- /** +- * The indexes of the items representing the interfaces implemented by = this class. The list will be +- * empty if there are no implemented interfaces. +- */ +- private final int[] interfaces; +- +- /** +- * The indexes of the items representing the mixins referenced by this = class. The list will be +- * empty if there are no classes mixed in to this class. +- */ +- private final int[] mixins; +- +- /** +- * The indexes of the items representing the subtypes of this class. Th= e list will be empty if +- * there are no subtypes or if this item represents a supertype of the = pivot type. +- */ +- private final int[] subclasses; +- +- /** +- * Constructor for {@link TypeHierarchyItem}. +- */ +- public TypeHierarchyItem(Element classElement, String displayName, Elem= ent memberElement, Integer superclass, int[] interfaces, int[] mixins, int[= ] subclasses) { +- this.classElement =3D classElement; +- this.displayName =3D displayName; +- this.memberElement =3D memberElement; +- this.superclass =3D superclass; +- this.interfaces =3D interfaces; +- this.mixins =3D mixins; +- this.subclasses =3D subclasses; +- } +- +- @Override +- public boolean equals(Object obj) { +- if (obj instanceof TypeHierarchyItem) { +- TypeHierarchyItem other =3D (TypeHierarchyItem) obj; +- return +- ObjectUtilities.equals(other.classElement, classElement) && +- ObjectUtilities.equals(other.displayName, displayName) && +- ObjectUtilities.equals(other.memberElement, memberElement) && +- ObjectUtilities.equals(other.superclass, superclass) && +- Arrays.equals(other.interfaces, interfaces) && +- Arrays.equals(other.mixins, mixins) && +- Arrays.equals(other.subclasses, subclasses); +- } +- return false; +- } +- +- public static TypeHierarchyItem fromJson(JsonObject jsonObject) { +- Element classElement =3D Element.fromJson(jsonObject.get("classElemen= t").getAsJsonObject()); +- String displayName =3D jsonObject.get("displayName") =3D=3D null ? nu= ll : jsonObject.get("displayName").getAsString(); +- Element memberElement =3D jsonObject.get("memberElement") =3D=3D null= ? null : Element.fromJson(jsonObject.get("memberElement").getAsJsonObject(= )); +- Integer superclass =3D jsonObject.get("superclass") =3D=3D null ? nul= l : jsonObject.get("superclass").getAsInt(); +- int[] interfaces =3D JsonUtilities.decodeIntArray(jsonObject.get("int= erfaces").getAsJsonArray()); +- int[] mixins =3D JsonUtilities.decodeIntArray(jsonObject.get("mixins"= ).getAsJsonArray()); +- int[] subclasses =3D JsonUtilities.decodeIntArray(jsonObject.get("sub= classes").getAsJsonArray()); +- return new TypeHierarchyItem(classElement, displayName, memberElement= , superclass, interfaces, mixins, subclasses); +- } +- +- public static List fromJsonArray(JsonArray jsonArray= ) { +- if (jsonArray =3D=3D null) { +- return EMPTY_LIST; +- } +- ArrayList list =3D new ArrayList(jsonArray.size()); +- Iterator iterator =3D jsonArray.iterator(); +- while (iterator.hasNext()) { +- list.add(fromJson(iterator.next().getAsJsonObject())); +- } +- return list; +- } +- +- public String getBestName() { +- if (displayName =3D=3D null) { +- return classElement.getName(); +- } else { +- return displayName; +- } +- } +- +- /** +- * The class element represented by this item. +- */ +- public Element getClassElement() { +- return classElement; +- } +- +- /** +- * The name to be displayed for the class. This field will be omitted i= f the display name is the +- * same as the name of the element. The display name is different if th= ere is additional type +- * information to be displayed, such as type arguments. +- */ +- public String getDisplayName() { +- return displayName; +- } +- +- /** +- * The indexes of the items representing the interfaces implemented by = this class. The list will be +- * empty if there are no implemented interfaces. +- */ +- public int[] getInterfaces() { +- return interfaces; +- } +- +- /** +- * The member in the class corresponding to the member on which the hie= rarchy was requested. This +- * field will be omitted if the hierarchy was not requested for a membe= r or if the class does not +- * have a corresponding member. +- */ +- public Element getMemberElement() { +- return memberElement; +- } +- +- /** +- * The indexes of the items representing the mixins referenced by this = class. The list will be +- * empty if there are no classes mixed in to this class. +- */ +- public int[] getMixins() { +- return mixins; +- } +- +- /** +- * The indexes of the items representing the subtypes of this class. Th= e list will be empty if +- * there are no subtypes or if this item represents a supertype of the = pivot type. +- */ +- public int[] getSubclasses() { +- return subclasses; +- } +- +- /** +- * The index of the item representing the superclass of this class. Thi= s field will be omitted if +- * this item represents the class Object. +- */ +- public Integer getSuperclass() { +- return superclass; +- } +- +- @Override +- public int hashCode() { +- HashCodeBuilder builder =3D new HashCodeBuilder(); +- builder.append(classElement); +- builder.append(displayName); +- builder.append(memberElement); +- builder.append(superclass); +- builder.append(interfaces); +- builder.append(mixins); +- builder.append(subclasses); +- return builder.toHashCode(); +- } +- +- public JsonObject toJson() { +- JsonObject jsonObject =3D new JsonObject(); +- jsonObject.add("classElement", classElement.toJson()); +- if (displayName !=3D null) { +- jsonObject.addProperty("displayName", displayName); +- } +- if (memberElement !=3D null) { +- jsonObject.add("memberElement", memberElement.toJson()); +- } +- if (superclass !=3D null) { +- jsonObject.addProperty("superclass", superclass); +- } +- JsonArray jsonArrayInterfaces =3D new JsonArray(); +- for (int elt : interfaces) { +- jsonArrayInterfaces.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("interfaces", jsonArrayInterfaces); +- JsonArray jsonArrayMixins =3D new JsonArray(); +- for (int elt : mixins) { +- jsonArrayMixins.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("mixins", jsonArrayMixins); +- JsonArray jsonArraySubclasses =3D new JsonArray(); +- for (int elt : subclasses) { +- jsonArraySubclasses.add(new JsonPrimitive(elt)); +- } +- jsonObject.add("subclasses", jsonArraySubclasses); +- return jsonObject; +- } +- +- @Override +- public String toString() { +- StringBuilder builder =3D new StringBuilder(); +- builder.append("["); +- builder.append("classElement=3D"); +- builder.append(classElement + ", "); +- builder.append("displayName=3D"); +- builder.append(displayName + ", "); +- builder.append("memberElement=3D"); +- builder.append(memberElement + ", "); +- builder.append("superclass=3D"); +- builder.append(superclass + ", "); +- builder.append("interfaces=3D"); +- builder.append(StringUtils.join(interfaces, ", ") + ", "); +- builder.append("mixins=3D"); +- builder.append(StringUtils.join(mixins, ", ") + ", "); +- builder.append("subclasses=3D"); +- builder.append(StringUtils.join(subclasses, ", ")); +- builder.append("]"); +- return builder.toString(); +- } +- +-} +diff --git a/pkg/analysis_server/tool/spec/implied_types.dart b/pkg/analys= is_server/tool/spec/implied_types.dart +deleted file mode 100644 +index 49531b7fb01..00000000000 +--- a/pkg/analysis_server/tool/spec/implied_types.dart ++++ /dev/null +@@ -1,89 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code for enumerating the set of types implied by the API. +- */ +-import 'package:analyzer/src/codegen/tools.dart'; +- +-import 'api.dart'; +- +-Map computeImpliedTypes(Api api) { +- _ImpliedTypesVisitor visitor =3D new _ImpliedTypesVisitor(api); +- visitor.visitApi(); +- return visitor.impliedTypes; +-} +- +-class ImpliedType { +- final String camelName; +- final String humanReadableName; +- final TypeDecl type; +- +- /** +- * Kind of implied type this is. One of: +- * - 'requestParams' +- * - 'requestResult' +- * - 'notificationParams' +- * - 'refactoringFeedback' +- * - 'refactoringOptions' +- * - 'typeDefinition' +- */ +- final String kind; +- +- /** +- * API node from which this type was inferred. +- */ +- final ApiNode apiNode; +- +- ImpliedType(this.camelName, this.humanReadableName, this.type, this.kin= d, +- this.apiNode); +-} +- +-class _ImpliedTypesVisitor extends HierarchicalApiVisitor { +- Map impliedTypes =3D {}; +- +- _ImpliedTypesVisitor(Api api) : super(api); +- +- void storeType(String name, String nameSuffix, TypeDecl type, String ki= nd, +- ApiNode apiNode) { +- String humanReadableName =3D name; +- List camelNameParts =3D name.split('.'); +- if (nameSuffix !=3D null) { +- humanReadableName +=3D ' $nameSuffix'; +- camelNameParts.add(nameSuffix); +- } +- String camelName =3D camelJoin(camelNameParts); +- impliedTypes[camelName] =3D +- new ImpliedType(camelName, humanReadableName, type, kind, apiNode= ); +- } +- +- @override +- visitNotification(Notification notification) { +- storeType(notification.longEvent, 'params', notification.params, +- 'notificationParams', notification); +- } +- +- @override +- visitRefactoring(Refactoring refactoring) { +- String camelKind =3D camelJoin(refactoring.kind.toLowerCase().split('= _')); +- storeType(camelKind, 'feedback', refactoring.feedback, +- 'refactoringFeedback', refactoring); +- storeType(camelKind, 'options', refactoring.options, 'refactoringOpti= ons', +- refactoring); +- } +- +- @override +- visitRequest(Request request) { +- storeType( +- request.longMethod, 'params', request.params, 'requestParams', re= quest); +- storeType( +- request.longMethod, 'result', request.result, 'requestResult', re= quest); +- } +- +- @override +- visitTypeDefinition(TypeDefinition typeDefinition) { +- storeType(typeDefinition.name, null, typeDefinition.type, 'typeDefini= tion', +- typeDefinition); +- } +-} +diff --git a/pkg/analysis_server/tool/spec/spec_input.html b/pkg/analysis_= server/tool/spec/spec_input.html +deleted file mode 100644 +index 29b17e6ddf0..00000000000 +--- a/pkg/analysis_server/tool/spec/spec_input.html ++++ /dev/null +@@ -1,3975 +0,0 @@ +- +- +- +- +- Analysis Server API Specification +- +- +-

    Analysis Server API Specification

    +-

    Version +- 1.18.4 +-

    +-

    +- This document contains a specification of the API provided by the +- analysis server. The API in this document is currently under +- development. Changes to the API will be accompanied by an update to the +- protocol version number according to the principles of semantic +- versioning (semver.org). +-

    +-

    Overview

    +-

    +- The analysis server API is a bi-directional client-server +- API. The API is independent of the transport mechanism used, but +- is heavily influenced by a model in which sockets or character +- streams are used to transport JSON-RPC encoded information. +-

    +-

    Transport Mechanism

    +-

    +- The characters passed to the server are expected to be encoded +- using UTF-8. +-

    +-

    +- When character streams are used as the transport, messages are +- delineated by newlines. This means, in particular, that the JSON +- encoding process must not introduce newlines within a +- message. Note however that newlines are used in this document +- for readability. +-

    +-

    +- It is the client's responsibility to read output from the server to +- avoid its blocking. +-

    +-

    +- To ease interoperability with Lisp-based clients (which may not +- be able to easily distinguish between empty lists, empty maps, +- and null), client-to-server communication is allowed to replace +- any instance of "{}" or "[]" with null. The +- server will always properly represent empty lists as +- "[]" and empty maps as "{}". +-

    +-

    Communication Structure

    +-

    +- Clients can make a request of the server and the server will +- provide a response for each request that it receives. While many +- of the requests that can be made by a client are informational +- in nature, we have chosen to always return a response so that +- clients can know whether the request was received and was +- correct. +-

    +-

    +- There is no guarantee concerning the order in which responses +- will be returned, but there is a guarantee that the server will +- process requests in the order in which they are sent as long as +- the transport mechanism also makes this guarantee. Responses can +- be returned in an order that is different from the order in +- which the requests were received because some requests take +- longer to process than others. +-

    +-

    +- Every request is required to have two fields and may have two +- additional optional fields. The first required field is the =E2=80=98id= =E2=80=99 +- field, which is only used by the server to associate a response +- with the request that generated the response. The second +- required field is the =E2=80=98method=E2=80=99 field, which is used to = determine +- what the server is being requested to do. One optional field is +- the =E2=80=98params=E2=80=99 field, whose structure is dependent on the= method +- being requested. The structure of this field is described with +- each request for which it is required. The other optional field +- is the 'clientRequestTime' field, which is a number indicating +- the time at which the client made the request (milliseconds +- since epoch). Providing clientRequestTime helps us track +- how responsive analysis server is to client requests +- and better address any issues that occur. +-

    +-

    +- Every response has up to three fields. The first field is the +- =E2=80=98id=E2=80=99 field, which is always present and whose value is = the +- identifier that was passed to the request that generated the +- response. The second field is the =E2=80=98error=E2=80=99 field, which = is only +- present if an error was encountered while processing the +- request. The third field is the =E2=80=98result=E2=80=99 field, whose s= tructure +- is dependent on the method being responded to, and is described +- with each request that will produce it. +-

    +-

    +- The server can also communicate to the clients by sending a +- notification. The purpose of these notifications is to provide +- information to clients as it becomes available rather than to +- require that clients poll for it. Unless explicitly stated, all +- notifications are designed to return the complete information +- available at the time the notification is sent; clients are not +- required to update previously communicated +- results. Consequently, the server can and should return partial +- results before all results are available. For example, the +- syntactic errors for a file can be returned as soon as the +- syntactic analysis is complete, and both syntactic and semantic +- errors can be returned together at a later time. +-

    +-

    +- Each notification has two fields. The first field is the =E2=80=98event= =E2=80=99 +- field, which identifies the kind of notification. The second +- field is the =E2=80=98params=E2=80=99 field, whose structure is depende= nt on the +- kind of notification being sent. The structure of this field is +- described with each notification. +-

    +-

    +- In order to be backward compatible, clients should ignore fields that w= ere +- not specified in the version of the API on which they were based. Clien= ts +- should also use the server.getVersion request to test that the version = of +- the server supports an API before using it. +-

    +-

    Eventual Consistency

    +-

    +- The analysis server satisfies requests under the principle of +- eventual +- consistency. +- That is, in some cases it may return responses with the currently avail= able +- results while it's catching up with unprocessed changes. +-

    +-

    Domains

    +-

    +- For convenience, the API is divided into domains. Each domain is specif= ied +- in a separate section below. The specifications of the API=E2=80=99s re= fer to data +- structures beyond the standard JSON primitives. These data structures a= re +- documented in the section titled Types. +-

    +- +-

    Command-line Arguments

    +-

    +- The command-line arguments that can be passed to the server. +-

    +-

    Options

    +-
    +-
    +-
    --client-id
    +-
    +-

    +- Specifies an identifier associated with the client. Used when +- generating error reports. +-

    +-

    +- Clients are strongly encouraged to provide this information in +- order to improve the quality of information that can be provided +- to them. +-

    +-
    +-
    +-
    +-
    --client-version
    +-
    +-

    +- Specifies the version of the client that is communicating with +- the server. Used when generating error reports. +-

    +-

    +- Clients are strongly encouraged to provide this information in +- order to improve the quality of information that can be provided +- to them. +-

    +-
    +-
    +-
    +-
    --no-error-notification
    +-
    +-

    Deprecated: clients should no longer pass this option in<= /p> +- Disable notifications about errors (see analysis.error). If this +- flag is not specified then notifications will be sent for all +- errors produced for all files in the actual analysis roots. +-

    +-
    +-
    +-
    --no-index
    +-
    +-

    Deprecated: clients should no longer pass this option in<= /p> +- This flag used to disable the server from generating an index, but = now +- it has no effect. +-

    +-
    +-
    +-
    --file-read-mode
    +-
    +-

    Deprecated: clients should no longer pass this option in<= /p> +- An enumeration of the ways files can be read from disk. Some clients +- normalize end of line characters which would make the file offset a= nd +- range information incorrect. The default option is as-is, = but +- can also be set to normalize-eol-always. The default option +- (as-is) reads files as they are on disk. The +- normalize-eol-always option does the following: +-

      +-
    • '\r\n' is converted to '\n';
    • +-
    • '\r' by itself is converted to '\n';
    • +-
    • this happens regardless of the OS editor is running on.
    • +-
    +-
    +-
    +-
    +- +- +-

    +- The server domain contains API=E2=80=99s related to the execution of +- the server. +-

    +- +-

    Return the version number of the analysis server.

    +- +- +- String +-

    The version number of the analysis server.

    +-
    +-
    +-
    +- +-

    +- Cleanly shutdown the analysis server. Requests that are +- received after this request will not be processed. Requests +- that were received before this request, but for which a +- response has not yet been sent, will not be responded to. No +- further responses or notifications will be sent after the +- response to this request has been sent. +-

    +-
    +- +-

    +- Subscribe for services. All previous subscriptions are +- replaced by the given set of services. +-

    +-

    +- It is an error if any of the elements in the list are not +- valid services. If there is an error, then the current +- subscriptions will remain unchanged. +-

    +- +- +- +- ServerService +- +-

    A list of the services being subscribed to.

    +-
    +-
    +-
    +- +-

    +- Reports that the server is running. This notification is +- issued once after the server has started running but before +- any requests are processed to let the client know that it +- started correctly. +-

    +-

    +- It is not possible to subscribe to or unsubscribe from this +- notification. +-

    +- +- +- String +-

    The version number of the analysis server.

    +-
    +- +- int +-

    The process id of the analysis server process.

    +-
    +- +- String +-

    The session id for this session.

    +-
    +-
    +-
    +- +-

    +- Reports that an unexpected error has occurred while +- executing the server. This notification is not used for +- problems with specific requests (which are returned as part +- of the response) but is used for exceptions that occur while +- performing other tasks, such as analysis or preparing +- notifications. +-

    +-

    +- It is not possible to subscribe to or unsubscribe from this +- notification. +-

    +- +- +- bool +-

    +- True if the error is a fatal error, meaning that the +- server will shutdown automatically after sending this +- notification. +-

    +-
    +- +- String +-

    +- The error message indicating what kind of error was +- encountered. +-

    +-
    +- +- String +-

    +- The stack trace associated with the generation of the +- error, used for debugging the server. +-

    +-
    +-
    +-
    +- +-

    +- Reports the current status of the server. Parameters are +- omitted if there has been no change in the status +- represented by that parameter. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "STATUS" in +- the list of services passed in a server.setSubscriptions +- request. +-

    +- +- +- AnalysisStatus +-

    +- The current status of analysis, including whether +- analysis is being performed and if so what is being +- analyzed. +-

    +-
    +- +- PubStatus +-

    +- The current status of pub execution, indicating whether we are +- currently running pub. +-

    +-
    +-
    +-
    +-
    +- +-

    +- The analysis domain contains API=E2=80=99s related to the analysis of +- files. +-

    +- +-

    +- Return the errors associated with the given file. If the +- errors for the given file have not yet been computed, or the +- most recently computed errors for the given file are out of +- date, then the response for this request will be delayed +- until they have been computed. If some or all of the errors +- for the file cannot be computed, then the subset of the +- errors that can be computed will be returned and the +- response will contain an error to indicate why the errors +- could not be computed. If the content of the file changes after this +- request was received but before a response could be sent, then an +- error of type CONTENT_MODIFIED will be generated. +-

    +-

    +- This request is intended to be used by clients that cannot +- asynchronously apply updated error information. Clients that +- can apply error information as it becomes available +- should use the information provided by the 'analysis.errors' +- notification. +-

    +-

    +- If a request is made for a file which does not exist, or +- which is not currently subject to analysis (e.g. because it +- is not associated with any analysis root specified to +- analysis.setAnalysisRoots), an error of type +- GET_ERRORS_INVALID_FILE will be generated. +-

    +- +- +- FilePath +-

    +- The file for which errors are being requested. +-

    +-
    +-
    +- +- +- +- AnalysisError +- +-

    +- The errors associated with the file. +-

    +-
    +-
    +-
    +- +-

    +- Return the hover information associate with the given +- location. If some or all of the hover information is not +- available at the time this request is processed the +- information will be omitted from the response. +-

    +- +- +- FilePath +-

    +- The file in which hover information is being requested. +-

    +-
    +- +- int +-

    +- The offset for which hover information is being requested. +-

    +-
    +-
    +- +- +- +- HoverInformation +- +-

    +- The hover information associated with the +- location. The list will be empty if no information +- could be determined for the location. The list can +- contain multiple items if the file is being analyzed +- in multiple contexts in conflicting ways (such as a +- part that is included in multiple libraries). +-

    +-
    +-
    +-
    +- +-

    +- Return a description of all of the elements referenced in a given r= egion +- of a given file that come from imported libraries. +-

    +-

    +- If a request is made for a file that does not exist, or that is not +- currently subject to analysis (e.g. because it is not associated wi= th any +- analysis root specified via analysis.setAnalysisRoots), an error of= type +- GET_IMPORTED_ELEMENTS_INVALID_FILE will be generated. +-

    +- +- +- FilePath +-

    +- The file in which import information is being requested. +-

    +-
    +- +- int +-

    +- The offset of the region for which import information is being +- requested. +-

    +-
    +- +- int +-

    +- The length of the region for which import information is being +- requested. +-

    +-
    +-
    +- +- +- +- ImportedElements +- +-

    +- The information about the elements that are referenced in the +- specified region of the specified file that come from imported +- libraries. +-

    +-
    +-
    +-
    +- +-

    +- Return library dependency information for use in client-side indexi= ng +- and package URI resolution. +-

    +-

    +- Clients that are only using the libraries field should consider usi= ng the +- analyzedFiles notification instead. +-

    +- +- +- +- FilePath +- +-

    +- A list of the paths of library elements referenced by +- files in existing analysis roots. +-

    +-
    +- +- +- +- String +- +- +- +- +- String +- +- +- +- FilePath +- +- +- +- +- +-

    +- A mapping from context source roots to package maps which map +- package names to source directories for use in client-side +- package URI resolution. +-

    +-
    +-
    +-
    +- +-

    +- Return the navigation information associated with the given region = of +- the given file. If the navigation information for the given file has +- not yet been computed, or the most recently computed navigation +- information for the given file is out of date, then the response for +- this request will be delayed until it has been computed. If the +- content of the file changes after this request was received but bef= ore +- a response could be sent, then an error of type +- CONTENT_MODIFIED will be generated. +-

    +-

    +- If a navigation region overlaps (but extends either before or after) +- the given region of the file it will be included in the result. This +- means that it is theoretically possible to get the same navigation +- region in response to multiple requests. Clients can avoid this by +- always choosing a region that starts at the beginning of a line and +- ends at the end of a (possibly different) line in the file. +-

    +-

    +- If a request is made for a file which does not exist, or +- which is not currently subject to analysis (e.g. because it +- is not associated with any analysis root specified to +- analysis.setAnalysisRoots), an error of type +- GET_NAVIGATION_INVALID_FILE will be generated. +-

    +- +- +- FilePath +-

    +- The file in which navigation information is being requested. +-

    +-
    +- +- int +-

    +- The offset of the region for which navigation information is be= ing +- requested. +-

    +-
    +- +- int +-

    +- The length of the region for which navigation information is be= ing +- requested. +-

    +-
    +-
    +- +- +- +- FilePath +- +-

    +- A list of the paths of files that are referenced by the navigat= ion +- targets. +-

    +-
    +- +- +- NavigationTarget +- +-

    +- A list of the navigation targets that are referenced by the +- navigation regions. +-

    +-
    +- +- +- NavigationRegion +- +-

    +- A list of the navigation regions within the requested region of +- the file. +-

    +-
    +-
    +-
    +- +-

    +- Return the transitive closure of reachable sources for a given file. +-

    +-

    +- If a request is made for a file which does not exist, or +- which is not currently subject to analysis (e.g. because it +- is not associated with any analysis root specified to +- analysis.setAnalysisRoots), an error of type +- GET_REACHABLE_SOURCES_INVALID_FILE will be generated. +-

    +- +- +- FilePath +-

    +- The file for which reachable source information is being reques= ted. +-

    +-
    +-
    +- +- +- +- +- String +- +- +- +- String +- +- +- +-

    +- A mapping from source URIs to directly reachable source URIs. F= or +- example, +- a file "foo.dart" that imports "bar.dart" would have the corres= ponding +- mapping +- { "file:///foo.dart" : ["file:///bar.dart"] }. If "bar.dart" has +- further imports +- (or exports) there will be a mapping from the URI "file:///bar.= dart" +- to them. +- To check if a specific URI is reachable from a given file, clie= nts can +- check +- for its presence in the resulting key set. +-

    +-
    +-
    +-
    +- +-

    +- Force the re-analysis of everything contained in the specified +- analysis roots. This will cause all previously computed analysis +- results to be discarded and recomputed, and will cause all subscrib= ed +- notifications to be re-sent. +-

    +-

    +- If no analysis roots are provided, then all current analysis roots +- will be re-analyzed. If an empty list of analysis roots is provided, +- then nothing will be re-analyzed. If the list contains one or more +- paths that are not currently analysis roots, then an error of type +- INVALID_ANALYSIS_ROOT will be generated. +-

    +- +- +- +- FilePath +- +-

    +- A list of the analysis roots that are to be re-analyzed. +-

    +-
    +-
    +-
    +- +-

    +- Sets the root paths used to determine which files to analyze. The s= et +- of files to be analyzed are all of the files in one of the root pat= hs +- that are not either explicitly or implicitly excluded. A file is +- explicitly excluded if it is in one of the excluded paths. A file is +- implicitly excluded if it is in a subdirectory of one of the root +- paths where the name of the subdirectory starts with a period (that +- is, a hidden directory). +-

    +-

    +- Note that this request determines the set of requested +- analysis roots. The actual set of analysis roots at any +- given time is the intersection of this set with the set of +- files and directories actually present on the +- filesystem. When the filesystem changes, the actual set of +- analysis roots is automatically updated, but the set of +- requested analysis roots is unchanged. This means that if +- the client sets an analysis root before the root becomes +- visible to server in the filesystem, there is no error; once +- the server sees the root in the filesystem it will start +- analyzing it. Similarly, server will stop analyzing files +- that are removed from the file system but they will remain +- in the set of requested roots. +-

    +-

    +- If an included path represents a file, then server will look +- in the directory containing the file for a pubspec.yaml +- file. If none is found, then the parents of the directory +- will be searched until such a file is found or the root of +- the file system is reached. If such a file is found, it will +- be used to resolve package: URI=E2=80=99s within the file. +-

    +- +- +- +- FilePath +- +-

    +- A list of the files and directories that should be +- analyzed. +-

    +-
    +- +- +- FilePath +- +-

    +- A list of the files and directories within the +- included directories that should not be analyzed. +-

    +-
    +- +- +- +- FilePath +- +- +- FilePath +- +- +-

    +- A mapping from source directories to package roots +- that should override the normal package: URI resolution +- mechanism. +-

    +-

    +- If a package root is a directory, then +- the analyzer will behave as though the associated +- source directory in the map contains a special +- pubspec.yaml file which resolves any package: URI to the +- corresponding path within that package root directory. The +- effect is the same as specifying the package root directory as +- a "--package_root" parameter to the Dart VM when +- executing any Dart file inside the source directory. +-

    +-

    +- If a package root is a file, then the analyzer +- will behave as though that file is a ".packages" file in the +- source directory. The effect is the same as specifying the file +- as a "--packages" parameter to the Dart VM when +- executing any Dart file inside the source directory. +-

    +-

    +- Files in any directories that are not overridden by this +- mapping have their package: URI's resolved using the +- normal pubspec.yaml mechanism. If this field is absent, +- or the empty map is specified, that indicates that the +- normal pubspec.yaml mechanism should always be used. +-

    +-
    +-
    +-
    +- +-

    +- Subscribe for general services (that is, services that are not +- specific to individual files). All previous subscriptions are repla= ced +- by the given set of services. +-

    +-

    +- It is an error if any of the elements in the list are not valid +- services. If there is an error, then the current subscriptions will +- remain unchanged. +-

    +- +- +- +- GeneralAnalysisService +- +-

    A list of the services being subscribed to.

    +-
    +-
    +-
    +- +-

    +- Set the priority files to the files in the given list. A +- priority file is a file that is given priority when +- scheduling which analysis work to do first. The list +- typically contains those files that are visible to the user +- and those for which analysis results will have the biggest +- impact on the user experience. The order of the files within +- the list is significant: the first file will be given higher +- priority than the second, the second higher priority than +- the third, and so on. +-

    +-

    +- Note that this request determines the set of requested +- priority files. The actual set of priority files is the +- intersection of the requested set of priority files with the +- set of files currently subject to analysis. (See +- analysis.setSubscriptions for a description of files that +- are subject to analysis.) +-

    +-

    +- If a requested priority file is a directory it is ignored, +- but remains in the set of requested priority files so that +- if it later becomes a file it can be included in the set of +- actual priority files. +-

    +- +- +- +- FilePath +- +-

    +- The files that are to be a priority for analysis. +-

    +-
    +-
    +-
    +- +-

    +- Subscribe for services that are specific to individual files. +- All previous subscriptions are replaced by the current set of +- subscriptions. If a given service is not included as a key in the m= ap +- then no files will be subscribed to the service, exactly as if the +- service had been included in the map with an explicit empty list of +- files. +-

    +-

    +- Note that this request determines the set of requested +- subscriptions. The actual set of subscriptions at any given +- time is the intersection of this set with the set of files +- currently subject to analysis. The files currently subject +- to analysis are the set of files contained within an actual +- analysis root but not excluded, plus all of the files +- transitively reachable from those files via import, export +- and part directives. (See analysis.setAnalysisRoots for an +- explanation of how the actual analysis roots are +- determined.) When the actual analysis roots change, the +- actual set of subscriptions is automatically updated, but +- the set of requested subscriptions is unchanged. +-

    +-

    +- If a requested subscription is a directory it is ignored, +- but remains in the set of requested subscriptions so that if +- it later becomes a file it can be included in the set of +- actual subscriptions. +-

    +-

    +- It is an error if any of the keys in the map are not valid +- services. If there is an error, then the existing +- subscriptions will remain unchanged. +-

    +- +- +- +- +- AnalysisService +- +- +- +- FilePath +- +- +- +-

    +- A table mapping services to a list of the files being +- subscribed to the service. +-

    +-
    +-
    +-
    +- +-

    +- Update the content of one or more files. Files that were +- previously updated but not included in this update remain +- unchanged. This effectively represents an overlay of the +- filesystem. The files whose content is overridden are +- therefore seen by server as being files with the given +- content, even if the files do not exist on the filesystem or +- if the file path represents the path to a directory on the +- filesystem. +-

    +- +- +- +- +- FilePath +- +- +- +- AddContentOverlay +- ChangeContentOverlay +- RemoveContentOverlay +- +- +- +-

    +- A table mapping the files whose content has changed to a +- description of the content change. +-

    +-
    +-
    +- +- +-
    +- +-

    Deprecated: all of the options can be set by users in +- an analysis options file.

    +-

    +- Update the options controlling analysis based on the given +- set of options. Any options that are not included in the +- analysis options will not be changed. If there are options +- in the analysis options that are not valid, they will be +- silently ignored. +-

    +- +- +- AnalysisOptions +-

    +- The options that are to be used to control analysis. +-

    +-
    +-
    +-
    +- +-

    +- Reports the paths of the files that are being analyzed. +-

    +-

    +- This notification is not subscribed to by default. Clients can +- subscribe by including the value "ANALYZED_FILES" in the l= ist +- of services passed in an analysis.setGeneralSubscriptions request. +-

    +- +- +- +- FilePath +- +-

    +- A list of the paths of the files that are being analyzed. +-

    +-
    +-
    +-
    +- +-

    +- Reports closing labels relevant to a given file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "CLOSING_LABELS" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

    +- +- +- FilePath +-

    +- The file the closing labels relate to. +-

    +-
    +- +- +- ClosingLabel +- +-

    +- Closing labels relevant to the file. Each item +- represents a useful label associated with some range +- with may be useful to display to the user within the editor +- at the end of the range to indicate what construct is closed +- at that location. Closing labels include constructor/method +- calls and List arguments that span multiple lines. +- Note that the ranges that are returned can overlap +- each other because they may be associated with +- constructs that can be nested. +-

    +-
    +-
    +-
    +- +-

    +- Reports the errors associated with a given file. The set of +- errors included in the notification is always a complete +- list that supersedes any previously reported errors. +-

    +- +- +- FilePath +-

    +- The file containing the errors. +-

    +-
    +- +- +- AnalysisError +- +-

    +- The errors contained in the file. +-

    +-
    +-
    +-
    +- +-

    +- Reports that any analysis results that were previously +- associated with the given files should be considered to be +- invalid because those files are no longer being analyzed, +- either because the analysis root that contained it is no +- longer being analyzed or because the file no longer exists. +-

    +-

    +- If a file is included in this notification and at some later +- time a notification with results for the file is received, +- clients should assume that the file is once again being +- analyzed and the information should be processed. +-

    +-

    +- It is not possible to subscribe to or unsubscribe from this +- notification. +-

    +- +- +- +- FilePath +- +-

    +- The files that are no longer being analyzed. +-

    +-
    +-
    +-
    +- +-

    +- Reports the folding regions associated with a given +- file. Folding regions can be nested, but will not be +- overlapping. Nesting occurs when a foldable element, such as +- a method, is nested inside another foldable element such as +- a class. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "FOLDING" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

    +- +- +- FilePath +-

    +- The file containing the folding regions. +-

    +-
    +- +- +- FoldingRegion +- +-

    +- The folding regions contained in the file. +-

    +-
    +-
    +-
    +- +-

    +- Reports the highlight regions associated with a given file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "HIGHLIGHTS" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

    +- +- +- FilePath +-

    +- The file containing the highlight regions. +-

    +-
    +- +- +- HighlightRegion +- +-

    +- The highlight regions contained in the file. Each +- highlight region represents a particular syntactic or +- semantic meaning associated with some range. Note that +- the highlight regions that are returned can overlap +- other highlight regions if there is more than one +- meaning associated with a particular region. +-

    +-
    +-
    +-
    +- +-

    +- Reports the classes that are implemented or extended and +- class members that are implemented or overridden in a file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "IMPLEMENTED" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

    +- +- +- FilePath +-

    +- The file with which the implementations are associated. +-

    +-
    +- +- +- ImplementedClass +- +-

    +- The classes defined in the file that are implemented or extende= d. +-

    +-
    +- +- +- ImplementedMember +- +-

    +- The member defined in the file that are implemented or overridd= en. +-

    +-
    +-
    +-
    +- +-

    +- Reports that the navigation information associated with a region of= a +- single file has become invalid and should be re-requested. +-

    +-

    +- This notification is not subscribed to by default. Clients can +- subscribe by including the value "INVALIDATE" in the list = of +- services passed in an analysis.setSubscriptions request. +-

    +- +- +- FilePath +-

    +- The file whose information has been invalidated. +-

    +-
    +- +- int +-

    +- The offset of the invalidated region. +-

    +-
    +- +- int +-

    +- The length of the invalidated region. +-

    +-
    +- +- int +-

    +- The delta to be applied to the offsets in information that foll= ows +- the invalidated region in order to update it so that it doesn't +- need to be re-requested. +-

    +-
    +-
    +-
    +- +-

    +- Reports the navigation targets associated with a given file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "NAVIGATION" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

    +- +- +- FilePath +-

    +- The file containing the navigation regions. +-

    +-
    +- +- +- NavigationRegion +- +-

    +- The navigation regions contained in the file. +- The regions are sorted by their offsets. +- Each navigation region represents a list of targets +- associated with some range. The lists will usually +- contain a single target, but can contain more in the +- case of a part that is included in multiple libraries +- or in Dart code that is compiled against multiple +- versions of a package. Note that the navigation +- regions that are returned do not overlap other +- navigation regions. +-

    +-
    +- +- +- NavigationTarget +- +-

    +- The navigation targets referenced in the file. +- They are referenced by NavigationRegions by their +- index in this array. +-

    +-
    +- +- +- FilePath +- +-

    +- The files containing navigation targets referenced in the file. +- They are referenced by NavigationTargets by their +- index in this array. +-

    +-
    +-
    +-
    +- +-

    +- Reports the occurrences of references to elements within a +- single file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "OCCURRENCES" +- in the list of services passed in an +- analysis.setSubscriptions request. +-

    +- +- +- FilePath +-

    +- The file in which the references occur. +-

    +-
    +- +- +- Occurrences +- +-

    +- The occurrences of references to elements within the +- file. +-

    +-
    +-
    +-
    +- +-

    +- Reports the outline associated with a single file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "OUTLINE" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

    +- +- +- FilePath +-

    +- The file with which the outline is associated. +-

    +-
    +- +- FileKind +-

    +- The kind of the file. +-

    +-
    +- +- String +-

    +- The name of the library defined by the file using a "library" +- directive, or referenced by a "part of" directive. If both +- "library" and "part of" directives are present, then the +- "library" directive takes precedence. +- This field will be omitted if the file has neither "library" +- nor "part of" directives. +-

    +-
    +- +- Outline +-

    +- The outline associated with the file. +-

    +-
    +-
    +-
    +- +-

    +- Reports the overriding members in a file. +-

    +-

    +- This notification is not subscribed to by default. Clients +- can subscribe by including the value "OVERRIDES" in +- the list of services passed in an analysis.setSubscriptions +- request. +-

    +- +- +- FilePath +-

    +- The file with which the overrides are associated. +-

    +-
    +- +- +- Override +- +-

    +- The overrides associated with the file. +-

    +-
    +-
    +-
    +-
    +- +-

    +- The code completion domain contains commands related to +- getting code completion suggestions. +-

    +- +-

    +- Request that completion suggestions for the given offset in +- the given file be returned. +-

    +- +- +- FilePath +-

    +- The file containing the point at which suggestions are +- to be made. +-

    +-
    +- +- int +-

    +- The offset within the file at which suggestions are to +- be made. +-

    +-
    +-
    +- +- +- CompletionId +-

    +- The identifier used to associate results with this +- completion request. +-

    +-
    +-
    +-
    +- +-

    +- Reports the completion suggestions that should be presented +- to the user. The set of suggestions included in the +- notification is always a complete list that supersedes any +- previously reported suggestions. +-

    +- +- +- CompletionId +-

    +- The id associated with the completion. +-

    +-
    +- +- int +-

    +- The offset of the start of the text to be +- replaced. This will be different than the offset used +- to request the completion suggestions if there was a +- portion of an identifier before the original +- offset. In particular, the replacementOffset will be +- the offset of the beginning of said identifier. +-

    +-
    +- +- int +-

    +- The length of the text to be replaced if the remainder +- of the identifier containing the cursor is to be +- replaced when the suggestion is applied (that is, the +- number of characters in the existing identifier). +-

    +-
    +- +- +- CompletionSuggestion +- +-

    +- The completion suggestions being reported. The +- notification contains all possible completions at the +- requested cursor position, even those that do not match +- the characters the user has already typed. This allows +- the client to respond to further keystrokes from the +- user without having to make additional requests. +-

    +-
    +- +- bool +-

    +- True if this is that last set of results that will be +- returned for the indicated completion. +-

    +-
    +-
    +-
    +-
    +- +-

    +- The search domain contains commands related to searches that +- can be performed against the code base. +-

    +- +-

    +- Perform a search for references to the element defined or +- referenced at the given offset in the given file. +-

    +-

    +- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

    +- +- +- FilePath +-

    +- The file containing the declaration of or reference to +- the element used to define the search. +-

    +-
    +- +- int +-

    +- The offset within the file of the declaration of or +- reference to the element. +-

    +-
    +- +- bool +-

    +- True if potential matches are to be included in the +- results. +-

    +-
    +-
    +- +- +- SearchId +-

    +- The identifier used to associate results with this +- search request. +-

    +-

    +- If no element was found at the given location, this +- field will be absent, and no results will be reported +- via the search.results notification. +-

    +-
    +- +- Element +-

    +- The element referenced or defined at the given offset +- and whose references will be returned in the search +- results. +-

    +-

    +- If no element was found at the given location, this +- field will be absent. +-

    +-
    +-
    +-
    +- +-

    +- Perform a search for declarations of members whose name is +- equal to the given name. +-

    +-

    +- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

    +- +- +- String +-

    +- The name of the declarations to be found. +-

    +-
    +-
    +- +- +- SearchId +-

    +- The identifier used to associate results with this +- search request. +-

    +-
    +-
    +-
    +- +-

    +- Perform a search for references to members whose name is +- equal to the given name. This search does not check to see +- that there is a member defined with the given name, so it is +- able to find references to undefined members as well. +-

    +-

    +- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

    +- +- +- String +-

    +- The name of the references to be found. +-

    +-
    +-
    +- +- +- SearchId +-

    +- The identifier used to associate results with this +- search request. +-

    +-
    +-
    +-
    +- +-

    +- Perform a search for declarations of top-level elements +- (classes, typedefs, getters, setters, functions and fields) +- whose name matches the given pattern. +-

    +-

    +- An identifier is returned immediately, and individual +- results will be returned via the search.results notification +- as they become available. +-

    +- +- +- String +-

    +- The regular expression used to match the names of the +- declarations to be found. +-

    +-
    +-
    +- +- +- SearchId +-

    +- The identifier used to associate results with this +- search request. +-

    +-
    +-
    +-
    +- +-

    +- Return the type hierarchy of the class declared or +- referenced at the given location. +-

    +- +- +- FilePath +-

    +- The file containing the declaration or reference to the +- type for which a hierarchy is being requested. +-

    +-
    +- +- int +-

    +- The offset of the name of the type within the file. +-

    +-
    +- +- bool +-

    +- True if the client is only requesting superclasses and +- interfaces hierarchy. +-

    +-
    +-
    +- +- +- +- TypeHierarchyItem +- +-

    +- A list of the types in the requested hierarchy. The +- first element of the list is the item representing the +- type for which the hierarchy was requested. The index of +- other elements of the list is unspecified, but +- correspond to the integers used to reference supertype +- and subtype items within the items. +-

    +-

    +- This field will be absent if the code at the given file +- and offset does not represent a type, or if the file has +- not been sufficiently analyzed to allow a type hierarchy +- to be produced. +-

    +-
    +-
    +-
    +- +-

    +- Reports some or all of the results of performing a requested +- search. Unlike other notifications, this notification +- contains search results that should be added to any +- previously received search results associated with the same +- search id. +-

    +- +- +- SearchId +-

    +- The id associated with the search. +-

    +-
    +- +- +- SearchResult +- +-

    +- The search results being reported. +-

    +-
    +- +- bool +-

    +- True if this is that last set of results that will be +- returned for the indicated search. +-

    +-
    +-
    +-
    +-
    +- +-

    +- The edit domain contains commands related to edits that can be +- applied to the code. +-

    +- +-

    +- Format the contents of a single file. The currently selected region= of +- text is passed in so that the selection can be preserved across the +- formatting operation. The updated selection will be as close to +- matching the original as possible, but whitespace at the beginning = or +- end of the selected region will be ignored. If preserving selection +- information is not required, zero (0) can be specified for both the +- selection offset and selection length. +-

    +-

    +- If a request is made for a file which does not exist, or which is n= ot +- currently subject to analysis (e.g. because it is not associated wi= th +- any analysis root specified to analysis.setAnalysisRoots), an error= of +- type FORMAT_INVALID_FILE will be generated. If the source +- contains syntax errors, an error of type FORMAT_WITH_ERRORS +- will be generated. +-

    +- +- +- FilePath +-

    +- The file containing the code to be formatted. +-

    +-
    +- +- int +-

    +- The offset of the current selection in the file. +-

    +-
    +- +- int +-

    +- The length of the current selection in the file. +-

    +-
    +- +- +- int +-

    +- The line length to be used by the formatter. +-

    +-
    +-
    +- +- +- +- SourceEdit +- +-

    +- The edit(s) to be applied in order to format the code. The list +- will be empty if the code was already formatted (there are no +- changes). +-

    +-
    +- +- int +-

    +- The offset of the selection after formatting the code. +-

    +-
    +- +- int +-

    +- The length of the selection after formatting the code. +-

    +-
    +-
    +-
    +- +-

    +- Return the set of assists that are available at the given +- location. An assist is distinguished from a refactoring +- primarily by the fact that it affects a single file and does +- not require user input in order to be performed. +-

    +- +- +- FilePath +-

    +- The file containing the code for which assists are being +- requested. +-

    +-
    +- +- int +-

    +- The offset of the code for which assists are being +- requested. +-

    +-
    +- +- int +-

    +- The length of the code for which assists are being +- requested. +-

    +-
    +-
    +- +- +- +- SourceChange +- +-

    +- The assists that are available at the given location. +-

    +-
    +-
    +-
    +- +-

    +- Get a list of the kinds of refactorings that are valid for +- the given selection in the given file. +-

    +- +- +- FilePath +-

    +- The file containing the code on which the refactoring +- would be based. +-

    +-
    +- +- int +-

    +- The offset of the code on which the refactoring would be +- based. +-

    +-
    +- +- int +-

    +- The length of the code on which the refactoring would be +- based. +-

    +-
    +-
    +- +- +- +- RefactoringKind +- +-

    +- The kinds of refactorings that are valid for the given +- selection. +-

    +-
    +-
    +-
    +- +-

    +- Return the set of fixes that are available for the errors at +- a given offset in a given file. +-

    +- +- +- FilePath +-

    +- The file containing the errors for which fixes are being +- requested. +-

    +-
    +- +- int +-

    +- The offset used to select the errors for which fixes +- will be returned. +-

    +-
    +-
    +- +- +- +- AnalysisErrorFixes +- +-

    +- The fixes that are available for the errors at the given offset. +-

    +-
    +-
    +-
    +- +-

    +- Get the changes required to convert the postfix template at the giv= en +- location into the template's expanded form. +-

    +- +- +- FilePath +-

    +- The file containing the postfix template to be expanded. +-

    +-
    +- +- String +-

    +- The unique name that identifies the template in use. +-

    +-
    +- +- int +-

    +- The offset used to identify the code to which the template will= be +- applied. +-

    +-
    +-
    +- +- +- SourceChange +-

    +- The change to be applied in order to complete the statement. +-

    +-
    +-
    +-
    +- +-

    +- Get the changes required to perform a refactoring. +-

    +-

    +- If another refactoring request is received during the processing +- of this one, an error of type REFACTORING_REQUEST_CANCELLED +- will be generated. +-

    +- +- +- RefactoringKind +-

    +- The kind of refactoring to be performed. +-

    +-
    +- +- FilePath +-

    +- The file containing the code involved in the +- refactoring. +-

    +-
    +- +- int +-

    +- The offset of the region involved in the refactoring. +-

    +-
    +- +- int +-

    +- The length of the region involved in the refactoring. +-

    +-
    +- +- bool +-

    +- True if the client is only requesting that the values of +- the options be validated and no change be generated. +-

    +-
    +- +- RefactoringOptions +-

    +- Data used to provide values provided by the user. The +- structure of the data is dependent on the kind of +- refactoring being performed. The data that is expected is +- documented in the section titled Refactorings, labeled as +- "Options". This field can be omitted if the refactoring +- does not require any options or if the values of those +- options are not known. +-

    +-
    +-
    +- +- +- +- RefactoringProblem +- +-

    +- The initial status of the refactoring, i.e. problems related to +- the context in which the refactoring is requested. +- The array will be empty if there are no known problems. +-

    +-
    +- +- +- RefactoringProblem +- +-

    +- The options validation status, i.e. problems in the given optio= ns, +- such as light-weight validation of a new name, flags +- compatibility, etc. +- The array will be empty if there are no known problems. +-

    +-
    +- +- +- RefactoringProblem +- +-

    +- The final status of the refactoring, i.e. problems identified in +- the result of a full, potentially expensive validation and / or +- change creation. +- The array will be empty if there are no known problems. +-

    +-
    +- +- RefactoringFeedback +-

    +- Data used to provide feedback to the user. The structure +- of the data is dependent on the kind of refactoring +- being created. The data that is returned is documented +- in the section titled Refactorings, labeled as +- "Feedback". +-

    +-
    +- +- SourceChange +-

    +- The changes that are to be applied to affect the +- refactoring. This field will be omitted if there are +- problems that prevent a set of changes from being +- computed, such as having no options specified for a +- refactoring that requires them, or if only validation +- was requested. +-

    +-
    +- +- +- String +- +-

    +- The ids of source edits that are not known to be valid. An edit= is +- not known to be valid if there was insufficient type information +- for the server to be able to determine whether or not the code +- needs to be modified, such as when a member is being renamed and +- there is a reference to a member from an unknown type. This fie= ld +- will be omitted if the change field is omitted or if there are = no +- potential edits for the refactoring. +-

    +-
    +-
    +-
    +- +-

    +- Get the changes required to convert the partial statement at the gi= ven +- location into a syntactically valid statement. If the current state= ment +- is already valid the change will insert a newline plus appropriate +- indentation at the end of the line containing the offset. +- If a change that makes the statement valid cannot be determined (pe= rhaps +- because it has not yet been implemented) the statement will be cons= idered +- already valid and the appropriate change returned. +-

    +- +- +- FilePath +-

    +- The file containing the statement to be completed. +-

    +-
    +- +- int +-

    +- The offset used to identify the statement to be completed. +-

    +-
    +-
    +- +- +- SourceChange +-

    +- The change to be applied in order to complete the statement. +-

    +-
    +- +- bool +-

    +- Will be true if the change contains nothing but whitespace +- characters, or is empty. +-

    +-
    +-
    +-
    +- +-

    +- Determine if the request postfix completion template is applicable = at +- the given location in the given file. +-

    +- +- +- FilePath +-

    +- The file containing the postfix template to be expanded. +-

    +-
    +- +- String +-

    +- The unique name that identifies the template in use. +-

    +-
    +- +- int +-

    +- The offset used to identify the code to which the template will= be +- applied. +-

    +-
    +-
    +- +- +- bool +-

    +- True if the template can be expanded at the given location. +-

    +-
    +-
    +-
    +- +-

    +- Return a list of all postfix templates currently available. +-

    +- +- +- +- PostfixTemplateDescriptor +- +-

    +- The list of available templates. +-

    +-
    +-
    +-
    +- +-

    +- Return a list of edits that would need to be applied in order to en= sure +- that all of the elements in the specified list of imported elements= are +- accessible within the library. +-

    +-

    +- If a request is made for a file that does not exist, or that is not +- currently subject to analysis (e.g. because it is not associated wi= th any +- analysis root specified via analysis.setAnalysisRoots), an error of= type +- IMPORT_ELEMENTS_INVALID_FILE will be generated. +-

    +- +- +- FilePath +-

    +- The file in which the specified elements are to be made accessi= ble. +-

    +-
    +- +- +- ImportedElements +- +-

    +- The elements to be made accessible in the specified file. +-

    +-
    +-
    +- +- +- SourceFileEdit +-

    +- The edits to be applied in order to make the specified elements +- accessible. The file to be edited will be the defining compilat= ion +- unit of the library containing the file specified in the reques= t, +- which can be different than the file specified in the request i= f the +- specified file is a part file. +-

    +-
    +-
    +-
    +- +-

    +- Sort all of the directives, unit and class members +- of the given Dart file. +-

    +-

    +- If a request is made for a file that does not exist, does not belong +- to an analysis root or is not a Dart file, +- SORT_MEMBERS_INVALID_FILE will be generated. +-

    +-

    +- If the Dart file has scan or parse errors, +- SORT_MEMBERS_PARSE_ERRORS will be generated. +-

    +- +- +- FilePath +-

    +- The Dart file to sort. +-

    +-
    +-
    +- +- +- SourceFileEdit +-

    +- The file edit that is to be applied to the given file to effect +- the sorting. +-

    +-
    +-
    +-
    +- +-

    +- Organizes all of the directives - removes unused imports and sorts +- directives of the given Dart file according to the +- Dart Sty= le +- Guide. +-

    +-

    +- If a request is made for a file that does not exist, does not belong +- to an analysis root or is not a Dart file, +- FILE_NOT_ANALYZED will be generated. +-

    +-

    +- If directives of the Dart file cannot be organized, for example +- because it has scan or parse errors, or by other reasons, +- ORGANIZE_DIRECTIVES_ERROR will be generated. The message +- will provide details about the reason. +-

    +- +- +- FilePath +-

    +- The Dart file to organize directives in. +-

    +-
    +-
    +- +- +- SourceFileEdit +-

    +- The file edit that is to be applied to the given file to effect +- the organizing. +-

    +-
    +-
    +-
    +-
    +- +-

    +- The execution domain contains commands related to providing an execut= ion +- or debugging experience. +-

    +- +-

    +- Create an execution context for the executable file with the given +- path. The context that is created will persist until +- execution.deleteContext is used to delete it. Clients, therefore, a= re +- responsible for managing the lifetime of execution contexts. +-

    +- +- +- FilePath +-

    +- The path of the Dart or HTML file that will be launched, or the +- path of the directory containing the file. +-

    +-
    +-
    +- +- +- ExecutionContextId +-

    +- The identifier used to refer to the execution context that was +- created. +-

    +-
    +-
    +-
    +- +-

    +- Delete the execution context with the given identifier. The context= id +- is no longer valid after this command. The server is allowed to re-= use +- ids when they are no longer valid. +-

    +- +- +- ExecutionContextId +-

    +- The identifier of the execution context that is to be deleted. +-

    +-
    +-
    +-
    +- +-

    +- Map a URI from the execution context to the file that it corresponds +- to, or map a file to the URI that it corresponds to in the execution +- context. +-

    +-

    +- Exactly one of the file and uri fields must be provided. If both +- fields are provided, then an error of type INVALID_PARAMETER +- will be generated. Similarly, if neither field is provided, then an +- error of type INVALID_PARAMETER will be generated. +-

    +-

    +- If the file field is provided and the value is not the path of a fi= le +- (either the file does not exist or the path references something ot= her +- than a file), then an error of type INVALID_PARAMETER will +- be generated. +-

    +-

    +- If the uri field is provided and the value is not a valid URI or if +- the URI references something that is not a file (either a file that +- does not exist or something other than a file), then an error of ty= pe +- INVALID_PARAMETER will be generated. +-

    +-

    +- If the contextRoot used to create the execution context does not +- exist, then an error of type INVALID_EXECUTION_CONTEXT will +- be generated. +-

    +- +- +- ExecutionContextId +-

    +- The identifier of the execution context in which the URI is to = be +- mapped. +-

    +-
    +- +- FilePath +-

    +- The path of the file to be mapped into a URI. +-

    +-
    +- +- String +-

    +- The URI to be mapped into a file path. +-

    +-
    +-
    +- +- +- FilePath +-

    +- The file to which the URI was mapped. This field is omitted if = the +- uri field was not given in the request. +-

    +-
    +- +- String +-

    +- The URI to which the file path was mapped. This field is omitted +- if the file field was not given in the request. +-

    +-
    +-
    +-
    +- +-

    +- Deprecated: the analysis server no longer fires +- LAUNCH_DATA events. +-

    +-

    +- Subscribe for services. All previous subscriptions are replaced by = the +- given set of services. +-

    +-

    +- It is an error if any of the elements in the list are not valid +- services. If there is an error, then the current subscriptions will +- remain unchanged. +-

    +- +- +- +- ExecutionService +- +-

    +- A list of the services being subscribed to. +-

    +-
    +-
    +-
    +- +-

    +- Reports information needed to allow a single file to be launched. +-

    +-

    +- This notification is not subscribed to by default. Clients can +- subscribe by including the value "LAUNCH_DATA" in the list of servi= ces +- passed in an execution.setSubscriptions request. +-

    +- +- +- FilePath +-

    +- The file for which launch data is being provided. This will eit= her +- be a Dart library or an HTML file. +-

    +-
    +- +- ExecutableKind +-

    +- The kind of the executable file. This field is omitted if the f= ile +- is not a Dart file. +-

    +-
    +- +- +- FilePath +- +-

    +- A list of the Dart files that are referenced by the file. This +- field is omitted if the file is not an HTML file. +-

    +-
    +-
    +-
    +-
    +- +-

    +- The diagnostic domain contains server diagnostics APIs. +-

    +- +-

    Return server diagnostics.

    +- +- +- +- ContextData +- +-

    The list of analysis contexts.

    +-
    +-
    +-
    +- +-

    +- Return the port of the diagnostic web server. If the server is not = running +- this call will start the server. If unable to start the diagnostic = web +- server, +- this call will return an error of DEBUG_PORT_COULD_NOT_BE_OPENE= D. +-

    +- +- +- int +-

    The diagnostic server port.

    +-
    +-
    +-
    +-
    +- +-

    +- The analytics domain contains APIs related to reporting analytics. +-

    +-

    +- This API allows clients to expose a UI option to enable and disable t= he +- analysis server's reporting of analytics. This value is shared with o= ther +- tools and can change outside of this API; because of this, clients sh= ould +- use the analysis server's flag as the system of record. Clients can c= hoose +- to send in additional analytics (see sendEvent and +- sendTiming) if they so choose. Dart command-line tools provi= de a +- disclaimer similar to: +- +- Dart SDK tools anonymously report feature usage statistics and basi= c crash +- reports to help improve Dart tools over time. See Google's privacy = policy: +- https://www.google.com/intl/en/policies/privacy/. +- +-

    +-

    +- The analysis server will send it's own analytics data (for example, +- operations performed, operating system type, SDK version). No data (f= rom the +- analysis server or from clients) will be sent if analytics is disable= d. +-

    +- +-

    Query whether analytics is enabled.

    +-

    +- This flag controls whether the analysis server sends any analytics = data to +- the cloud. If disabled, the analysis server does not send any analy= tics +- data, and any data sent to it by clients (from sendEvent a= nd +- sendTiming) will be ignored. +-

    +-

    +- The value of this flag can be changed by other tools outside of the +- analysis server's process. When you query the flag, you get the val= ue of +- the flag at a given moment. Clients should not use the value return= ed to +- decide whether or not to send the sendEvent and +- sendTiming requests. Those requests should be used +- unconditionally and server will determine whether or not it is appr= opriate +- to forward the information to the cloud at the time each request is +- received. +-

    +- +- +- bool +-

    Whether sending analytics is enabled or not.

    +-
    +-
    +-
    +- +-

    +- Enable or disable the sending of analytics data. Note that there ar= e other +- ways for users to change this setting, so clients cannot assume tha= t they +- have complete control over this setting. In particular, there is no +- guarantee that the result returned by the isEnabled reques= t will +- match the last value set via this request. +-

    +- +- +- bool +-

    Enable or disable analytics.

    +-
    +-
    +-
    +- +-

    Send information about client events.

    +-

    +- Ask the analysis server to include the fact that an action was perf= ormed +- in the client as part of the analytics data being sent. The data wi= ll only +- be included if the sending of analytics data is enabled at the time= the +- request is processed. The action that was performed is indicated by= the +- value of the action field. +-

    +-

    +- The value of the action field should not include the identity of the +- client. The analytics data sent by server will include the client id +- passed in using the --client-id command-line argument. The +- request will be ignored if the client id was not provided when serv= er was +- started. +-

    +- +- +- String +-

    The value used to indicate which action was performed.

    +-
    +-
    +-
    +- +-

    Send timing information for client events (e.g. code completions).=

    +-

    +- Ask the analysis server to include the fact that a timed event occu= rred as +- part of the analytics data being sent. The data will only be includ= ed if +- the sending of analytics data is enabled at the time the request is +- processed. +-

    +-

    +- The value of the event field should not include the identity of the +- client. The analytics data sent by server will include the client id +- passed in using the --client-id command-line argument. The +- request will be ignored if the client id was not provided when serv= er was +- started. +-

    +- +- +- String +-

    The name of the event.

    +-
    +- +- int +-

    The duration of the event in milliseconds.

    +-
    +-
    +-
    +-
    +- +-

    +- The kythe domain contains APIs related to generating Dart content in = the +- Kythe format. +-

    +- +-

    +- Return the list of KytheEntry objects for some file, given= the +- current state of the file system populated by "analysis.updateConte= nt". +-

    +-

    +- If a request is made for a file that does not exist, or that is not +- currently subject to analysis (e.g. because it is not associated wi= th any +- analysis root specified to analysis.setAnalysisRoots), an error of = type +- GET_KYTHE_ENTRIES_INVALID_FILE will be generated. +-

    +- +- +- FilePath +-

    +- The file containing the code for which the Kythe Entry objects = are +- being requested. +-

    +-
    +-
    +- +- +- +- KytheEntry +- +-

    +- The list of KytheEntry objects for the queried file. +-

    +-
    +- +- +- FilePath +- +-

    +- The set of files paths that were required, but not in the file = system, +- to give a complete and accurate Kythe graph for the file. This = could +- be due to a referenced file that does not exist or generated fi= les not +- being generated or passed before the call to "getKytheEntries". +-

    +-
    +-
    +-
    +-
    +- +-

    Types

    +-

    +- This section contains descriptions of the data types referenced +- in the API=E2=80=99s of the various domains. +-

    +- +- +-

    +- A list of fixes associated with a specific error. +-

    +- +- +- AnalysisError +-

    +- The error with which the fixes are associated. +-

    +-
    +- +- +- SourceChange +- +-

    +- The fixes associated with the error. +-

    +-
    +-
    +-
    +- +-

    Deprecated: the only reference to this type has been +- deprecated.

    +-

    +- A set of options controlling what kind of analysis is to be +- performed. If the value of a field is omitted the value of the +- option will not be changed. +-

    +- +- +- bool +-

    Deprecated: this feature is always enabled.

    +-

    +- True if the client wants to enable support for the +- proposed async feature. +-

    +-
    +- +- bool +-

    Deprecated: this feature is always enabled.

    +-

    +- True if the client wants to enable support for the +- proposed deferred loading feature. +-

    +-
    +- +- bool +-

    Deprecated: this feature is always enabled.

    +-

    +- True if the client wants to enable support for the +- proposed enum feature. +-

    +-
    +- +- bool +-

    Deprecated: this feature is always enabled.

    +-

    +- True if the client wants to enable support for the +- proposed "null aware operators" feature. +-

    +-
    +- +- bool +-

    +- True if the client wants to enable support for the +- proposed "less restricted mixins" proposal (DEP 34). +-

    +-
    +- +- bool +-

    +- True if hints that are specific to dart2js should be +- generated. This option is ignored if generateHints is false. +-

    +-
    +- +- bool +-

    +- True if hints should be generated as part of generating +- errors and warnings. +-

    +-
    +- +- bool +-

    +- True if lints should be generated as part of generating +- errors and warnings. +-

    +-
    +-
    +-
    +- +-

    +- An enumeration of the services provided by the analysis domain that +- are related to a specific list of files. +-

    +- +- CLOSING_LABELS +- FOLDING +- HIGHLIGHTS +- IMPLEMENTED +- +- INVALIDATE +-

    +- This service is not currently implemented and will become a +- GeneralAnalysisService in a future release. +-

    +-
    +- NAVIGATION +- OCCURRENCES +- OUTLINE +- OVERRIDES +-
    +-
    +- +-

    +- An indication of the current state of analysis. +-

    +- +- +- bool +-

    True if analysis is currently being performed.

    +-
    +- +- String +-

    +- The name of the current target of analysis. This field is +- omitted if analyzing is false. +-

    +-
    +-
    +-
    +- +-

    +- A label that is associated with a range of code that may be useful = to +- render at the end of the range to aid code readability. For example= , a +- constructor call that spans multiple lines may result in a closing = label +- to allow the constructor type/name to be rendered alongside the clo= sing +- parenthesis. +-

    +- +- +- int +-

    +- The offset of the construct being labelled. +-

    +-
    +- +- int +-

    +- The length of the whole construct to be labelled. +-

    +-
    +- +- String +-

    +- The label associated with this range that should be displayed t= o the +- user. +-

    +-
    +-
    +-
    +- +- String +-

    +- An identifier used to associate completion results with a +- completion request. +-

    +-
    +- +-

    +- Information about an analysis context. +-

    +- +- +- String +-

    +- The name of the context. +-

    +-
    +- +- int +-

    +- Explicitly analyzed files. +-

    +-
    +- +- int +-

    +- Implicitly analyzed files. +-

    +-
    +- +- int +-

    +- The number of work items in the queue. +-

    +-
    +- +- +- String +- +-

    +- Exceptions associated with cache entries. +-

    +-
    +-
    +-
    +- +-

    +- A description of an executable file. +-

    +- +- +- FilePath +-

    +- The path of the executable file. +-

    +-
    +- +- ExecutableKind +-

    +- The kind of the executable file. +-

    +-
    +-
    +-
    +- +-

    +- An enumeration of the kinds of executable files. +-

    +- +- CLIENT +- EITHER +- NOT_EXECUTABLE +- SERVER +- +-
    +- +- String +-

    +- The identifier for a execution context. +-

    +-
    +- +-

    +- An enumeration of the services provided by the execution +- domain. +-

    +- +- LAUNCH_DATA +- +-
    +- +-

    +- An enumeration of the kinds of files. +-

    +- +- LIBRARY +- PART +- +-
    +- +-

    +- An enumeration of the services provided by the analysis domain that= are +- general in nature (that is, are not specific to some list of files). +-

    +- +- ANALYZED_FILES +- +-
    +- +-

    +- The hover information associated with a specific location. +-

    +- +- +- int +-

    +- The offset of the range of characters that encompasses the +- cursor position and has the same hover information as the +- cursor position. +-

    +-
    +- +- int +-

    +- The length of the range of characters that encompasses the +- cursor position and has the same hover information as the +- cursor position. +-

    +-
    +- +- String +-

    +- The path to the defining compilation unit of the library +- in which the referenced element is declared. This data is +- omitted if there is no referenced element, or if the +- element is declared inside an HTML file. +-

    +-
    +- +- String +-

    +- The name of the library in which the referenced element is +- declared. This data is omitted if there is no referenced +- element, or if the element is declared inside an HTML +- file. +-

    +-
    +- +- String +-

    +- A human-readable description of the class declaring the element +- being referenced. This data is omitted if there is no referenced +- element, or if the element is not a class member. +-

    +-
    +- +- String +-

    +- The dartdoc associated with the referenced element. Other +- than the removal of the comment delimiters, including +- leading asterisks in the case of a block comment, the +- dartdoc is unprocessed markdown. This data is omitted if +- there is no referenced element, or if the element has no +- dartdoc. +-

    +-
    +- +- String +-

    +- A human-readable description of the element being +- referenced. This data is omitted if there is no referenced +- element. +-

    +-
    +- +- String +-

    +- A human-readable description of the kind of element being +- referenced (such as "class" or "function type +- alias"). This data is omitted if there is no referenced +- element. +-

    +-
    +- +- bool +-

    +- True if the referenced element is deprecated. +-

    +-
    +- +- String +-

    +- A human-readable description of the parameter +- corresponding to the expression being hovered over. This +- data is omitted if the location is not in an argument to a +- function. +-

    +-
    +- +- String +-

    +- The name of the propagated type of the expression. This +- data is omitted if the location does not correspond to an +- expression or if there is no propagated type information. +-

    +-
    +- +- String +-

    +- The name of the static type of the expression. This data +- is omitted if the location does not correspond to an +- expression. +-

    +-
    +-
    +-
    +- +-

    +- A description of a class that is implemented or extended. +-

    +- +- +- int +-

    +- The offset of the name of the implemented class. +-

    +-
    +- +- int +-

    +- The length of the name of the implemented class. +-

    +-
    +-
    +-
    +- +-

    +- A description of a class member that is implemented or overridden. +-

    +- +- +- int +-

    +- The offset of the name of the implemented member. +-

    +-
    +- +- int +-

    +- The length of the name of the implemented member. +-

    +-
    +-
    +-
    +- +-

    +- A description of the elements that are referenced in a region of a = file +- that come from a single imported library. +-

    +- +- +- FilePath +-

    +- The absolute and normalized path of the file containing the lib= rary. +-

    +-
    +- +- String +-

    +- The prefix that was used when importing the library into the or= iginal +- source. +-

    +-
    +- +- +- String +- +-

    +- The names of the elements imported from the library. +-

    +-
    +-
    +-
    +- +-

    +- A description of a member that overrides an inherited member. +-

    +- +- +- int +-

    +- The offset of the name of the overriding member. +-

    +-
    +- +- int +-

    +- The length of the name of the overriding member. +-

    +-
    +- +- OverriddenMember +-

    +- The member inherited from a superclass that is overridden +- by the overriding member. The field is omitted if there is +- no superclass member, in which case there must be at least +- one interface member. +-

    +-
    +- +- +- OverriddenMember +- +-

    +- The members inherited from interfaces that are overridden +- by the overriding member. The field is omitted if there +- are no interface members, in which case there must be a +- superclass member. +-

    +-
    +-
    +-
    +- +-

    +- A description of a member that is being overridden. +-

    +- +- +- Element +-

    +- The element that is being overridden. +-

    +-
    +- +- String +-

    +- The name of the class in which the member is defined. +-

    +-
    +-
    +-
    +- +-

    +- The description of a postfix completion template. +-

    +- +- +- String +-

    +- The template name, shown in the UI. +-

    +-
    +- +- String +-

    +- The unique template key, not shown in the UI. +-

    +-
    +- +- String +-

    +- A short example of the transformation performed when the templa= te is +- applied. +-

    +-
    +-
    +-
    +- +-

    +- An indication of the current state of pub execution. +-

    +- +- +- bool +-

    +- True if the server is currently running pub to produce a list of +- package directories. +-

    +-
    +-
    +-
    +- +-

    +- An abstract superclass of all refactoring feedbacks. +-

    +- +- +-
    +- +-

    +- An abstract superclass of all refactoring options. +-

    +- +- +-
    +- +-

    +- An indication of a problem with the execution of the server, +- typically in response to a request. +-

    +- +- +- RequestErrorCode +-

    +- A code that uniquely identifies the error that occurred. +-

    +-
    +- +- String +-

    +- A short description of the error. +-

    +-
    +- +- String +-

    +- The stack trace associated with processing the request, +- used for debugging the server. +-

    +-
    +-
    +-
    +- +-

    +- An enumeration of the types of errors that can occur in the +- execution of the server. +-

    +- +- +- CONTENT_MODIFIED +-

    +- An "analysis.getErrors" or "analysis.getNavigation" request cou= ld +- not be satisfied because the content of the file changed before +- the requested results could be computed. +-

    +-
    +- +- DEBUG_PORT_COULD_NOT_BE_OPENED +-

    +- The server was unable to open a port for the diagnostic server. +-

    +-
    +- +- FILE_NOT_ANALYZED +-

    +- A request specified a FilePath which does not match a file in +- an analysis root, or the requested operation is not available +- for the file. +-

    +-
    +- +- FORMAT_INVALID_FILE +-

    +- An "edit.format" request specified a FilePath +- which does not match a Dart file in an analysis root. +-

    +-
    +- +- FORMAT_WITH_ERRORS +-

    +- An "edit.format" request specified a file that contains syntax +- errors. +-

    +-
    +- +- GET_ERRORS_INVALID_FILE +-

    +- An "analysis.getErrors" request specified a FilePath +- which does not match a file currently subject to +- analysis. +-

    +-
    +- +- GET_IMPORTED_ELEMENTS_INVALID_FILE +-

    +- An "analysis.getImportedElements" request specified a FilePath = that +- does not match a file currently subject to analysis. +-

    +-
    +- +- GET_KYTHE_ENTRIES_INVALID_FILE +-

    +- An "analysis.getKytheEntries" request specified a FilePath that= does +- not match a file that is currently subject to analysis. +-

    +-
    +- +- GET_NAVIGATION_INVALID_FILE +-

    +- An "analysis.getNavigation" request specified a FilePath +- which does not match a file currently subject to +- analysis. +-

    +-
    +- +- GET_REACHABLE_SOURCES_INVALID_FILE +-

    +- An "analysis.getReachableSources" request specified a FilePath +- which does not match a file currently subject to +- analysis. +-

    +-
    +- +- IMPORT_ELEMENTS_INVALID_FILE +-

    +- An "edit.importElements" request specified a FilePath that does= not +- match a file currently subject to analysis. +-

    +-
    +- +- INVALID_ANALYSIS_ROOT +-

    +- A path passed as an argument to a request (such as +- analysis.reanalyze) is required to be an analysis root, but isn= 't. +-

    +-
    +- +- INVALID_EXECUTION_CONTEXT +-

    +- The context root used to create an execution context does not +- exist. +-

    +-
    +- +- INVALID_FILE_PATH_FORMAT +-

    +- The format of the given file path is invalid, e.g. is not +- absolute and normalized. +-

    +-
    +- +- INVALID_OVERLAY_CHANGE +-

    +- An "analysis.updateContent" request contained a +- ChangeContentOverlay object which can't be applied, due +- to an edit having an offset or length that is out of +- range. +-

    +-
    +- +- INVALID_PARAMETER +-

    +- One of the method parameters was invalid. +-

    +-
    +- +- INVALID_REQUEST +-

    +- A malformed request was received. +-

    +-
    +- +- ORGANIZE_DIRECTIVES_ERROR +-

    +- An "edit.organizeDirectives" request specified a Dart file that +- cannot be analyzed. The reason is described in the message. +-

    +-
    +- +- REFACTORING_REQUEST_CANCELLED +-

    +- Another refactoring request was received during processing of +- this one. +-

    +-
    +- +- SERVER_ALREADY_STARTED +-

    +- The analysis server has already been started (and hence +- won't accept new connections). +-

    +-

    +- This error is included for future expansion; at present +- the analysis server can only speak to one client at a +- time so this error will never occur. +-

    +-
    +- +- SERVER_ERROR +-

    +- An internal error occurred in the analysis server. +- Also see the server.error notification. +-

    +-
    +- +- SORT_MEMBERS_INVALID_FILE +-

    +- An "edit.sortMembers" request specified a FilePath +- which does not match a Dart file in an analysis root. +-

    +-
    +- +- SORT_MEMBERS_PARSE_ERRORS +-

    +- An "edit.sortMembers" request specified a Dart file that has +- scan or parse errors. +-

    +-
    +- +- UNANALYZED_PRIORITY_FILES +-

    +- An "analysis.setPriorityFiles" request includes one or +- more files that are not being analyzed. +-

    +-

    +- This is a legacy error; it will be removed before the +- API reaches version 1.0. +-

    +- +-
    +- +- UNKNOWN_REQUEST +-

    +- A request was received which the analysis server does +- not recognize, or cannot handle in its current +- configuration. +-

    +-
    +- +- UNKNOWN_SOURCE +-

    +- The analysis server was requested to perform an action +- on a source that does not exist. +-

    +-
    +- +- UNSUPPORTED_FEATURE +-

    +- The analysis server was requested to perform an action +- which is not supported. +-

    +-

    +- This is a legacy error; it will be removed before the +- API reaches version 1.0. +-

    +- +-
    +-
    +-
    +- +- String +-

    +- An identifier used to associate search results with a search +- request. +-

    +-
    +- +-

    +- A single result from a search request. +-

    +- +- +- Location +-

    +- The location of the code that matched the search criteria. +-

    +-
    +- +- SearchResultKind +-

    +- The kind of element that was found or the kind of +- reference that was found. +-

    +-
    +- +- bool +-

    +- True if the result is a potential match but cannot be +- confirmed to be a match. For example, if all references to +- a method m defined in some class were requested, and a +- reference to a method m from an unknown class were found, +- it would be marked as being a potential match. +-

    +-
    +- +- +- Element +- +-

    +- The elements that contain the result, starting with the +- most immediately enclosing ancestor and ending with the +- library. +-

    +-
    +-
    +-
    +- +-

    +- An enumeration of the kinds of search results returned by the +- search domain. +-

    +- +- +- DECLARATION +-

    +- The declaration of an element. +-

    +-
    +- +- INVOCATION +-

    +- The invocation of a function or method. +-

    +-
    +- +- READ +-

    +- A reference to a field, parameter or variable where it is being= read. +-

    +-
    +- +- READ_WRITE +-

    +- A reference to a field, parameter or variable where it is being= read +- and written. +-

    +-
    +- +- REFERENCE +-

    +- A reference to an element. +-

    +-
    +- +- UNKNOWN +-

    +- Some other kind of search result. +-

    +-
    +- +- WRITE +-

    +- A reference to a field, parameter or variable where it is being +- written. +-

    +-
    +-
    +-
    +- +-

    +- An enumeration of the services provided by the server domain. +-

    +- +- STATUS +- +-
    +- +-

    +- A representation of a class in a type hierarchy. +-

    +- +- +- Element +-

    +- The class element represented by this item. +-

    +-
    +- +- String +-

    +- The name to be displayed for the class. This field will be +- omitted if the display name is the same as the name of the +- element. The display name is different if there is +- additional type information to be displayed, such as type +- arguments. +-

    +-
    +- +- Element +-

    +- The member in the class corresponding to the member on +- which the hierarchy was requested. This field will be +- omitted if the hierarchy was not requested for a member or +- if the class does not have a corresponding member. +-

    +-
    +- +- int +-

    +- The index of the item representing the superclass of +- this class. This field will be omitted if this item +- represents the class Object. +-

    +-
    +- +- +- int +- +-

    +- The indexes of the items representing the interfaces +- implemented by this class. The list will be empty if +- there are no implemented interfaces. +-

    +-
    +- +- +- int +- +-

    +- The indexes of the items representing the mixins +- referenced by this class. The list will be empty if +- there are no classes mixed in to this class. +-

    +-
    +- +- +- int +- +-

    +- The indexes of the items representing the subtypes of +- this class. The list will be empty if there are no +- subtypes or if this item represents a supertype of the +- pivot type. +-

    +-
    +-
    +-
    +-
    +- +-

    Refactorings

    +-

    +- This section contains additional information for each kind of +- refactoring. In addition to a brief description of the +- refactoring, there is a specification of the feedback that is +- provided when a refactoring is requested using the +- edit.getRefactoring request (designed to improve the UX) +- and the options that may be provided to edit.getRefactoring. +-

    +- +-

    +- Convert a getter into a method by removing the keyword get +- and adding an empty parameter list. +-

    +-

    +- It is an error if the range contains anything other than all +- or part of the name of a single getter. +-

    +-
    +- +-

    +- Convert a method into a getter by adding the keyword get and +- removing the parameter list. +-

    +-

    +- It is an error if the range contains anything other than all +- or part of the name of a single method or if the method has +- a non-empty parameter list. +-

    +-
    +- +-

    +- Create a local variable initialized by the expression that covers +- the specified selection. +-

    +-

    +- It is an error if the selection range is not covered by a +- complete expression. +-

    +- +- +- +- int +- +-

    +- The offsets of the expressions that cover the specified +- selection, from the down most to the up most. +-

    +-
    +- +- +- int +- +-

    +- The lengths of the expressions that cover the specified +- selection, from the down most to the up most. +-

    +-
    +- +- +- String +- +-

    +- The proposed names for the local variable. +-

    +-
    +- +- +- int +- +-

    +- The offsets of the expressions that would be replaced by +- a reference to the variable. +-

    +-
    +- +- +- int +- +-

    +- The lengths of the expressions that would be replaced by +- a reference to the variable. The lengths correspond to +- the offsets. In other words, for a given expression, if +- the offset of that expression is offsets[i], then +- the length of that expression is lengths[i]. +-

    +-
    +-
    +- +- +- String +-

    +- The name that the local variable should be given. +-

    +-
    +- +- bool +-

    +- True if all occurrences of the expression within the +- scope in which the variable will be defined should be +- replaced by a reference to the local variable. The +- expression used to initiate the refactoring will always +- be replaced. +-

    +-
    +-
    +-
    +- +-

    +- Create a method whose body is the specified expression or +- list of statements, possibly augmented with a return +- statement. +-

    +-

    +- It is an error if the range contains anything other than a +- complete expression (no partial expressions are allowed) or +- a complete sequence of statements. +-

    +- +- +- int +-

    +- The offset to the beginning of the expression or +- statements that will be extracted. +-

    +-
    +- +- int +-

    +- The length of the expression or statements that will be +- extracted. +-

    +-
    +- +- String +-

    +- The proposed return type for the method. +- If the returned element does not have a declared return type, +- this field will contain an empty string. +-

    +-
    +- +- +- String +- +-

    +- The proposed names for the method. +-

    +-
    +- +- bool +-

    +- True if a getter could be created rather than a method. +-

    +-
    +- +- +- RefactoringMethodParameter +- +-

    +- The proposed parameters for the method. +-

    +-
    +- +- +- int +- +-

    +- The offsets of the expressions or statements that would +- be replaced by an invocation of the method. +-

    +-
    +- +- +- int +- +-

    +- The lengths of the expressions or statements that would +- be replaced by an invocation of the method. The lengths +- correspond to the offsets. In other words, for a given +- expression (or block of statements), if the offset of +- that expression is offsets[i], then the length +- of that expression is lengths[i]. +-

    +-
    +-
    +- +- +- String +-

    +- The return type that should be defined for the method. +-

    +-
    +- +- bool +-

    +- True if a getter should be created rather than a +- method. It is an error if this field is true and the +- list of parameters is non-empty. +-

    +-
    +- +- String +-

    +- The name that the method should be given. +-

    +-
    +- +- +- RefactoringMethodParameter +- +-

    +- The parameters that should be defined for the method. +-

    +-

    +- It is an error if a REQUIRED or NAMED parameter follows a +- POSITIONAL parameter. +- It is an error if a REQUIRED or POSITIONAL parameter follows a +- NAMED parameter. +-

    +-
      +-
    • +- To change the order and/or update proposed parameters, add +- parameters with the same identifiers as proposed. +-
    • +-
    • To add new parameters, omit their identifier.
    • +-
    • To remove some parameters, omit them in this list.
    • +-
    +-
    +- +- bool +-

    +- True if all occurrences of the expression or statements +- should be replaced by an invocation of the method. The +- expression or statements used to initiate the +- refactoring will always be replaced. +-

    +-
    +-
    +-
    +- +-

    +- Inline the initializer expression of a local variable in +- place of any references to that variable. +-

    +-

    +- It is an error if the range contains anything other than all +- or part of the name of a single local variable. +-

    +- +- +- String +-

    +- The name of the variable being inlined. +-

    +-
    +- +- int +-

    +- The number of times the variable occurs. +-

    +-
    +-
    +-
    +- +-

    +- Inline a method in place of one or all references to that +- method. +-

    +-

    +- It is an error if the range contains anything other than all +- or part of the name of a single method. +-

    +- +- +- String +-

    +- The name of the class enclosing the method being inlined. +- If not a class member is being inlined, this field will be abse= nt. +-

    +-
    +- +- String +-

    +- The name of the method (or function) being inlined. +-

    +-
    +- +- bool +-

    +- True if the declaration of the method is selected. +- So all references should be inlined. +-

    +-
    +-
    +- +- +- bool +-

    +- True if the method being inlined should be removed. +- It is an error if this field is true and inlineAll is false. +-

    +-
    +- +- bool +-

    +- True if all invocations of the method should be inlined, +- or false if only the invocation site used to create this +- refactoring should be inlined. +-

    +-
    +-
    +-
    +- +-

    +- Move the given file and update all of the references to that file +- and from it. The move operation is supported in general case - for +- renaming a file in the same folder, moving it to a different folder +- or both. +-

    +-

    +- The refactoring must be activated before an actual file moving +- operation is performed. +-

    +-

    +- The "offset" and "length" fields from the request are ignored, but = the +- file specified in the request specifies the file to be moved. +-

    +- +- +- FilePath +-

    +- The new file path to which the given file is being moved. +-

    +-
    +-
    +-
    +- +-

    +- Rename a given element and all of the references to that +- element. +-

    +-

    +- It is an error if the range contains anything other than all +- or part of the name of a single function (including methods, +- getters and setters), variable (including fields, parameters +- and local variables), class or function type. +-

    +- +- +- int +-

    +- The offset to the beginning of the name selected to be +- renamed. +-

    +-
    +- +- int +-

    +- The length of the name selected to be renamed. +-

    +-
    +- +- String +-

    +- The human-readable description of the kind of element being +- renamed (such as "class" or "function type +- alias"). +-

    +-
    +- +- String +-

    +- The old name of the element before the refactoring. +-

    +-
    +-
    +- +- +- String +-

    +- The name that the element should have after the +- refactoring. +-

    +-
    +-
    +-
    +-
    +-

    Errors

    +-

    +- This section contains a list of all of the errors that are +- produced by the server and the data that is returned with each. +-

    +-

    +- TODO: TBD +-

    +-

    Index

    +- +- +- +diff --git a/pkg/analysis_server/tool/spec/to_html.dart b/pkg/analysis_ser= ver/tool/spec/to_html.dart +deleted file mode 100644 +index 82a93c753e9..00000000000 +--- a/pkg/analysis_server/tool/spec/to_html.dart ++++ /dev/null +@@ -1,831 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-/** +- * Code for displaying the API as HTML. This is used both for generating= a +- * full description of the API as a web page, and for generating doc comm= ents +- * in generated code. +- */ +-import 'dart:convert'; +- +-import 'package:analyzer/src/codegen/html.dart'; +-import 'package:analyzer/src/codegen/tools.dart'; +-import 'package:front_end/src/codegen/tools.dart'; +-import 'package:html/dom.dart' as dom; +- +-import 'api.dart'; +-import 'from_html.dart'; +- +-/** +- * Embedded stylesheet +- */ +-final String stylesheet =3D ''' +-body { +- font-family: 'Roboto', sans-serif; +- max-width: 800px; +- margin: 0 auto; +- padding: 0 16px; +- font-size: 16px; +- line-height: 1.5; +- color: #111; +- background-color: #fdfdfd; +- font-weight: 300; +- -webkit-font-smoothing: auto; +-} +- +-h2, h3, h4, h5 { +- margin-bottom: 0; +-} +- +-h2.domain { +- border-bottom: 1px solid rgb(200, 200, 200); +- margin-bottom: 0.5em; +-} +- +-h4 { +- font-size: 18px; +-} +- +-h5 { +- font-size: 16px; +-} +- +-p { +- margin-top: 0; +-} +- +-pre { +- margin: 0; +- font-family: 'Source Code Pro', monospace; +- font-size: 15px; +-} +- +-div.box { +- background-color: rgb(240, 245, 240); +- border-radius: 4px; +- padding: 4px 12px; +- margin: 16px 0; +-} +- +-div.hangingIndent { +- padding-left: 3em; +- text-indent: -3em; +-} +- +-dl dt { +- font-weight: bold; +-} +- +-dl dd { +- margin-left: 16px; +-} +- +-dt { +- margin-top: 1em; +-} +- +-dt.notification { +- font-weight: bold; +-} +- +-dt.refactoring { +- font-weight: bold; +-} +- +-dt.request { +- font-weight: bold; +-} +- +-dt.typeDefinition { +- font-weight: bold; +-} +- +-a { +- text-decoration: none; +-} +- +-a:focus, a:hover { +- text-decoration: underline; +-} +- +-.deprecated { +- text-decoration: line-through; +-} +- +-/* Styles for index */ +- +-.subindex ul { +- padding-left: 0; +- margin-left: 0; +- +- -webkit-margin-before: 0; +- -webkit-margin-start: 0; +- -webkit-padding-start: 0; +- +- list-style-type: none; +-} +-''' +- .trim(); +- +-final GeneratedFile target =3D +- new GeneratedFile('doc/api.html', (String pkgPath) async { +- ToHtmlVisitor visitor =3D new ToHtmlVisitor(readApi(pkgPath)); +- dom.Document document =3D new dom.Document(); +- document.append(new dom.DocumentType('html', null, null)); +- for (dom.Node node in visitor.collectHtml(visitor.visitApi)) { +- document.append(node); +- } +- return document.outerHtml; +-}); +- +-String _toTitleCase(String str) { +- if (str.isEmpty) return str; +- return str.substring(0, 1).toUpperCase() + str.substring(1); +-} +- +-/** +- * Visitor that records the mapping from HTML elements to various kinds o= f API +- * nodes. +- */ +-class ApiMappings extends HierarchicalApiVisitor { +- Map domains =3D {}; +- +- ApiMappings(Api api) : super(api); +- +- @override +- void visitDomain(Domain domain) { +- domains[domain.html] =3D domain; +- } +-} +- +-/** +- * Helper methods for creating HTML elements. +- */ +-abstract class HtmlMixin { +- void anchor(String id, void callback()) { +- element('a', {'name': id}, callback); +- } +- +- void b(void callback()) =3D> element('b', {}, callback); +- void body(void callback()) =3D> element('body', {}, callback); +- void box(void callback()) { +- element('div', {'class': 'box'}, callback); +- } +- +- void br() =3D> element('br', {}); +- void dd(void callback()) =3D> element('dd', {}, callback); +- void dl(void callback()) =3D> element('dl', {}, callback); +- void dt(String cls, void callback()) =3D> +- element('dt', {'class': cls}, callback); +- void element(String name, Map attributes, [void callba= ck()]); +- void gray(void callback()) =3D> +- element('span', {'style': 'color:#999999'}, callback); +- void h1(void callback()) =3D> element('h1', {}, callback); +- void h2(String cls, void callback()) { +- if (cls =3D=3D null) { +- return element('h2', {}, callback); +- } +- return element('h2', {'class': cls}, callback); +- } +- +- void h3(void callback()) =3D> element('h3', {}, callback); +- void h4(void callback()) =3D> element('h4', {}, callback); +- void h5(void callback()) =3D> element('h5', {}, callback); +- void hangingIndent(void callback()) =3D> +- element('div', {'class': 'hangingIndent'}, callback); +- void head(void callback()) =3D> element('head', {}, callback); +- void html(void callback()) =3D> element('html', {}, callback); +- void i(void callback()) =3D> element('i', {}, callback); +- void li(void callback()) =3D> element('li', {}, callback); +- void link(String id, void callback(), [Map attributes]= ) { +- attributes ??=3D {}; +- attributes['href'] =3D '#$id'; +- element('a', attributes, callback); +- } +- +- void p(void callback()) =3D> element('p', {}, callback); +- void pre(void callback()) =3D> element('pre', {}, callback); +- void span(String cls, void callback()) =3D> +- element('span', {'class': cls}, callback); +- void title(void callback()) =3D> element('title', {}, callback); +- void tt(void callback()) =3D> element('tt', {}, callback); +- void ul(void callback()) =3D> element('ul', {}, callback); +-} +- +-/** +- * Visitor that generates HTML documentation of the API. +- */ +-class ToHtmlVisitor extends HierarchicalApiVisitor +- with HtmlMixin, HtmlGenerator { +- /** +- * Set of types defined in the API. +- */ +- Set definedTypes =3D new Set(); +- +- /** +- * Mappings from HTML elements to API nodes. +- */ +- ApiMappings apiMappings; +- +- ToHtmlVisitor(Api api) +- : apiMappings =3D new ApiMappings(api), +- super(api) { +- apiMappings.visitApi(); +- } +- +- /** +- * Describe the payload of request, response, notification, refactoring +- * feedback, or refactoring options. +- * +- * If [force] is true, then a section is inserted even if the payload is +- * null. +- */ +- void describePayload(TypeObject subType, String name, {bool force: fals= e}) { +- if (force || subType !=3D null) { +- h4(() { +- write(name); +- }); +- if (subType =3D=3D null) { +- p(() { +- write('none'); +- }); +- } else { +- visitTypeDecl(subType); +- } +- } +- } +- +- void generateDomainIndex(Domain domain) { +- h4(() { +- write(domain.name); +- write(' ('); +- link('domain_${domain.name}', () =3D> write('\u2191')); +- write(')'); +- }); +- if (domain.requests.length > 0) { +- element('div', {'class': 'subindex'}, () { +- generateRequestsIndex(domain.requests); +- if (domain.notifications.length > 0) { +- generateNotificationsIndex(domain.notifications); +- } +- }); +- } else if (domain.notifications.length > 0) { +- element('div', {'class': 'subindex'}, () { +- generateNotificationsIndex(domain.notifications); +- }); +- } +- } +- +- void generateDomainsHeader() { +- h1(() { +- write('Domains'); +- }); +- } +- +- void generateIndex() { +- h3(() =3D> write('Domains')); +- for (var domain in api.domains) { +- if (domain.experimental || +- (domain.requests.length =3D=3D 0 && domain.notifications =3D=3D= 0)) { +- continue; +- } +- generateDomainIndex(domain); +- } +- +- generateTypesIndex(definedTypes); +- generateRefactoringsIndex(api.refactorings); +- } +- +- void generateNotificationsIndex(Iterable notifications) { +- h5(() =3D> write("Notifications")); +- element('div', {'class': 'subindex'}, () { +- element('ul', {}, () { +- for (var notification in notifications) { +- element( +- 'li', +- {}, +- () =3D> link('notification_${notification.longEvent}', +- () =3D> write(notification.event))); +- } +- }); +- }); +- } +- +- void generateRefactoringsIndex(Iterable refactorings) { +- if (refactorings =3D=3D null) { +- return; +- } +- h3(() { +- write("Refactorings"); +- write(' ('); +- link('refactorings', () =3D> write('\u2191')); +- write(')'); +- }); +- // TODO: Individual refactorings are not yet hyperlinked. +- element('div', {'class': 'subindex'}, () { +- element('ul', {}, () { +- for (var refactoring in refactorings) { +- element( +- 'li', +- {}, +- () =3D> link('refactoring_${refactoring.kind}', +- () =3D> write(refactoring.kind))); +- } +- }); +- }); +- } +- +- void generateRequestsIndex(Iterable requests) { +- h5(() =3D> write("Requests")); +- element('ul', {}, () { +- for (var request in requests) { +- if (!request.experimental) { +- element( +- 'li', +- {}, +- () =3D> link('request_${request.longMethod}', +- () =3D> write(request.method))); +- } +- } +- }); +- } +- +- void generateTableOfContents() { +- for (var domain in api.domains.where((domain) =3D> !domain.experiment= al)) { +- if (domain.experimental) continue; +- +- writeln(); +- +- p(() { +- link('domain_${domain.name}', () { +- write(_toTitleCase(domain.name)); +- }); +- }); +- +- ul(() { +- for (Request request in domain.requests) { +- if (request.experimental) continue; +- +- li(() { +- link('request_${request.longMethod}', () { +- write(request.longMethod); +- }, request.deprecated ? {'class': 'deprecated'} : null); +- }); +- writeln(); +- } +- }); +- +- writeln(); +- } +- } +- +- void generateTypesIndex(Set types) { +- h3(() { +- write("Types"); +- write(' ('); +- link('types', () =3D> write('\u2191')); +- write(')'); +- }); +- List sortedTypes =3D types.toList(); +- sortedTypes.sort(); +- element('div', {'class': 'subindex'}, () { +- element('ul', {}, () { +- for (var type in sortedTypes) { +- element('li', {}, () =3D> link('type_$type', () =3D> write(type= ))); +- } +- }); +- }); +- } +- +- void javadocParams(TypeObject typeObject) { +- if (typeObject !=3D null) { +- for (TypeObjectField field in typeObject.fields) { +- hangingIndent(() { +- write('@param ${field.name} '); +- translateHtml(field.html, squashParagraphs: true); +- }); +- } +- } +- } +- +- /** +- * Generate a description of [type] using [TypeVisitor]. +- * +- * If [shortDesc] is non-null, the output is prefixed with this string +- * and a colon. +- * +- * If [typeForBolding] is supplied, then fields in this type are shown = in +- * boldface. +- */ +- void showType(String shortDesc, TypeDecl type, [TypeObject typeForBoldi= ng]) { +- Set fieldsToBold =3D new Set(); +- if (typeForBolding !=3D null) { +- for (TypeObjectField field in typeForBolding.fields) { +- fieldsToBold.add(field.name); +- } +- } +- pre(() { +- if (shortDesc !=3D null) { +- write('$shortDesc: '); +- } +- TypeVisitor typeVisitor =3D +- new TypeVisitor(api, fieldsToBold: fieldsToBold); +- addAll(typeVisitor.collectHtml(() { +- typeVisitor.visitTypeDecl(type); +- })); +- }); +- } +- +- /** +- * Copy the contents of the given HTML element, translating the special +- * elements that define the API appropriately. +- */ +- void translateHtml(dom.Element html, {bool squashParagraphs: false}) { +- for (dom.Node node in html.nodes) { +- if (node is dom.Element) { +- if (squashParagraphs && node.localName =3D=3D 'p') { +- translateHtml(node, squashParagraphs: squashParagraphs); +- continue; +- } +- switch (node.localName) { +- case 'domains': +- generateDomainsHeader(); +- break; +- case 'domain': +- visitDomain(apiMappings.domains[node]); +- break; +- case 'head': +- head(() { +- translateHtml(node, squashParagraphs: squashParagraphs); +- element('link', { +- 'rel': 'stylesheet', +- 'href': +- 'https://fonts.googleapis.com/css?family=3DSource+Cod= e+Pro|Roboto:500,400italic,300,400', +- 'type': 'text/css' +- }); +- element('style', {}, () { +- writeln(stylesheet); +- }); +- }); +- break; +- case 'refactorings': +- visitRefactorings(api.refactorings); +- break; +- case 'types': +- visitTypes(api.types); +- break; +- case 'version': +- translateHtml(node, squashParagraphs: squashParagraphs); +- break; +- case 'toc': +- generateTableOfContents(); +- break; +- case 'index': +- generateIndex(); +- break; +- default: +- if (!ApiReader.specialElements.contains(node.localName)) { +- element(node.localName, node.attributes, () { +- translateHtml(node, squashParagraphs: squashParagraphs); +- }); +- } +- } +- } else if (node is dom.Text) { +- String text =3D node.text; +- write(text); +- } +- } +- } +- +- @override +- void visitApi() { +- Iterable apiTypes =3D +- api.types.where((TypeDefinition td) =3D> !td.experimental); +- definedTypes =3D apiTypes.map((TypeDefinition td) =3D> td.name).toSet= (); +- +- html(() { +- translateHtml(api.html); +- }); +- } +- +- @override +- void visitDomain(Domain domain) { +- if (domain.experimental) { +- return; +- } +- h2('domain', () { +- anchor('domain_${domain.name}', () { +- write('${domain.name} domain'); +- }); +- }); +- translateHtml(domain.html); +- if (domain.requests.isNotEmpty) { +- h3(() { +- write('Requests'); +- }); +- dl(() { +- domain.requests.forEach(visitRequest); +- }); +- } +- if (domain.notifications.isNotEmpty) { +- h3(() { +- write('Notifications'); +- }); +- dl(() { +- domain.notifications.forEach(visitNotification); +- }); +- } +- } +- +- @override +- void visitNotification(Notification notification) { +- if (notification.experimental) { +- return; +- } +- dt('notification', () { +- anchor('notification_${notification.longEvent}', () { +- write(notification.longEvent); +- }); +- }); +- dd(() { +- box(() { +- showType( +- 'notification', notification.notificationType, notification.p= arams); +- }); +- translateHtml(notification.html); +- describePayload(notification.params, 'parameters:'); +- }); +- } +- +- @override +- visitRefactoring(Refactoring refactoring) { +- dt('refactoring', () { +- write(refactoring.kind); +- }); +- dd(() { +- translateHtml(refactoring.html); +- describePayload(refactoring.feedback, 'Feedback:', force: true); +- describePayload(refactoring.options, 'Options:', force: true); +- }); +- } +- +- @override +- void visitRefactorings(Refactorings refactorings) { +- translateHtml(refactorings.html); +- dl(() { +- super.visitRefactorings(refactorings); +- }); +- } +- +- @override +- void visitRequest(Request request) { +- if (request.experimental) { +- return; +- } +- dt(request.deprecated ? 'request deprecated' : 'request', () { +- anchor('request_${request.longMethod}', () { +- write(request.longMethod); +- }); +- }); +- dd(() { +- box(() { +- showType('request', request.requestType, request.params); +- br(); +- showType('response', request.responseType, request.result); +- }); +- translateHtml(request.html); +- describePayload(request.params, 'parameters:'); +- describePayload(request.result, 'returns:'); +- }); +- } +- +- @override +- void visitTypeDefinition(TypeDefinition typeDefinition) { +- if (typeDefinition.experimental) { +- return; +- } +- dt( +- typeDefinition.deprecated +- ? 'typeDefinition deprecated' +- : 'typeDefinition', () { +- anchor('type_${typeDefinition.name}', () { +- write('${typeDefinition.name}: '); +- TypeVisitor typeVisitor =3D new TypeVisitor(api, short: true); +- addAll(typeVisitor.collectHtml(() { +- typeVisitor.visitTypeDecl(typeDefinition.type); +- })); +- }); +- }); +- dd(() { +- translateHtml(typeDefinition.html); +- visitTypeDecl(typeDefinition.type); +- }); +- } +- +- @override +- void visitTypeEnum(TypeEnum typeEnum) { +- dl(() { +- super.visitTypeEnum(typeEnum); +- }); +- } +- +- @override +- void visitTypeEnumValue(TypeEnumValue typeEnumValue) { +- bool isDocumented =3D false; +- for (dom.Node node in typeEnumValue.html.nodes) { +- if ((node is dom.Element && node.localName !=3D 'code') || +- (node is dom.Text && node.text.trim().isNotEmpty)) { +- isDocumented =3D true; +- break; +- } +- } +- dt(typeEnumValue.deprecated ? 'value deprecated' : 'value', () { +- write(typeEnumValue.value); +- }); +- if (isDocumented) { +- dd(() { +- translateHtml(typeEnumValue.html); +- }); +- } +- } +- +- @override +- void visitTypeList(TypeList typeList) { +- visitTypeDecl(typeList.itemType); +- } +- +- @override +- void visitTypeMap(TypeMap typeMap) { +- visitTypeDecl(typeMap.valueType); +- } +- +- @override +- void visitTypeObject(TypeObject typeObject) { +- dl(() { +- super.visitTypeObject(typeObject); +- }); +- } +- +- @override +- void visitTypeObjectField(TypeObjectField typeObjectField) { +- dt('field', () { +- b(() { +- if (typeObjectField.deprecated) { +- span('deprecated', () { +- write(typeObjectField.name); +- }); +- } else { +- write(typeObjectField.name); +- } +- if (typeObjectField.value !=3D null) { +- write(' =3D ${JSON.encode(typeObjectField.value)}'); +- } else { +- write(': '); +- TypeVisitor typeVisitor =3D new TypeVisitor(api, short: true); +- addAll(typeVisitor.collectHtml(() { +- typeVisitor.visitTypeDecl(typeObjectField.type); +- })); +- if (typeObjectField.optional) { +- gray(() =3D> write(' (optional)')); +- } +- } +- }); +- }); +- dd(() { +- translateHtml(typeObjectField.html); +- }); +- } +- +- @override +- void visitTypeReference(TypeReference typeReference) {} +- +- @override +- void visitTypes(Types types) { +- translateHtml(types.html); +- dl(() { +- List sortedTypes =3D types.toList(); +- sortedTypes.sort((TypeDefinition first, TypeDefinition second) =3D> +- first.name.compareTo(second.name)); +- sortedTypes.forEach(visitTypeDefinition); +- }); +- } +-} +- +-/** +- * Visitor that generates a compact representation of a type, such as: +- * +- * { +- * "id": String +- * "error": optional Error +- * "result": { +- * "version": String +- * } +- * } +- */ +-class TypeVisitor extends HierarchicalApiVisitor +- with HtmlMixin, HtmlCodeGenerator { +- /** +- * Set of fields which should be shown in boldface, or null if no field +- * should be shown in boldface. +- */ +- final Set fieldsToBold; +- +- /** +- * True if a short description should be generated. In a short descrip= tion, +- * objects are shown as simply "object", and enums are shown as "String= ". +- */ +- final bool short; +- +- TypeVisitor(Api api, {this.fieldsToBold, this.short: false}) : super(ap= i); +- +- @override +- void visitTypeEnum(TypeEnum typeEnum) { +- if (short) { +- write('String'); +- return; +- } +- writeln('enum {'); +- indent(() { +- for (TypeEnumValue value in typeEnum.values) { +- writeln(value.value); +- } +- }); +- write('}'); +- } +- +- @override +- void visitTypeList(TypeList typeList) { +- write('List<'); +- visitTypeDecl(typeList.itemType); +- write('>'); +- } +- +- @override +- void visitTypeMap(TypeMap typeMap) { +- write('Map<'); +- visitTypeDecl(typeMap.keyType); +- write(', '); +- visitTypeDecl(typeMap.valueType); +- write('>'); +- } +- +- @override +- void visitTypeObject(TypeObject typeObject) { +- if (short) { +- write('object'); +- return; +- } +- writeln('{'); +- indent(() { +- for (TypeObjectField field in typeObject.fields) { +- write('"'); +- if (fieldsToBold !=3D null && fieldsToBold.contains(field.name)) { +- b(() { +- write(field.name); +- }); +- } else { +- write(field.name); +- } +- write('": '); +- if (field.value !=3D null) { +- write(JSON.encode(field.value)); +- } else { +- if (field.optional) { +- gray(() { +- write('optional'); +- }); +- write(' '); +- } +- visitTypeDecl(field.type); +- } +- writeln(); +- } +- }); +- write('}'); +- } +- +- @override +- void visitTypeReference(TypeReference typeReference) { +- String displayName =3D typeReference.typeName; +- if (api.types.containsKey(typeReference.typeName)) { +- link('type_${typeReference.typeName}', () { +- write(displayName); +- }); +- } else { +- write(displayName); +- } +- } +- +- @override +- void visitTypeUnion(TypeUnion typeUnion) { +- bool verticalBarNeeded =3D false; +- for (TypeDecl choice in typeUnion.choices) { +- if (verticalBarNeeded) { +- write(' | '); +- } +- visitTypeDecl(choice); +- verticalBarNeeded =3D true; +- } +- } +-} +diff --git a/pkg/analysis_server_client/CHANGELOG.md b/pkg/analysis_server= _client/CHANGELOG.md +deleted file mode 100644 +index 14d2f07d088..00000000000 +--- a/pkg/analysis_server_client/CHANGELOG.md ++++ /dev/null +@@ -1,5 +0,0 @@ +-#1.0.1 +-* Update path on homepage +- +-#1.0.0 +-* Initial version +\ No newline at end of file +diff --git a/pkg/analysis_server_client/LICENSE b/pkg/analysis_server_clie= nt/LICENSE +deleted file mode 100644 +index 076334f7ab7..00000000000 +--- a/pkg/analysis_server_client/LICENSE ++++ /dev/null +@@ -1,26 +0,0 @@ +-Copyright 2017, the Dart project authors. All rights reserved. +-Redistribution and use in source and binary forms, with or without +-modification, are permitted provided that the following conditions are +-met: +- +- * Redistributions of source code must retain the above copyright +- notice, this list of conditions and the following disclaimer. +- * Redistributions in binary form must reproduce the above +- copyright notice, this list of conditions and the following +- disclaimer in the documentation and/or other materials provided +- with the distribution. +- * Neither the name of Google Inc. nor the names of its +- contributors may be used to endorse or promote products derived +- from this software without specific prior written permission. +- +-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +\ No newline at end of file +diff --git a/pkg/analysis_server_client/README.md b/pkg/analysis_server_cl= ient/README.md +deleted file mode 100644 +index 3351705598b..00000000000 +--- a/pkg/analysis_server_client/README.md ++++ /dev/null +@@ -1,13 +0,0 @@ +-# Analysis Server Client +- +-A client wrapper over Analysis Server. Instances of this client manages +-connection to Analysis Server and process and faciliates JSON protocol +-communication to and from the server.=20 +- +-Current implementation has no knowledge of the Analysis Server library ye= t. +-Future updates will allow for full class-access of Analysis Server protoc= ol +-objects.=20 +- +-Analysis Server process must be instantiated separately and loaded into +-Analysis Server Client. To learn how to generate an Analysis Server Proce= ss, +-refer to the [Analysis Server page.](https://github.com/dart-lang/sdk/tre= e/master/pkg/analysis_server) +diff --git a/pkg/analysis_server_client/lib/analysis_server_client.dart b/= pkg/analysis_server_client/lib/analysis_server_client.dart +deleted file mode 100644 +index 96286e40dd9..00000000000 +--- a/pkg/analysis_server_client/lib/analysis_server_client.dart ++++ /dev/null +@@ -1,101 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-/// Type of callbacks used to process notification. +-typedef void NotificationProcessor(String event, Map para= ms); +- +-/// Instances of the class [AnalysisServerClient] manage a connection to = an +-/// [AnalysisServer] process, and facilitate communication to and from the +-/// client/user. +-class AnalysisServerClient { +- /// AnalysisServer process object, or null if the server has been shut = down. +- final Process _process; +- +- /// Commands that have been sent to the server but not yet acknowledged, +- /// and the [Completer] objects which should be completed when +- /// acknowledgement is received. +- final Map _pendingCommands =3D {}; +- +- /// Number which should be used to compute the 'id' to send to the next +- /// command sent to the server. +- int _nextId =3D 0; +- +- AnalysisServerClient(this._process); +- +- /// Return a future that will complete when all commands that have been +- /// sent to the server so far have been flushed to the OS buffer. +- Future flushCommands() { +- return _process.stdin.flush(); +- } +- +- void listenToOutput({NotificationProcessor notificationProcessor}) { +- _process.stdout +- .transform((new Utf8Codec()).decoder) +- .transform(new LineSplitter()) +- .listen((String line) { +- String trimmedLine =3D line.trim(); +- if (trimmedLine.startsWith('Observatory listening on ')) { +- return; +- } +- final result =3D JSON.decoder.convert(trimmedLine) as Map; +- if (result.containsKey('id')) { +- final id =3D result['id'] as String; +- final completer =3D _pendingCommands.remove(id); +- +- if (result.containsKey('error')) { +- completer.completeError(new ServerErrorMessage(result['error'])= ); +- } else { +- completer.complete(result['result']); +- } +- } else if (notificationProcessor !=3D null && result.containsKey('e= vent')) { +- // Message is a notification. It should have an event and possibly +- // params. +- notificationProcessor(result['event'], result['params']); +- } +- }); +- } +- +- /// Sends a command to the server. An 'id' will be automatically assign= ed. +- /// The returned [Future] will be completed when the server acknowledges +- /// the command with a response. If the server acknowledges the command +- /// with a normal (non-error) response, the future will be completed +- /// with the 'result' field from the response. If the server acknowledg= es +- /// the command with an error response, the future will be completed wi= th an +- /// error. +- Future send(String method, Map params) { +- String id =3D '${_nextId++}'; +- Map command =3D { +- 'id': id, +- 'method': method +- }; +- if (params !=3D null) { +- command['params'] =3D params; +- } +- Completer completer =3D new Completer(); +- _pendingCommands[id] =3D completer; +- String commandAsJson =3D JSON.encode(command); +- _process.stdin.add(UTF8.encoder.convert('$commandAsJson\n')); +- return completer.future; +- } +- +- /// Force kill the server. Returns exit code future. +- Future kill() { +- _process.kill(); +- return _process.exitCode; +- } +-} +- +-class ServerErrorMessage { +- final Map errorJson; +- +- ServerErrorMessage(this.errorJson); +- +- String get code =3D> errorJson['code'].toString(); +- String get message =3D> errorJson['message']; +- String get stackTrace =3D> errorJson['stackTrace']; +-} +diff --git a/pkg/analysis_server_client/pubspec.yaml b/pkg/analysis_server= _client/pubspec.yaml +deleted file mode 100644 +index 25ea57e87a0..00000000000 +--- a/pkg/analysis_server_client/pubspec.yaml ++++ /dev/null +@@ -1,13 +0,0 @@ +-name: analysis_server_client +-version: 1.0.1 +-author: Dart Team +-description: +- A client wrapper over analysis_server. Instances of this client +- manage a connection to the analysis_server process and +- facilitates communication to and from the server. +-homepage: http://github.com/dart-lang/sdk/pkg/analysis_server_client +-dev_dependencies: +- test: ">=3D0.12.0 <0.13.0" +- mockito: ^2.0.2 +-environment: +- sdk: ">=3D1.0.0 < 2.0.0-dev.infinity" +diff --git a/pkg/analysis_server_client/test/analysis_server_client_test.d= art b/pkg/analysis_server_client/test/analysis_server_client_test.dart +deleted file mode 100644 +index 900bd52b0b0..00000000000 +--- a/pkg/analysis_server_client/test/analysis_server_client_test.dart ++++ /dev/null +@@ -1,97 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:convert'; +-import 'dart:io'; +- +-import 'package:analysis_server_client/analysis_server_client.dart'; +-import 'package:mockito/mockito.dart'; +-import 'package:test/test.dart'; +- +-void main() { +- Process _process; +- AnalysisServerClient serverWrapper; +- +- setUp(() async { +- _process =3D new MockProcess(); +- final _mockStdin =3D new MockStdin(); +- serverWrapper =3D new AnalysisServerClient(_process); +- when(_process.stdin).thenReturn(_mockStdin); +- when(_mockStdin.add).thenReturn(null); +- }); +- +- test('test_listenToOutput_good', () async { +- when(_process.stdout).thenReturn(_goodMessage()); +- +- final future =3D serverWrapper.send('blahMethod', null); +- serverWrapper.listenToOutput(); +- +- final response =3D await future; +- expect(response, new isInstanceOf()); +- final responseAsMap =3D response as Map; +- expect(responseAsMap['foo'], 'bar'); +- }); +- +- test('test_listenToOutput_error', () async { +- when(_process.stdout).thenReturn(_badMessage()); +- final future =3D serverWrapper.send('blahMethod', null); +- future.catchError((e) { +- expect(e, new isInstanceOf()); +- final e2 =3D e as ServerErrorMessage; +- expect(e2.code, 'someErrorCode'); +- expect(e2.message, 'something went wrong'); +- expect(e2.stackTrace, 'some long stack trace'); +- }); +- serverWrapper.listenToOutput(); +- }); +- +- test('test_listenToOutput_event', () async { +- when(_process.stdout).thenReturn(_eventMessage()); +- +- void eventHandler(String event, Map params) { +- expect(event, 'fooEvent'); +- expect(params.length, 2); +- expect(params['foo'] as String, 'bar'); +- expect(params['baz'] as String, 'bang'); +- } +- +- serverWrapper.send('blahMethod', null); +- serverWrapper.listenToOutput(notificationProcessor: eventHandler); +- }); +-} +- +-Stream> _goodMessage() async* { +- yield UTF8.encoder.convert('Observatory listening on foo bar\n'); +- final sampleJson =3D { +- 'id': '0', +- 'result': {'foo': 'bar'} +- }; +- yield UTF8.encoder.convert(JSON.encode(sampleJson)); +-} +- +-final _badErrorMessage =3D { +- 'code': 'someErrorCode', +- 'message': 'something went wrong', +- 'stackTrace': 'some long stack trace' +-}; +- +-Stream> _badMessage() async* { +- yield UTF8.encoder.convert('Observatory listening on foo bar\n'); +- final sampleJson =3D {'id': '0', 'error': _badErrorMessage}; +- yield UTF8.encoder.convert(JSON.encode(sampleJson)); +-} +- +-Stream> _eventMessage() async* { +- yield UTF8.encoder.convert('Observatory listening on foo bar\n'); +- final sampleJson =3D { +- 'event': 'fooEvent', +- 'params': {'foo': 'bar', 'baz': 'bang'} +- }; +- yield UTF8.encoder.convert(JSON.encode(sampleJson)); +-} +- +-class MockProcess extends Mock implements Process {} +- +-class MockStdin extends Mock implements List {} +diff --git a/pkg/analyzer/README.md b/pkg/analyzer/README.md +index fe5289fd810..bb8841d809b 100644 +--- a/pkg/analyzer/README.md ++++ b/pkg/analyzer/README.md +@@ -102,7 +102,6 @@ this causes for our clients, but some pain is inevitab= le. +=20 + See the [LICENSE] file. +=20 +-[serverapi]: https://htmlpreview.github.io/?https://github.com/dart-lang/= sdk/blob/master/pkg/analysis_server/doc/api.html + [analyzercli]: https://github.com/dart-lang/sdk/tree/master/pkg/analyzer_= cli + [list]: https://groups.google.com/a/dartlang.org/forum/#!forum/analyzer-d= iscuss + [lintrules]: http://dart-lang.github.io/linter/lints/ +@@ -111,4 +110,3 @@ See the [LICENSE] file. + [LICENSE]: https://github.com/dart-lang/sdk/blob/master/pkg/analyzer/LICE= NSE + [dartfmt]: https://github.com/dart-lang/dart_style + [dartdoc]: https://github.com/dart-lang/dartdoc +-[analysis_sever]: https://github.com/dart-lang/sdk/tree/master/pkg/analys= is_server +diff --git a/pkg/analyzer/lib/src/codegen/tools.dart b/pkg/analyzer/lib/sr= c/codegen/tools.dart +index a12ac3541dd..5b01e589c85 100644 +--- a/pkg/analyzer/lib/src/codegen/tools.dart ++++ b/pkg/analyzer/lib/src/codegen/tools.dart +@@ -158,7 +158,6 @@ class CodeGenerator { + * the License. + * + * This file has been automatically generated. Please do not edit it man= ually. +- * To regenerate the file, use the script "pkg/analysis_server/tool/spec/= generate_files". + */'''; + } else if (codeGeneratorSettings.languageName =3D=3D 'python') { + header =3D ''' +@@ -168,7 +167,6 @@ class CodeGenerator { + # + # This file has been automatically generated. Please do not edit it manu= ally. + # To regenerate the file, use the script +-# "pkg/analysis_server/tool/spec/generate_files". + '''; + } else { + header =3D ''' +diff --git a/pkg/analyzer_cli/lib/src/driver.dart b/pkg/analyzer_cli/lib/s= rc/driver.dart +index cace64a389e..00387e52ace 100644 +--- a/pkg/analyzer_cli/lib/src/driver.dart ++++ b/pkg/analyzer_cli/lib/src/driver.dart +@@ -50,12 +50,8 @@ import 'package:package_config/src/packages_impl.dart' = show MapPackages; + import 'package:path/path.dart' as path; + import 'package:plugin/manager.dart'; + import 'package:plugin/plugin.dart'; +-import 'package:telemetry/crash_reporting.dart'; +-import 'package:telemetry/telemetry.dart' as telemetry; + import 'package:yaml/yaml.dart'; +=20 +-const _analyticsID =3D 'UA-26406144-28'; +- + /// Shared IO sink for standard error reporting. + @visibleForTesting + StringSink errorSink =3D io.stderr; +@@ -64,30 +60,12 @@ StringSink errorSink =3D io.stderr; + @visibleForTesting + StringSink outSink =3D io.stdout; +=20 +-telemetry.Analytics _analytics; +- +-/// The analytics instance for analyzer-cli. +-telemetry.Analytics get analytics =3D> (_analytics ??=3D +- telemetry.createAnalyticsInstance(_analyticsID, 'analyzer-cli')); +- + /// Test this option map to see if it specifies lint rules. + bool containsLintRuleEntry(Map options) { + var linterNode =3D options['linter']; + return linterNode is YamlMap && linterNode.containsKey('rules'); + } +=20 +-/// Make sure that we create an analytics instance that doesn't send for = this +-/// session. +-void disableAnalyticsForSession() { +- _analytics =3D telemetry.createAnalyticsInstance(_analyticsID, 'analyze= r-cli', +- disableForSession: true); +-} +- +-@visibleForTesting +-void setAnalytics(telemetry.Analytics replacementAnalytics) { +- _analytics =3D replacementAnalytics; +-} +- + class Driver implements CommandLineStarter { + static final PerformanceTag _analyzeAllTag =3D + new PerformanceTag("Driver._analyzeAll"); +@@ -130,26 +108,15 @@ class Driver implements CommandLineStarter { + /// Collected analysis statistics. + final AnalysisStats stats =3D new AnalysisStats(); +=20 +- CrashReportSender _crashReportSender; +- + /// Create a new Driver instance. + /// + /// [isTesting] is true if we're running in a test environment. +- Driver({bool isTesting: false}) { +- if (isTesting) { +- disableAnalyticsForSession(); +- } +- } ++ Driver({bool isTesting: false}) { } +=20 + /// This Driver's current analysis context. + @visibleForTesting + AnalysisContext get context =3D> _context; +=20 +- /// The crash reporting instance for analyzer-cli. +- /// TODO(devoncarew): Replace with the real crash product ID. +- CrashReportSender get crashReportSender =3D> (_crashReportSender ??=3D +- new CrashReportSender('Dart_analyzer_cli', analytics)); +- + @override + void set userDefinedPlugins(List plugins) { + _userDefinedPlugins =3D plugins ?? []; +@@ -169,15 +136,6 @@ class Driver implements CommandLineStarter { + // Parse commandline options. + CommandLineOptions options =3D CommandLineOptions.parse(args); +=20 +- if (options.batchMode || options.buildMode) { +- disableAnalyticsForSession(); +- } +- +- // Ping analytics with our initial call. +- analytics.sendScreenView('home'); +- +- var timer =3D analytics.startTimer('analyze'); +- + // Do analysis. + if (options.buildMode) { + ErrorSeverity severity =3D await _buildModeAnalyze(options); +@@ -202,22 +160,11 @@ class Driver implements CommandLineStarter { + if (_context !=3D null) { + _analyzedFileCount +=3D _context.sources.length; + } +- +- // Send how long analysis took. +- timer.finish(); +- +- // Send how many files were analyzed. +- analytics.sendEvent('analyze', 'fileCount', value: _analyzedFileCount= ); +- + if (options.perfReport !=3D null) { + String json =3D makePerfReport( + startTime, currentTimeMillis, options, _analyzedFileCount, stat= s); + new io.File(options.perfReport).writeAsStringSync(json); + } +- +- // Wait a brief time for any analytics calls to finish. +- await analytics.waitForLastPing(timeout: new Duration(milliseconds: 2= 00)); +- analytics.close(); + } +=20 + Future _analyzeAll(CommandLineOptions options) async { +@@ -225,9 +172,6 @@ class Driver implements CommandLineStarter { + try { + return await _analyzeAllImpl(options); + } catch (e, st) { +- // Catch and ignore any exceptions when reporting exceptions (netwo= rk +- // errors or other). +- crashReportSender.sendReport(e, stackTrace: st).catchError((_) {}); + rethrow; + } finally { + previous.makeCurrent(); +diff --git a/pkg/analyzer_cli/lib/src/options.dart b/pkg/analyzer_cli/lib/= src/options.dart +index 1ab9c6464ba..64bc54386e0 100644 +--- a/pkg/analyzer_cli/lib/src/options.dart ++++ b/pkg/analyzer_cli/lib/src/options.dart +@@ -11,7 +11,6 @@ import 'package:analyzer/src/util/sdk.dart'; + import 'package:analyzer_cli/src/ansi.dart' as ansi; + import 'package:analyzer_cli/src/driver.dart'; + import 'package:args/args.dart'; +-import 'package:telemetry/telemetry.dart' as telemetry; +=20 + const _binaryName =3D 'dartanalyzer'; +=20 +@@ -366,11 +365,6 @@ class CommandLineOptions { + help: 'Verbose output.', + negatable: false); +=20 +- if (telemetry.SHOW_ANALYTICS_UI) { +- parser.addFlag('analytics', +- help: 'Enable or disable sending analytics information to Googl= e.'); +- } +- + // Build mode options. + if (!hide) { + parser.addSeparator('Build mode flags:'); +@@ -543,27 +537,16 @@ class CommandLineOptions { +=20 + // Help requests. + if (results['help']) { +- _showUsage(parser, analytics, fromHelp: true); ++ _showUsage(parser, fromHelp: true); + exitHandler(0); + return null; // Only reachable in testing. + } +=20 +- // Enable / disable analytics. +- if (telemetry.SHOW_ANALYTICS_UI) { +- if (results.wasParsed('analytics')) { +- analytics.enabled =3D results['analytics']; +- outSink.writeln( +- telemetry.createAnalyticsStatusMessage(analytics.enabled)); +- exitHandler(0); +- return null; // Only reachable in testing. +- } +- } +- + // Batch mode and input files. + if (results['batch']) { + if (results.rest.isNotEmpty) { + errorSink.writeln('No source files expected in the batch mode.'= ); +- _showUsage(parser, analytics); ++ _showUsage(parser); + exitHandler(15); + return null; // Only reachable in testing. + } +@@ -571,7 +554,7 @@ class CommandLineOptions { + if (results.rest.isNotEmpty) { + errorSink.writeln( + 'No source files expected in the persistent worker mode.'); +- _showUsage(parser, analytics); ++ _showUsage(parser); + exitHandler(15); + return null; // Only reachable in testing. + } +@@ -581,7 +564,7 @@ class CommandLineOptions { + return null; // Only reachable in testing. + } else { + if (results.rest.isEmpty && !results['build-mode']) { +- _showUsage(parser, analytics, fromHelp: true); ++ _showUsage(parser, fromHelp: true); + exitHandler(15); + return null; // Only reachable in testing. + } +@@ -595,41 +578,15 @@ class CommandLineOptions { + } + } +=20 +- static _showUsage(ArgParser parser, telemetry.Analytics analytics, ++ static _showUsage(ArgParser parser, + {bool fromHelp: false}) { +- void printAnalyticsInfo() { +- if (!telemetry.SHOW_ANALYTICS_UI) { +- return; +- } +- +- if (fromHelp) { +- errorSink.writeln(''); +- errorSink.writeln(telemetry.analyticsNotice); +- } +- +- if (analytics !=3D null) { +- errorSink.writeln(''); +- errorSink.writeln(telemetry.createAnalyticsStatusMessage( +- analytics.enabled, +- command: 'analytics')); +- } +- } +=20 +- errorSink.writeln( ++ errorSink.writeln( + 'Usage: $_binaryName [options...] '); +=20 +- // If it's our first run, we display the analytics info more prominen= tly. +- if (analytics !=3D null && analytics.firstRun) { +- printAnalyticsInfo(); +- } +- + errorSink.writeln(''); + errorSink.writeln(parser.usage); +=20 +- if (analytics !=3D null && !analytics.firstRun) { +- printAnalyticsInfo(); +- } +- + errorSink.writeln(''); + errorSink.writeln(''' + Run "dartanalyzer -h -v" for verbose help output, including less commonly= used options. +diff --git a/pkg/analyzer_cli/pubspec.yaml b/pkg/analyzer_cli/pubspec.yaml +index baf4e6f650f..aa0a1c908d9 100644 +--- a/pkg/analyzer_cli/pubspec.yaml ++++ b/pkg/analyzer_cli/pubspec.yaml +@@ -15,7 +15,6 @@ dependencies: + package_config: '>=3D0.1.5 <2.0.0' + plugin: '>=3D0.1.0 <0.3.0' + protobuf: ^0.5.0 +- telemetry: ^0.0.1 + yaml: ^2.1.2 + dev_dependencies: + test_reflective_loader: ^0.1.0 +diff --git a/pkg/analyzer_cli/test/options_test.dart b/pkg/analyzer_cli/te= st/options_test.dart +index acfac627f1f..4af39838e2c 100644 +--- a/pkg/analyzer_cli/test/options_test.dart ++++ b/pkg/analyzer_cli/test/options_test.dart +@@ -8,7 +8,6 @@ import 'dart:io'; +=20 + import 'package:analyzer_cli/src/driver.dart'; + import 'package:analyzer_cli/src/options.dart'; +-import 'package:telemetry/telemetry.dart' as telemetry; + import 'package:test/test.dart'; + import 'package:test_reflective_loader/test_reflective_loader.dart'; + import 'package:usage/usage.dart'; +@@ -229,28 +228,6 @@ main() { + expect(failureMessage, equals('Invalid Dart SDK path: &&&&&')); + }); +=20 +- if (telemetry.SHOW_ANALYTICS_UI) { +- test('--analytics', () { +- AnalyticsMock mock =3D new AnalyticsMock()..enabled =3D false; +- setAnalytics(mock); +- CommandLineOptions.parse(['--analytics']); +- expect(mock.enabled, true); +- expect(lastExitHandlerCode, 0); +- expect( +- outStringBuffer.toString(), contains('Analytics are current= ly')); +- }); +- +- test('--no-analytics', () { +- AnalyticsMock mock =3D new AnalyticsMock()..enabled =3D false; +- setAnalytics(mock); +- CommandLineOptions.parse(['--no-analytics']); +- expect(mock.enabled, false); +- expect(lastExitHandlerCode, 0); +- expect( +- outStringBuffer.toString(), contains('Analytics are current= ly')); +- }); +- } +- + test('preview FE', () { + CommandLineOptions options =3D + CommandLineOptions.parse(['--preview-dart-2', 'foo.dart']); +diff --git a/pkg/analyzer_plugin/test/integration/support/integration_test= _methods.dart b/pkg/analyzer_plugin/test/integration/support/integration_te= st_methods.dart +deleted file mode 100644 +index 58bf8dd8cba..00000000000 +--- a/pkg/analyzer_plugin/test/integration/support/integration_test_method= s.dart ++++ /dev/null +@@ -1,815 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +-// +-// This file has been automatically generated. Please do not edit it man= ually. +-// To regenerate the file, use the script +-// "pkg/analysis_server/tool/spec/generate_files". +- +-/** +- * Convenience methods for running integration tests +- */ +-import 'dart:async'; +- +-import 'package:analyzer_plugin/protocol/protocol_generated.dart'; +-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart'; +-import 'package:test/test.dart'; +- +-import 'integration_tests.dart'; +-import 'protocol_matchers.dart'; +-import 'package:analyzer_plugin/protocol/protocol_common.dart'; +- +-/** +- * Convenience methods for running integration tests +- */ +-abstract class IntegrationTestMixin { +- Server get server; +- +- /** +- * Used to request that the plugin perform a version check to confirm t= hat it +- * works with the version of the analysis server that is executing it. +- * +- * Parameters +- * +- * byteStorePath: FilePath +- * +- * The path to the directory containing the on-disk byte store that i= s to +- * be used by any analysis drivers that are created. +- * +- * sdkPath: FilePath +- * +- * The path to the directory containing the SDK that is to be used by= any +- * analysis drivers that are created. +- * +- * version: String +- * +- * The version number of the plugin spec supported by the analysis se= rver +- * that is executing the plugin. +- * +- * Returns +- * +- * isCompatible: bool +- * +- * A flag indicating whether the plugin supports the same version of = the +- * plugin spec as the analysis server. If the value is false, then the +- * plugin is expected to shutdown after returning the response. +- * +- * name: String +- * +- * The name of the plugin. This value is only used when the server ne= eds to +- * identify the plugin, either to the user or for debugging purposes. +- * +- * version: String +- * +- * The version of the plugin. This value is only used when the server= needs +- * to identify the plugin, either to the user or for debugging purpos= es. +- * +- * contactInfo: String (optional) +- * +- * Information that the user can use to use to contact the maintainer= s of +- * the plugin when there is a problem. +- * +- * interestingFiles: List +- * +- * The glob patterns of the files for which the plugin will provide +- * information. This value is ignored if the isCompatible field is fa= lse. +- * Otherwise, it will be used to identify the files for which the plu= gin +- * should be notified of changes. +- */ +- Future sendPluginVersionCheck( +- String byteStorePath, String sdkPath, String version) async { +- var params =3D +- new PluginVersionCheckParams(byteStorePath, sdkPath, version).toJ= son(); +- var result =3D await server.send("plugin.versionCheck", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new PluginVersionCheckResult.fromJson(decoder, 'result', resul= t); +- } +- +- /** +- * Used to request that the plugin exit. The server will not send any o= ther +- * requests after this request. The plugin should not send any response= s or +- * notifications after sending the response to this request. +- */ +- Future sendPluginShutdown() async { +- var result =3D await server.send("plugin.shutdown", null); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Used to report that an unexpected error has occurred while executing= the +- * plugin. This notification is not used for problems with specific req= uests +- * (which should be returned as part of the response) but is used for +- * exceptions that occur while performing other tasks, such as analysis= or +- * preparing notifications. +- * +- * Parameters +- * +- * isFatal: bool +- * +- * A flag indicating whether the error is a fatal error, meaning that= the +- * plugin will shutdown automatically after sending this notification= . If +- * true, the server will not expect any other responses or notificati= ons +- * from the plugin. +- * +- * message: String +- * +- * The error message indicating what kind of error was encountered. +- * +- * stackTrace: String +- * +- * The stack trace associated with the generation of the error, used = for +- * debugging the plugin. +- */ +- Stream onPluginError; +- +- /** +- * Stream controller for [onPluginError]. +- */ +- StreamController _onPluginError; +- +- /** +- * Return the navigation information associated with the given region o= f the +- * given file. If the navigation information for the given file has not= yet +- * been computed, or the most recently computed navigation information = for +- * the given file is out of date, then the response for this request wi= ll be +- * delayed until it has been computed. If the content of the file chang= es +- * after this request was received but before a response could be sent,= then +- * an error of type CONTENT_MODIFIED will be generated. +- * +- * If a navigation region overlaps (but extends either before or after)= the +- * given region of the file it will be included in the result. This mea= ns +- * that it is theoretically possible to get the same navigation region = in +- * response to multiple requests. Clients can avoid this by always choo= sing a +- * region that starts at the beginning of a line and ends at the end of= a +- * (possibly different) line in the file. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which navigation information is being requested. +- * +- * offset: int +- * +- * The offset of the region for which navigation information is being +- * requested. +- * +- * length: int +- * +- * The length of the region for which navigation information is being +- * requested. +- * +- * Returns +- * +- * files: List +- * +- * A list of the paths of files that are referenced by the navigation +- * targets. +- * +- * targets: List +- * +- * A list of the navigation targets that are referenced by the naviga= tion +- * regions. +- * +- * regions: List +- * +- * A list of the navigation regions within the requested region of the +- * file. +- */ +- Future sendAnalysisGetNavigation( +- String file, int offset, int length) async { +- var params =3D new AnalysisGetNavigationParams(file, offset, length).= toJson(); +- var result =3D await server.send("analysis.getNavigation", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new AnalysisGetNavigationResult.fromJson(decoder, 'result', re= sult); +- } +- +- /** +- * Used to inform the plugin of changes to files in the file system. On= ly +- * events associated with files that match the interestingFiles glob pa= tterns +- * will be forwarded to the plugin. +- * +- * Parameters +- * +- * events: List +- * +- * The watch events that the plugin should handle. +- */ +- Future sendAnalysisHandleWatchEvents(List events) async { +- var params =3D new AnalysisHandleWatchEventsParams(events).toJson(); +- var result =3D await server.send("analysis.handleWatchEvents", params= ); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Set the list of context roots that should be analyzed. +- * +- * Parameters +- * +- * roots: List +- * +- * A list of the context roots that should be analyzed. +- */ +- Future sendAnalysisSetContextRoots(List roots) async { +- var params =3D new AnalysisSetContextRootsParams(roots).toJson(); +- var result =3D await server.send("analysis.setContextRoots", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Used to set the priority files to the files in the given list. A pri= ority +- * file is a file that should be given priority when scheduling which +- * analysis work to do first. The list typically contains those files t= hat +- * are visible to the user and those for which analysis results will ha= ve the +- * biggest impact on the user experience. The order of the files within= the +- * list is significant: the first file will be given higher priority th= an the +- * second, the second higher priority than the third, and so on. +- * +- * Parameters +- * +- * files: List +- * +- * The files that are to be a priority for analysis. +- */ +- Future sendAnalysisSetPriorityFiles(List files) async { +- var params =3D new AnalysisSetPriorityFilesParams(files).toJson(); +- var result =3D await server.send("analysis.setPriorityFiles", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Used to subscribe for services that are specific to individual files= . All +- * previous subscriptions should be replaced by the current set of +- * subscriptions. If a given service is not included as a key in the ma= p then +- * no files should be subscribed to the service, exactly as if the serv= ice +- * had been included in the map with an explicit empty list of files. +- * +- * Parameters +- * +- * subscriptions: Map> +- * +- * A table mapping services to a list of the files being subscribed t= o the +- * service. +- */ +- Future sendAnalysisSetSubscriptions( +- Map> subscriptions) async { +- var params =3D new AnalysisSetSubscriptionsParams(subscriptions).toJs= on(); +- var result =3D await server.send("analysis.setSubscriptions", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Used to update the content of one or more files. Files that were +- * previously updated but not included in this update remain unchanged.= This +- * effectively represents an overlay of the filesystem. The files whose +- * content is overridden are therefore seen by the plugin as being file= s with +- * the given content, even if the files do not exist on the filesystem = or if +- * the file path represents the path to a directory on the filesystem. +- * +- * Parameters +- * +- * files: Map +- * +- * A table mapping the files whose content has changed to a descripti= on of +- * the content change. +- */ +- Future sendAnalysisUpdateContent(Map files) async { +- var params =3D new AnalysisUpdateContentParams(files).toJson(); +- var result =3D await server.send("analysis.updateContent", params); +- outOfTestExpect(result, isNull); +- return null; +- } +- +- /** +- * Used to report the errors associated with a given file. The set of e= rrors +- * included in the notification is always a complete list that supersed= es any +- * previously reported errors. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the errors. +- * +- * errors: List +- * +- * The errors contained in the file. +- */ +- Stream onAnalysisErrors; +- +- /** +- * Stream controller for [onAnalysisErrors]. +- */ +- StreamController _onAnalysisErrors; +- +- /** +- * Used to report the folding regions associated with a given file. Fol= ding +- * regions can be nested, but cannot be overlapping. Nesting occurs whe= n a +- * foldable element, such as a method, is nested inside another foldable +- * element such as a class. +- * +- * Folding regions that overlap a folding region computed by the server= , or +- * by one of the other plugins that are currently running, might be dro= pped +- * by the server in order to present a consistent view to the client. +- * +- * This notification should only be sent if the server has subscribed t= o it +- * by including the value "FOLDING" in the list of services passed in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the folding regions. +- * +- * regions: List +- * +- * The folding regions contained in the file. +- */ +- Stream onAnalysisFolding; +- +- /** +- * Stream controller for [onAnalysisFolding]. +- */ +- StreamController _onAnalysisFolding; +- +- /** +- * Used to report the highlight regions associated with a given file. E= ach +- * highlight region represents a particular syntactic or semantic meani= ng +- * associated with some range. Note that the highlight regions that are +- * returned can overlap other highlight regions if there is more than o= ne +- * meaning associated with a particular region. +- * +- * This notification should only be sent if the server has subscribed t= o it +- * by including the value "HIGHLIGHTS" in the list of services passed i= n an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the highlight regions. +- * +- * regions: List +- * +- * The highlight regions contained in the file. +- */ +- Stream onAnalysisHighlights; +- +- /** +- * Stream controller for [onAnalysisHighlights]. +- */ +- StreamController _onAnalysisHighlights; +- +- /** +- * Used to report the navigation regions associated with a given file. = Each +- * navigation region represents a list of targets associated with some = range. +- * The lists will usually contain a single target, but can contain more= in +- * the case of a part that is included in multiple libraries or in Dart= code +- * that is compiled against multiple versions of a package. Note that t= he +- * navigation regions that are returned should not overlap other naviga= tion +- * regions. +- * +- * Navigation regions that overlap a navigation region computed by the +- * server, or by one of the other plugins that are currently running, m= ight +- * be dropped or modified by the server in order to present a consisten= t view +- * to the client. +- * +- * This notification should only be sent if the server has subscribed t= o it +- * by including the value "NAVIGATION" in the list of services passed i= n an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the navigation regions. +- * +- * regions: List +- * +- * The navigation regions contained in the file. +- * +- * targets: List +- * +- * The navigation targets referenced in the file. They are referenced= by +- * NavigationRegions by their index in this array. +- * +- * files: List +- * +- * The files containing navigation targets referenced in the file. Th= ey are +- * referenced by NavigationTargets by their index in this array. +- */ +- Stream onAnalysisNavigation; +- +- /** +- * Stream controller for [onAnalysisNavigation]. +- */ +- StreamController _onAnalysisNavigation; +- +- /** +- * Used to report the occurrences of references to elements within a si= ngle +- * file. None of the occurrence regions should overlap. +- * +- * Occurrence regions that overlap an occurrence region computed by the +- * server, or by one of the other plugins that are currently running, m= ight +- * be dropped or modified by the server in order to present a consisten= t view +- * to the client. +- * +- * This notification should only be sent if the server has subscribed t= o it +- * by including the value "OCCURRENCES" in the list of services passed = in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file in which the references occur. +- * +- * occurrences: List +- * +- * The occurrences of references to elements within the file. +- */ +- Stream onAnalysisOccurrences; +- +- /** +- * Stream controller for [onAnalysisOccurrences]. +- */ +- StreamController _onAnalysisOccurrences; +- +- /** +- * Used to report the outline fragments associated with a single file. +- * +- * The outline fragments will be merged with any outline produced by the +- * server and with any fragments produced by other plugins. If the serv= er +- * cannot create a coherent outline, some fragments might be dropped. +- * +- * This notification should only be sent if the server has subscribed t= o it +- * by including the value "OUTLINE" in the list of services passed in an +- * analysis.setSubscriptions request. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file with which the outline is associated. +- * +- * outline: List +- * +- * The outline fragments associated with the file. +- */ +- Stream onAnalysisOutline; +- +- /** +- * Stream controller for [onAnalysisOutline]. +- */ +- StreamController _onAnalysisOutline; +- +- /** +- * Used to request that completion suggestions for the given offset in = the +- * given file be returned. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the point at which suggestions are to be made. +- * +- * offset: int +- * +- * The offset within the file at which suggestions are to be made. +- * +- * Returns +- * +- * replacementOffset: int +- * +- * The offset of the start of the text to be replaced. This will be +- * different than the offset used to request the completion suggestio= ns if +- * there was a portion of an identifier before the original offset. In +- * particular, the replacementOffset will be the offset of the beginn= ing of +- * said identifier. +- * +- * replacementLength: int +- * +- * The length of the text to be replaced if the remainder of the iden= tifier +- * containing the cursor is to be replaced when the suggestion is app= lied +- * (that is, the number of characters in the existing identifier). +- * +- * results: List +- * +- * The completion suggestions being reported. The notification contai= ns all +- * possible completions at the requested cursor position, even those = that +- * do not match the characters the user has already typed. This allow= s the +- * client to respond to further keystrokes from the user without havi= ng to +- * make additional requests. +- */ +- Future sendCompletionGetSuggestions( +- String file, int offset) async { +- var params =3D new CompletionGetSuggestionsParams(file, offset).toJso= n(); +- var result =3D await server.send("completion.getSuggestions", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new CompletionGetSuggestionsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Used to request the set of assists that are available at the given +- * location. An assist is distinguished from a refactoring primarily by= the +- * fact that it affects a single file and does not require user input in +- * order to be performed. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code for which assists are being requested. +- * +- * offset: int +- * +- * The offset of the code for which assists are being requested. +- * +- * length: int +- * +- * The length of the code for which assists are being requested. +- * +- * Returns +- * +- * assists: List +- * +- * The assists that are available at the given location. +- */ +- Future sendEditGetAssists( +- String file, int offset, int length) async { +- var params =3D new EditGetAssistsParams(file, offset, length).toJson(= ); +- var result =3D await server.send("edit.getAssists", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetAssistsResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Used to request a list of the kinds of refactorings that are valid f= or the +- * given selection in the given file. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code on which the refactoring would be bas= ed. +- * +- * offset: int +- * +- * The offset of the code on which the refactoring would be based. +- * +- * length: int +- * +- * The length of the code on which the refactoring would be based. +- * +- * Returns +- * +- * kinds: List +- * +- * The kinds of refactorings that are valid for the given selection. +- * +- * The list of refactoring kinds is currently limited to those define= d by +- * the server API, preventing plugins from adding their own refactori= ngs. +- * However, plugins can support pre-defined refactorings, such as a r= ename +- * refactoring, at locations not supported by server. +- */ +- Future sendEditGetAvailableRefactor= ings( +- String file, int offset, int length) async { +- var params =3D +- new EditGetAvailableRefactoringsParams(file, offset, length).toJs= on(); +- var result =3D await server.send("edit.getAvailableRefactorings", par= ams); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetAvailableRefactoringsResult.fromJson( +- decoder, 'result', result); +- } +- +- /** +- * Used to request the set of fixes that are available for the errors a= t a +- * given offset in a given file. +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the errors for which fixes are being requested. +- * +- * offset: int +- * +- * The offset used to select the errors for which fixes will be retur= ned. +- * +- * Returns +- * +- * fixes: List +- * +- * The fixes that are available for the errors at the given offset. +- */ +- Future sendEditGetFixes(String file, int offset) as= ync { +- var params =3D new EditGetFixesParams(file, offset).toJson(); +- var result =3D await server.send("edit.getFixes", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new EditGetFixesResult.fromJson(decoder, 'result', result); +- } +- +- /** +- * Used to request the changes required to perform a refactoring. +- * +- * Parameters +- * +- * kind: RefactoringKind +- * +- * The kind of refactoring to be performed. +- * +- * file: FilePath +- * +- * The file containing the code involved in the refactoring. +- * +- * offset: int +- * +- * The offset of the region involved in the refactoring. +- * +- * length: int +- * +- * The length of the region involved in the refactoring. +- * +- * validateOnly: bool +- * +- * True if the client is only requesting that the values of the optio= ns be +- * validated and no change be generated. +- * +- * options: RefactoringOptions (optional) +- * +- * Data used to provide values provided by the user. The structure of= the +- * data is dependent on the kind of refactoring being performed. The = data +- * that is expected is documented in the section titled Refactorings, +- * labeled as "Options". This field can be omitted if the refactoring= does +- * not require any options or if the values of those options are not = known. +- * +- * Returns +- * +- * initialProblems: List +- * +- * The initial status of the refactoring, that is, problems related t= o the +- * context in which the refactoring is requested. The list should be = empty +- * if there are no known problems. +- * +- * optionsProblems: List +- * +- * The options validation status, that is, problems in the given opti= ons, +- * such as light-weight validation of a new name, flags compatibility= , etc. +- * The list should be empty if there are no known problems. +- * +- * finalProblems: List +- * +- * The final status of the refactoring, that is, problems identified = in the +- * result of a full, potentially expensive validation and / or change +- * creation. The list should be empty if there are no known problems. +- * +- * feedback: RefactoringFeedback (optional) +- * +- * Data used to provide feedback to the user. The structure of the da= ta is +- * dependent on the kind of refactoring being created. The data that = is +- * returned is documented in the section titled Refactorings, labeled= as +- * "Feedback". +- * +- * change: SourceChange (optional) +- * +- * The changes that are to be applied to affect the refactoring. This= field +- * can be omitted if there are problems that prevent a set of changes= from +- * being computed, such as having no options specified for a refactor= ing +- * that requires them, or if only validation was requested. +- * +- * potentialEdits: List (optional) +- * +- * The ids of source edits that are not known to be valid. An edit is= not +- * known to be valid if there was insufficient type information for t= he +- * plugin to be able to determine whether or not the code needs to be +- * modified, such as when a member is being renamed and there is a +- * reference to a member from an unknown type. This field can be omit= ted if +- * the change field is omitted or if there are no potential edits for= the +- * refactoring. +- */ +- Future sendEditGetRefactoring(RefactoringKind= kind, +- String file, int offset, int length, bool validateOnly, +- {RefactoringOptions options}) async { +- var params =3D new EditGetRefactoringParams( +- kind, file, offset, length, validateOnly, +- options: options) +- .toJson(); +- var result =3D await server.send("edit.getRefactoring", params); +- ResponseDecoder decoder =3D new ResponseDecoder(kind); +- return new EditGetRefactoringResult.fromJson(decoder, 'result', resul= t); +- } +- +- /** +- * Return the list of KytheEntry objects for some file, given the curre= nt +- * state of the file system populated by "analysis.updateContent". +- * +- * Parameters +- * +- * file: FilePath +- * +- * The file containing the code for which the Kythe Entry objects are= being +- * requested. +- * +- * Returns +- * +- * entries: List +- * +- * The list of KytheEntry objects for the queried file. +- * +- * files: List +- * +- * The set of files paths that were required, but not in the file sys= tem, +- * to give a complete and accurate Kythe graph for the file. This cou= ld be +- * due to a referenced file that does not exist or generated files not +- * being generated or passed before the call to "getKytheEntries". +- */ +- Future sendKytheGetKytheEntries( +- String file) async { +- var params =3D new KytheGetKytheEntriesParams(file).toJson(); +- var result =3D await server.send("kythe.getKytheEntries", params); +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- return new KytheGetKytheEntriesResult.fromJson(decoder, 'result', res= ult); +- } +- +- /** +- * Initialize the fields in InttestMixin, and ensure that notifications= will +- * be handled. +- */ +- void initializeInttestMixin() { +- _onPluginError =3D new StreamController(sync: true= ); +- onPluginError =3D _onPluginError.stream.asBroadcastStream(); +- _onAnalysisErrors =3D new StreamController(sync= : true); +- onAnalysisErrors =3D _onAnalysisErrors.stream.asBroadcastStream(); +- _onAnalysisFolding =3D +- new StreamController(sync: true); +- onAnalysisFolding =3D _onAnalysisFolding.stream.asBroadcastStream(); +- _onAnalysisHighlights =3D +- new StreamController(sync: true); +- onAnalysisHighlights =3D _onAnalysisHighlights.stream.asBroadcastStre= am(); +- _onAnalysisNavigation =3D +- new StreamController(sync: true); +- onAnalysisNavigation =3D _onAnalysisNavigation.stream.asBroadcastStre= am(); +- _onAnalysisOccurrences =3D +- new StreamController(sync: true); +- onAnalysisOccurrences =3D _onAnalysisOccurrences.stream.asBroadcastSt= ream(); +- _onAnalysisOutline =3D +- new StreamController(sync: true); +- onAnalysisOutline =3D _onAnalysisOutline.stream.asBroadcastStream(); +- } +- +- /** +- * Dispatch the notification named [event], and containing parameters +- * [params], to the appropriate stream. +- */ +- void dispatchNotification(String event, params) { +- ResponseDecoder decoder =3D new ResponseDecoder(null); +- switch (event) { +- case "plugin.error": +- outOfTestExpect(params, isPluginErrorParams); +- _onPluginError +- .add(new PluginErrorParams.fromJson(decoder, 'params', params= )); +- break; +- case "analysis.errors": +- outOfTestExpect(params, isAnalysisErrorsParams); +- _onAnalysisErrors +- .add(new AnalysisErrorsParams.fromJson(decoder, 'params', par= ams)); +- break; +- case "analysis.folding": +- outOfTestExpect(params, isAnalysisFoldingParams); +- _onAnalysisFolding +- .add(new AnalysisFoldingParams.fromJson(decoder, 'params', pa= rams)); +- break; +- case "analysis.highlights": +- outOfTestExpect(params, isAnalysisHighlightsParams); +- _onAnalysisHighlights.add( +- new AnalysisHighlightsParams.fromJson(decoder, 'params', para= ms)); +- break; +- case "analysis.navigation": +- outOfTestExpect(params, isAnalysisNavigationParams); +- _onAnalysisNavigation.add( +- new AnalysisNavigationParams.fromJson(decoder, 'params', para= ms)); +- break; +- case "analysis.occurrences": +- outOfTestExpect(params, isAnalysisOccurrencesParams); +- _onAnalysisOccurrences.add( +- new AnalysisOccurrencesParams.fromJson(decoder, 'params', par= ams)); +- break; +- case "analysis.outline": +- outOfTestExpect(params, isAnalysisOutlineParams); +- _onAnalysisOutline +- .add(new AnalysisOutlineParams.fromJson(decoder, 'params', pa= rams)); +- break; +- default: +- fail('Unexpected notification: $event'); +- break; +- } +- } +-} +diff --git a/pkg/analyzer_plugin/test/integration/support/integration_test= s.dart b/pkg/analyzer_plugin/test/integration/support/integration_tests.dart +index 3f6a1c34839..ff96e461528 100644 +--- a/pkg/analyzer_plugin/test/integration/support/integration_tests.dart ++++ b/pkg/analyzer_plugin/test/integration/support/integration_tests.dart +@@ -492,21 +492,6 @@ class Server { + } + } +=20 +- /** +- * Find the root directory of the analysis_server package by proceeding +- * upward to the 'test' dir, and then going up one more directory. +- */ +- String findRoot(String pathname) { +- while (!['benchmark', 'test'].contains(basename(pathname))) { +- String parent =3D dirname(pathname); +- if (parent.length >=3D pathname.length) { +- throw new Exception("Can't find root directory"); +- } +- pathname =3D parent; +- } +- return dirname(pathname); +- } +- + /** + * Return a future that will complete when all commands that have been = sent + * to the server so far have been flushed to the OS buffer. +diff --git a/pkg/front_end/testing.json b/pkg/front_end/testing.json +index 3272f0d8370..648178c597e 100644 +--- a/pkg/front_end/testing.json ++++ b/pkg/front_end/testing.json +@@ -246,7 +246,6 @@ + }, +=20 + "exclude": [ +- "^pkg/analysis_server/lib/src/analysis_server\\.dart", + "^pkg/dev_compiler/" + ] + } +diff --git a/pkg/microlytics/example/simple.dart b/pkg/microlytics/example= /simple.dart +deleted file mode 100644 +index 42b323e2114..00000000000 +--- a/pkg/microlytics/example/simple.dart ++++ /dev/null +@@ -1,26 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'package:microlytics/channels.dart'; +-import 'package:microlytics/io_channels.dart'; +-import 'package:microlytics/microlytics.dart'; +- +-void main(List arguments) { +- // Create the channel that will be used to communicate to analytics. +- var channel =3D new RateLimitingBufferedChannel(new HttpClientChannel(), +- packetsPerSecond: 1.0); +- +- if (arguments.length !=3D 1) { +- print("usage: dart simple.dart GA-Client-ID"); +- return; +- } +- final String clientID =3D arguments.single; +- +- // Create the logger. +- var lg =3D new AnalyticsLogger(channel, "555", clientID, "test", "1.2"); +- +- // Send some messages. +- lg.logAnonymousEvent("hello", "world"); +- lg.logAnonymousTiming("loader", "var", 42); +-} +diff --git a/pkg/microlytics/lib/channels.dart b/pkg/microlytics/lib/chann= els.dart +deleted file mode 100644 +index 18f233c19f9..00000000000 +--- a/pkg/microlytics/lib/channels.dart ++++ /dev/null +@@ -1,53 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library microlytics.channels; +- +-import 'dart:async'; +- +-const String ANALYTICS_URL =3D "https://ssl.google-analytics.com/collect"; +- +-abstract class Channel { +- void sendData(String data); +- void shutdown() {} +-} +- +-/// [Channel] that implements a leaky bucket +-/// algorithm to provide rate limiting. +-/// See [http://en.wikipedia.org/wiki/Leaky_bucket]. +-class RateLimitingBufferedChannel extends Channel { +- final List _buffer =3D []; +- final Channel _innerChannel; +- final int _bufferSizeLimit; +- Timer _timer; +- +- RateLimitingBufferedChannel(this._innerChannel, +- {int bufferSizeLimit: 10, double packetsPerSecond: 1.0}) +- : this._bufferSizeLimit =3D bufferSizeLimit { +- if (!(packetsPerSecond > 0)) { +- throw new ArgumentError("packetsPerSecond must be larger than zero.= "); +- } +- +- int transmitDelay =3D (1000 / packetsPerSecond).floor(); +- _timer =3D new Timer.periodic( +- new Duration(milliseconds: transmitDelay), _onTimerTick); +- } +- +- void _onTimerTick(_) { +- if (_buffer.length > 0) { +- String item =3D _buffer.removeLast(); +- _innerChannel.sendData(item); +- } +- } +- +- void sendData(String data) { +- if (_buffer.length >=3D _bufferSizeLimit) return; +- _buffer.add(data); +- } +- +- void shutdown() { +- _timer.cancel(); +- _innerChannel.shutdown(); +- } +-} +diff --git a/pkg/microlytics/lib/html_channels.dart b/pkg/microlytics/lib/= html_channels.dart +deleted file mode 100644 +index b3eef43bbac..00000000000 +--- a/pkg/microlytics/lib/html_channels.dart ++++ /dev/null +@@ -1,14 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library microlytics.html_channels; +- +-import 'dart:html'; +-import 'channels.dart'; +- +-class HttpRequestChannel extends Channel { +- void sendData(String data) { +- HttpRequest.request(ANALYTICS_URL, method: "POST", sendData: data); +- } +-} +diff --git a/pkg/microlytics/lib/io_channels.dart b/pkg/microlytics/lib/io= _channels.dart +deleted file mode 100644 +index 044005cef8a..00000000000 +--- a/pkg/microlytics/lib/io_channels.dart ++++ /dev/null +@@ -1,20 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library microlytics.io_channels; +- +-import 'dart:io'; +-import 'channels.dart'; +- +-class HttpClientChannel extends Channel { +- void sendData(String data) { +- HttpClient client =3D new HttpClient(); +- client.postUrl(Uri.parse(ANALYTICS_URL)).then((HttpClientRequest req)= { +- req.write(data); +- return req.close(); +- }).then((HttpClientResponse response) { +- response.drain(); +- }); +- } +-} +diff --git a/pkg/microlytics/lib/microlytics.dart b/pkg/microlytics/lib/mi= crolytics.dart +deleted file mode 100644 +index 509ae26dea7..00000000000 +--- a/pkg/microlytics/lib/microlytics.dart ++++ /dev/null +@@ -1,57 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library microlytics; +- +-import 'channels.dart'; +- +-/// Very limited implementation of an API to report usage to Google Analy= tics. +-/// No Personally Identifiable Information must ever be passed to this cl= ass. +-class AnalyticsLogger { +- final Channel _channel; +- final String _clientID; +- final String _analyticsID; +- final String _appName; +- final String _appVersion; +- final String _messagePrefix; //Computed prefix for analytics messages +- +- /// Create a new logger +- /// [channel] represents how this is going to be sent, this would typic= ally +- /// be a [RateLimitingBufferedChannel] wrapping either a [HttpRequestCh= annel] +- /// or a [HttpClientChannel]. +- /// [clientID] is a version 4 UUID associated with the site or app. +- /// [appName] is an application name. +- /// [appVersion] is a verion string. +- AnalyticsLogger(Channel channel, String clientID, String analyticsID, +- String appName, String appVersion) +- : this._channel =3D channel, +- this._clientID =3D clientID, +- this._analyticsID =3D analyticsID, +- this._appName =3D appName, +- this._appVersion =3D appVersion, +- this._messagePrefix =3D "v=3D1" +- "&tid=3D$analyticsID" +- "&cid=3D$clientID" +- "&an=3D$appName" +- "&av=3D$appVersion"; +- +- void logAnonymousTiming(String category, String variable, int ms) { +- category =3D Uri.encodeComponent(category); +- variable =3D Uri.encodeComponent(variable); +- _channel.sendData("${this._messagePrefix}" +- "&t=3Dtiming" +- "&utc=3D$category" +- "&utv=3D$variable" +- "&utt=3D$ms"); +- } +- +- void logAnonymousEvent(String category, String event) { +- category =3D Uri.encodeComponent(category); +- event =3D Uri.encodeComponent(event); +- _channel.sendData("${this._messagePrefix}" +- "&t=3Devent" +- "&ec=3D$category" +- "&ea=3D$event"); +- } +-} +diff --git a/pkg/microlytics/pubspec.yaml b/pkg/microlytics/pubspec.yaml +deleted file mode 100644 +index 620b7cb6f83..00000000000 +--- a/pkg/microlytics/pubspec.yaml ++++ /dev/null +@@ -1,8 +0,0 @@ +-# Copyright (c) 2014, the Dart project authors. Please see the AUTHORS f= ile +-# for details. All rights reserved. Use of this source code is governed b= y a +-# BSD-style license that can be found in the LICENSE file. +- +-name: microlytics +-description: A minimal implementation of the Analytics API in pure Dart +-dev_dependencies: +- unittest: any +diff --git a/pkg/microlytics/test/dart_microlytics_test.dart b/pkg/microly= tics/test/dart_microlytics_test.dart +deleted file mode 100644 +index ca76b7592f6..00000000000 +--- a/pkg/microlytics/test/dart_microlytics_test.dart ++++ /dev/null +@@ -1,114 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library microlytics.test; +- +-import 'package:expect/expect.dart'; +-import 'package:microlytics/microlytics.dart'; +- +-import 'test_channel.dart'; +- +-void main() { +- testBasicEventRead(); +- testBasicNegativeEventRead(); +- testBasicTimingRead(); +- testBasicTimingMultiread(); +-} +- +-void testBasicEventRead() { +- TestChannel c =3D new TestChannel(); +- AnalyticsLogger logger =3D new AnalyticsLogger( +- c, +- "2cfac780-31e2-11e4-8c21-0800200c9a66", +- "UA-53895644-1", +- "TestApp", +- "0.42"); +- logger.logAnonymousEvent("video", "play"); +- Expect.isTrue(c.contains("v=3D1" +- "&tid=3DUA-53895644-1" +- "&cid=3D2cfac780-31e2-11e4-8c21-0800200c9a66" +- "&an=3DTestApp" +- "&av=3D0.42" +- "&t=3Devent" +- "&ec=3Dvideo" +- "&ea=3Dplay")); +-} +- +-void testBasicNegativeEventRead() { +- TestChannel c =3D new TestChannel(); +- AnalyticsLogger logger =3D new AnalyticsLogger( +- c, +- "2cfac780-31e2-11e4-8c21-0800200c9a66", +- "UA-53895644-1", +- "TestApp", +- "0.42"); +- logger.logAnonymousEvent("video", "play"); +- Expect.isFalse(c.contains("v=3D1" +- "&tid=3DUA-53895644-1" +- "&cid=3D2cfac780-31e2-11e4-8c21-0800200c9a66" +- "&an=3DTestApp" +- "&av=3DXXX" +- "&t=3Devent" +- "&ec=3Dvideo" +- "&ea=3Dplay")); +-} +- +-void testBasicTimingRead() { +- TestChannel c =3D new TestChannel(); +- AnalyticsLogger logger =3D new AnalyticsLogger( +- c, +- "2cfac780-31e2-11e4-8c21-0800200c9a66", +- "UA-53895644-1", +- "TestApp", +- "0.42"); +- logger.logAnonymousTiming("video", "delay", 157); +- Expect.isTrue(c.contains("v=3D1" +- "&tid=3DUA-53895644-1" +- "&cid=3D2cfac780-31e2-11e4-8c21-0800200c9a66" +- "&an=3DTestApp" +- "&av=3D0.42" +- "&t=3Dtiming" +- "&utc=3Dvideo" +- "&utv=3Ddelay" +- "&utt=3D157")); +-} +- +-void testBasicTimingMultiread() { +- TestChannel c =3D new TestChannel(); +- AnalyticsLogger logger =3D new AnalyticsLogger( +- c, +- "2cfac780-31e2-11e4-8c21-0800200c9a66", +- "UA-53895644-1", +- "TestApp", +- "0.42"); +- logger.logAnonymousTiming("video", "delay", 159); +- logger.logAnonymousTiming("video", "delay", 152); +- Expect.isTrue(c.contains("v=3D1" +- "&tid=3DUA-53895644-1" +- "&cid=3D2cfac780-31e2-11e4-8c21-0800200c9a66" +- "&an=3DTestApp" +- "&av=3D0.42" +- "&t=3Dtiming" +- "&utc=3Dvideo" +- "&utv=3Ddelay" +- "&utt=3D152")); +- Expect.isTrue(c.contains("v=3D1" +- "&tid=3DUA-53895644-1" +- "&cid=3D2cfac780-31e2-11e4-8c21-0800200c9a66" +- "&an=3DTestApp" +- "&av=3D0.42" +- "&t=3Dtiming" +- "&utc=3Dvideo" +- "&utv=3Ddelay" +- "&utt=3D159")); +- Expect.isFalse(c.contains("v=3D1" +- "&tid=3DUA-53895644-1" +- "&cid=3D2cfac780-31e2-11e4-8c21-0800200c9a66" +- "&an=3DTestApp" +- "&av=3D0.42" +- "&t=3Dtiming" +- "&utc=3Dvideo" +- "&utv=3Ddelay" +- "&utt=3D19")); +-} +diff --git a/pkg/microlytics/test/test_channel.dart b/pkg/microlytics/test= /test_channel.dart +deleted file mode 100644 +index a7f9c8bd8b1..00000000000 +--- a/pkg/microlytics/test/test_channel.dart ++++ /dev/null +@@ -1,19 +0,0 @@ +-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-library microlytics.test_channel; +- +-import 'package:microlytics/channels.dart'; +- +-class TestChannel extends Channel { +- List _channelLog =3D []; +- +- void sendData(String data) { +- _channelLog.add(data); +- } +- +- bool contains(String data) { +- return _channelLog.contains(data); +- } +-} +diff --git a/pkg/pkg.status b/pkg/pkg.status +index 4c454cfe5e4..f75e2ed9216 100644 +--- a/pkg/pkg.status ++++ b/pkg/pkg.status +@@ -11,7 +11,6 @@ + */*/*/*/packages/*/*: Skip + */*/*/*/*/packages/*/*: Skip +=20 +-analysis_server/tool/spec/check_all_test: Skip # Issue 29133 + analyzer_plugin/tool/spec/check_all_test: Skip # Issue 29133 +=20 + analyzer/test/generated/compile_time_error_code_driver_test: Slow, Pass +@@ -90,13 +89,7 @@ mutation_observer: Skip # Issue 21149 + unittest/*: Skip # Issue 21949 + front_end/*: SkipByDesign +=20 +-[ $runtime =3D=3D vm && $mode =3D=3D debug ] +-analysis_server/test/completion_test: Pass, Slow +- + [ $runtime =3D=3D vm && $checked ] +-analysis_server/test/completion_test: Pass, Slow +-analysis_server/test/services/correction/fix_test: Pass, Slow +-analysis_server/test/socket_server_test: Skip # Pass, Slow + analyzer/test/generated/non_error_resolver_kernel_test: Skip # Timing out= even with Pass, Slow: Issue 30796 + analyzer/test/src/summary/resynthesize_ast_test: Pass, Slow + analyzer/test/src/task/strong/front_end_inference_test: Pass, Slow +@@ -124,16 +117,12 @@ front_end/test/summary_generator_test: SkipByDesign = # depends on patched_sdk whi + front_end/test/mixin_export_test: SkipByDesign # depends on patched_sdk w= hich is not built into the sdk +=20 + [ $runtime =3D=3D vm && $system =3D=3D windows] +-analysis_server/*: Skip # Issue 27557 +-analysis_server/test/analysis/get_errors_test: Skip # runtime error, Issu= e 22180 +-analysis_server/test/integration/analysis/analysis_options_test: RuntimeE= rror # Issue 24796 + analyzer/test/generated/non_error_resolver_kernel_test: RuntimeError # Is= sue 30785 + kernel/test/baseline_spec_mode_test: RuntimeError # Issue 28243 + kernel/test/baseline_strong_mode_test: RuntimeError # Issue 28243 + analyzer/tool/task_dependency_graph/check_test: Slow, Pass +=20 + [ $compiler =3D=3D dart2js ] +-analysis_server/test/integration: SkipByDesign # Analysis server integrat= ion tests don't make sense to run under dart2js, since the code under test = always runs in the Dart vm as a subprocess. + analyzer_cli/test/*: SkipByDesign # Only meant to run on vm + analyzer_plugin/test/*: SkipByDesign # Only meant to run on vm + analyzer_plugin/tool/*: SkipByDesign # Only meant to run on vm +@@ -145,7 +134,6 @@ collection/test/equality_test/05: Fail # Issue 1533 + collection/test/equality_test/none: Pass, Fail # Issue 14348 + compiler/tool/*: SkipByDesign # Only meant to run on vm + front_end/tool/*: SkipByDesign # Only meant to run on vm +-telemetry/test/*: SkipByDesign # Only meant to run on vm + typed_data/test/typed_buffers_test/01: Fail # Not supporting Int64List, U= int64List. + front_end/test/incremental_kernel_generator_test: SkipByDesign # Uses dar= t:io + front_end/test/incremental_resolved_ast_generator_test: SkipByDesign # Us= es dart:io +@@ -166,7 +154,6 @@ front_end/test/*: SkipByDesign # Tests written with da= rt:mirrors. + [ $compiler =3D=3D dart2js && $builder_tag !=3D dart2js_analyzer ] + analyzer/test/*: Skip # Issue 26813 + analyzer/tool/*: Skip # Issue 26813 +-analysis_server/test/*: Skip # Issue 26813 +=20 + [ $compiler =3D=3D dart2js && $checked ] + crypto/test/base64_test: Slow, Pass +@@ -202,8 +189,6 @@ crypto/test/sha1_test: Slow, Pass + [ $browser ] + analyzer_cli/*: SkipByDesign # Uses dart:io. + */test/analyzer_test: SkipByDesign # No need to run analysis tests on bro= wser bots +-analysis_server/test/*: SkipByDesign # Uses dart:io. +-analysis_server/tool/spec/check_all_test: SkipByDesign # Uses dart:io. + analyzer/test/*: SkipByDesign # Uses dart:io. + analyzer/tool/task_dependency_graph/check_test: SkipByDesign # Uses dart:= io. + analyzer/tool/summary/check_test: SkipByDesign # Uses dart:io. +diff --git a/pkg/telemetry/LICENSE b/pkg/telemetry/LICENSE +deleted file mode 100644 +index 389ce985634..00000000000 +--- a/pkg/telemetry/LICENSE ++++ /dev/null +@@ -1,26 +0,0 @@ +-Copyright 2017, the Dart project authors. All rights reserved. +-Redistribution and use in source and binary forms, with or without +-modification, are permitted provided that the following conditions are +-met: +- +- * Redistributions of source code must retain the above copyright +- notice, this list of conditions and the following disclaimer. +- * Redistributions in binary form must reproduce the above +- copyright notice, this list of conditions and the following +- disclaimer in the documentation and/or other materials provided +- with the distribution. +- * Neither the name of Google Inc. nor the names of its +- contributors may be used to endorse or promote products derived +- from this software without specific prior written permission. +- +-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +diff --git a/pkg/telemetry/README.md b/pkg/telemetry/README.md +deleted file mode 100644 +index 26804b04610..00000000000 +--- a/pkg/telemetry/README.md ++++ /dev/null +@@ -1,51 +0,0 @@ +-# telemetry +- +-A library to facilitate reporting analytics and crash reports. +- +-## Analytics +- +-This library is designed to allow all Dart SDK tools to easily send analy= tics +-information and crash reports. The tools share a common setting to config= ure +-sending analytics data. To use this library for a specific tool: +- +-``` +-import 'package:telemetry/telemetry.dart'; +-import 'package:usage/usage.dart'; +- +-main() async { +- final String myAppTrackingID =3D ...; +- final String myAppName =3D ...; +- +- Analytics analytics =3D createAnalyticsInstance(myAppTrackingID, myAppN= ame); +- ... +- analytics.sendScreenView('home'); +- ... +- await analytics.waitForLastPing(); +-} +-``` +- +-The analytics object reads from the correct user configuration file +-automatically without any additional configuration. Analytics will not be= sent +-if the user has opted-out. +- +-## Crash reporting +- +-To use the crash reporting functionality, import `crash_reporting.dart`, = and +-create a new `CrashReportSender` instance: +- +-```dart +-import 'package:telemetry/crash_reporting.dart'; +- +-main() { +- Analytics analytics =3D ...; +- CrashReportSender sender =3D new CrashReportSender(analytics); +- try { +- ... +- } catch (e, st) { +- sender.sendReport(e, st); +- } +-} +-``` +- +-Crash reports will only be sent if the cooresponding [Analytics] object is +-configured to send analytics. +diff --git a/pkg/telemetry/analysis_options.yaml b/pkg/telemetry/analysis_= options.yaml +deleted file mode 100644 +index 85f01f0a5d4..00000000000 +--- a/pkg/telemetry/analysis_options.yaml ++++ /dev/null +@@ -1,10 +0,0 @@ +-analyzer: +- strong-mode: true +-linter: +- rules: +- - annotate_overrides +- - empty_constructor_bodies +- - empty_statements +- - unawaited_futures +- - unnecessary_brace_in_string_interps +- - valid_regexps +diff --git a/pkg/telemetry/lib/crash_reporting.dart b/pkg/telemetry/lib/cr= ash_reporting.dart +deleted file mode 100644 +index c34766eb0b8..00000000000 +--- a/pkg/telemetry/lib/crash_reporting.dart ++++ /dev/null +@@ -1,94 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:async'; +-import 'dart:io'; +- +-import 'package:http/http.dart' as http; +-import 'package:stack_trace/stack_trace.dart'; +-import 'package:usage/usage.dart'; +- +-/// Crash backend host. +-const String _crashServerHost =3D 'clients2.google.com'; +- +-/// Path to the crash servlet. +-const String _crashEndpointPath =3D '/cr/report'; // or, staging_report +- +-/// The field corresponding to the multipart/form-data file attachment wh= ere +-/// crash backend expects to find the Dart stack trace. +-const String _stackTraceFileField =3D 'DartError'; +- +-/// The name of the file attached as [stackTraceFileField]. +-/// +-/// The precise value is not important. It is ignored by the crash back e= nd, but +-/// it must be supplied in the request. +-const String _stackTraceFilename =3D 'stacktrace_file'; +- +-/// Sends crash reports to Google. +-/// +-/// Clients shouldn't extend, mixin or implement this class. +-class CrashReportSender { +- static final Uri _baseUri =3D new Uri( +- scheme: 'https', host: _crashServerHost, path: _crashEndpointPath); +- +- final String crashProductId; +- final Analytics analytics; +- final http.Client _httpClient; +- +- /// Create a new [CrashReportSender], using the data from the given +- /// [Analytics] instance. +- CrashReportSender(this.crashProductId, this.analytics, +- {http.Client httpClient}) +- : _httpClient =3D httpClient ?? new http.Client(); +- +- /// Sends one crash report. +- /// +- /// The report is populated from data in [error] and [stackTrace]. +- Future sendReport(dynamic error, {StackTrace stackTrace}) async { +- if (!analytics.enabled) { +- return; +- } +- +- try { +- final Uri uri =3D _baseUri.replace( +- queryParameters: { +- 'product': analytics.trackingId, +- 'version': analytics.applicationVersion, +- }, +- ); +- +- final http.MultipartRequest req =3D new http.MultipartRequest('POST= ', uri); +- req.fields['uuid'] =3D analytics.clientId; +- req.fields['product'] =3D crashProductId; +- req.fields['version'] =3D analytics.applicationVersion; +- req.fields['osName'] =3D Platform.operatingSystem; +- // TODO(devoncarew): Report the operating system version when we're= able. +- //req.fields['osVersion'] =3D Platform.operatingSystemVersion; +- req.fields['type'] =3D 'DartError'; +- req.fields['error_runtime_type'] =3D '${error.runtimeType}'; +- +- final Chain chain =3D new Chain.parse(stackTrace.toString()); +- req.files.add(new http.MultipartFile.fromString( +- _stackTraceFileField, chain.terse.toString(), +- filename: _stackTraceFilename)); +- +- final http.StreamedResponse resp =3D await _httpClient.send(req); +- +- if (resp.statusCode !=3D 200) { +- throw 'server responded with HTTP status code ${resp.statusCode}'; +- } +- } on SocketException catch (error) { +- throw 'network error while sending crash report: $error'; +- } catch (error, stackTrace) { +- // If the sender itself crashes, just print. +- throw 'exception while sending crash report: $error\n$stackTrace'; +- } +- } +- +- /// Closes the client and cleans up any resources associated with it. T= his +- /// will close the associated [http.Client]. +- void dispose() { +- _httpClient.close(); +- } +-} +diff --git a/pkg/telemetry/lib/telemetry.dart b/pkg/telemetry/lib/telemetr= y.dart +deleted file mode 100644 +index 7b05ec13cbe..00000000000 +--- a/pkg/telemetry/lib/telemetry.dart ++++ /dev/null +@@ -1,126 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:path/path.dart' as path; +-import 'package:usage/src/usage_impl.dart'; +-import 'package:usage/src/usage_impl_io.dart'; +-import 'package:usage/src/usage_impl_io.dart' as usage_io show getDartVer= sion; +-import 'package:usage/usage.dart'; +-import 'package:usage/usage_io.dart'; +- +-export 'package:usage/usage.dart' show Analytics; +- +-// TODO(devoncarew): Hard-coded to off for now. Remove when we're ready t= o ship. +-final bool _HARD_CODE_OFF =3D true; +- +-// TODO(devoncarew): Don't show the UI until we're ready to ship. +-final bool SHOW_ANALYTICS_UI =3D false; +- +-final String _dartDirectoryName =3D '.dart'; +-final String _settingsFileName =3D 'analytics.json'; +- +-/// Dart SDK tools with analytics should display this notice. +-/// +-/// In addition, they should support displaying the analytics' status, an= d have +-/// a flag to toggle analytics. This may look something like: +-/// +-/// `Analytics are currently enabled (and can be disabled with --no-analy= tics).` +-final String analyticsNotice =3D +- "Dart SDK tools anonymously report feature usage statistics and basic= crash\n" +- "reports to help improve Dart tools over time. See Google's privacy p= olicy:\n" +- "https://www.google.com/intl/en/policies/privacy/."; +- +-/// Return a customized message for command-line tools to display about t= he +-/// state of analytics, and how users can enabled or disable analytics. +-/// +-/// An example return value might be `'Analytics are currently enabled (a= nd can +-/// be disabled with --no-analytics).'` +-String createAnalyticsStatusMessage(bool enabled, +- {String command: 'analytics'}) { +- String currentState =3D enabled ? 'enabled' : 'disabled'; +- String toggleState =3D enabled ? 'disabled' : 'enabled'; +- String commandToggle =3D enabled ? 'no-$command' : command; +- +- return 'Analytics are currently $currentState ' +- '(and can be $toggleState with --$commandToggle).'; +-} +- +-/// Create an [Analytics] instance with the given trackingID and +-/// applicationName. +-/// +-/// This analytics instance will share a common enablement state with the= rest +-/// of the Dart SDK tools. +-Analytics createAnalyticsInstance(String trackingId, String applicationNa= me, +- {bool disableForSession: false}) { +- Directory dir =3D getDartStorageDirectory(); +- if (!dir.existsSync()) { +- dir.createSync(); +- } +- +- if (_HARD_CODE_OFF) { +- disableForSession =3D true; +- } +- +- File file =3D new File(path.join(dir.path, _settingsFileName)); +- return new _TelemetryAnalytics( +- trackingId, applicationName, getDartVersion(), file, disableForSess= ion); +-} +- +-/// The directory used to store the analytics settings file. +-/// +-/// Typically, the directory is `~/.dart/` (and the settings file is +-/// `analytics.json`). +-Directory getDartStorageDirectory() =3D> +- new Directory(path.join(userHomeDir(), _dartDirectoryName)); +- +-/// Return the version of the Dart SDK. +-String getDartVersion() =3D> usage_io.getDartVersion(); +- +-class _TelemetryAnalytics extends AnalyticsImpl { +- final bool disableForSession; +- +- _TelemetryAnalytics( +- String trackingId, +- String applicationName, +- String applicationVersion, +- File file, +- this.disableForSession, +- ) +- : super( +- trackingId, +- new IOPersistentProperties.fromFile(file), +- new IOPostHandler(), +- applicationName: applicationName, +- applicationVersion: applicationVersion, +- ) { +- final String locale =3D getPlatformLocale(); +- if (locale !=3D null) { +- setSessionValue('ul', locale); +- } +- } +- +- @override +- bool get enabled { +- if (disableForSession || isRunningOnBot()) { +- return false; +- } +- return super.enabled; +- } +-} +- +-bool isRunningOnBot() { +- // - https://docs.travis-ci.com/user/environment-variables/ +- // - https://www.appveyor.com/docs/environment-variables/ +- // - CHROME_HEADLESS and BUILDBOT_BUILDERNAME are properties on Chrome = infra +- // bots. +- return Platform.environment['TRAVIS'] =3D=3D 'true' || +- Platform.environment['BOT'] =3D=3D 'true' || +- Platform.environment['CONTINUOUS_INTEGRATION'] =3D=3D 'true' || +- Platform.environment['CHROME_HEADLESS'] =3D=3D '1' || +- Platform.environment.containsKey('BUILDBOT_BUILDERNAME') || +- Platform.environment.containsKey('APPVEYOR') || +- Platform.environment.containsKey('CI'); +-} +diff --git a/pkg/telemetry/pubspec.yaml b/pkg/telemetry/pubspec.yaml +deleted file mode 100644 +index 2da46fb7e37..00000000000 +--- a/pkg/telemetry/pubspec.yaml ++++ /dev/null +@@ -1,16 +0,0 @@ +-name: telemetry +-description: A library to facilitate reporting analytics and crash report= s. +-version: 0.0.1 +-author: Dart Team +- +-environment: +- sdk: '>=3D1.0.0 <2.0.0' +- +-dependencies: +- http: ^0.11.3+12 +- path: ^1.4.0 +- stack_trace: ^1.7.0 +- usage: ^3.2.0+1 +- +-dev_dependencies: +- test: ^0.12.0 +diff --git a/pkg/telemetry/test/crash_reporting_test.dart b/pkg/telemetry/= test/crash_reporting_test.dart +deleted file mode 100644 +index c4e812d3133..00000000000 +--- a/pkg/telemetry/test/crash_reporting_test.dart ++++ /dev/null +@@ -1,41 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:convert' show UTF8; +- +-import 'package:http/http.dart'; +-import 'package:http/testing.dart'; +-import 'package:telemetry/crash_reporting.dart'; +-import 'package:test/test.dart'; +-import 'package:usage/usage.dart'; +- +-void main() { +- group('crash_reporting', () { +- MockClient mockClient; +- +- Request request; +- +- setUp(() { +- mockClient =3D new MockClient((Request r) async { +- request =3D r; +- return new Response('crash-report-001', 200); +- }); +- }); +- +- test('CrashReportSender', () async { +- AnalyticsMock analytics =3D new AnalyticsMock()..enabled =3D true; +- CrashReportSender sender =3D new CrashReportSender( +- analytics.trackingId, analytics, +- httpClient: mockClient); +- +- await sender.sendReport('test-error', stackTrace: StackTrace.curren= t); +- +- String body =3D UTF8.decode(request.bodyBytes); +- expect(body, contains('String')); // error.runtimeType +- expect(body, contains(analytics.trackingId)); +- expect(body, contains('1.0.0')); +- expect(body, contains(analytics.clientId)); +- }); +- }); +-} +diff --git a/pkg/telemetry/test/telemetry_test.dart b/pkg/telemetry/test/t= elemetry_test.dart +deleted file mode 100644 +index 7a9b70a4668..00000000000 +--- a/pkg/telemetry/test/telemetry_test.dart ++++ /dev/null +@@ -1,31 +0,0 @@ +-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-import 'dart:io'; +- +-import 'package:telemetry/telemetry.dart'; +-import 'package:test/test.dart'; +-import 'package:usage/usage.dart'; +- +-void main() { +- group('telemetry', () { +- test('getDartStorageDirectory', () { +- Directory dir =3D getDartStorageDirectory(); +- expect(dir, isNotNull); +- }); +- +- test('getDartVersion', () { +- expect(getDartVersion(), isNotNull); +- }); +- +- test('createAnalyticsInstance', () { +- Analytics analytics =3D createAnalyticsInstance('UA-0', 'test-app'); +- expect(analytics, isNotNull); +- expect(analytics.trackingId, 'UA-0'); +- expect(analytics.getSessionValue('an'), 'test-app'); +- expect(analytics.getSessionValue('av'), isNotNull); +- expect(analytics.clientId, isNotNull); +- }); +- }); +-} +diff --git a/runtime/observatory/lib/app.dart b/runtime/observatory/lib/ap= p.dart +index f096ad88229..34b71d4a6da 100644 +--- a/runtime/observatory/lib/app.dart ++++ b/runtime/observatory/lib/app.dart +@@ -27,5 +27,4 @@ part 'src/app/location_manager.dart'; + part 'src/app/notification.dart'; + part 'src/app/page.dart'; + part 'src/app/settings.dart'; +-part 'src/app/view_model.dart'; +-part 'src/app/analytics.dart'; ++part 'src/app/view_model.dart'; +\ No newline at end of file +diff --git a/runtime/observatory/lib/src/app/analytics.dart b/runtime/obse= rvatory/lib/src/app/analytics.dart +deleted file mode 100644 +index 8f09f61c668..00000000000 +--- a/runtime/observatory/lib/src/app/analytics.dart ++++ /dev/null +@@ -1,31 +0,0 @@ +-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS = file +-// for details. All rights reserved. Use of this source code is governed = by a +-// BSD-style license that can be found in the LICENSE file. +- +-part of app; +- +-class Analytics { +- static final _UA =3D 'UA-26406144-17'; +- static final _name =3D 'Observatory'; +- static final _version =3D const String.fromEnvironment('OBS_VER'); +- static final _googleAnalytics =3D new AnalyticsHtml(_UA, _name, _versio= n); +- +- static initialize() { +- // We only send screen views. This is allowed without user permission. +- // Note, before flipping this to be true we need a UI to allow users = to +- // control this. +- _googleAnalytics.optIn =3D false; +- } +- +- /// Called whenever an Observatory page is viewed. +- static Future reportPageView(Uri uri) { +- // Only report analytics when running in JavaScript. +- if (Utils.runningInJavaScript()) { +- // The screen name is the uri's path. e.g. inspect, profile. +- final screenName =3D uri.path; +- return _googleAnalytics.sendScreenView(screenName); +- } else { +- return new Future.value(null); +- } +- } +-} +diff --git a/runtime/observatory/observatory_sources.gni b/runtime/observa= tory/observatory_sources.gni +index 15ddbe526a0..760399f4768 100644 +--- a/runtime/observatory/observatory_sources.gni ++++ b/runtime/observatory/observatory_sources.gni +@@ -22,7 +22,6 @@ observatory_sources =3D [ + "lib/service_html.dart", + "lib/service_io.dart", + "lib/src/allocation_profile/allocation_profile.dart", +- "lib/src/app/analytics.dart", + "lib/src/app/application.dart", + "lib/src/app/location_manager.dart", + "lib/src/app/notification.dart", +diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn +index 8702969e800..17ef0ab346c 100644 +--- a/sdk/BUILD.gn ++++ b/sdk/BUILD.gn +@@ -36,7 +36,6 @@ declare_args() { + # ......dartdevc + # ......pub + # ......snapshots/ +-# ........analysis_server.dart.snapshot + # ........dart2js.dart.snapshot + # ........dartanalyzer.dart.snapshot + # ........dartdoc.dart.snapshot +@@ -67,7 +66,6 @@ declare_args() { + #.........vm_platform.dill + #.........vm_platform_strong.dill + #.........dev_compiler/ +-# ......analysis_server/ + # ......analyzer/ + # ......async/ + # ......collection/ +@@ -107,10 +105,6 @@ _scripts =3D [ "dartdoc" ] +=20 + # Snapshots that go under bin/snapshots + _platform_sdk_snapshots =3D [ +- [ +- "analysis_server", +- "../utils/analysis_server", +- ], + [ + "dartanalyzer", + "../utils/dartanalyzer:generate_dartanalyzer_snapshot", +@@ -130,10 +124,6 @@ _platform_sdk_snapshots =3D [ + ] +=20 + _full_sdk_snapshots =3D [ +- [ +- "analysis_server", +- "../utils/analysis_server", +- ], + [ + "dart2js", + "../utils/compiler:dart2js", +@@ -212,7 +202,6 @@ _full_sdk_libraries =3D [ + # Package sources copied to lib/ + _analyzer_source_dirs =3D [ + "analyzer", +- "analysis_server", + "front_end", + "kernel", + ] +diff --git a/tests/lib/analyzer/analyze_library.status b/tests/lib/analyze= r/analyze_library.status +index 3abc3f80a2d..3eca5d81337 100644 +--- a/tests/lib/analyzer/analyze_library.status ++++ b/tests/lib/analyzer/analyze_library.status +@@ -5,7 +5,6 @@ + [ $compiler =3D=3D dart2analyzer && $use_sdk ] + lib/*: Skip # Issue 28620 + lib/analyzer: Skip # Issue 28620 +-lib/analysis_server: Skip # Issue 28620 + lib/dev_compiler: Skip # Issue 28620 + lib/front_end: Skip # Issue 28620 +=20 +diff --git a/tools/bots/dartdoc_footer.html b/tools/bots/dartdoc_footer.ht= ml +index 63de697d483..e69de29bb2d 100644 +--- a/tools/bots/dartdoc_footer.html ++++ b/tools/bots/dartdoc_footer.html +@@ -1,13 +0,0 @@ +- +- +- +diff --git a/tools/bots/test_matrix.json b/tools/bots/test_matrix.json +index 2cf500eb743..f380acccaf0 100644 +--- a/tools/bots/test_matrix.json ++++ b/tools/bots/test_matrix.json +@@ -1077,16 +1077,6 @@ + "pkg/analyzer" + ] + }, +- { +- "name": "analysis_server unit tests", +- "arguments": [ +- "--compiler=3Dnone", +- "--runtime=3Dvm", +- "--checked", +- "--use-sdk", +- "pkg/analysis_server" +- ] +- }, + { + "name": "analysis_cli unit tests", + "arguments": [ +@@ -1134,26 +1124,6 @@ + } + ] + }, +- { +- "builders": ["analyzer-analysis-server-linux"], +- "steps": [ +- { +- "name": "Analyze analysis_server", +- "script": "out/ReleaseX64/dart-sdk/bin/dartanalyzer", +- "arguments": ["--no-hints","pkg/analysis_server"] +- }, +- { +- "name": "Analyze analysis_server", +- "script": "out/ReleaseX64/dart-sdk/bin/dartanalyzer", +- "arguments": ["--no-hints","pkg/analyzer"] +- }, +- { +- "name": "Analyze analysis_server", +- "script": "out/ReleaseX64/dart-sdk/bin/dartanalyzer", +- "arguments": ["--no-hints","pkg/analyzer_plugin"] +- } +- ] +- }, + { + "builders": ["pkg-linux-release","pkg-win-release","pkg-mac-release= "], + "meta": { +diff --git a/tools/bots/try_benchmarks.sh b/tools/bots/try_benchmarks.sh +index 3932c704c2e..3990f254eed 100755 +--- a/tools/bots/try_benchmarks.sh ++++ b/tools/bots/try_benchmarks.sh +@@ -409,7 +409,6 @@ EOF + out/ReleaseX64/dart pkg/front_end/tool/fasta_perf.dart scan hello.dart + out/ReleaseX64/dart pkg/front_end/tool/perf.dart unlinked_summarize h= ello.dart + out/ReleaseX64/dart pkg/front_end/tool/perf.dart unlinked_summarize_f= rom_sources hello.dart +- out/ReleaseX64/dart pkg/analysis_server/benchmark/benchmarks.dart run= --quick --repeat 1 analysis-server-cold + out/ReleaseX64/dart --print_metrics pkg/analyzer_cli/bin/analyzer.dar= t --dart-sdk=3Dsdk hello.dart + echo '[{"name":"foo","edits":[["pkg/compiler/lib/src/dart2js.dart","2= 016","2017"],["pkg/compiler/lib/src/options.dart","2016","2017"]]}]' > appj= it_train_edits.json + out/ReleaseX64/dart --background-compilation=3Dfalse --snapshot-kind= =3Dapp-jit --snapshot=3Dpkg/front_end/tool/incremental_perf.dart.appjit pkg= /front_end/tool/incremental_perf.dart --target=3Dvm --sdk-summary=3Dout/Rel= easeX64/vm_platform.dill --sdk-library-specification=3Dsdk/lib/libraries.js= on pkg/compiler/lib/src/dart2js.dart appjit_train_edits.json +diff --git a/utils/analysis_server/.gitignore b/utils/analysis_server/.git= ignore +deleted file mode 100644 +index 010faca1007..00000000000 +--- a/utils/analysis_server/.gitignore ++++ /dev/null +@@ -1,3 +0,0 @@ +-/analysis_server.Makefile +-/analysis_server.target.mk +- +diff --git a/utils/analysis_server/BUILD.gn b/utils/analysis_server/BUILD.= gn +deleted file mode 100644 +index 9359e2c6fc5..00000000000 +--- a/utils/analysis_server/BUILD.gn ++++ /dev/null +@@ -1,10 +0,0 @@ +-# Copyright (c) 2016, the Dart project authors. Please see the AUTHORS f= ile +-# for details. All rights reserved. Use of this source code is governed b= y a +-# BSD-style license that can be found in the LICENSE file. +- +-import("../application_snapshot.gni") +- +-application_snapshot("analysis_server") { +- main_dart =3D "../../pkg/analysis_server/bin/server.dart" +- training_args =3D [ "--help" ] +-} +--=20 +2.29.2 + --=20 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0009-gnu-Add-dart-2.0.0-dev.20.0.patch >From 974bd4d52d503fe310472816019a767d33ef007a Mon Sep 17 00:00:00 2001 From: nixo Date: Thu, 26 Nov 2020 21:26:24 +0100 Subject: [PATCH 09/20] gnu: Add dart-2.0.0-dev.20.0. * gnu/packages/dart.scm (dart-2.0.0-dev.20.0): New variable. --- gnu/packages/dart.scm | 60 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 4918f56d2c..65c55625a0 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -465,3 +465,63 @@ @item Supported both on desktop and on mobile @end") (license license:bsd-3))) + +(define-public dart-2.0.0-dev.20.0 + (package + (inherit dart-2.0.0-dev.8.0) + (name "dart") + (version "2.0.0-dev.20.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (file-name (string-append name "-" version)) + (sha256 + (base32 + "1k2zc27r3b7ha5bvlhaqr75xiyf6rg7nwk3r0qrjl7dk9k50iyix")))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.0.0-dev.8.0) + ((#:phases phases) + `(modify-phases ,phases + (add-before 'configure 'set-dart-path + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "runtime/observatory/BUILD.gn" + (("\"--sdk=True\" \\]") + (string-append + "\"--sdk=True\", " + "\"--dart-executable\"," + "\"" (assoc-ref inputs "dart") "/bin/dart\"," + "\"--pub-executable\"," + "\"" (assoc-ref inputs "dart") "/bin/pub\" ]"))) + (substitute* "tools/utils.py" + (("os.path.join\\(CheckedInSdkPath\\(\\), 'bin', name)") + (string-append "os.path.join(\"" + (assoc-ref %build-inputs "dart") "/bin/\", name)"))) + (substitute* "build/prebuilt_dart_sdk.gni" + (("\\$_dart_root/tools/sdks/\\$host_os/dart-sdk/bin/") + (string-append (assoc-ref %build-inputs "dart") "/bin/"))))) + (add-before 'configure 'disable-Werror + (lambda _ + (substitute* "runtime/BUILD.gn" + (("\"-Werror\"") "# -Werror") + (("\"-Wall\"") "# -Wall") + (("\"-Wextra\"") "# -Wextra")) + (substitute* "build/config/compiler/BUILD.gn" + (("\"-Wl,--icf=all\"") "") + (("\"-Wall") "# \"-Wall") + (("\"-Wextra") "# \"-Wextra") + (("\"-Werror") "# \"-Werror")))) + (add-before 'configure 'fix-get-timestamp + (lambda _ + (substitute* "tools/make_version.py" + (("utils.GetGitTimestamp") "\"0\" # ")))) + (add-before 'configure 'fix-zlib-build + (lambda _ + (substitute* "third_party/zlib/BUILD.gn" + (("direct_dependent_configs") "# direct_dependent_configs") + (("\"//base\",") "")))))))) + (native-inputs + (cons `("dart" ,dart-2.0.0-dev.8.0) + (package-native-inputs dart-2.0.0-dev.8.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0010-gnu-dart.scm-Add-helper-function.patch >From eb1f12966919585a282c2f161ba6bc2e6994bafb Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 00:41:49 +0100 Subject: [PATCH 10/20] gnu: dart.scm: Add helper function. * gnu/packages/dart.scm (replace-inputs): New function. --- gnu/packages/dart.scm | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 65c55625a0..89462d7355 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -22,6 +22,9 @@ #:use-module (guix git-download) #:use-module (guix packages) #:use-module (guix utils) + #:use-module (ice-9 match) + #:use-module (srfi srfi-1) + #:use-module ((guix build utils) #:select (alist-replace)) #:use-module (gnu packages) #:use-module (gnu packages build-tools) #:use-module (gnu packages gcc) @@ -525,3 +528,12 @@ (native-inputs (cons `("dart" ,dart-2.0.0-dev.8.0) (package-native-inputs dart-2.0.0-dev.8.0))))) + +(define (replace-inputs pkg inputs) + "Replace multiple inputs at once. `PKG' is the source package and +`INPUTS' the list of replacements." + (fold (lambda (pkg inputs) + (match-let (((name pkg) pkg)) + (alist-replace name (list pkg) inputs))) + (package-inputs pkg) + inputs)) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0011-gnu-Add-dart-2.0.0-dev.36.0.patch >From 47aa9e9461bdad2aef0a9dd90f31756bd882222d Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 10:12:25 +0100 Subject: [PATCH 11/20] gnu: Add dart-2.0.0-dev.36.0. * gnu/packages.dart.scm (dart-2.0.0-dev.36.0): New variable. --- gnu/packages/dart.scm | 129 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 89462d7355..f60e0b6a8a 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -537,3 +537,132 @@ (alist-replace name (list pkg) inputs))) (package-inputs pkg) inputs)) + +(define-public dart-2.0.0-dev.36.0 + (package + (inherit dart-2.0.0-dev.20.0) + (name "dart") + ;; This version adds jsonEncode, required to build 2.0 + (version "2.0.0-dev.36.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (file-name (string-append name "-" version)) + (sha256 + (base32 + "0q5am2c9mva96slv7flabs0h0hhc65hk0hsy9axgi0s1xnzrxlmp")))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.0.0-dev.20.0) + ((#:phases phases) + `(modify-phases ,phases + (add-before 'configure 'copy-bootstrap-dart + (lambda* (#:key inputs #:allow-other-keys) + (copy-recursively + (assoc-ref inputs "dart") + "tools/sdks/linux/dart-sdk"))))))) + (inputs + (append + `(("dart-pkg-http-io" + ,(dart-pkg "http-io" "35dc43c9144cf7ed4236843dacd62ebaf89df21a" + "1f23dpvig3c6966fhiz1mbmswkx0fqwxmprm8237ymgpji5hp6rw")) + ("dart-pkg-http-retry" + ,(dart-pkg "http-retry" "0.1.0" + "1qr92gjfgyxg2vcfw7vynahz5cd3h7gwf75djwrrjxs4ccabj24k")) + ("dart-pkg-test-descriptor" + ,(dart-pkg "test-descriptor" "1.0.3" + "0gvj8q1h07qprgx9jjljjasx65pzrsviyfhkbdk7c6znxs7kmdq1")) + ("dart-pkg-test-process" + ,(dart-pkg "test-process" "1.0.1" + "1vbni0kr6fz6nb8wfn6sxx8cnwp19xb8l548371qs8xf25lg61q3"))) + (replace-inputs + dart-2.0.0-dev.8.0 + `(("root-certificates" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/root_certificates.git") + (commit "a4c7c6f23a664a37bc1b6f15a819e3f2a292791a"))) + (sha256 + (base32 "0646gywipvk9m4l17f6c1mi9hhimcsh0x5vdkczhy5zhm8w6l9v7")))) + ("dart-pkg-async" + ,(dart-pkg "async" "corelib_2_2_1" + "1j3n02ricaf97wigsqdnnsj1ahw3d92ybp3kckrki4rlrq87a75v")) + ("dart-pkg-bazel-worker" + ,(dart-pkg "bazel-worker" "v0.1.9" + "1579a3kdif93mazz5wlny3axib04aysgfpgnx3fjxfnl60cw52b7")) + ("dart-pkg-collection" + ,(dart-pkg "collection" "1.14.5" + "1w46ffqd2808haqr49wf1f05qigwswhn904ph1qvb1fwlybj9s3p")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.16.0" + "0g17y9s4xf79bsccs3cybxal6yisbz1qhwqyzg7hdivb6jx6qqgn")) + ("dart-pkg-html" + ,(dart-pkg "html" "0.13.2+2" + "16xgff229r4palkgahbmby6hxi59wswg45l04q083ym6l4mwkac1")) + ("dart-pkg-json-rpc-2" + ,(dart-pkg "json_rpc_2" "2.0.6" + "0a0rjws0g9vpivjgpzv7k1j4i57qma447si0ipihk5sifvjhqjpn")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.43" + "0jaqh5jmqhmkajgbza7ij6w6fwafpr7shs1ad9dskhg57d0kkkp3")) + ("dart-pkg-path" + ,(dart-pkg "path" "1.5.1" + "1121qy0k59va7wsbcc96pnvs0226c2s3iyjc2xycvv2nm4y84hyz")) + ("dart-pkg-plugin" + ,(dart-pkg "plugin" "0.2.0+2" + "1nxr7b636vyrjqrism7s4mhazyac3qdq3b0g3xph2naknxipbnrx")) + ("dart-pkg-pub" + ,(dart-pkg "pub" "64c5f40adf6828da1b63320dd39bcedbef1354c6" + "1sb5kv41v0q4b1nqdc4vm9wg64schywadj5iz3g4k95q5j2i1q26")) + ("dart-pkg-markdown" + ,(dart-pkg "markdown" "1.0.0" + "0001k41sf7d9yf70jbmm5nxjby75x5ka1wg5yjl1zyggwxfcdv25")) + ("dart-pkg-mime" + ,(dart-pkg "mime" "0.9.6" + "1wazn5zwc59idd9yf85llwnwdk8m0mvcsn8b8bakm7j5rqzqxz4j")) + ("dart-pkg-mockito" + ,(dart-pkg "mockito" "a92db054fba18bc2d605be7670aee74b7cadc00a" + "0p3zxd83i61w4p4sf40zdq2cn8s3yg9ij1ydww4x32d42nsh7vmv")) + ("dart-pkg-pool" + ,(dart-pkg "pool" "1.3.4" + "087b60d07c9j8qa3dk1g1mz8yisxxhmjmqcnwkr2rpai89ji0mfm")) + ("dart-pkg-protobuf" + ,(dart-pkg "protobuf" "0.7.0" + "0kfpdw4cj74qpy5w7zx13kvw9bjz8ps6zdsycfx3hc4ml7876c4v")) + ("dart-pkg-quiver" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/google/quiver-dart.git") + (commit "0.28.0"))) + (sha256 (base32 + "1zji18fw1sb4y88snaxmz632v9px0z4c2wlh3bfwncsrc3h49i7z")))) + ("dart-pkg-shelf" + ,(dart-pkg "shelf" "0.7.1" + "199ivhgbf18x3zh5v3sr7dkkp8ndnvy6mb8r1brv01bykhkwp1k9")) + ("dart-pkg-stack-trace" + ,(dart-pkg "stack-trace" "1.9.0" + "1rb1nn9k8lwghx3kzfbfza1zdmd9s07xpgchv4lakd4hw7wbkvm6")) + ("dart-pkg-test" + ,(dart-pkg "test" "0.12.30+1" + "03n7cr1a3ajw6nb54iwwiyjmyyp63nrn9fbk6fsjyfx9ahgsxj18")) + ("dart-pkg-utf" + ,(dart-pkg "utf" "0.9.0+4" + "0lsdjfds1c6mcpgw4w5bvfbvhs1iyjb2yx0kggd4yky4gq6109r5")) + ("dart-pkg-watcher" + ,(dart-pkg "watcher" "0.9.7+7" + "1y50zzln9a5qqrzrgd62wwj0a6qhfsv9jj0wya8mlsp9xpq1bhbd")) + ("dart-pkg-web-socket-channel" + ,(dart-pkg "web-socket-channel" + "c2a2874b6e6366654e8b98fe1ef20a9f3d798eee" + "13wk7al7v7fynggq3x73y68yzs0wm7jziwv0m2qh5986i6wkcw78")) + ("dart-pkgtested-dart-style" + ,(dart-pkg + "dart-style" "1.0.9" + "0wsyb6giffz8w03wqfrlwj88igcnj33gxzfcmpsv8kb5spd2v8pk")))))) + (native-inputs + (alist-replace "dart" `(,dart-2.0.0-dev.20.0) + (package-native-inputs dart-2.0.0-dev.20.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0012-gnu-Add-dart-2.0.0-dev.54.0.patch >From 27df6925cc1c6200cdaf7517767f5cc775627331 Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 12:26:29 +0100 Subject: [PATCH 12/20] gnu: Add dart-2.0.0-dev.54.0. * gnu/packages/dart.scm (dart-2.0.0-dev.54.0): New variable. --- gnu/packages/dart.scm | 97 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index f60e0b6a8a..826f4f0f96 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -666,3 +666,100 @@ (native-inputs (alist-replace "dart" `(,dart-2.0.0-dev.20.0) (package-native-inputs dart-2.0.0-dev.20.0))))) + +(define-public dart-2.0.0-dev.54.0 + (package + (inherit dart-2.0.0-dev.36.0) + ;; This version adds FileMode, required to build 2.0 + (version "2.0.0-dev.54.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "05m64i6wa9nk3x3dby5yp06aqyl2pd7sk8sm1wiaijbish1q5drc")))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.0.0-dev.36.0) + ((#:phases phases) + `(modify-phases ,phases + (replace 'set-dart-path + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "tools/utils.py" + (("os.path.join\\(CheckedInSdkPath\\(\\), 'bin', name)") + (string-append "os.path.join(\"" + (assoc-ref %build-inputs "dart") + "/bin/\", name)"))))))))) + (inputs + (replace-inputs + dart-2.0.0-dev.36.0 + `(("dart-pkg-args" + ,(dart-pkg "args" "1.4.1" + "0ylasxd8v0q80pz0h518yxhbdklabbly1g4n81v8w19vlk2nd8aj")) + ("dart-pkg-async" + ,(dart-pkg "async" "2.0.6" + "1zibp9hiys9f0y3lpxhbbpg2q824jc7x5gcqdicxpylv7smmcdd5")) + ("dart-pkg-barback" + ,(dart-pkg "barback" "0.15.2+14" + "17v6l3z3dm4indr1z787mcdgirsz0y34yccsnfs8yf0yb9mbhqk4")) + ("dart-pkg-collection" + ,(dart-pkg "collection" "1.14.6" + "1majrhazk0ccrrnhxa1pji803r5yywv0a2bmhp5n6sk0a89ps7v7")) + ("dart-pkg-dart2js-info" + ,(dart-pkg "dart2js-info" "0.5.6+2" + "1k5kylr1805gdsbkvwv8fsh0vv5znikgrd2p2m7mvywlzaaaw5v3")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.19.0" + "0x95pwvw1b5dwix65rizz15ri2kblw7z6jnq3qb0b9s82b46l7sm")) + ("dart-pkg-html" + ,(dart-pkg "html" "0.13.3" + "1d78m0f6jvcam4w47733w94ln01rwq9bbk6l219mg6ppczdsps4n")) + ("dart-pkg-http" + ,(dart-pkg "http" "0.11.3+16" + "1r0gikhy1g2viiic2yfav5xf8xwp21z06blvwmdf4h9fvmj00ac2")) + ("dart-pkg-http-retry" + ,(dart-pkg "http-retry" "0.1.1" + "1pi6f3jm6kzch8nzdjbwzzyc5spiwl2609c6h7kb2zj6cxyjsm9h")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.46" + "03298xfpb1blxh4js2ia73dl077aivfjffdqmy47nilkijwva4cs")) + ("dart-pkg-markdown" + ,(dart-pkg "markdown" "1.1.1" + "1qj7dmwz6dwq7jsvzxa2qw2fcf68m5yhr8xs8mm65c6rlsxz6vm5")) + ("dart-pkg-protobuf" + ,(dart-pkg "protobuf" "0.7.1" + "0fwq06ls5x9q8z2xydd0a00lj8mnkn0zdc365qsdnzj8dkgm3006")) + ("dart-pkg-pub" + ,(dart-pkg "pub" "875d35005a7d33f367d70a3e31e9d3bad5d1ebd8" + "1hb0c9fnyjzd0bz2rmn9ja7ybbwnvyvkmaqh7y1mhg4vk4pzcbmm")) + ("dart-pkg-quiver" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/google/quiver-dart.git") + (commit "5aaa3f58c48608af5b027444d561270b53f15dbf"))) + (sha256 (base32 + "0mv97c2f0z0bb1917bjlb903fjjw794pdbv4vk7kcfg1wzp907vl")))) + ("dart-pkg-scheduled-test" + ,(dart-pkg "scheduled-test" "0.12.11" + "1r631dvq3pwr10kc1wmqvlhx5lc0hx5h2ix9sp462w6yv03ry7rq")) + ("dart-pkg-shelf" + ,(dart-pkg "shelf" "0.7.2" + "1z88dwjlwf88ckg0wi4b9kcn44c4y4mnkdppxv0g1hg6b07jsd3x")) + ("dart-pkg-stack-trace" + ,(dart-pkg "stack-trace" "1.9.2" + "1a2mmjs4c7p6g3pr346hqhfx25d4h1i5vb2np03ydh7pkp19lgmw")) + ("dart-pkg-stream-channel" + ,(dart-pkg "stream-channel" "1.6.4" + "1qj9n0pk7n1zlkdffy70cllqpxkvfqxswr70nw7ycygxm9bsnbwq")) + ("dart-pkg-test-reflective-loader" + ,(dart-pkg "test-reflective-loader" "0.1.4" + "1rkgpsnl9izfy97dbsc4y53kmiin6pyhj5652bw8sl0z2n6za1pp")) + ("dart-pkg-yaml" + ,(dart-pkg "yaml" "2.1.13" + "16xnx7xgm8vsf22dzg6p7zyjax5jad5x4ibky3gqkqh7wavfxhwg"))))) + (native-inputs + (alist-replace "dart" `(,dart-2.0.0-dev.36.0) + (package-native-inputs dart-2.0.0-dev.36.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0013-gnu-Add-dart-2.0.0-dev.65.0.patch >From 1941f930690eacc2e49ab8847cf95d635e3f6439 Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 15:50:58 +0100 Subject: [PATCH 13/20] gnu: Add dart-2.0.0-dev.65.0. * gnu/packages/dart.scm (dart-2.0.0-dev.65.0-bin-only): New variable. * gnu/packages/dart.scm (dart-2.0.0-dev.65.0): New variable. * gnu/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch: New file * gnu/local.mk: Add patch file. The bin-only variant is used to bootstrap the full version. We compile only a subset of the package, enough to build itself in the next step. --- gnu/local.mk | 1 + gnu/packages/dart.scm | 164 + ...art-2.0.0-dev.65-compile-with-dev.54.patch | 2674 +++++++++++++++++ 3 files changed, 2839 insertions(+) create mode 100644 gnu/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch diff --git a/gnu/local.mk b/gnu/local.mk index ee4ade0139..a6c949f574 100644 --- a/gnu/local.mk +++ b/gnu/local.mk @@ -906,6 +906,7 @@ dist_patch_DATA = \ %D%/packages/patches/cvs-CVE-2017-12836.patch \ %D%/packages/patches/cyrus-sasl-ac-try-run-fix.patch \ %D%/packages/patches/dart-2.0.0-dev.8-disable-analytics.patch \ + %D%/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch \ %D%/packages/patches/date-output-pkg-config-files.patch \ %D%/packages/patches/datefudge-gettimeofday.patch \ %D%/packages/patches/dbacl-include-locale.h.patch \ diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 826f4f0f96..052ceb40b2 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -763,3 +763,167 @@ (native-inputs (alist-replace "dart" `(,dart-2.0.0-dev.36.0) (package-native-inputs dart-2.0.0-dev.36.0))))) + +(define-public dart-2.0.0-dev.65.0-bin-only + (package + (inherit dart-2.0.0-dev.54.0) + ;; This version adds FileMode, required to build 2.0 + (version "2.0.0-dev.65.0-bin-only") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "08lvng2ib127d980ib6cflprxzl3figpblras07d5zm1k2fpjzi0")) + (patches + (list (search-patch "dart-2.0.0-dev.65-compile-with-dev.54.patch"))))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.0.0-dev.54.0) + ((#:phases phases) + `(modify-phases ,phases + (add-after 'add-git-revision 'add-git-HEAD + (lambda _ + (mkdir-p ".git/logs") + (with-output-to-file ".git/logs/HEAD" + (lambda () + (display "0"))))) + (add-before 'configure 'patch-dart-action + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "build/dart/dart_action.gni" + ;; FIX: assignment had no effect + (("dfe =") "# dfe =") + (("\"\\$_dart_root/tools/sdks/\\$host_os/.*service.dart.snapshot\"") + "")))) + (add-before 'configure 'no-dart-preview + ;; We are compiling with an older dart version which does not + ;; support this flag + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "utils/application_snapshot.gni" + (("\"--no-preview-dart-2\",") "") + (("\"--no-preview-dart-2\"") "")) + (substitute* "tools/observatory_tool.py" + (("'--no-preview-dart-2'") "")))) + (replace 'build + ;; This build fails, but the product is enough for next build. + ;; TODO: check if we can reduce the output generated by previous + ;; dart version, leading to faster compile times and maybe less + ;; patches to the build system + (lambda* (#:key configure-flags #:allow-other-keys) + (system* "ninja" "-C" "out/Release") + (system* "ninja" "most" "-C" "out/Release"))) + (replace 'install + ;; The build is incomplete, so the path is different from previous + ;; builds + (lambda* (#:key outputs #:allow-other-keys) + (let* ((out (assoc-ref outputs "out")) + (bin (string-append out "/bin/"))) + ;; This should depend on the architecture as before + (copy-recursively "out/Release/dart-sdk/" out) + ;; (mkdir-p bin) + (copy-file "out/Release/dart" + (string-append bin "/dart")) + (copy-file "out/Release/dart_bootstrap" + (string-append bin "/dart_bootstrap"))))))))) + (inputs + (replace-inputs + dart-2.0.0-dev.54.0 + `(("gperftools" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/gperftools/gperftools.git") + (commit "9608fa3bcf8020d35f59fbf70cd3cbe4b015b972"))) + (sha256 (base32 "0amvwrzn5qc0b0jpxpy5g6zkmj97zjh4hhjrd130hsg2lwwcwhy1"))))))) + (native-inputs + (alist-replace "dart" `(,dart-2.0.0-dev.54.0) + (alist-replace "gcc" `(,gcc-7) + (package-native-inputs dart-2.0.0-dev.54.0)))))) + +(define-public dart-2.0.0-dev.65.0 + (package + (inherit dart-2.0.0-dev.54.0) + ;; This version adds FileMode, required to build 2.0 + (version "2.0.0-dev.65.0") + (source + ;; FIXME: Inherit + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "08lvng2ib127d980ib6cflprxzl3figpblras07d5zm1k2fpjzi0")))) + (arguments + ;; Inheriting from the previous, as we don't want the patched phases + (substitute-keyword-arguments (package-arguments dart-2.0.0-dev.54.0) + ((#:phases phases) + `(modify-phases ,phases + (delete 'no-dart-preview) + (add-before 'configure 'disable-observatory-tool + (lambda _ + (substitute* "tools/observatory_tool.py" + (("sys.exit\\(main\\(\\)\\)") "sys.exit(0)")))) + (add-after 'add-git-revision 'add-git-HEAD + (lambda _ + (mkdir-p ".git/logs") + (with-output-to-file ".git/logs/HEAD" + (lambda () + (display "0"))))) + (add-before 'configure 'patch-dart-action + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "build/dart/dart_action.gni" + ;; FIX: assignment had no effect + (("dfe =") "# dfe =") + (("\"\\$_dart_root/tools/sdks/\\$host_os/.*service.dart.snapshot\"") + "")))))))) + (inputs + (replace-inputs + dart-2.0.0-dev.65.0-bin-only + `(("observatory-pub-packages" + ,(dart-pkg "observatory-pub-packages" + "caf0aecfb15077fc7a34d48e9df13606c793fddf" + "0c8y33sfp3q1v0f9dgf5x4vz1yz52q9zhqqkv74dyal7pj4q4rzd")) + ("dart-pkgtested-dart-style" + ,(dart-pkg "dart-style" "1.0.12" + "1fniyq6h1x12ib2aza1fklcp2vg2knljihw3dpng9k196dny26k3")) + ("dart-pkgtested-package-config" + ,(dart-pkg "package-config" "1.0.3" + "03w67nb1dhi2yqb63z1301p88hjws1d8azmw8m5ap4zapqdbhzgn")) + ("dart-pkg-async" + ,(dart-pkg "async" "2.0.7" + "1m1izf333jnl740j4nvp7iaqljgyhxrfxn6w0z6jjjl1pn3brhb8")) + ("dart-pkg-collection" + ,(dart-pkg "collection" "1.14.10" + "1h1n7q345lbcv0lfbxmcy0ncwvr8zzr3p4154k7l7dyqflvnij18")) + ("dart-pkg-crypto" + ,(dart-pkg "crypto" "2.0.5" + "1s9nhybnkkq363722fdpignm14asw8pyasryz5mkxd1bhh3v44fm")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.20.1" + "0i860pjq09dl1y20axjw2my2cnkq3jarfiqg9qb7dqs9l6apfcs0")) + ("dart-pkg-http-throttle" + ,(dart-pkg "http-throttle" "1.0.2" + "0irc3gx7gwv9xwychsd49j8v6r8na4k7lv8vz4008qp2sf90b5fa")) + ("dart-pkg-mustache4dart" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/valotas/mustache4dart.git") + (commit "v2.1.2"))) + (sha256 (base32 "0gww2g03ybfg3ffn2jz3f6351sqhaqvjfslng6w3l67s4gm3p3y6")))) + ("dart-pkg-pub" + ,(dart-pkg "pub" "2258022cb7fd6ec43900d3b88012efb268020019" + "0f1nj564mps7mzmpbyj7h4za8cv5d3wsck97262yzk9wz9wl4sls")) + ("dart-pkg-pub-semver" + ,(dart-pkg "pub-semver" "1.4.1" + "0sql7q00ydpxcgnscgjrg7mlykjwp0s77v3ik8lj1fdr86iqsiix")) + ("dart-pkg-shelf-web-socket" + ,(dart-pkg "shelf-web-socket" "0.2.2" + "0p36dkx4picaf7lxcysjm8wfz0x3s55i5j3dj6d36y9avvgjq5fr"))))) + (native-inputs + (alist-replace "dart" `(,dart-2.0.0-dev.65.0-bin-only) + (package-native-inputs dart-2.0.0-dev.65.0-bin-only))))) diff --git a/gnu/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch b/gnu/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch new file mode 100644 index 0000000000..88fa42171c --- /dev/null +++ b/gnu/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch @@ -0,0 +1,2674 @@ +From 989da057a7b68bd9edcc72b6c15473df71490339 Mon Sep 17 00:00:00 2001 +From: nixo +Date: Sat, 21 Nov 2020 21:29:19 +0100 +Subject: [PATCH] Make it compile with older dart version + +--- + build/config/compiler/BUILD.gn | 6 +- + build/config/gcc/BUILD.gn | 2 +- + build/dart/dart_action.gni | 6 +- + .../lib/src/analyzer/code_generator.dart | 64 +++---- + .../lib/src/analyzer/property_model.dart | 18 +- + .../lib/src/analyzer/type_utilities.dart | 4 +- + .../lib/src/compiler/js_metalet.dart | 8 +- + .../lib/src/compiler/js_names.dart | 2 +- + .../lib/src/compiler/module_builder.dart | 14 +- + .../lib/src/compiler/shared_compiler.dart | 10 +- + pkg/dev_compiler/lib/src/js_ast/builder.dart | 158 +++++++++--------- + pkg/dev_compiler/lib/src/js_ast/nodes.dart | 16 +- + pkg/dev_compiler/lib/src/js_ast/printer.dart | 14 +- + pkg/dev_compiler/lib/src/js_ast/template.dart | 118 ++++++------- + pkg/dev_compiler/lib/src/kernel/compiler.dart | 122 +++++++------- + .../lib/src/kernel/constants.dart | 12 +- + .../lib/src/kernel/native_types.dart | 6 +- + .../lib/src/kernel/nullable_inference.dart | 8 +- + .../lib/src/kernel/property_model.dart | 10 +- + pkg/dev_compiler/lib/src/kernel/target.dart | 20 +-- + .../lib/src/kernel/type_table.dart | 4 +- + pkg/dev_compiler/tool/kernel_sdk.dart | 16 +- + pkg/dev_compiler/tool/patch_sdk.dart | 36 ++-- + pkg/front_end/tool/fasta | 2 +- + pkg/js_ast/lib/src/builder.dart | 2 +- + runtime/BUILD.gn | 6 +- + sdk/BUILD.gn | 68 ++++---- + tools/observatory_tool.py | 2 +- + utils/application_snapshot.gni | 6 +- + utils/dartdevc/BUILD.gn | 8 +- + 30 files changed, 385 insertions(+), 383 deletions(-) + +diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn +index 8154e4e9a2..ec56ca353e 100644 +--- a/build/config/compiler/BUILD.gn ++++ b/build/config/compiler/BUILD.gn +@@ -578,9 +578,9 @@ config("chromium_code") { + cflags = [] + } else { + cflags = [ +- "-Wall", +- "-Wextra", +- "-Werror", ++ # "-Wall", ++ # "-Wextra", ++ # -Werror, + ] + + defines = [] +diff --git a/build/config/gcc/BUILD.gn b/build/config/gcc/BUILD.gn +index 110f1cceb5..93517f0496 100644 +--- a/build/config/gcc/BUILD.gn ++++ b/build/config/gcc/BUILD.gn +@@ -35,7 +35,7 @@ config("executable_ldconfig") { + + # Newer binutils don't set DT_RPATH unless you disable "new" dtags + # and the new DT_RUNPATH doesn't work without --no-as-needed flag. +- "-Wl,--disable-new-dtags", ++ "-Wl,--enable-new-dtags", + ] + } + } +diff --git a/build/dart/dart_action.gni b/build/dart/dart_action.gni +index 91f5e293f8..f7e81ac593 100644 +--- a/build/dart/dart_action.gni ++++ b/build/dart/dart_action.gni +@@ -224,12 +224,12 @@ template("prebuilt_dart_action") { + forward_variables_from(invoker, "*") + if (_is_fuchsia) { + binary = prebuilt_dart +- dfe = "$prebuilt_dart_sdk/bin/snapshots/kernel-service.dart.snapshot" ++ # dfe = "$prebuilt_dart_sdk/bin/snapshots/kernel-service.dart.snapshot" + } else { + binary = + "$_dart_root/tools/sdks/$host_os/dart-sdk/bin/dart$executable_suffix" +- dfe = +- "$_dart_root/tools/sdks/$host_os/dart-sdk/bin/snapshots/kernel-service.dart.snapshot" ++ # dfe = ++ # "$_dart_root/tools/sdks/$host_os/dart-sdk/bin/snapshots/kernel-service.dart.snapshot" + } + target = "$_dart_root/runtime/bin:dart_bootstrap" + } +diff --git a/pkg/dev_compiler/lib/src/analyzer/code_generator.dart b/pkg/dev_compiler/lib/src/analyzer/code_generator.dart +index fdda18f780..6b545ef850 100644 +--- a/pkg/dev_compiler/lib/src/analyzer/code_generator.dart ++++ b/pkg/dev_compiler/lib/src/analyzer/code_generator.dart +@@ -91,10 +91,10 @@ class CodeGenerator extends Object + /// + /// We sometimes special case codegen for a single library, as it simplifies + /// name scoping requirements. +- final _libraries = Map(); ++ final _libraries = new Map(); + + /// Imported libraries, and the temporaries used to refer to them. +- final _imports = Map(); ++ final _imports = new Map(); + + /// The list of dart:_runtime SDK functions; these are assumed by other code + /// in the SDK to be generated before anything else. +@@ -118,10 +118,10 @@ class CodeGenerator extends Object + /// In an async* function, this represents the stream controller parameter. + JS.TemporaryId _asyncStarController; + +- final _initializingFormalTemps = HashMap(); ++ final _initializingFormalTemps = new HashMap(); + + JS.Identifier _extensionSymbolsModule; +- final _extensionSymbols = Map(); ++ final _extensionSymbols = new Map(); + + /// The type provider from the current Analysis [context]. + final TypeProvider types; +@@ -200,9 +200,9 @@ class CodeGenerator extends Object + + /// Information about virtual fields for all libraries in the current build + /// unit. +- final virtualFields = VirtualFieldModel(); ++ final virtualFields = new VirtualFieldModel(); + +- final _usedCovariantPrivateMembers = HashSet(); ++ final _usedCovariantPrivateMembers = new HashSet(); + + CodeGenerator( + AnalysisContext c, this.summaryData, this.options, this._extensionTypes) +@@ -326,8 +326,8 @@ class CodeGenerator extends Object + _extensionSymbolsModule = JS.Identifier('dartx'); + } else { + // Otherwise allow these to be renamed so users can write them. +- runtimeModule = JS.TemporaryId('dart'); +- _extensionSymbolsModule = JS.TemporaryId('dartx'); ++ runtimeModule = new JS.TemporaryId('dart'); ++ _extensionSymbolsModule = new JS.TemporaryId('dartx'); + } + _typeTable = TypeTable(runtimeModule); + +@@ -1147,7 +1147,7 @@ class CodeGenerator extends Object + if (isClassSymbol == null) { + // TODO(jmesserly): we could export these symbols, if we want to mark + // implemented interfaces for user-defined classes. +- var id = JS.TemporaryId("_is_${classElem.name}_default"); ++ var id = new JS.TemporaryId("_is_${classElem.name}_default"); + moduleItems.add( + js.statement('const # = Symbol(#);', [id, js.string(id.name, "'")])); + isClassSymbol = id; +@@ -1250,7 +1250,7 @@ class CodeGenerator extends Object + .toStatement(); + } + var classExpr = JS.ClassExpression( +- JS.TemporaryId(classElem.name), heritage, methods, ++ new JS.TemporaryId(classElem.name), heritage, methods, + typeParams: typeParams, fields: jsFields); + return js.statement('# = #;', [className, classExpr]); + } +@@ -1378,8 +1378,8 @@ class CodeGenerator extends Object + // mixinMembers(C, class C$ extends M { }); + mixinBody.add(runtimeStatement('mixinMembers(#, #)', [ + classExpr, +- JS.ClassExpression( +- JS.TemporaryId(classElem.name), mixinClass, methods) ++ new JS.ClassExpression( ++ new JS.TemporaryId(classElem.name), mixinClass, methods) + ])); + } + +@@ -1391,10 +1391,10 @@ class CodeGenerator extends Object + var m = classElem.mixins[i]; + + var mixinString = classElem.supertype.name + '_' + m.name; +- var mixinClassName = JS.TemporaryId(mixinString); +- var mixinId = JS.TemporaryId(mixinString + '\$'); ++ var mixinClassName = new JS.TemporaryId(mixinString); ++ var mixinId = new JS.TemporaryId(mixinString + '\$'); + var mixinClassExpression = +- JS.ClassExpression(mixinClassName, baseClass, []); ++ new JS.ClassExpression(mixinClassName, baseClass, []); + // Bind the mixin class to a name to workaround a V8 bug with es6 classes + // and anonymous function names. + // TODO(leafp:) Eliminate this once the bug is fixed: +@@ -1447,10 +1447,10 @@ class CodeGenerator extends Object + + // Generate setter + if (!decl.isFinal) { +- var value = JS.TemporaryId('value'); +- fn = JS.Fun([value], js.block('{ this.# = #; }', [name, value])); ++ var value = new JS.TemporaryId('value'); ++ fn = new JS.Fun([value], js.block('{ this.# = #; }', [name, value])); + method = +- JS.Method(_declareMemberName(field.setter), fn, isSetter: true); ++ new JS.Method(_declareMemberName(field.setter), fn, isSetter: true); + jsMethods.add(method); + } + } +@@ -2864,8 +2864,8 @@ class CodeGenerator extends Object + var name = element.name; + JS.Expression gen = genFn; + if (name.isNotEmpty) { +- gen = JS.NamedFunction( +- JS.TemporaryId(JS.friendlyNameForDartOperator[name] ?? name), ++ gen = new JS.NamedFunction( ++ new JS.TemporaryId(JS.friendlyNameForDartOperator[name] ?? name), + genFn); + } + gen.sourceInformation = _functionEnd(body); +@@ -2916,7 +2916,7 @@ class CodeGenerator extends Object + // `await` is generated as `yield`. + // + // _AsyncStarImpl has an example of the generated code. +- var asyncStarParam = JS.TemporaryId('stream'); ++ var asyncStarParam = new JS.TemporaryId('stream'); + var gen = emitGeneratorFn([asyncStarParam], asyncStarParam); + + var asyncStarImpl = asyncStarImplType.instantiate([returnType]); +@@ -3132,11 +3132,11 @@ class CodeGenerator extends Object + /// The renamer would handle this, but it would prefer to rename the + /// temporary used for the private symbol. Instead rename the parameter. + return _initializingFormalTemps.putIfAbsent( +- element, () => JS.TemporaryId(element.name.substring(1))); ++ element, () => new JS.TemporaryId(element.name.substring(1))); + } + + var type = declaration ? emitTypeRef(element.type) : null; +- return JS.Identifier(element.name, type: type); ++ return new JS.Identifier(element.name, type: type); + } + + List _parameterMetadata(FormalParameter p) => +@@ -3699,7 +3699,7 @@ class CodeGenerator extends Object + ? 'function(x) { super[#] = x; }' + : 'function() { return super[#]; }', + [jsName]); +- return JS.Method(JS.TemporaryId(member.variable.name), fn, ++ return new JS.Method(new JS.TemporaryId(member.variable.name), fn, + isGetter: !isSetter, isSetter: isSetter); + } else { + var method = member as MethodElement; +@@ -3710,17 +3710,17 @@ class CodeGenerator extends Object + params.add(namedArgumentTemp); + break; + } +- params.add(JS.Identifier(param.name)); ++ params.add(new JS.Identifier(param.name)); + } + + var fn = js.fun( + 'function(#) { return super[#](#); }', [params, jsName, params]); + var name = method.name; + name = JS.friendlyNameForDartOperator[name] ?? name; +- return JS.Method(JS.TemporaryId(name), fn); ++ return new JS.Method(new JS.TemporaryId(name), fn); + } + }); +- return JS.PropertyAccess(JS.This(), jsMethod.name); ++ return new JS.PropertyAccess(new JS.This(), jsMethod.name); + } + + JS.Expression _emitMethodCall(Expression target, MethodInvocation node) { +@@ -4900,7 +4900,7 @@ class CodeGenerator extends Object + var id = astFactory + .simpleIdentifier(StringToken(TokenType.IDENTIFIER, name, -1)); + +- variable ??= JS.TemporaryId(name); ++ variable ??= new JS.TemporaryId(name); + + var idElement = TemporaryVariableElement.forNode(id, variable) + ..enclosingElement = _currentElement; +@@ -4925,7 +4925,7 @@ class CodeGenerator extends Object + // params are available. + if (_currentFunction == null || usesTypeParams) return jsExpr; + +- var temp = JS.TemporaryId('const'); ++ var temp = new JS.TemporaryId('const'); + moduleItems.add(js.statement('let #;', [temp])); + return js.call('# || (# = #)', [temp, temp, jsExpr]); + } +@@ -5462,7 +5462,7 @@ class CodeGenerator extends Object + streamIterator.element.unnamedConstructor, + streamIterator, + () => [_visitExpression(node.iterable)]); +- var iter = JS.TemporaryId('iter'); ++ var iter = new JS.TemporaryId('iter'); + var variable = node.identifier ?? node.loopVariable.identifier; + var init = _visitExpression(node.identifier); + if (init == null) { +@@ -6068,7 +6068,7 @@ class CodeGenerator extends Object + JS.TemporaryId _getExtensionSymbolInternal(String name) { + return _extensionSymbols.putIfAbsent( + name, +- () => JS.TemporaryId( ++ () => new JS.TemporaryId( + '\$${JS.friendlyNameForDartOperator[name] ?? name}')); + } + +@@ -6141,7 +6141,7 @@ class CodeGenerator extends Object + // It's either one of the libraries in this module, or it's an import. + return _libraries[library] ?? + _imports.putIfAbsent(library, +- () => JS.TemporaryId(jsLibraryName(_libraryRoot, library))); ++ () => new JS.TemporaryId(jsLibraryName(_libraryRoot, library))); + } + + T closureAnnotate( +diff --git a/pkg/dev_compiler/lib/src/analyzer/property_model.dart b/pkg/dev_compiler/lib/src/analyzer/property_model.dart +index b625554e1c..2f6b38fc46 100644 +--- a/pkg/dev_compiler/lib/src/analyzer/property_model.dart ++++ b/pkg/dev_compiler/lib/src/analyzer/property_model.dart +@@ -22,11 +22,11 @@ import 'extension_types.dart'; + /// which members are private and thus, could not be overridden outside of the + /// current library. + class VirtualFieldModel { +- final _modelForLibrary = HashMap(); ++ final _modelForLibrary = new HashMap(); + + _LibraryVirtualFieldModel _getModel(LibraryElement library) => + _modelForLibrary.putIfAbsent( +- library, () => _LibraryVirtualFieldModel.build(library)); ++ library, () => new _LibraryVirtualFieldModel.build(library)); + + /// Returns true if a field is virtual. + bool isVirtual(FieldElement field) => +@@ -41,7 +41,7 @@ class _LibraryVirtualFieldModel { + /// + /// This means we must generate them as virtual fields using a property pair + /// in JavaScript. +- final _overriddenPrivateFields = HashSet(); ++ final _overriddenPrivateFields = new HashSet(); + + /// Private classes that can be extended outside of this library. + /// +@@ -55,7 +55,7 @@ class _LibraryVirtualFieldModel { + /// class C extends _A {} + /// + /// The class _A must treat is "x" as virtual, however _B does not. +- final _extensiblePrivateClasses = HashSet(); ++ final _extensiblePrivateClasses = new HashSet(); + + _LibraryVirtualFieldModel.build(LibraryElement library) { + var allTypes = library.units.expand((u) => u.types).toList(); +@@ -176,18 +176,18 @@ class ClassPropertyModel { + /// The set of inherited getters, used because JS getters/setters are paired, + /// so if we're generating a setter we may need to emit a getter that calls + /// super. +- final inheritedGetters = HashSet(); ++ final inheritedGetters = new HashSet(); + + /// The set of inherited setters, used because JS getters/setters are paired, + /// so if we're generating a getter we may need to emit a setter that calls + /// super. +- final inheritedSetters = HashSet(); ++ final inheritedSetters = new HashSet(); + + final mockMembers = {}; + +- final extensionMethods = Set(); ++ final extensionMethods = new Set(); + +- final extensionAccessors = Set(); ++ final extensionAccessors = new Set(); + + /// Parameters that are covariant due to covariant generics. + final Set covariantParameters; +@@ -245,7 +245,7 @@ class ClassPropertyModel { + covariantParameters != null && + covariantParameters.contains(setter.parameters[0]) && + covariantPrivateMembers.contains(setter)) { +- virtualFields[field] = JS.TemporaryId(name); ++ virtualFields[field] = new JS.TemporaryId(name); + } + } + } +diff --git a/pkg/dev_compiler/lib/src/analyzer/type_utilities.dart b/pkg/dev_compiler/lib/src/analyzer/type_utilities.dart +index f1bef3c158..4695e421a1 100644 +--- a/pkg/dev_compiler/lib/src/analyzer/type_utilities.dart ++++ b/pkg/dev_compiler/lib/src/analyzer/type_utilities.dart +@@ -43,7 +43,7 @@ class _CacheTable { + // Use a LinkedHashMap to maintain key insertion order so the generated code + // is stable under slight perturbation. (If this is not good enough we could + // sort by name to canonicalize order.) +- final _names = LinkedHashMap( ++ final _names = new LinkedHashMap( + equals: typesAreEqual, hashCode: typeHashCode); + Iterable get keys => _names.keys.toList(); + +@@ -109,7 +109,7 @@ class _CacheTable { + /// Heuristically choose a good name for the cache and generator + /// variables. + JS.TemporaryId chooseTypeName(DartType type) { +- return JS.TemporaryId(_typeString(type)); ++ return new JS.TemporaryId(_typeString(type)); + } + } + +diff --git a/pkg/dev_compiler/lib/src/compiler/js_metalet.dart b/pkg/dev_compiler/lib/src/compiler/js_metalet.dart +index 65cfe52ca0..57f143d062 100644 +--- a/pkg/dev_compiler/lib/src/compiler/js_metalet.dart ++++ b/pkg/dev_compiler/lib/src/compiler/js_metalet.dart +@@ -213,9 +213,9 @@ class MetaLet extends Expression { + substitutions[variable] = init; + } else { + // Otherwise replace it with a temp, which will be assigned once. +- var temp = TemporaryId(variable.displayName); ++ var temp = new TemporaryId(variable.displayName); + substitutions[variable] = temp; +- initializers.add(VariableInitialization(temp, init)); ++ initializers.add(new VariableInitialization(temp, init)); + } + }); + +@@ -223,10 +223,10 @@ class MetaLet extends Expression { + node = _substitute(node, substitutions); + if (initializers.isNotEmpty) { + var first = initializers[0]; +- node = Block([ ++ node = new Block([ + initializers.length == 1 + ? first.value.toVariableDeclaration(first.declaration) +- : VariableDeclarationList('let', initializers).toStatement(), ++ : new VariableDeclarationList('let', initializers).toStatement(), + node + ]); + } +diff --git a/pkg/dev_compiler/lib/src/compiler/js_names.dart b/pkg/dev_compiler/lib/src/compiler/js_names.dart +index 7de9cf9293..958eb51e74 100644 +--- a/pkg/dev_compiler/lib/src/compiler/js_names.dart ++++ b/pkg/dev_compiler/lib/src/compiler/js_names.dart +@@ -34,7 +34,7 @@ class MaybeQualifiedId extends Expression { + + /// Helper to create an [Identifier] from something that starts as a property. + static Identifier identifier(LiteralString propertyName) => +- Identifier(propertyName.valueWithoutQuotes); ++ new Identifier(propertyName.valueWithoutQuotes); + + void setQualified(bool qualified) { + var name = this.name; +diff --git a/pkg/dev_compiler/lib/src/compiler/module_builder.dart b/pkg/dev_compiler/lib/src/compiler/module_builder.dart +index a3f41e05a7..88745ae71d 100644 +--- a/pkg/dev_compiler/lib/src/compiler/module_builder.dart ++++ b/pkg/dev_compiler/lib/src/compiler/module_builder.dart +@@ -150,7 +150,7 @@ class LegacyModuleBuilder extends _ModuleBuilder { + visitProgram(module); + + // Build import parameters. +- var exportsVar = TemporaryId('exports'); ++ var exportsVar = new TemporaryId('exports'); + var parameters = [exportsVar]; + var importNames = []; + var importStatements = []; +@@ -158,7 +158,7 @@ class LegacyModuleBuilder extends _ModuleBuilder { + importNames.add(import.from); + // TODO(jmesserly): we could use destructuring here. + var moduleVar = +- TemporaryId(pathToJSIdentifier(import.from.valueWithoutQuotes)); ++ new TemporaryId(pathToJSIdentifier(import.from.valueWithoutQuotes)); + parameters.add(moduleVar); + for (var importName in import.namedImports) { + assert(!importName.isStar); // import * not supported in legacy modules. +@@ -195,8 +195,8 @@ class LegacyModuleBuilder extends _ModuleBuilder { + + var functionName = + 'load__' + pathToJSIdentifier(module.name.replaceAll('.', '_')); +- var resultModule = NamedFunction( +- Identifier(functionName), ++ var resultModule = new NamedFunction( ++ new Identifier(functionName), + js.fun("function(#) { 'use strict'; #; }", [parameters, statements]), + true); + +@@ -224,7 +224,7 @@ class CommonJSModuleBuilder extends _ModuleBuilder { + for (var import in imports) { + // TODO(jmesserly): we could use destructuring here. + var moduleVar = +- TemporaryId(pathToJSIdentifier(import.from.valueWithoutQuotes)); ++ new TemporaryId(pathToJSIdentifier(import.from.valueWithoutQuotes)); + importStatements + .add(js.statement('const # = require(#);', [moduleVar, import.from])); + +@@ -240,7 +240,7 @@ class CommonJSModuleBuilder extends _ModuleBuilder { + statements.insertAll(0, importStatements); + + if (exports.isNotEmpty) { +- var exportsVar = Identifier('exports'); ++ var exportsVar = new Identifier('exports'); + statements.add(js.comment('Exports:')); + for (var export in exports) { + var names = export.exportedNames; +@@ -274,7 +274,7 @@ class AmdModuleBuilder extends _ModuleBuilder { + for (var import in imports) { + // TODO(jmesserly): we could use destructuring once Atom supports it. + var moduleVar = +- TemporaryId(pathToJSIdentifier(import.from.valueWithoutQuotes)); ++ new TemporaryId(pathToJSIdentifier(import.from.valueWithoutQuotes)); + fnParams.add(moduleVar); + dependencies.add(import.from); + +diff --git a/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart b/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart +index f716813f98..fce7213524 100644 +--- a/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart ++++ b/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart +@@ -21,9 +21,9 @@ abstract class SharedCompiler { + final List _operatorSetResultStack = []; + + JS.Identifier runtimeModule; +- final namedArgumentTemp = JS.TemporaryId('opts'); ++ final namedArgumentTemp = new JS.TemporaryId('opts'); + +- final _privateNames = HashMap>(); ++ final _privateNames = new HashMap>(); + + /// The list of output module items, in the order they need to be emitted in. + final moduleItems = []; +@@ -43,7 +43,7 @@ abstract class SharedCompiler { + bool Function() isLastParamMutated) { + if (name == '[]=') { + _operatorSetResultStack.add(isLastParamMutated() +- ? JS.TemporaryId((formals.last as JS.Identifier).name) ++ ? new JS.TemporaryId((formals.last as JS.Identifier).name) + : formals.last); + } else { + _operatorSetResultStack.add(null); +@@ -128,13 +128,13 @@ abstract class SharedCompiler { + } + + JS.TemporaryId emitPrivateNameSymbol(Library library, String name) { +- return _privateNames.putIfAbsent(library, () => HashMap()).putIfAbsent(name, ++ return _privateNames.putIfAbsent(library, () => new HashMap()).putIfAbsent(name, + () { + var idName = name; + if (idName.endsWith('=')) { + idName = idName.replaceAll('=', '_'); + } +- var id = JS.TemporaryId(idName); ++ var id = new JS.TemporaryId(idName); + moduleItems.add( + js.statement('const # = Symbol(#);', [id, js.string(name, "'")])); + return id; +diff --git a/pkg/dev_compiler/lib/src/js_ast/builder.dart b/pkg/dev_compiler/lib/src/js_ast/builder.dart +index 117f447785..052fb15d66 100644 +--- a/pkg/dev_compiler/lib/src/js_ast/builder.dart ++++ b/pkg/dev_compiler/lib/src/js_ast/builder.dart +@@ -15,7 +15,7 @@ part of js_ast; + * TODO(sra): Find the remaining places where js('xxx') used to parse an + * unbounded number of expression, or institute a cache policy. + */ +-TemplateManager templateManager = TemplateManager(); ++TemplateManager templateManager = new TemplateManager(); + + /** + +@@ -188,7 +188,7 @@ What is not implemented: + var # = 1; + + */ +-const JsBuilder js = JsBuilder(); ++JsBuilder js = new JsBuilder(); + + class JsBuilder { + const JsBuilder(); +@@ -307,7 +307,7 @@ class JsBuilder { + // > closing quote code points, U+005C (REVERSE SOLIDUS), + // > U+000D (CARRIAGE RETURN), U+2028 (LINE SEPARATOR), + // > U+2029 (PARAGRAPH SEPARATOR), and U+000A (LINE FEED). +- var re = RegExp('[\n\r$quoteReplace\b\f\t\v\u2028\u2029]'); ++ var re = new RegExp('[\n\r$quoteReplace\b\f\t\v\u2028\u2029]'); + escaped = escaped.replaceAllMapped(re, (m) { + switch (m.group(0)) { + case "\n": +@@ -412,7 +412,7 @@ class MiniJsParserError { + + // Replace non-tabs with spaces, giving a print indent that matches the text + // for tabbing. +- String spaces = prefix.replaceAll(RegExp(r'[^\t]'), ' '); ++ String spaces = prefix.replaceAll(new RegExp(r'[^\t]'), ' '); + return 'Error in MiniJsParser:\n${src}\n$spaces^\n$spaces$message\n'; + } + } +@@ -822,28 +822,28 @@ class MiniJsParser { + String last = lastToken; + if (acceptCategory(ALPHA)) { + if (last == "true") { +- return LiteralBool(true); ++ return new LiteralBool(true); + } else if (last == "false") { +- return LiteralBool(false); ++ return new LiteralBool(false); + } else if (last == "null") { +- return LiteralNull(); ++ return new LiteralNull(); + } else if (last == "function") { + return parseFunctionExpression(); + } else if (last == "this") { +- return This(); ++ return new This(); + } else if (last == "super") { +- return Super(); ++ return new Super(); + } else if (last == "class") { + return parseClass(); + } else { +- return Identifier(last); ++ return new Identifier(last); + } + } else if (acceptCategory(LPAREN)) { + return parseExpressionOrArrowFunction(); + } else if (acceptCategory(STRING)) { +- return LiteralString(last); ++ return new LiteralString(last); + } else if (acceptCategory(NUMERIC)) { +- return LiteralNumber(last); ++ return new LiteralNumber(last); + } else if (acceptCategory(LBRACE)) { + return parseObjectInitializer(); + } else if (acceptCategory(LSQUARE)) { +@@ -851,7 +851,7 @@ class MiniJsParser { + + while (true) { + if (acceptCategory(COMMA)) { +- values.add(ArrayHole()); ++ values.add(new ArrayHole()); + continue; + } + if (acceptCategory(RSQUARE)) break; +@@ -865,7 +865,7 @@ class MiniJsParser { + getToken(); + String flags = lastToken; + if (!acceptCategory(ALPHA)) flags = ""; +- Expression expression = RegExpLiteral(regexp + flags); ++ Expression expression = new RegExpLiteral(regexp + flags); + return expression; + } else if (acceptCategory(HASH)) { + return parseInterpolatedExpression(); +@@ -876,13 +876,13 @@ class MiniJsParser { + } + + InterpolatedExpression parseInterpolatedExpression() { +- var expression = InterpolatedExpression(parseHash()); ++ var expression = new InterpolatedExpression(parseHash()); + interpolatedValues.add(expression); + return expression; + } + + InterpolatedIdentifier parseInterpolatedIdentifier() { +- var id = InterpolatedIdentifier(parseHash()); ++ var id = new InterpolatedIdentifier(parseHash()); + interpolatedValues.add(id); + return id; + } +@@ -891,7 +891,7 @@ class MiniJsParser { + if (acceptCategory(HASH)) { + return parseInterpolatedIdentifier(); + } else { +- var id = Identifier(lastToken); ++ var id = new Identifier(lastToken); + expectCategory(ALPHA); + return id; + } +@@ -920,13 +920,13 @@ class MiniJsParser { + if (acceptCategory(ELLIPSIS)) { + var params = []; + _expressionToParameterList(expression, params); +- params.add(RestParameter(parseParameter())); ++ params.add(new RestParameter(parseParameter())); + expectCategory(RPAREN); + expectCategory(ARROW); + return parseArrowFunctionBody(params); + } + Expression right = parseAssignment(); +- expression = Binary(',', expression, right); ++ expression = new Binary(',', expression, right); + } + expectCategory(RPAREN); + if (acceptCategory(ARROW)) { +@@ -952,7 +952,7 @@ class MiniJsParser { + _expressionToParameterList(node.left, params); + _expressionToParameterList(node.right, params); + } else if (node is InterpolatedExpression) { +- params.add(InterpolatedParameter(node.nameOrPosition)); ++ params.add(new InterpolatedParameter(node.nameOrPosition)); + } else { + error("Expected arrow function parameter list"); + } +@@ -965,14 +965,14 @@ class MiniJsParser { + } else { + body = parseAssignment(); + } +- return ArrowFun(params, body); ++ return new ArrowFun(params, body); + } + + Expression parseFunctionExpression() { + String last = lastToken; + if (acceptCategory(ALPHA)) { + String functionName = last; +- return NamedFunction(Identifier(functionName), parseFun()); ++ return new NamedFunction(new Identifier(functionName), parseFun()); + } + return parseFun(); + } +@@ -984,7 +984,7 @@ class MiniJsParser { + if (!acceptCategory(RPAREN)) { + for (;;) { + if (acceptCategory(ELLIPSIS)) { +- params.add(RestParameter(parseParameter())); ++ params.add(new RestParameter(parseParameter())); + expectCategory(RPAREN); + break; + } +@@ -1018,14 +1018,14 @@ class MiniJsParser { + Identifier parseParameter() { + if (acceptCategory(HASH)) { + var nameOrPosition = parseHash(); +- var parameter = InterpolatedParameter(nameOrPosition); ++ var parameter = new InterpolatedParameter(nameOrPosition); + interpolatedValues.add(parameter); + return parameter; + } else { + // TODO(jmesserly): validate this is not a keyword + String argumentName = lastToken; + expectCategory(ALPHA); +- return Identifier(argumentName); ++ return new Identifier(argumentName); + } + } + +@@ -1043,7 +1043,7 @@ class MiniJsParser { + if (acceptCategory(RBRACE)) break; + expectCategory(COMMA); + } +- return ObjectInitializer(properties); ++ return new ObjectInitializer(properties); + } + + Expression parseMember() { +@@ -1054,7 +1054,7 @@ class MiniJsParser { + } else if (acceptCategory(LSQUARE)) { + Expression inBraces = parseExpression(); + expectCategory(RSQUARE); +- receiver = PropertyAccess(receiver, inBraces); ++ receiver = new PropertyAccess(receiver, inBraces); + } else { + break; + } +@@ -1071,7 +1071,7 @@ class MiniJsParser { + if (!acceptCategory(RPAREN)) { + while (true) { + if (acceptCategory(ELLIPSIS)) { +- arguments.add(Spread(parseAssignment())); ++ arguments.add(new Spread(parseAssignment())); + expectCategory(RPAREN); + break; + } +@@ -1081,12 +1081,12 @@ class MiniJsParser { + } + } + receiver = +- constructor ? New(receiver, arguments) : Call(receiver, arguments); ++ constructor ? new New(receiver, arguments) : new Call(receiver, arguments); + constructor = false; + } else if (!constructor && acceptCategory(LSQUARE)) { + Expression inBraces = parseExpression(); + expectCategory(RSQUARE); +- receiver = PropertyAccess(receiver, inBraces); ++ receiver = new PropertyAccess(receiver, inBraces); + } else if (!constructor && acceptCategory(DOT)) { + receiver = getDotRhs(receiver); + } else { +@@ -1101,9 +1101,9 @@ class MiniJsParser { + Expression getDotRhs(Expression receiver) { + if (acceptCategory(HASH)) { + var nameOrPosition = parseHash(); +- InterpolatedSelector property = InterpolatedSelector(nameOrPosition); ++ InterpolatedSelector property = new InterpolatedSelector(nameOrPosition); + interpolatedValues.add(property); +- return PropertyAccess(receiver, property); ++ return new PropertyAccess(receiver, property); + } + String identifier = lastToken; + // In ES5 keywords like delete and continue are allowed as property +@@ -1139,8 +1139,8 @@ class MiniJsParser { + if (lastCategory == SYMBOL && + UNARY_OPERATORS.contains(operator) && + (acceptString("++") || acceptString("--") || acceptString('await'))) { +- if (operator == "await") return Await(parsePostfix()); +- return Prefix(operator, parsePostfix()); ++ if (operator == "await") return new Await(parsePostfix()); ++ return new Prefix(operator, parsePostfix()); + } + return parsePostfix(); + } +@@ -1152,8 +1152,8 @@ class MiniJsParser { + operator != "++" && + operator != "--") { + expectCategory(SYMBOL); +- if (operator == "await") return Await(parsePostfix()); +- return Prefix(operator, parseUnaryLow()); ++ if (operator == "await") return new Await(parsePostfix()); ++ return new Prefix(operator, parseUnaryLow()); + } + return parseUnaryHigh(); + } +@@ -1172,17 +1172,17 @@ class MiniJsParser { + } + expectCategory(SYMBOL); + if (rhs == null || BINARY_PRECEDENCE[symbol] >= minPrecedence) { +- if (rhs != null) lhs = Binary(lastSymbol, lhs, rhs); ++ if (rhs != null) lhs = new Binary(lastSymbol, lhs, rhs); + minPrecedence = BINARY_PRECEDENCE[symbol]; + rhs = parseUnaryLow(); + lastSymbol = symbol; + } else { + Expression higher = parseBinary(BINARY_PRECEDENCE[symbol]); +- rhs = Binary(symbol, rhs, higher); ++ rhs = new Binary(symbol, rhs, higher); + } + } + if (rhs == null) return lhs; +- return Binary(lastSymbol, lhs, rhs); ++ return new Binary(lastSymbol, lhs, rhs); + } + + Expression parseConditional() { +@@ -1191,7 +1191,7 @@ class MiniJsParser { + Expression ifTrue = parseAssignment(); + expectCategory(COLON); + Expression ifFalse = parseAssignment(); +- return Conditional(lhs, ifTrue, ifFalse); ++ return new Conditional(lhs, ifTrue, ifFalse); + } + + Expression parseLeftHandSide() => parseConditional(); +@@ -1202,7 +1202,7 @@ class MiniJsParser { + if (acceptCategory(ASSIGNMENT)) { + Expression rhs = parseAssignment(); + if (assignmentOperator == "=") { +- return Assignment(lhs, rhs); ++ return new Assignment(lhs, rhs); + } else { + // Handle +=, -=, etc. + String operator = +@@ -1217,7 +1217,7 @@ class MiniJsParser { + Expression expression = parseAssignment(); + while (acceptCategory(COMMA)) { + Expression right = parseAssignment(); +- expression = Binary(',', expression, right); ++ expression = new Binary(',', expression, right); + } + return expression; + } +@@ -1230,17 +1230,17 @@ class MiniJsParser { + do { + VariableBinding declarator; + if (firstIdentifier != null) { +- declarator = Identifier(firstIdentifier); ++ declarator = new Identifier(firstIdentifier); + firstIdentifier = null; + } else { + declarator = parseVariableBinding(); + } + + var initializer = acceptString("=") ? parseAssignment() : null; +- initialization.add(VariableInitialization(declarator, initializer)); ++ initialization.add(new VariableInitialization(declarator, initializer)); + } while (acceptCategory(COMMA)); + +- return VariableDeclarationList(keyword, initialization); ++ return new VariableDeclarationList(keyword, initialization); + } + + VariableBinding parseVariableBinding() { +@@ -1291,12 +1291,12 @@ class MiniJsParser { + if (acceptString("=")) { + defaultValue = parseExpression(); + } +- variables.add(DestructuredVariable( ++ variables.add(new DestructuredVariable( + name: name, structure: structure, defaultValue: defaultValue)); + } while (acceptCategory(COMMA)); + + expectCategory(RSQUARE); +- return ArrayBindingPattern(variables); ++ return new ArrayBindingPattern(variables); + } + + ObjectBindingPattern parseObjectBindingPattern() { +@@ -1311,12 +1311,12 @@ class MiniJsParser { + } else if (acceptString("=")) { + defaultValue = parseExpression(); + } +- variables.add(DestructuredVariable( ++ variables.add(new DestructuredVariable( + name: name, structure: structure, defaultValue: defaultValue)); + } while (acceptCategory(COMMA)); + + expectCategory(RBRACE); +- return ObjectBindingPattern(variables); ++ return new ObjectBindingPattern(variables); + } + + Expression parseVarDeclarationOrExpression() { +@@ -1360,13 +1360,13 @@ class MiniJsParser { + Statement statement = parseStatement(); + statements.add(statement); + } +- return Block(statements); ++ return new Block(statements); + } + + Statement parseStatement() { + if (acceptCategory(LBRACE)) return parseBlock(); + +- if (acceptCategory(SEMICOLON)) return EmptyStatement(); ++ if (acceptCategory(SEMICOLON)) return new EmptyStatement(); + + if (lastCategory == ALPHA) { + if (acceptString('return')) return parseReturn(); +@@ -1374,16 +1374,16 @@ class MiniJsParser { + if (acceptString('throw')) return parseThrow(); + + if (acceptString('break')) { +- return parseBreakOrContinue((label) => Break(label)); ++ return parseBreakOrContinue((label) => new Break(label)); + } + + if (acceptString('continue')) { +- return parseBreakOrContinue((label) => Continue(label)); ++ return parseBreakOrContinue((label) => new Continue(label)); + } + + if (acceptString('debugger')) { + expectSemicolon(); +- return DebuggerStatement(); ++ return new DebuggerStatement(); + } + + if (acceptString('if')) return parseIfThenElse(); +@@ -1392,7 +1392,7 @@ class MiniJsParser { + + if (acceptString('function')) return parseFunctionDeclaration(); + +- if (acceptString('class')) return ClassDeclaration(parseClass()); ++ if (acceptString('class')) return new ClassDeclaration(parseClass()); + + if (acceptString('try')) return parseTry(); + +@@ -1425,7 +1425,7 @@ class MiniJsParser { + Expression expression = parseExpression(); + + if (expression is Identifier && acceptCategory(COLON)) { +- return LabeledStatement(expression.name, parseStatement()); ++ return new LabeledStatement(expression.name, parseStatement()); + } + + expectSemicolon(); +@@ -1436,17 +1436,17 @@ class MiniJsParser { + if (expression is InterpolatedExpression) { + assert(identical(interpolatedValues.last, expression)); + InterpolatedStatement statement = +- InterpolatedStatement(expression.nameOrPosition); ++ new InterpolatedStatement(expression.nameOrPosition); + interpolatedValues[interpolatedValues.length - 1] = statement; + return statement; + } + } + +- return ExpressionStatement(expression); ++ return new ExpressionStatement(expression); + } + + Statement parseReturn() { +- if (acceptSemicolon()) return Return(); ++ if (acceptSemicolon()) return new Return(); + Expression expression = parseExpression(); + expectSemicolon(); + return Return(expression); +@@ -1456,14 +1456,14 @@ class MiniJsParser { + bool hasStar = acceptString('*'); + Expression expression = parseExpression(); + expectSemicolon(); +- return DartYield(expression, hasStar); ++ return new DartYield(expression, hasStar); + } + + Statement parseThrow() { + if (skippedNewline) error('throw expression must be on same line'); + Expression expression = parseExpression(); + expectSemicolon(); +- return Throw(expression); ++ return new Throw(expression); + } + + Statement parseBreakOrContinue(Statement Function(String) constructor) { +@@ -1484,7 +1484,7 @@ class MiniJsParser { + if (acceptString('else')) { + // Resolves dangling else by binding 'else' to closest 'if'. + Statement elseStatement = parseStatement(); +- return If(condition, thenStatement, elseStatement); ++ return new If(condition, thenStatement, elseStatement); + } else { + return If.noElse(condition, thenStatement); + } +@@ -1551,15 +1551,15 @@ class MiniJsParser { + + static VariableDeclarationList _createVariableDeclarationList( + String keyword, String identifier) { +- return VariableDeclarationList( +- keyword, [VariableInitialization(Identifier(identifier), null)]); ++ return new VariableDeclarationList( ++ keyword, [new VariableInitialization(new Identifier(identifier), null)]); + } + + Statement parseFunctionDeclaration() { + String name = lastToken; + expectCategory(ALPHA); + var fun = parseFun(); +- return FunctionDeclaration(Identifier(name), fun); ++ return new FunctionDeclaration(new Identifier(name), fun); + } + + Statement parseTry() { +@@ -1574,7 +1574,7 @@ class MiniJsParser { + } else { + if (catchPart == null) error("expected 'finally'"); + } +- return Try(body, catchPart, finallyPart); ++ return new Try(body, catchPart, finallyPart); + } + + SwitchCase parseSwitchClause() { +@@ -1594,7 +1594,7 @@ class MiniJsParser { + lastToken != 'default') { + statements.add(parseStatement()); + } +- return SwitchCase(expression, Block(statements)); ++ return new SwitchCase(expression, new Block(statements)); + } + + Statement parseWhile() { +@@ -1602,7 +1602,7 @@ class MiniJsParser { + Expression condition = parseExpression(); + expectCategory(RPAREN); + Statement body = parseStatement(); +- return While(condition, body); ++ return new While(condition, body); + } + + Statement parseDo() { +@@ -1613,7 +1613,7 @@ class MiniJsParser { + Expression condition = parseExpression(); + expectCategory(RPAREN); + expectSemicolon(); +- return Do(body, condition); ++ return new Do(body, condition); + } + + Statement parseSwitch() { +@@ -1626,7 +1626,7 @@ class MiniJsParser { + clauses.add(parseSwitchClause()); + } + expectCategory(RBRACE); +- return Switch(key, clauses); ++ return new Switch(key, clauses); + } + + Catch parseCatch() { +@@ -1636,7 +1636,7 @@ class MiniJsParser { + expectCategory(RPAREN); + expectCategory(LBRACE); + Block body = parseBlock(); +- return Catch(Identifier(identifier), body); ++ return new Catch(new Identifier(identifier), body); + } + + ClassExpression parseClass() { +@@ -1646,12 +1646,12 @@ class MiniJsParser { + heritage = parseConditional(); + } + expectCategory(LBRACE); +- var methods = List(); ++ var methods = new List(); + while (lastCategory != RBRACE) { + methods.add(parseMethodOrProperty(onlyMethods: true) as Method); + } + expectCategory(RBRACE); +- return ClassExpression(name, heritage, methods); ++ return new ClassExpression(name, heritage, methods); + } + + /** +@@ -1677,13 +1677,13 @@ class MiniJsParser { + if (lastCategory == COLON) { + // That wasn't a accessor but the 'get' or 'set' property: retropedal. + isGetter = isSetter = false; +- name = LiteralString('"$token"'); ++ name = new LiteralString('"$token"'); + } + } + if (acceptCategory(HASH)) { + if (lastCategory != LPAREN && (onlyMethods || lastCategory != COLON)) { + // Interpolated method +- var member = InterpolatedMethod(parseHash()); ++ var member = new InterpolatedMethod(parseHash()); + interpolatedValues.add(member); + return member; + } +@@ -1694,10 +1694,10 @@ class MiniJsParser { + + if (!onlyMethods && acceptCategory(COLON)) { + Expression value = parseAssignment(); +- return Property(name, value); ++ return new Property(name, value); + } else { + var fun = parseFun(); +- return Method(name, fun, ++ return new Method(name, fun, + isGetter: isGetter, isSetter: isSetter, isStatic: isStatic); + } + } +@@ -1705,10 +1705,10 @@ class MiniJsParser { + Expression parsePropertyName() { + String identifier = lastToken; + if (acceptCategory(STRING)) { +- return LiteralString(identifier); ++ return new LiteralString(identifier); + } else if (acceptCategory(ALPHA) || acceptCategory(SYMBOL)) { + // ALPHA or a SYMBOL, e.g. void +- return LiteralString('"$identifier"'); ++ return new LiteralString('"$identifier"'); + } else if (acceptCategory(LSQUARE)) { + var expr = parseAssignment(); + expectCategory(RSQUARE); +diff --git a/pkg/dev_compiler/lib/src/js_ast/nodes.dart b/pkg/dev_compiler/lib/src/js_ast/nodes.dart +index 2af42b14ac..e0a7572b04 100644 +--- a/pkg/dev_compiler/lib/src/js_ast/nodes.dart ++++ b/pkg/dev_compiler/lib/src/js_ast/nodes.dart +@@ -1191,11 +1191,11 @@ class Identifier extends Expression implements Parameter { + throw ArgumentError.value(name, "name", "not a valid identifier"); + } + } +- static RegExp _identifierRE = RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$'); ++ static RegExp _identifierRE = new RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$'); + + bool shadows(Set names) => names.contains(name); + +- Identifier _clone() => Identifier(name, allowRename: allowRename); ++ Identifier _clone() => new Identifier(name, allowRename: allowRename); + T accept(NodeVisitor visitor) => visitor.visitIdentifier(this); + int get precedenceLevel => PRIMARY; + void visitChildren(NodeVisitor visitor) {} +@@ -1806,7 +1806,7 @@ class InterpolatedIdentifier extends Expression + T accept(NodeVisitor visitor) => + visitor.visitInterpolatedIdentifier(this); + void visitChildren(NodeVisitor visitor) {} +- InterpolatedIdentifier _clone() => InterpolatedIdentifier(nameOrPosition); ++ InterpolatedIdentifier _clone() => new InterpolatedIdentifier(nameOrPosition); + + int get precedenceLevel => PRIMARY; + String get name => throw '$runtimeType does not support this member.'; +@@ -1826,7 +1826,7 @@ class RegExpLiteral extends Expression { + + T accept(NodeVisitor visitor) => visitor.visitRegExpLiteral(this); + void visitChildren(NodeVisitor visitor) {} +- RegExpLiteral _clone() => RegExpLiteral(pattern); ++ RegExpLiteral _clone() => new RegExpLiteral(pattern); + + int get precedenceLevel => PRIMARY; + } +@@ -1846,7 +1846,7 @@ class Await extends Expression { + int get precedenceLevel => UNARY; + T accept(NodeVisitor visitor) => visitor.visitAwait(this); + void visitChildren(NodeVisitor visitor) => expression.accept(visitor); +- Await _clone() => Await(expression); ++ Await _clone() => new Await(expression); + } + + /** +@@ -1861,7 +1861,7 @@ class Comment extends Statement { + Comment(this.comment); + + T accept(NodeVisitor visitor) => visitor.visitComment(this); +- Comment _clone() => Comment(comment); ++ Comment _clone() => new Comment(comment); + + void visitChildren(NodeVisitor visitor) {} + } +@@ -1880,14 +1880,14 @@ class CommentExpression extends Expression { + + int get precedenceLevel => PRIMARY; + T accept(NodeVisitor visitor) => visitor.visitCommentExpression(this); +- CommentExpression _clone() => CommentExpression(comment, expression); ++ CommentExpression _clone() => new CommentExpression(comment, expression); + + void visitChildren(NodeVisitor visitor) => expression.accept(visitor); + } + + class DebuggerStatement extends Statement { + T accept(NodeVisitor visitor) => visitor.visitDebuggerStatement(this); +- DebuggerStatement _clone() => DebuggerStatement(); ++ DebuggerStatement _clone() => new DebuggerStatement(); + void visitChildren(NodeVisitor visitor) {} + } + +diff --git a/pkg/dev_compiler/lib/src/js_ast/printer.dart b/pkg/dev_compiler/lib/src/js_ast/printer.dart +index da7274518a..f8a055666c 100644 +--- a/pkg/dev_compiler/lib/src/js_ast/printer.dart ++++ b/pkg/dev_compiler/lib/src/js_ast/printer.dart +@@ -79,15 +79,15 @@ class Printer extends TypeScriptTypePrinter implements NodeVisitor { + /// Whether the next call to [indent] should just be a no-op. + bool _skipNextIndent = false; + +- static final identifierCharacterRegExp = RegExp(r'^[a-zA-Z_0-9$]'); +- static final expressionContinuationRegExp = RegExp(r'^[-+([]'); ++ static final identifierCharacterRegExp = new RegExp(r'^[a-zA-Z_0-9$]'); ++ static final expressionContinuationRegExp = new RegExp(r'^[-+([]'); + + Printer(JavaScriptPrintingOptions options, JavaScriptPrintingContext context, + {LocalNamer localNamer}) + : options = options, + context = context, + shouldCompressOutput = options.shouldCompressOutput, +- danglingElseVisitor = DanglingElseVisitor(context), ++ danglingElseVisitor = new DanglingElseVisitor(context), + localNamer = determineRenamer(localNamer, options) { + context.printer = this; + } +@@ -96,8 +96,8 @@ class Printer extends TypeScriptTypePrinter implements NodeVisitor { + LocalNamer localNamer, JavaScriptPrintingOptions options) { + if (localNamer != null) return localNamer; + return (options.shouldCompressOutput && options.minifyLocalVariables) +- ? MinifyRenamer() +- : IdentityNamer(); ++ ? new MinifyRenamer() ++ : new IdentityNamer(); + } + + // The current indentation string. +@@ -1671,9 +1671,9 @@ class MinifyRenamer implements LocalNamer { + codes.add(nthLetter((n ~/ nameSpaceSize) % LETTERS)); + } + codes.add(charCodes.$0 + digit); +- newName = String.fromCharCodes(codes); ++ newName = new String.fromCharCodes(codes); + } +- assert(RegExp(r'[a-zA-Z][a-zA-Z0-9]*').hasMatch(newName)); ++ assert(new RegExp(r'[a-zA-Z][a-zA-Z0-9]*').hasMatch(newName)); + maps.last[oldName] = newName; + return newName; + } +diff --git a/pkg/dev_compiler/lib/src/js_ast/template.dart b/pkg/dev_compiler/lib/src/js_ast/template.dart +index 6475446fbf..cffb11da50 100644 +--- a/pkg/dev_compiler/lib/src/js_ast/template.dart ++++ b/pkg/dev_compiler/lib/src/js_ast/template.dart +@@ -182,8 +182,8 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + return (arguments) { + var value = arguments[nameOrPosition]; + if (value is Expression) return value; +- if (value is String) return Identifier(value); +- throw StateError( ++ if (value is String) return new Identifier(value); ++ throw new StateError( + 'Interpolated value #$nameOrPosition is not an Expression: $value'); + }; + } +@@ -195,7 +195,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + var value = arguments[nameOrPosition]; + Expression toExpression(item) { + if (item is Expression) return item; +- if (item is String) return Identifier(item); ++ if (item is String) return new Identifier(item); + throw StateError('Interpolated value #$nameOrPosition is not ' + 'an Expression or List of Expressions: $value'); + } +@@ -237,8 +237,8 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + + Parameter toIdentifier(item) { + if (item is Parameter) return item; +- if (item is String) return Identifier(item); +- throw StateError( ++ if (item is String) return new Identifier(item); ++ throw new StateError( + 'Interpolated value #$nameOrPosition is not an Identifier' + ' or List of Identifiers: $value'); + } +@@ -295,7 +295,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + return (arguments) { + var item = arguments[nameOrPosition]; + if (item is Identifier) return item; +- if (item is String) return Identifier(item); ++ if (item is String) return new Identifier(item); + throw StateError('Interpolated value #$nameOrPosition is not a ' + 'Identifier or String: $item'); + }; +@@ -322,7 +322,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + + Instantiator visitProgram(Program node) { + var instantiators = node.body.map(visitSplayableStatement).toList(); +- return (a) => Program(splayStatements(instantiators, a)); ++ return (a) => new Program(splayStatements(instantiators, a)); + } + + List splayStatements(List instantiators, arguments) { +@@ -343,7 +343,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + + Instantiator visitBlock(Block node) { + var instantiators = node.statements.map(visitSplayableStatement).toList(); +- return (a) => Block(splayStatements(instantiators, a)); ++ return (a) => new Block(splayStatements(instantiators, a)); + } + + Instantiator visitExpressionStatement(ExpressionStatement node) { +@@ -377,7 +377,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + if (value is bool) { + return value ? makeThen(arguments) : makeOtherwise(arguments); + } +- var cond = value is String ? Identifier(value) : value as Expression; ++ var cond = value is String ? new Identifier(value) : value as Expression; + return If(cond, makeThen(arguments), makeOtherwise(arguments)); + }; + } +@@ -386,7 +386,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator makeCondition = visit(node.condition); + Instantiator makeThen = visit(node.then); + Instantiator makeOtherwise = visit(node.otherwise); +- return (a) => If(makeCondition(a), makeThen(a), makeOtherwise(a)); ++ return (a) => new If(makeCondition(a), makeThen(a), makeOtherwise(a)); + } + + Instantiator visitFor(For node) { +@@ -394,7 +394,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator makeCondition = visitNullable(node.condition); + Instantiator makeUpdate = visitNullable(node.update); + Instantiator makeBody = visit(node.body); +- return (a) => For(makeInit(a), makeCondition(a), ++ return (a) => new For(makeInit(a), makeCondition(a), + makeUpdate(a)?.toVoidExpression(), makeBody(a)); + } + +@@ -402,26 +402,26 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator makeLeftHandSide = visit(node.leftHandSide); + Instantiator makeObject = visit(node.object); + Instantiator makeBody = visit(node.body); +- return (a) => ForIn(makeLeftHandSide(a), makeObject(a), makeBody(a)); ++ return (a) => new ForIn(makeLeftHandSide(a), makeObject(a), makeBody(a)); + } + + Instantiator visitForOf(ForOf node) { + Instantiator makeLeftHandSide = visit(node.leftHandSide); + Instantiator makeObject = visit(node.iterable); + Instantiator makeBody = visit(node.body); +- return (a) => ForOf(makeLeftHandSide(a), makeObject(a), makeBody(a)); ++ return (a) => new ForOf(makeLeftHandSide(a), makeObject(a), makeBody(a)); + } + + Instantiator visitWhile(While node) { + Instantiator makeCondition = visit(node.condition); + Instantiator makeBody = visit(node.body); +- return (a) => While(makeCondition(a), makeBody(a)); ++ return (a) => new While(makeCondition(a), makeBody(a)); + } + + Instantiator visitDo(Do node) { + Instantiator makeBody = visit(node.body); + Instantiator makeCondition = visit(node.condition); +- return (a) => Do(makeBody(a), makeCondition(a)); ++ return (a) => new Do(makeBody(a), makeCondition(a)); + } + + Instantiator visitContinue(Continue node) => +@@ -432,36 +432,36 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator visitReturn(Return node) { + if (node.value == null) return (args) => Return(); + Instantiator makeExpression = visit(node.value); +- return (a) => makeExpression(a).toReturn(); ++ return (a) => new makeExpression(a).toReturn(); + } + + Instantiator visitDartYield(DartYield node) { + Instantiator makeExpression = visit(node.expression); +- return (a) => DartYield(makeExpression(a), node.hasStar); ++ return (a) => new DartYield(makeExpression(a), node.hasStar); + } + + Instantiator visitThrow(Throw node) { + Instantiator makeExpression = visit(node.expression); +- return (a) => Throw(makeExpression(a)); ++ return (a) => new Throw(makeExpression(a)); + } + + Instantiator visitTry(Try node) { + Instantiator makeBody = visit(node.body); + Instantiator makeCatch = visitNullable(node.catchPart); + Instantiator makeFinally = visitNullable(node.finallyPart); +- return (a) => Try(makeBody(a), makeCatch(a), makeFinally(a)); ++ return (a) => new Try(makeBody(a), makeCatch(a), makeFinally(a)); + } + + Instantiator visitCatch(Catch node) { + Instantiator makeDeclaration = visit(node.declaration); + Instantiator makeBody = visit(node.body); +- return (a) => Catch(makeDeclaration(a), makeBody(a)); ++ return (a) => new Catch(makeDeclaration(a), makeBody(a)); + } + + Instantiator visitSwitch(Switch node) { + Instantiator makeKey = visit(node.key); + var makeCases = node.cases.map(visitSwitchCase).toList(); +- return (a) => Switch(makeKey(a), makeCases.map((m) => m(a)).toList()); ++ return (a) => new Switch(makeKey(a), makeCases.map((m) => m(a)).toList()); + } + + Instantiator visitSwitchCase(SwitchCase node) { +@@ -476,12 +476,12 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + FunctionDeclaration node) { + Instantiator makeName = visit(node.name); + Instantiator makeFunction = visit(node.function); +- return (a) => FunctionDeclaration(makeName(a), makeFunction(a)); ++ return (a) => new FunctionDeclaration(makeName(a), makeFunction(a)); + } + + Instantiator visitLabeledStatement(LabeledStatement node) { + Instantiator makeBody = visit(node.body); +- return (a) => LabeledStatement(node.label, makeBody(a)); ++ return (a) => new LabeledStatement(node.label, makeBody(a)); + } + + Instantiator visitLiteralStatement(LiteralStatement node) => visitNode(node); +@@ -492,7 +492,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + VariableDeclarationList node) { + var declarationMakers = + node.declarations.map(visitVariableInitialization).toList(); +- return (a) => VariableDeclarationList( ++ return (a) => new VariableDeclarationList( + node.keyword, declarationMakers.map((m) => m(a)).toList()); + } + +@@ -510,14 +510,14 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + VariableInitialization node) { + Instantiator makeDeclaration = visit(node.declaration); + Instantiator makeValue = visitNullable(node.value); +- return (a) => VariableInitialization(makeDeclaration(a), makeValue(a)); ++ return (a) => new VariableInitialization(makeDeclaration(a), makeValue(a)); + } + + Instantiator visitConditional(Conditional cond) { + Instantiator makeCondition = visit(cond.condition); + Instantiator makeThen = visit(cond.then); + Instantiator makeOtherwise = visit(cond.otherwise); +- return (a) => Conditional(makeCondition(a), makeThen(a), makeOtherwise(a)); ++ return (a) => new Conditional(makeCondition(a), makeThen(a), makeOtherwise(a)); + } + + Instantiator visitNew(New node) => handleCallOrNew(node, true); +@@ -533,7 +533,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + return (a) { + var target = makeTarget(a); + var callArgs = splayNodes(argumentMakers, a); +- return isNew ? New(target, callArgs) : Call(target, callArgs); ++ return isNew ? new New(target, callArgs) : new Call(target, callArgs); + }; + } + +@@ -541,117 +541,117 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator makeLeft = visit(node.left); + Instantiator makeRight = visit(node.right); + String op = node.op; +- return (a) => Binary(op, makeLeft(a), makeRight(a)); ++ return (a) => new Binary(op, makeLeft(a), makeRight(a)); + } + + Instantiator visitPrefix(Prefix node) { + Instantiator makeOperand = visit(node.argument); + String op = node.op; +- return (a) => Prefix(op, makeOperand(a)); ++ return (a) => new Prefix(op, makeOperand(a)); + } + + Instantiator visitPostfix(Postfix node) { + Instantiator makeOperand = visit(node.argument); + String op = node.op; +- return (a) => Postfix(op, makeOperand(a)); ++ return (a) => new Postfix(op, makeOperand(a)); + } + + Instantiator visitThis(This node) => (a) => This(); + Instantiator visitSuper(Super node) => (a) => Super(); + + Instantiator visitIdentifier(Identifier node) => +- (a) => Identifier(node.name); ++ (a) => new Identifier(node.name); + + Instantiator visitSpread(Spread node) { + var maker = visit(node.argument); +- return (a) => Spread(maker(a) as Expression); ++ return (a) => new Spread(maker(a) as Expression); + } + + Instantiator visitYield(Yield node) { + var maker = visitNullable(node.value); +- return (a) => Yield(maker(a) as Expression, star: node.star); ++ return (a) => new Yield(maker(a) as Expression, star: node.star); + } + + Instantiator visitRestParameter(RestParameter node) { + var maker = visit(node.parameter); +- return (a) => RestParameter(maker(a) as Identifier); ++ return (a) => new RestParameter(maker(a) as Identifier); + } + + Instantiator visitAccess(PropertyAccess node) { + Instantiator makeReceiver = visit(node.receiver); + Instantiator makeSelector = visit(node.selector); +- return (a) => PropertyAccess(makeReceiver(a), makeSelector(a)); ++ return (a) => new PropertyAccess(makeReceiver(a), makeSelector(a)); + } + + Instantiator visitNamedFunction(NamedFunction node) { + Instantiator makeDeclaration = visit(node.name); + Instantiator makeFunction = visit(node.function); +- return (a) => NamedFunction(makeDeclaration(a), makeFunction(a)); ++ return (a) => new NamedFunction(makeDeclaration(a), makeFunction(a)); + } + + Instantiator visitFun(Fun node) { + var paramMakers = node.params.map(visitSplayable).toList(); + Instantiator makeBody = visit(node.body); +- return (a) => Fun(splayNodes(paramMakers, a), makeBody(a), ++ return (a) => new Fun(splayNodes(paramMakers, a), makeBody(a), + isGenerator: node.isGenerator, asyncModifier: node.asyncModifier); + } + + Instantiator visitArrowFun(ArrowFun node) { + var paramMakers = node.params.map(visitSplayable).toList(); + Instantiator makeBody = visit(node.body as Node); +- return (a) => ArrowFun(splayNodes(paramMakers, a), makeBody(a)); ++ return (a) => new ArrowFun(splayNodes(paramMakers, a), makeBody(a)); + } + + Instantiator visitLiteralBool(LiteralBool node) => +- (a) => LiteralBool(node.value); ++ (a) => new LiteralBool(node.value); + + Instantiator visitLiteralString(LiteralString node) => +- (a) => LiteralString(node.value); ++ (a) => new LiteralString(node.value); + + Instantiator visitLiteralNumber(LiteralNumber node) => +- (a) => LiteralNumber(node.value); ++ (a) => new LiteralNumber(node.value); + + Instantiator visitLiteralNull(LiteralNull node) => +- (a) => LiteralNull(); ++ (a) => new LiteralNull(); + + Instantiator visitArrayInitializer(ArrayInitializer node) { + var makers = node.elements.map(visitSplayableExpression).toList(); +- return (a) => ArrayInitializer(splayNodes(makers, a)); ++ return (a) => new ArrayInitializer(splayNodes(makers, a)); + } + + Instantiator visitArrayHole(ArrayHole node) { +- return (arguments) => ArrayHole(); ++ return (arguments) => new ArrayHole(); + } + + Instantiator visitObjectInitializer( + ObjectInitializer node) { + var propertyMakers = node.properties.map(visitSplayable).toList(); +- return (a) => ObjectInitializer(splayNodes(propertyMakers, a)); ++ return (a) => new ObjectInitializer(splayNodes(propertyMakers, a)); + } + + Instantiator visitProperty(Property node) { + Instantiator makeName = visit(node.name); + Instantiator makeValue = visit(node.value); +- return (a) => Property(makeName(a), makeValue(a)); ++ return (a) => new Property(makeName(a), makeValue(a)); + } + + Instantiator visitRegExpLiteral(RegExpLiteral node) => +- (a) => RegExpLiteral(node.pattern); ++ (a) => new RegExpLiteral(node.pattern); + + Instantiator visitTemplateString(TemplateString node) { + var makeElements = node.interpolations.map(visit).toList(); +- return (a) => TemplateString(node.strings, splayNodes(makeElements, a)); ++ return (a) => new TemplateString(node.strings, splayNodes(makeElements, a)); + } + + Instantiator visitTaggedTemplate(TaggedTemplate node) { + Instantiator makeTag = visit(node.tag); + var makeTemplate = visitTemplateString(node.template); +- return (a) => TaggedTemplate(makeTag(a), makeTemplate(a)); ++ return (a) => new TaggedTemplate(makeTag(a), makeTemplate(a)); + } + + Instantiator visitClassDeclaration(ClassDeclaration node) { + var makeClass = visitClassExpression(node.classExpr); +- return (a) => ClassDeclaration(makeClass(a)); ++ return (a) => new ClassDeclaration(makeClass(a)); + } + + Instantiator visitClassExpression(ClassExpression node) { +@@ -659,31 +659,31 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator makeName = visit(node.name); + Instantiator makeHeritage = visit(node.heritage); + +- return (a) => ClassExpression( ++ return (a) => new ClassExpression( + makeName(a), makeHeritage(a), splayNodes(makeMethods, a)); + } + + Instantiator visitMethod(Method node) { + Instantiator makeName = visit(node.name); + Instantiator makeFunction = visit(node.function); +- return (a) => Method(makeName(a), makeFunction(a), ++ return (a) => new Method(makeName(a), makeFunction(a), + isGetter: node.isGetter, + isSetter: node.isSetter, + isStatic: node.isStatic); + } + + Instantiator visitComment(Comment node) => +- (a) => Comment(node.comment); ++ (a) => new Comment(node.comment); + + Instantiator visitCommentExpression( + CommentExpression node) { + Instantiator makeExpr = visit(node.expression); +- return (a) => CommentExpression(node.comment, makeExpr(a)); ++ return (a) => new CommentExpression(node.comment, makeExpr(a)); + } + + Instantiator visitAwait(Await node) { + Instantiator makeExpr = visit(node.expression); +- return (a) => Await(makeExpr(a)); ++ return (a) => new Await(makeExpr(a)); + } + + // Note: these are not supported yet in the interpolation grammar. +@@ -734,7 +734,7 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator makeStructure = visitNullable(node.structure); + Instantiator makeDefaultValue = + visitNullable(node.defaultValue); +- return (a) => DestructuredVariable( ++ return (a) => new DestructuredVariable( + name: makeName(a), + property: makeProperty(a), + structure: makeStructure(a), +@@ -745,18 +745,18 @@ class InstantiatorGeneratorVisitor implements NodeVisitor { + Instantiator visitArrayBindingPattern( + ArrayBindingPattern node) { + List makeVars = node.variables.map(this.visit).toList(); +- return (a) => ArrayBindingPattern(splayNodes(makeVars, a)); ++ return (a) => new ArrayBindingPattern(splayNodes(makeVars, a)); + } + + @override + Instantiator visitObjectBindingPattern(ObjectBindingPattern node) { + List makeVars = node.variables.map(this.visit).toList(); +- return (a) => ObjectBindingPattern(splayNodes(makeVars, a)); ++ return (a) => new ObjectBindingPattern(splayNodes(makeVars, a)); + } + + @override + Instantiator visitSimpleBindingPattern(SimpleBindingPattern node) => +- (a) => SimpleBindingPattern(Identifier(node.name.name)); ++ (a) => new SimpleBindingPattern(Identifier(node.name.name)); + } + + /** +diff --git a/pkg/dev_compiler/lib/src/kernel/compiler.dart b/pkg/dev_compiler/lib/src/kernel/compiler.dart +index 3d6f202cd7..cd587b1ad4 100644 +--- a/pkg/dev_compiler/lib/src/kernel/compiler.dart ++++ b/pkg/dev_compiler/lib/src/kernel/compiler.dart +@@ -42,17 +42,17 @@ class ProgramCompiler extends Object + /// + /// We sometimes special case codegen for a single library, as it simplifies + /// name scoping requirements. +- final _libraries = Map.identity(); ++ final _libraries = new Map.identity(); + + /// Maps a library URI import, that is not in [_libraries], to the + /// corresponding Kernel summary module we imported it with. +- final _importToSummary = Map.identity(); ++ final _importToSummary = new Map.identity(); + + /// Maps a summary to the file URI we used to load it from disk. +- final _summaryToUri = Map.identity(); ++ final _summaryToUri = new Map.identity(); + + /// Imported libraries, and the temporaries used to refer to them. +- final _imports = Map(); ++ final _imports = new Map(); + + /// The variable for the current catch clause + VariableDeclaration _catchParameter; +@@ -61,7 +61,7 @@ class ProgramCompiler extends Object + JS.TemporaryId _asyncStarController; + + JS.Identifier _extensionSymbolsModule; +- final _extensionSymbols = Map(); ++ final _extensionSymbols = new Map(); + + Set _pendingClasses; + +@@ -119,13 +119,13 @@ class ProgramCompiler extends Object + + /// Information about virtual fields for all libraries in the current build + /// unit. +- final virtualFields = VirtualFieldModel(); ++ final virtualFields = new VirtualFieldModel(); + + final JSTypeRep _typeRep; + + bool _superAllowed = true; + +- final _superHelpers = Map(); ++ final _superHelpers = new Map(); + + final bool emitMetadata; + final bool enableAsserts; +@@ -171,14 +171,14 @@ class ProgramCompiler extends Object + /// statement that is not a loop body is the outermost non-labeled statement + /// that it encloses. A [BreakStatement] targeting this statement can be + /// compiled to `break` either with or without a label. +- final _effectiveTargets = HashMap.identity(); ++ final _effectiveTargets = new HashMap.identity(); + + /// A map from effective targets to their label names. + /// + /// If the target needs to be labeled when compiled to JS, because it was + /// targeted by a break or continue with a label, then this map contains the + /// label name that was assigned to it. +- final _labelNames = HashMap.identity(); ++ final _labelNames = new HashMap.identity(); + + final Class _jsArrayClass; + final Class privateSymbolClass; +@@ -201,14 +201,14 @@ class ProgramCompiler extends Object + bool replCompile = false, + bool enableAsserts = true, + Map declaredVariables = const {}}) { +- var coreTypes = CoreTypes(component); ++ var coreTypes = new CoreTypes(component); + var types = +- TypeSchemaEnvironment(coreTypes, ClassHierarchy(component), true); +- var constants = DevCompilerConstants(types, declaredVariables); +- var nativeTypes = NativeTypeSet(coreTypes, constants); +- var jsTypeRep = JSTypeRep(types); +- return ProgramCompiler._(coreTypes, coreTypes.index, nativeTypes, constants, +- types, jsTypeRep, NullableInference(jsTypeRep), ++ new TypeSchemaEnvironment(coreTypes, new ClassHierarchy(component), true); ++ var constants = new DevCompilerConstants(types, declaredVariables); ++ var nativeTypes = new NativeTypeSet(coreTypes, constants); ++ var jsTypeRep = new JSTypeRep(types); ++ return new ProgramCompiler._(coreTypes, coreTypes.index, nativeTypes, constants, ++ types, jsTypeRep, new NullableInference(jsTypeRep), + emitMetadata: emitMetadata, + enableAsserts: enableAsserts, + replCompile: replCompile); +@@ -237,7 +237,7 @@ class ProgramCompiler extends Object + JS.Program emitModule( + Component buildUnit, List summaries, List summaryUris) { + if (moduleItems.isNotEmpty) { +- throw StateError('Can only call emitModule once.'); ++ throw new StateError('Can only call emitModule once.'); + } + _component = buildUnit; + +@@ -257,33 +257,33 @@ class ProgramCompiler extends Object + if (ddcRuntime != null) { + // Don't allow these to be renamed when we're building the SDK. + // There is JS code in dart:* that depends on their names. +- runtimeModule = JS.Identifier('dart'); +- _extensionSymbolsModule = JS.Identifier('dartx'); ++ runtimeModule = new JS.Identifier('dart'); ++ _extensionSymbolsModule = new JS.Identifier('dartx'); + _nullableInference.allowNotNullDeclarations = true; + } else { + // Otherwise allow these to be renamed so users can write them. +- runtimeModule = JS.TemporaryId('dart'); +- _extensionSymbolsModule = JS.TemporaryId('dartx'); ++ runtimeModule = new JS.TemporaryId('dart'); ++ _extensionSymbolsModule = new JS.TemporaryId('dartx'); + } +- _typeTable = TypeTable(runtimeModule); ++ _typeTable = new TypeTable(runtimeModule); + + // Initialize our library variables. + var items = []; + var exports = []; + // TODO(jmesserly): this is a performance optimization for V8 to prevent it + // from treating our Dart library objects as JS Maps. +- var root = JS.Identifier('_root'); ++ var root = new JS.Identifier('_root'); + items.add(js.statement('const # = Object.create(null)', [root])); + + void emitLibrary(JS.Identifier id) { + items.add(js.statement('const # = Object.create(#)', [id, root])); +- exports.add(JS.NameSpecifier(id)); ++ exports.add(new JS.NameSpecifier(id)); + } + + for (var library in libraries) { + var libraryTemp = library == ddcRuntime + ? runtimeModule +- : JS.TemporaryId(jsLibraryName(library)); ++ : new JS.TemporaryId(jsLibraryName(library)); + _libraries[library] = libraryTemp; + emitLibrary(libraryTemp); + } +@@ -292,7 +292,7 @@ class ProgramCompiler extends Object + // TODO(jmesserly): find a cleaner design for this. + if (ddcRuntime != null) emitLibrary(_extensionSymbolsModule); + +- items.add(JS.ExportDeclaration(JS.ExportClause(exports))); ++ items.add(new JS.ExportDeclaration(new JS.ExportClause(exports))); + + // Collect all class/type Element -> Node mappings + // in case we need to forward declare any classes. +@@ -319,7 +319,7 @@ class ProgramCompiler extends Object + // Initialize extension symbols + _extensionSymbols.forEach((name, id) { + JS.Expression value = +- JS.PropertyAccess(_extensionSymbolsModule, _propertyName(name)); ++ new JS.PropertyAccess(_extensionSymbolsModule, _propertyName(name)); + if (ddcRuntime != null) { + value = js.call('# = Symbol(#)', [value, js.string("dartx.$name")]); + } +@@ -334,7 +334,7 @@ class ProgramCompiler extends Object + _copyAndFlattenBlocks(items, moduleItems); + + // Build the module. +- return JS.Program(items, name: buildUnit.root.name); ++ return new JS.Program(items, name: buildUnit.root.name); + } + + /// Flattens blocks in [items] to a single list. +@@ -356,7 +356,7 @@ class ProgramCompiler extends Object + // It's either one of the libraries in this module, or it's an import. + return _libraries[library] ?? + _imports.putIfAbsent( +- library, () => JS.TemporaryId(jsLibraryName(library))); ++ library, () => new JS.TemporaryId(jsLibraryName(library))); + } + + String _libraryToModule(Library library) { +@@ -381,7 +381,7 @@ class ProgramCompiler extends Object + } + + void _finishImports(List items) { +- var modules = Map>(); ++ var modules = new Map>(); + + for (var import in _imports.keys) { + modules.putIfAbsent(_libraryToModule(import), () => []).add(import); +@@ -402,13 +402,13 @@ class ProgramCompiler extends Object + // import {foo as foo$} from 'foo'; // if rename was needed + // + var imports = +- libraries.map((l) => JS.NameSpecifier(_imports[l])).toList(); ++ libraries.map((l) => new JS.NameSpecifier(_imports[l])).toList(); + if (module == coreModuleName) { +- imports.add(JS.NameSpecifier(runtimeModule)); +- imports.add(JS.NameSpecifier(_extensionSymbolsModule)); ++ imports.add(new JS.NameSpecifier(runtimeModule)); ++ imports.add(new JS.NameSpecifier(_extensionSymbolsModule)); + } + +- items.add(JS.ImportDeclaration( ++ items.add(new JS.ImportDeclaration( + namedImports: imports, from: js.string(module, "'"))); + }); + } +@@ -531,8 +531,8 @@ class ProgramCompiler extends Object + // https://github.com/dart-lang/sdk/issues/31003 + var className = c.typeParameters.isNotEmpty + ? (c == _jsArrayClass +- ? JS.Identifier(c.name) +- : JS.TemporaryId(getLocalClassName(c))) ++ ? new JS.Identifier(c.name) ++ : new JS.TemporaryId(getLocalClassName(c))) + : _emitTopLevelName(c); + + var savedClassProperties = _classProperties; +@@ -566,7 +566,7 @@ class ProgramCompiler extends Object + _defineExtensionMembers(className, body); + _emitClassMetadata(c.annotations, className, body); + +- var classDef = JS.Statement.from(body); ++ var classDef = new JS.Statement.from(body); + var typeFormals = c.typeParameters; + if (typeFormals.isNotEmpty) { + classDef = _defineClassTypeArguments( +@@ -615,11 +615,11 @@ class ProgramCompiler extends Object + JS.Statement _emitClassStatement(Class c, JS.Expression className, + JS.Expression heritage, List methods) { + if (c.typeParameters.isNotEmpty) { +- return JS.ClassExpression(className as JS.Identifier, heritage, methods) ++ return new JS.ClassExpression(className as JS.Identifier, heritage, methods) + .toStatement(); + } +- var classExpr = JS.ClassExpression( +- JS.TemporaryId(getLocalClassName(c)), heritage, methods); ++ var classExpr = new JS.ClassExpression( ++ new JS.TemporaryId(getLocalClassName(c)), heritage, methods); + return js.statement('# = #;', [className, classExpr]); + } + +@@ -718,7 +718,7 @@ class ProgramCompiler extends Object + ctorBody.add(_emitSuperConstructorCall(className, name, jsParams)); + } + body.add(_addConstructorToClass( +- className, name, JS.Fun(jsParams, JS.Block(ctorBody)))); ++ className, name, new JS.Fun(jsParams, new JS.Block(ctorBody)))); + } + } + +@@ -761,8 +761,8 @@ class ProgramCompiler extends Object + // mixinMembers(C, class C$ extends M { }); + mixinBody.add(runtimeStatement('mixinMembers(#, #)', [ + classExpr, +- JS.ClassExpression( +- JS.TemporaryId(getLocalClassName(c)), mixinClass, methods) ++ new JS.ClassExpression( ++ new JS.TemporaryId(getLocalClassName(c)), mixinClass, methods) + ])); + } + +@@ -780,14 +780,14 @@ class ProgramCompiler extends Object + var m = mixins[i]; + var mixinName = + getLocalClassName(superclass) + '_' + getLocalClassName(m.classNode); +- var mixinId = JS.TemporaryId(mixinName + '\$'); ++ var mixinId = new JS.TemporaryId(mixinName + '\$'); + // Bind the mixin class to a name to workaround a V8 bug with es6 classes + // and anonymous function names. + // TODO(leafp:) Eliminate this once the bug is fixed: + // https://bugs.chromium.org/p/v8/issues/detail?id=7069 + body.add(js.statement("const # = #", [ + mixinId, +- JS.ClassExpression(JS.TemporaryId(mixinName), baseClass, []) ++ JS.ClassExpression(new JS.TemporaryId(mixinName), baseClass, []) + ])); + + emitMixinConstructors(mixinId, m); +@@ -1035,7 +1035,7 @@ class ProgramCompiler extends Object + if (isClassSymbol == null) { + // TODO(jmesserly): we could export these symbols, if we want to mark + // implemented interfaces for user-defined classes. +- var id = JS.TemporaryId("_is_${getLocalClassName(c)}_default"); ++ var id = new JS.TemporaryId("_is_${getLocalClassName(c)}_default"); + moduleItems.add( + js.statement('const # = Symbol(#);', [id, js.string(id.name, "'")])); + isClassSymbol = id; +@@ -1583,8 +1583,8 @@ class ProgramCompiler extends Object + } + } + +- var getters = Map(); +- var setters = Map(); ++ var getters = new Map(); ++ var setters = new Map(); + for (var m in c.procedures) { + if (m.isAbstract) continue; + if (m.isGetter) { +@@ -1845,13 +1845,13 @@ class ProgramCompiler extends Object + + var name = getAnnotationName(field, isJSName) ?? field.name.name; + // Generate getter +- var fn = JS.Fun([], js.block('{ return this.#; }', [name])); +- var method = JS.Method(_declareMemberName(field), fn, isGetter: true); ++ var fn = new JS.Fun([], js.block('{ return this.#; }', [name])); ++ var method = new JS.Method(_declareMemberName(field), fn, isGetter: true); + jsMethods.add(method); + + // Generate setter + if (!field.isFinal) { +- var value = JS.TemporaryId('value'); ++ var value = new JS.TemporaryId('value'); + fn = JS.Fun([value], js.block('{ this.# = #; }', [name, value])); + method = JS.Method(_declareMemberName(field), fn, isSetter: true); + jsMethods.add(method); +@@ -2156,7 +2156,7 @@ class ProgramCompiler extends Object + JS.TemporaryId _getExtensionSymbolInternal(String name) { + return _extensionSymbols.putIfAbsent( + name, +- () => JS.TemporaryId( ++ () => new JS.TemporaryId( + '\$${JS.friendlyNameForDartOperator[name] ?? name}')); + } + +@@ -2192,7 +2192,7 @@ class ProgramCompiler extends Object + return _extensionTypes.isNativeInterface(c); + } + +- var _forwardingCache = HashMap>(); ++ var _forwardingCache = new HashMap>(); + + Member _lookupForwardedMember(Class c, String name) { + // We only care about public methods. +@@ -2681,7 +2681,7 @@ class ProgramCompiler extends Object + emitGeneratorFn(List getParameters(JS.Block jsBody)) { + var savedController = _asyncStarController; + _asyncStarController = function.asyncMarker == AsyncMarker.AsyncStar +- ? JS.TemporaryId('stream') ++ ? new JS.TemporaryId('stream') + : null; + + JS.Expression gen; +@@ -2696,8 +2696,8 @@ class ProgramCompiler extends Object + // Name the function if possible, to get better stack traces. + gen = genFn; + if (name != null) { +- gen = JS.NamedFunction( +- JS.TemporaryId(JS.friendlyNameForDartOperator[name] ?? name), ++ gen = new JS.NamedFunction( ++ new JS.TemporaryId(JS.friendlyNameForDartOperator[name] ?? name), + genFn); + } + +@@ -3310,7 +3310,7 @@ class ProgramCompiler extends Object + .firstWhere((p) => p.isFactory && p.name.name == '')), + [_visitExpression(node.iterable)]); + +- var iter = JS.TemporaryId('iter'); ++ var iter = new JS.TemporaryId('iter'); + return js.statement( + '{' + ' let # = #;' +@@ -3573,7 +3573,7 @@ class ProgramCompiler extends Object + var name = v.name; + if (name == null || name.startsWith('#')) { + name = name == null ? 't${_tempVariables.length}' : name.substring(1); +- return _tempVariables.putIfAbsent(v, () => JS.TemporaryId(name)); ++ return _tempVariables.putIfAbsent(v, () => new JS.TemporaryId(name)); + } + return JS.Identifier(name); + } +@@ -4209,7 +4209,7 @@ class ProgramCompiler extends Object + : 'function() { return super[#]; }', + [jsName]); + +- return JS.Method(JS.TemporaryId(name), fn, ++ return new JS.Method(new JS.TemporaryId(name), fn, + isGetter: !setter, isSetter: setter); + } else { + var function = member.function; +@@ -4224,7 +4224,7 @@ class ProgramCompiler extends Object + var fn = js.fun( + 'function(#) { return super[#](#); }', [params, jsName, params]); + name = JS.friendlyNameForDartOperator[name] ?? name; +- return JS.Method(JS.TemporaryId(name), fn); ++ return new JS.Method(new JS.TemporaryId(name), fn); + } + }); + return JS.PropertyAccess(JS.This(), jsMethod.name); +@@ -4728,7 +4728,7 @@ class ProgramCompiler extends Object + // params are available. + if (_currentFunction == null || usesTypeParams) return jsExpr; + +- var temp = JS.TemporaryId('const'); ++ var temp = new JS.TemporaryId('const'); + moduleItems.add(js.statement('let #;', [temp])); + return js.call('# || (# = #)', [temp, temp, jsExpr]); + } +diff --git a/pkg/dev_compiler/lib/src/kernel/constants.dart b/pkg/dev_compiler/lib/src/kernel/constants.dart +index 79448fc565..295de9d9d8 100644 +--- a/pkg/dev_compiler/lib/src/kernel/constants.dart ++++ b/pkg/dev_compiler/lib/src/kernel/constants.dart +@@ -18,8 +18,8 @@ class DevCompilerConstants { + + DevCompilerConstants( + TypeEnvironment types, Map declaredVariables) +- : _visitor = _ConstantVisitor(types.coreTypes), +- _evaluator = _ConstantEvaluator(types, declaredVariables); ++ : _visitor = new _ConstantVisitor(types.coreTypes), ++ _evaluator = new _ConstantEvaluator(types, declaredVariables); + + /// Determines if an expression is constant. + bool isConstant(Expression e) => _visitor.isConstant(e); +@@ -181,15 +181,15 @@ class _ConstantEvaluator extends ConstantEvaluator { + + _ConstantEvaluator(TypeEnvironment types, this.declaredVariables, + {bool enableAsserts}) +- : unavailableConstant = InstanceConstant( ++ : unavailableConstant = new InstanceConstant( + types.coreTypes.index + .getClass('dart:core', '_ConstantExpressionError') + .reference, + [], + {}), +- super(_ConstantsBackend(types.coreTypes), types, types.coreTypes, true, ++ super(new _ConstantsBackend(types.coreTypes), types, types.coreTypes, true, + enableAsserts, const _ErrorReporter()) { +- env = EvaluationEnvironment(); ++ env = new EvaluationEnvironment(); + } + + @override +@@ -305,7 +305,7 @@ class _ConstantsBackend implements ConstantsBackend { + + @override + buildSymbolConstant(StringConstant value) { +- return InstanceConstant( ++ return new InstanceConstant( + coreTypes.internalSymbolClass.reference, + const [], + {symbolNameField.reference: value}); +diff --git a/pkg/dev_compiler/lib/src/kernel/native_types.dart b/pkg/dev_compiler/lib/src/kernel/native_types.dart +index 1daac64285..cde8c08f45 100644 +--- a/pkg/dev_compiler/lib/src/kernel/native_types.dart ++++ b/pkg/dev_compiler/lib/src/kernel/native_types.dart +@@ -30,11 +30,11 @@ class NativeTypeSet { + + // Abstract types that may be implemented by both native and non-native + // classes. +- final _extensibleTypes = HashSet.identity(); ++ final _extensibleTypes = new HashSet.identity(); + + // Concrete native types. +- final _nativeTypes = HashSet.identity(); +- final _pendingLibraries = HashSet.identity(); ++ final _nativeTypes = new HashSet.identity(); ++ final _pendingLibraries = new HashSet.identity(); + + NativeTypeSet(this.coreTypes, this.constants) { + // First, core types: +diff --git a/pkg/dev_compiler/lib/src/kernel/nullable_inference.dart b/pkg/dev_compiler/lib/src/kernel/nullable_inference.dart +index 8e212cfb1b..edf71afc72 100644 +--- a/pkg/dev_compiler/lib/src/kernel/nullable_inference.dart ++++ b/pkg/dev_compiler/lib/src/kernel/nullable_inference.dart +@@ -36,7 +36,7 @@ class NullableInference extends ExpressionVisitor { + /// [allowNotNullDeclarations]. + bool allowPackageMetaAnnotations = false; + +- final _variableInference = _NullableVariableInference(); ++ final _variableInference = new _NullableVariableInference(); + + NullableInference(this.jsTypeRep) + : types = jsTypeRep.types, +@@ -276,19 +276,19 @@ class _NullableVariableInference extends RecursiveVisitor { + NullableInference _nullInference; + + /// Variables that are currently believed to be not-null. +- final _notNullLocals = HashSet.identity(); ++ final _notNullLocals = new HashSet.identity(); + + /// For each variable currently believed to be not-null ([_notNullLocals]), + /// this collects variables that it is assigned to, so we update them if we + /// later determine that the variable can be null. + final _assignedTo = +- HashMap>.identity(); ++ new HashMap>.identity(); + + /// All functions that have been analyzed with [analyzeFunction]. + /// + /// In practice this will include the outermost function (typically a + /// [Procedure]) as well as an local functions it contains. +- final _functions = HashSet.identity(); ++ final _functions = new HashSet.identity(); + + /// The current variable we are setting/initializing, so we can track if it + /// is [_assignedTo] from another variable. +diff --git a/pkg/dev_compiler/lib/src/kernel/property_model.dart b/pkg/dev_compiler/lib/src/kernel/property_model.dart +index 4242554bf6..85bc267822 100644 +--- a/pkg/dev_compiler/lib/src/kernel/property_model.dart ++++ b/pkg/dev_compiler/lib/src/kernel/property_model.dart +@@ -21,10 +21,10 @@ import 'native_types.dart'; + /// which members are private and thus, could not be overridden outside of the + /// current library. + class VirtualFieldModel { +- final _modelForLibrary = HashMap(); ++ final _modelForLibrary = new HashMap(); + + _LibraryVirtualFieldModel _getModel(Library library) => _modelForLibrary +- .putIfAbsent(library, () => _LibraryVirtualFieldModel.build(library)); ++ .putIfAbsent(library, () => new _LibraryVirtualFieldModel.build(library)); + + /// Returns true if a field is virtual. + bool isVirtual(Field field) => +@@ -39,7 +39,7 @@ class _LibraryVirtualFieldModel { + /// + /// This means we must generate them as virtual fields using a property pair + /// in JavaScript. +- final _overriddenPrivateFields = HashSet(); ++ final _overriddenPrivateFields = new HashSet(); + + /// Private classes that can be extended outside of this library. + /// +@@ -53,7 +53,7 @@ class _LibraryVirtualFieldModel { + /// class C extends _A {} + /// + /// The class _A must treat is "x" as virtual, however _B does not. +- final _extensiblePrivateClasses = HashSet(); ++ final _extensiblePrivateClasses = new HashSet(); + + _LibraryVirtualFieldModel.build(Library library) { + var allClasses = library.classes; +@@ -247,7 +247,7 @@ class ClassPropertyModel { + fieldModel.isVirtual(field) || + field.isCovariant || + field.isGenericCovariantImpl) { +- virtualFields[field] = JS.TemporaryId(name); ++ virtualFields[field] = new JS.TemporaryId(name); + } + } + } +diff --git a/pkg/dev_compiler/lib/src/kernel/target.dart b/pkg/dev_compiler/lib/src/kernel/target.dart +index 56f5b5f188..3e3ae26b3b 100644 +--- a/pkg/dev_compiler/lib/src/kernel/target.dart ++++ b/pkg/dev_compiler/lib/src/kernel/target.dart +@@ -88,31 +88,31 @@ class DevCompilerTarget extends Target { + .getClass('dart:core', '_Invocation') + .constructors + .firstWhere((c) => c.name.name == name); +- return ConstructorInvocation(ctor, Arguments(positional)); ++ return new ConstructorInvocation(ctor, new Arguments(positional)); + } + + if (name.startsWith('get:')) { +- return createInvocation('getter', [SymbolLiteral(name.substring(4))]); ++ return createInvocation('getter', [new SymbolLiteral(name.substring(4))]); + } + if (name.startsWith('set:')) { + return createInvocation('setter', [ +- SymbolLiteral(name.substring(4) + '='), ++ new SymbolLiteral(name.substring(4) + '='), + arguments.positional.single + ]); + } +- var ctorArgs = [SymbolLiteral(name)]; ++ var ctorArgs = [new SymbolLiteral(name)]; + bool isGeneric = arguments.types.isNotEmpty; + if (isGeneric) { + ctorArgs.add( +- ListLiteral(arguments.types.map((t) => TypeLiteral(t)).toList())); ++ new ListLiteral(arguments.types.map((t) => new TypeLiteral(t)).toList())); + } else { +- ctorArgs.add(NullLiteral()); ++ ctorArgs.add(new NullLiteral()); + } +- ctorArgs.add(ListLiteral(arguments.positional)); ++ ctorArgs.add(new ListLiteral(arguments.positional)); + if (arguments.named.isNotEmpty) { +- ctorArgs.add(MapLiteral( ++ ctorArgs.add(new MapLiteral( + arguments.named +- .map((n) => MapEntry(SymbolLiteral(n.name), n.value)) ++ .map((n) => new MapEntry(new SymbolLiteral(n.name), n.value)) + .toList(), + keyType: coreTypes.symbolClass.rawType)); + } +@@ -133,6 +133,6 @@ class DevCompilerTarget extends Target { + bool isConstructor = false, + bool isTopLevel = false}) { + // TODO(sigmund): implement; +- return InvalidExpression(null); ++ return new InvalidExpression(null); + } + } +diff --git a/pkg/dev_compiler/lib/src/kernel/type_table.dart b/pkg/dev_compiler/lib/src/kernel/type_table.dart +index 313e8c946a..d2d72537a4 100644 +--- a/pkg/dev_compiler/lib/src/kernel/type_table.dart ++++ b/pkg/dev_compiler/lib/src/kernel/type_table.dart +@@ -103,7 +103,7 @@ class _CacheTable { + /// Heuristically choose a good name for the cache and generator + /// variables. + JS.TemporaryId chooseTypeName(DartType type) { +- return JS.TemporaryId(_typeString(type)); ++ return new JS.TemporaryId(_typeString(type)); + } + } + +@@ -150,7 +150,7 @@ class TypeTable { + /// parameter. + final _scopeDependencies = >{}; + +- TypeTable(JS.Identifier runtime) : _generators = _GeneratorTable(runtime); ++ TypeTable(JS.Identifier runtime) : _generators = new _GeneratorTable(runtime); + + /// Emit a list of statements declaring the cache variables and generator + /// definitions tracked by the table. If [formals] is present, only +diff --git a/pkg/dev_compiler/tool/kernel_sdk.dart b/pkg/dev_compiler/tool/kernel_sdk.dart +index 6be14ed63e..ae5273a52b 100755 +--- a/pkg/dev_compiler/tool/kernel_sdk.dart ++++ b/pkg/dev_compiler/tool/kernel_sdk.dart +@@ -18,7 +18,7 @@ import 'package:path/path.dart' as path; + + Future main(List args) async { + // Parse flags. +- var parser = ArgParser(); ++ var parser = new ArgParser(); + var parserOptions = parser.parse(args); + var rest = parserOptions.rest; + +@@ -36,8 +36,8 @@ Future main(List args) async { + } + + var inputPath = path.absolute('tool/input_sdk'); +- var target = DevCompilerTarget(); +- var options = CompilerOptions() ++ var target = new DevCompilerTarget(); ++ var options = new CompilerOptions() + ..compileSdk = true + ..packagesFileUri = path.toUri(path.absolute('../../.packages')) + ..sdkRoot = path.toUri(inputPath) +@@ -47,10 +47,10 @@ Future main(List args) async { + var component = await kernelForComponent(inputs, options); + + var outputDir = path.dirname(outputPath); +- await Directory(outputDir).create(recursive: true); ++ await new Directory(outputDir).create(recursive: true); + await writeComponentToBinary(component, outputPath); + +- var jsModule = ProgramCompiler(component, declaredVariables: {}) ++ var jsModule = new ProgramCompiler(component, declaredVariables: {}) + .emitModule(component, [], []); + var moduleFormats = { + 'amd': ModuleFormat.amd, +@@ -63,9 +63,9 @@ Future main(List args) async { + var format = moduleFormats[name]; + var jsDir = path.join(outputDir, name); + var jsPath = path.join(jsDir, 'dart_sdk.js'); +- await Directory(jsDir).create(); ++ await new Directory(jsDir).create(); + var jsCode = jsProgramToCode(jsModule, format); +- await File(jsPath).writeAsString(jsCode.code); +- await File('$jsPath.map').writeAsString(json.encode(jsCode.sourceMap)); ++ await new File(jsPath).writeAsString(jsCode.code); ++ await new File('$jsPath.map').writeAsString(json.encode(jsCode.sourceMap)); + } + } +diff --git a/pkg/dev_compiler/tool/patch_sdk.dart b/pkg/dev_compiler/tool/patch_sdk.dart +index 85060f0315..c8119aba69 100755 +--- a/pkg/dev_compiler/tool/patch_sdk.dart ++++ b/pkg/dev_compiler/tool/patch_sdk.dart +@@ -30,7 +30,7 @@ void main(List argv) { + exit(1); + } + +- var selfModifyTime = File(self).lastModifiedSync().millisecondsSinceEpoch; ++ var selfModifyTime = new File(self).lastModifiedSync().millisecondsSinceEpoch; + + var repoDir = argv[0]; + var patchDir = argv[1]; +@@ -43,17 +43,17 @@ void main(List argv) { + + // Copy libraries.dart, libraries.json and version + var librariesDart = path.join(patchDir, 'libraries.dart'); +- var libContents = File(librariesDart).readAsStringSync(); ++ var libContents = new File(librariesDart).readAsStringSync(); + // TODO(jmesserly): can we remove this? + _writeSync(path.join(sdkOut, '_internal', 'libraries.dart'), libContents); + _writeSync(path.join(sdkOut, 'libraries.json'), +- File(path.join(patchDir, 'libraries.json')).readAsStringSync()); ++ new File(path.join(patchDir, 'libraries.json')).readAsStringSync()); + _writeSync( + path.join( + sdkOut, '_internal', 'sdk_library_metadata', 'lib', 'libraries.dart'), + libContents); + _writeSync(path.join(sdkOut, '..', 'version'), +- File(path.join(repoDir, 'tools', 'VERSION')).readAsStringSync()); ++ new File(path.join(repoDir, 'tools', 'VERSION')).readAsStringSync()); + + // Parse libraries.dart + var sdkLibraries = _getSdkLibraries(libContents); +@@ -71,13 +71,13 @@ void main(List argv) { + if (library.path.contains(INTERNAL_PATH)) { + libraryIn = + path.join(privateIn, library.path.replaceAll(INTERNAL_PATH, '')); +- } else if (File(libraryOverride).existsSync()) { ++ } else if (new File(libraryOverride).existsSync()) { + libraryIn = libraryOverride; + } else { + libraryIn = libraryOut; + } + +- var libraryFile = File(libraryIn); ++ var libraryFile = new File(libraryIn); + if (libraryFile.existsSync()) { + var outPaths = [libraryOut]; + var libraryContents = libraryFile.readAsStringSync(); +@@ -90,7 +90,7 @@ void main(List argv) { + var partPath = part.uri.stringValue; + outPaths.add(path.join(path.dirname(libraryOut), partPath)); + +- var partFile = File(path.join(path.dirname(libraryIn), partPath)); ++ var partFile = new File(path.join(path.dirname(libraryIn), partPath)); + partFiles.add(partFile); + inputModifyTime = math.max(inputModifyTime, + partFile.lastModifiedSync().millisecondsSinceEpoch); +@@ -101,7 +101,7 @@ void main(List argv) { + var patchPath = path.join( + patchIn, path.basenameWithoutExtension(libraryIn) + '_patch.dart'); + +- var patchFile = File(patchPath); ++ var patchFile = new File(patchPath); + bool patchExists = patchFile.existsSync(); + if (patchExists) { + inputModifyTime = math.max(inputModifyTime, +@@ -116,7 +116,7 @@ void main(List argv) { + // Compare output modify time with input modify time. + bool needsUpdate = false; + for (var outPath in outPaths) { +- var outFile = File(outPath); ++ var outFile = new File(outPath); + if (!outFile.existsSync() || + outFile.lastModifiedSync().millisecondsSinceEpoch < + inputModifyTime) { +@@ -147,10 +147,10 @@ void main(List argv) { + + /// Writes a file, creating the directory if needed. + void _writeSync(String filePath, String contents) { +- var outDir = Directory(path.dirname(filePath)); ++ var outDir = new Directory(path.dirname(filePath)); + if (!outDir.existsSync()) outDir.createSync(recursive: true); + +- File(filePath).writeAsStringSync(contents); ++ new File(filePath).writeAsStringSync(contents); + } + + /// Merges dart:* library code with code from *_patch.dart file. +@@ -177,20 +177,20 @@ List _patchLibrary(List partsContents, String patchContents) { + + // Parse the patch first. We'll need to extract bits of this as we go through + // the other files. +- var patchFinder = PatchFinder.parseAndVisit(patchContents); ++ var patchFinder = new PatchFinder.parseAndVisit(patchContents); + + // Merge `external` declarations with the corresponding `@patch` code. + bool failed = false; + for (var partContent in partsContents) { +- var partEdits = StringEditBuffer(partContent); ++ var partEdits = new StringEditBuffer(partContent); + var partUnit = parseCompilationUnit(partContent); +- var patcher = PatchApplier(partEdits, patchFinder); ++ var patcher = new PatchApplier(partEdits, patchFinder); + partUnit.accept(patcher); + if (!failed) failed = patcher.patchWasMissing; + results.add(partEdits); + } + if (failed) return null; +- return List.from(results.map((e) => e.toString())); ++ return results.map((e) => e.toString()).toList(); + } + + /// Merge `@patch` declarations into `external` declarations. +@@ -395,7 +395,7 @@ class StringEditBuffer { + /// Edit the original text, replacing text on the range [begin] and + /// exclusive [end] with the [replacement] string. + void replace(int begin, int end, String replacement) { +- _edits.add(_StringEdit(begin, end, replacement)); ++ _edits.add(new _StringEdit(begin, end, replacement)); + } + + /// Insert [string] at [offset]. +@@ -415,7 +415,7 @@ class StringEditBuffer { + /// Throws [UnsupportedError] if the edits were overlapping. If no edits were + /// made, the original string will be returned. + String toString() { +- var sb = StringBuffer(); ++ var sb = new StringBuffer(); + if (_edits.length == 0) return original; + + // Sort edits by start location. +@@ -473,7 +473,7 @@ List _getSdkLibraries(String contents) { + // TODO(jmesserly): fix SdkLibrariesReader_LibraryBuilder in Analyzer. + // It doesn't understand optional new/const in Dart 2. For now, we keep + // redundant `const` in tool/input_sdk/libraries.dart as a workaround. +- var libraryBuilder = SdkLibrariesReader_LibraryBuilder(true); ++ var libraryBuilder = new SdkLibrariesReader_LibraryBuilder(true); + parseCompilationUnit(contents).accept(libraryBuilder); + return libraryBuilder.librariesMap.sdkLibraries; + } +diff --git a/pkg/front_end/tool/fasta b/pkg/front_end/tool/fasta +index 32485f4344..c9928da490 100755 +--- a/pkg/front_end/tool/fasta ++++ b/pkg/front_end/tool/fasta +@@ -54,7 +54,7 @@ case "${1//_/-}" in + PATCHED_SDK_DIR=$( + ls -d {xcodebuild,out}/${DART_CONFIGURATION} 2>/dev/null \ + | head -1) +- exec "${DART_VM}" --preview_dart_2 -DDFE_VERBOSE=true "$@" ++ exec "${DART_VM}" -DDFE_VERBOSE=true "$@" + ;; + testing) + SCRIPT="${REPO_DIR}/pkg/testing/bin/testing.dart" +diff --git a/pkg/js_ast/lib/src/builder.dart b/pkg/js_ast/lib/src/builder.dart +index 1de3981b7d..c5909472b1 100644 +--- a/pkg/js_ast/lib/src/builder.dart ++++ b/pkg/js_ast/lib/src/builder.dart +@@ -183,7 +183,7 @@ What is not implemented: + should be splice or is intended as a single value. + + */ +-const JsBuilder js = const JsBuilder(); ++JsBuilder js = new JsBuilder(); + + class JsBuilder { + const JsBuilder(); +diff --git a/runtime/BUILD.gn b/runtime/BUILD.gn +index 29f6545010..4aef72ce91 100644 +--- a/runtime/BUILD.gn ++++ b/runtime/BUILD.gn +@@ -161,9 +161,9 @@ config("dart_config") { + + if (!is_win) { + cflags = [ +- "-Werror", +- "-Wall", +- "-Wextra", # Also known as -W. ++ # -Werror, ++ # -Wall, ++ # -Wextra, # Also known as -W. + "-Wno-unused-parameter", + "-Wnon-virtual-dtor", + "-Wvla", +diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn +index 226f9595f8..676bfb0d1c 100644 +--- a/sdk/BUILD.gn ++++ b/sdk/BUILD.gn +@@ -710,48 +710,48 @@ copy("copy_dev_compiler_js_legacy_kernel") { + } + + # Copies all of the JS artifacts needed by DDC. +-group("copy_dev_compiler_js") { +- visibility = [ +- ":copy_dev_compiler_sdk", +- ":copy_dev_compiler_tools", +- ] +- public_deps = [ +- ":copy_dev_compiler_js_amd", +- ":copy_dev_compiler_js_amd_kernel", +- ":copy_dev_compiler_js_common", +- ":copy_dev_compiler_js_common_kernel", +- ":copy_dev_compiler_js_es6", +- ":copy_dev_compiler_js_es6_kernel", +- ":copy_dev_compiler_js_legacy", +- ":copy_dev_compiler_js_legacy_kernel", +- ] +-} ++# group("copy_dev_compiler_js") { ++# visibility = [ ++# ":copy_dev_compiler_sdk", ++# ":copy_dev_compiler_tools", ++# ] ++# public_deps = [ ++# ":copy_dev_compiler_js_amd", ++# ":copy_dev_compiler_js_amd_kernel", ++# ":copy_dev_compiler_js_common", ++# ":copy_dev_compiler_js_common_kernel", ++# ":copy_dev_compiler_js_es6", ++# ":copy_dev_compiler_js_es6_kernel", ++# ":copy_dev_compiler_js_legacy", ++# ":copy_dev_compiler_js_legacy_kernel", ++# ] ++# } + + # This rule copies tools to go along with ddc. +-copy("copy_dev_compiler_tools") { +- visibility = [ ":copy_dev_compiler_sdk" ] +- deps = [ +- ":copy_dev_compiler_js", +- "../utils/dartdevc:dartdevc_web", +- "../utils/dartdevc:stack_trace_mapper", +- ] +- dart_out = get_label_info("../utils/dartdevc:dartdevc_web", "root_out_dir") +- sources = [ +- "$dart_out/dev_compiler/build/web/dart_stack_trace_mapper.js", +- "$dart_out/dev_compiler/build/web/ddc_web_compiler.js", +- ] +- outputs = [ +- "$root_out_dir/dart-sdk/lib/dev_compiler/web/{{source_file_part}}", +- ] +-} ++#copy("copy_dev_compiler_tools") { ++# visibility = [ ":copy_dev_compiler_sdk" ] ++# deps = [ ++# ":copy_dev_compiler_js", ++# "../utils/dartdevc:dartdevc_web", ++# "../utils/dartdevc:stack_trace_mapper", ++# ] ++# dart_out = get_label_info("../utils/dartdevc:dartdevc_web", "root_out_dir") ++# sources = [ ++# "$dart_out/dev_compiler/build/web/dart_stack_trace_mapper.js", ++# "$dart_out/dev_compiler/build/web/ddc_web_compiler.js", ++# ] ++# outputs = [ ++# "$root_out_dir/dart-sdk/lib/dev_compiler/web/{{source_file_part}}", ++# ] ++#} + + # This is the main rule for copying ddc's dependencies to lib/ + group("copy_dev_compiler_sdk") { + visibility = [ ":create_full_sdk" ] + public_deps = [ +- ":copy_dev_compiler_js", ++ # ":copy_dev_compiler_js", + ":copy_dev_compiler_summary", +- ":copy_dev_compiler_tools", ++ # ":copy_dev_compiler_tools", + ] + } + +diff --git a/tools/observatory_tool.py b/tools/observatory_tool.py +index 42028b75bf..4bd64645d0 100755 +--- a/tools/observatory_tool.py ++++ b/tools/observatory_tool.py +@@ -179,7 +179,7 @@ def Build(dart_executable, + if not silent: + DisplayBootstrapWarning() + command = [dart_executable, DART2JS_PATH] +- command += ['--no-preview-dart-2'] ++ command += [] + command += ['-DOBS_VER=' + utils.GetVersion(no_git_hash=True)] + command += [script_path, '-o', output_path, '--packages=%s' % packages_path] + # Add the defaults pub used +diff --git a/utils/application_snapshot.gni b/utils/application_snapshot.gni +index 5ed85b2d38..96cc2fc67b 100644 +--- a/utils/application_snapshot.gni ++++ b/utils/application_snapshot.gni +@@ -87,7 +87,7 @@ template("application_snapshot") { + deps = extra_deps + + if (dart_version == 1) { +- snapshot_vm_args += [ "--no-preview-dart-2" ] ++ snapshot_vm_args += [ ] + } else { + # HACK: When creating app-jit snapshots for Dart 2 apps, the standalone + # Dart VM binary requires the app-jit snapshot for the kernel service to +@@ -112,6 +112,7 @@ template("application_snapshot") { + + vm_args = [ + "--deterministic", ++ "--no_preview_dart_2", + "--packages=$dot_packages", + "--snapshot=$abs_output", + "--snapshot-depfile=$abs_depfile", +@@ -177,8 +178,9 @@ template("aot_assembly") { + vm_args = [ + # TODO(asiva): For not use --no-preview-dart-2, need to flip this to use + # gen_kernel to generate a kernel file before creating an app snapshot. +- "--no-preview-dart-2", ++ + "--deterministic", ++ "--no_preview_dart_2", + "--packages=$dot_packages", + "--snapshot-kind=app-aot", + "--snapshot=$abs_output", +diff --git a/utils/dartdevc/BUILD.gn b/utils/dartdevc/BUILD.gn +index ab80bccb5f..b5667bf98f 100644 +--- a/utils/dartdevc/BUILD.gn ++++ b/utils/dartdevc/BUILD.gn +@@ -117,10 +117,10 @@ template("dart2js_compile") { + } + } + +-dart2js_compile("dartdevc_web") { +- main = rebase_path("../../pkg/dev_compiler/web/main.dart") +- out = "$root_out_dir/dev_compiler/build/web/ddc_web_compiler.js" +-} ++# dart2js_compile("dartdevc_web") { ++# main = rebase_path("../../pkg/dev_compiler/web/main.dart") ++# out = "$root_out_dir/dev_compiler/build/web/ddc_web_compiler.js" ++# } + + dart2js_compile("stack_trace_mapper") { + main = rebase_path("../../pkg/dev_compiler/web/stack_trace_mapper.dart") +-- +2.29.2 \ No newline at end of file -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0014-gnu-Add-dart-2.1.0-dev.5.0.patch >From a21cb9899dffc7c5d9d8afd454d4d93ea0c65d0f Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 18:31:12 +0100 Subject: [PATCH 14/20] gnu: Add dart-2.1.0-dev.5.0. * gnu/packages/dart.scm (dart-2.1.0-dev.5.0): New variable. --- gnu/packages/dart.scm | 108 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 052ceb40b2..a1446b74a2 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -927,3 +927,111 @@ (native-inputs (alist-replace "dart" `(,dart-2.0.0-dev.65.0-bin-only) (package-native-inputs dart-2.0.0-dev.65.0-bin-only))))) + +(define-public dart-2.1.0-dev.5.0 + (package + (inherit dart-2.0.0-dev.65.0) + (version "2.1.0-dev.5.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "07yj5w9fry3has1800sp2yfwijfmc206s5simiiqzw78a0k0r4b0")))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.0.0-dev.65.0) + ((#:phases phases) + `(modify-phases ,phases + (delete 'no-dart-preview) + (delete 'disable-observatory-tool) + (replace 'copy-bootstrap-dart + ;; changed path from sdks/linux/dart-sdk to sdks/dart-sdk + (lambda* (#:key inputs #:allow-other-keys) + (copy-recursively + (assoc-ref inputs "dart") + "tools/sdks/dart-sdk"))))))) + (inputs + (append + `(("icu" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://chromium.googlesource.com/chromium/deps/icu.git") + (commit "c56c671998902fcc4fc9ace88c83daa99f980793"))) + (sha256 + (base32 + "1kw4x116kdv9cbvfv1ciib3brri9a0x0p3qpgz957rki213z89zf"))))) + (replace-inputs + dart-2.0.0-dev.65.0 + `(("boringssl" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://boringssl.googlesource.com/boringssl") + (commit "672f6fc2486745d0cabc3aaeb4e0a3cd13b37b12"))) + (sha256 (base32 "14zjxg00hp752lys7gxpp91apnbwkzy3snvqp5wi99y78rhl7cyn")))) + ("boringssl-gen" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/boringssl_gen") + (commit "344f455fd13d46f054726638e76026156ea73aa9"))) + (sha256 (base32 "0s8rwjmkbsf4dg7b6v247wf9fq018wvgh9psjicjg7nfs7pbvs71")))) + ("observatory-pub-packages" + ,(dart-pkg "observatory-pub-packages" + "0894122173b0f98eb08863a7712e78407d4477bc" + "1gc6wfq05mwvbx61aym1vlngc92x4b5fcmxa4q843118mnhmxjfp")) + ("dart-pkg-bazel-worker" + ,(dart-pkg "bazel-worker" "0.1.14" + "17l0bd30dllg5bhpd68hyx6g6s1krz4nb4qzp51n8ia13crrsr0f")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.24.1" + "01rxayn8lmvb05yij7ad4r8yyadm1iaf47ks4ckyxf5k09padm81")) + ("dart-pkg-fixnum" + ,(dart-pkg "fixnum" "0.10.8" + "1w4gc4gz12ryfngvd11q91j8b5j0slzcbic89vizklq4psv2qgn8")) + ("dart-pkg-glob" + ,(dart-pkg "glob" "1.1.7" + "01659iwdvqpw7s6ransqmwzvh36pyfiiy4yd3q3arpdk35264464")) + ("dart-pkg-http" + ,(dart-pkg "http" "0.11.3+17" + "04wqkj0fkqzn0a8fw20bl4vc59hqcpf834ahw44p89jib72w311i")) + ("dart-pkg-intl" + ,(dart-pkg "intl" "0.15.6" + "0rlgr2fdrviph38ij6idpslxn7ly4apfr9fjgy86sax9j8zbnigq")) + ("dart-pkg-markdown" + ,(dart-pkg "markdown" "2.0.2" + "13mn1ksjnr1hdgcy9p7d1kq9jvh24rg1hzxb2yzcwb6nkhfn03wl")) + ("dart-pkg-matcher" + ,(dart-pkg "matcher" "0.12.3" + "0xsbgrky011r3c1jbk4i1ahxw02m38hxgmy2vn65vv8qf9470kq0")) + ("dart-pkg-oauth2" + ,(dart-pkg "oauth2" "1.2.1" + "0wqrz5k7mf16rihkx4bwxd82iy2841zpqzqxxph00vf11aflrmal")) + ("dart-pkg-protobuf" + ,(dart-pkg "protobuf" "0.9.0" + "16pg6zsvphr6yd4vy13icq68i8g14ll1j04vhdz0k5p2mz57wqq5")) + ("dart-pkg-resource" + ,(dart-pkg "resource" "2.1.5" + "0qqixp6qj8qks4iww6zlallxs1w8z6nx3842g8fl7f3s59km9d76")) + ("dart-pkg-shelf" + ,(dart-pkg "shelf" "0.7.3+3" + "1q3mh1mmis7w1rbvwvzf3avgh2yfznb8hc194f3xbvhic01r1d2m")) + ("dart-pkg-source-maps" + ,(dart-pkg "source-maps" "0.10.9" + "0dk2v7hzv4yknkz44wjfjisfb7yj8xgqhnxw34vi3jf6v7ix67zv")) + ("dart-pkg-unittest" + ,(dart-pkg "unittest" "2b8375bc98bb9dc81c539c91aaea6adce12e1072" + "15mcvxckqjlmvhb5azprhz0psp6r8409cd2kjgd0irhaldkvjifh")) + ("dart-pkg-usage" + ,(dart-pkg "usage" "3.4.0" + "1d9dvqk3s1xr4sx50hahl7iq38z9wf0iw006hb9vhdsvda9mkcsr")) + ("dart-pkg-yaml" + ,(dart-pkg "yaml" "2.1.15" + "00p7hkkj5kbz4vkgzrsi4h405jrbl6gg66j88ysfgaq37c3k4v04")))))) + (native-inputs + (alist-replace "dart" `(,dart-2.0.0-dev.65.0) + (package-native-inputs dart-2.0.0-dev.65.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0015-gnu-Add-dart-2.1.0-dev.6.0.patch >From 290463f772f43f3d1e38e83a52bb78b35ff24ea9 Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 18:41:25 +0100 Subject: [PATCH 15/20] gnu: Add dart-2.1.0-dev.6.0. * gnu/packages/dart.scm (dart-2.1.0-dev.6.0): New variable. --- gnu/packages/dart.scm | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index a1446b74a2..4b6c7a1b48 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -1035,3 +1035,20 @@ (native-inputs (alist-replace "dart" `(,dart-2.0.0-dev.65.0) (package-native-inputs dart-2.0.0-dev.65.0))))) + +(define-public dart-2.1.0-dev.6.0 + (package + (inherit dart-2.1.0-dev.5.0) + (version "2.1.0-dev.6.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "04x0zgz4ns0njkga81lds61r53il1rllj5k2gq83vl8dr8ksq6r5")))) + (native-inputs + (alist-replace "dart" `(,dart-2.1.0-dev.5.0) + (package-native-inputs dart-2.1.0-dev.5.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0016-gnu-Add-dart-2.4.0.patch >From 99c202a05872be2ffbbcddabe55b42ed3aa9bd90 Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 19:13:30 +0100 Subject: [PATCH 16/20] gnu: Add dart-2.4.0. * gnu/packages/dart.scm (dart-2.4.0): New variable. * gnu/packages/patches/dart-2.4.0-fix-build-with-2.1.patch: New file. * gnu/local.mk: Add the patch. --- gnu/local.mk | 1 + gnu/packages/dart.scm | 75 ++++ .../dart-2.4.0-fix-build-with-2.1.patch | 340 ++++++++++++++++++ 3 files changed, 416 insertions(+) create mode 100644 gnu/packages/patches/dart-2.4.0-fix-build-with-2.1.patch diff --git a/gnu/local.mk b/gnu/local.mk index a6c949f574..5ad14f18ef 100644 --- a/gnu/local.mk +++ b/gnu/local.mk @@ -907,6 +907,7 @@ dist_patch_DATA = \ %D%/packages/patches/cyrus-sasl-ac-try-run-fix.patch \ %D%/packages/patches/dart-2.0.0-dev.8-disable-analytics.patch \ %D%/packages/patches/dart-2.0.0-dev.65-compile-with-dev.54.patch \ + %D%/packages/patches/dart-2.4.0-fix-build-with-2.1.patch \ %D%/packages/patches/date-output-pkg-config-files.patch \ %D%/packages/patches/datefudge-gettimeofday.patch \ %D%/packages/patches/dbacl-include-locale.h.patch \ diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 4b6c7a1b48..eaa02bf5fd 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -1052,3 +1052,78 @@ (native-inputs (alist-replace "dart" `(,dart-2.1.0-dev.5.0) (package-native-inputs dart-2.1.0-dev.5.0))))) + +(define-public dart-2.4.0 + (package + (inherit dart-2.1.0-dev.6.0) + (version "2.4.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "0akm53mfxn3vrs512ml4qyljw2yw92g7mdszcx96hw7zr21d15s2")) + (patches + (list (search-patch "dart-2.4.0-fix-build-with-2.1.patch"))))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.1.0-dev.6.0) + ((#:phases phases) + `(modify-phases ,phases + (add-before 'configure 'fix-terminal-color-detection + ;; Instead of trying to run bin/sh and check for tty, just + ;; disable color supports + (lambda _ + (substitute* + "pkg/front_end/lib/src/api_prototype/terminal_color_support.dart" + (("/bin/sh") "false")))) + (add-after 'add-third-party-src 'add-icu + (lambda* (#:key inputs #:allow-other-keys) + (copy-recursively (assoc-ref inputs "icu") + "third_party/icu"))) + (add-before 'configure 'remove-fuzzer-no-link + (lambda _ + (substitute* "runtime/BUILD.gn" + ((",fuzzer-no-link") "")))) + (replace 'patch-dart-action + ;; Path changed in this version + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "build/dart/dart_action.gni" + ;; FIX: assignment had no effect + (("dfe =") "# dfe =") + ((".*dart_root/tools/sdks/dart-sdk/bin/snapshots.*" all) + (string-append "# " all))))))))) + (inputs + (replace-inputs + dart-2.1.0-dev.6.0 + `(("zlib" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://chromium.googlesource.com/chromium/src/third_party/zlib.git") + (commit "c44fb7248079cc3d5563b14b3f758aee60d6b415"))) + (sha256 (base32 "1r14mnrm7zmz2afp92fqdfbcr5gpjvcy46fs7s4qqrzspkjnpwik")))) + ("dart-pkg-bazel-worker" + ,(dart-pkg "bazel-worker" "bazel_worker-v0.1.20" + "02g4cycbrwr833qkjj4dcq7n9alkq4xmkdrxpmjdjv54ilxg5xx9")) + ("dart-pkg-dart2js-info" + ,(dart-pkg "dart2js-info" "0.6.0" + "1cirqph6yr1dn07979v1p2dyhn01r2c32w2k5ndpkjk7z9cx0bbr")) + ("dart-pkg-html" + ,(dart-pkg "html" "0.14.0+1" + "0kf290mhpr1bklsgc35inpqafhc3wm8amh5a6933y3jiw2dgi94k")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.91" + "0slmsgm0ficwd85ljqxkzi64jlcwpkzwlnyfcx46plmnzxjvbmbc")) + ("dart-pkg-protobuf" + ,(dart-pkg "protobuf" "7d34c9e4e552a4f66acce32e4344ae27756a1949" + "0ksfqq6a7xbivalwl7knbm7f7ihv8pq19d4j6rwffqdnh9wqza42")) + ("dart-pkgtested-dart-style" + ,(dart-pkg "dart-style" "1.2.8" + "1km62cgp0fyc5zxliq2ny6bzxj2amnjhkkc2rm06x1fv53vll26n"))))) + (native-inputs + (alist-replace "dart" `(,dart-2.1.0-dev.6.0) + (alist-replace "gcc" `(,gcc-8) + (package-native-inputs dart-2.1.0-dev.6.0)))))) diff --git a/gnu/packages/patches/dart-2.4.0-fix-build-with-2.1.patch b/gnu/packages/patches/dart-2.4.0-fix-build-with-2.1.patch new file mode 100644 index 0000000000..f9a43e2c25 --- /dev/null +++ b/gnu/packages/patches/dart-2.4.0-fix-build-with-2.1.patch @@ -0,0 +1,340 @@ +From 05739627950567885293f42fc4d4661be5e1ac04 Mon Sep 17 00:00:00 2001 +From: nixo +Date: Tue, 24 Nov 2020 10:27:55 +0100 +Subject: [PATCH] Replace unsupported '...' and 'if' in lists + +--- + .../lib/src/analyzer/code_generator.dart | 27 +-- + .../lib/src/compiler/shared_compiler.dart | 9 +- + pkg/dev_compiler/lib/src/kernel/compiler.dart | 169 ++++++++++-------- + 3 files changed, 121 insertions(+), 84 deletions(-) + +diff --git a/pkg/dev_compiler/lib/src/analyzer/code_generator.dart b/pkg/dev_compiler/lib/src/analyzer/code_generator.dart +index 3ff97b0df18..8ab1afa6855 100644 +--- a/pkg/dev_compiler/lib/src/analyzer/code_generator.dart ++++ b/pkg/dev_compiler/lib/src/analyzer/code_generator.dart +@@ -4161,19 +4161,24 @@ class CodeGenerator extends Object + } + + var location = _getLocation(condition.offset); +- return js.statement(' if (!#) #.assertFailed(#, #, #, #, #);', [ ++ var newvar = [ + jsCondition, + runtimeModule, +- if (message == null) +- JS.LiteralNull() +- else +- _visitExpression(message), +- js.escapedString(location.sourceUrl.toString()), +- // Lines and columns are typically printed with 1 based indexing. +- js.number(location.line + 1), +- js.number(location.column + 1), +- js.escapedString(condition.toSource()), +- ]); ++ ]; ++ ++ if (message == null) { ++ newvar.add(JS.LiteralNull()); ++ } else { ++ newvar.add(_visitExpression(message)); ++ } ++ newvar.addAll([ ++ js.escapedString(location.sourceUrl.toString()), ++ // Lines and columns are typically printed with 1 based indexing. ++ js.number(location.line + 1), ++ js.number(location.column + 1), ++ js.escapedString(condition.toSource()),]); ++ ++ return js.statement(' if (!#) #.assertFailed(#, #, #, #, #);', newvar); + } + + @override +diff --git a/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart b/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart +index 6a3182d0607..86741493a69 100644 +--- a/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart ++++ b/pkg/dev_compiler/lib/src/compiler/shared_compiler.dart +@@ -213,8 +213,13 @@ abstract class SharedCompiler { + /// dart.asInt() + /// + @protected +- JS.Expression runtimeCall(String code, [List args]) => +- js.call('#.$code', [runtimeModule, ...?args]); ++ JS.Expression runtimeCall(String code, [List args]) { ++ var obj = [runtimeModule]; ++ if (args != null) { ++ obj.addAll(args); ++ } ++ return js.call('#.$code', obj); ++ } + + /// Calls [runtimeCall] and uses `toStatement()` to convert the resulting + /// expression into a statement. +diff --git a/pkg/dev_compiler/lib/src/kernel/compiler.dart b/pkg/dev_compiler/lib/src/kernel/compiler.dart +index 531ca405cff..81424212e4c 100644 +--- a/pkg/dev_compiler/lib/src/kernel/compiler.dart ++++ b/pkg/dev_compiler/lib/src/kernel/compiler.dart +@@ -554,9 +554,10 @@ class ProgramCompiler extends Object + + var genericArgs = [ + typeConstructor, +- if (deferredBaseClass != null && deferredBaseClass.isNotEmpty) +- js.call('(#) => { #; }', [jsFormals, deferredBaseClass]), + ]; ++ if (deferredBaseClass != null && deferredBaseClass.isNotEmpty) { ++ genericArgs.add(js.call('(#) => { #; }', [jsFormals, deferredBaseClass])); ++ } + + var genericCall = runtimeCall('generic(#)', [genericArgs]); + +@@ -726,11 +727,14 @@ class ProgramCompiler extends Object + var jsParams = _emitParameters(ctor.function); + _currentUri = savedUri; + var name = ctor.name.name; +- var ctorBody = [ +- if (mixinCtor != null) mixinCtor, +- if (name != '' || hasUnnamedSuper) +- _emitSuperConstructorCall(className, name, jsParams), ++ var ctorBody = [ + ]; ++ if (mixinCtor != null) { ++ ctorBody.add(mixinCtor); ++ } ++ if (name != '' || hasUnnamedSuper) { ++ ctorBody.add(_emitSuperConstructorCall(className, name, jsParams)); ++ } + body.add(_addConstructorToClass( + c, className, name, JS.Fun(jsParams, JS.Block(ctorBody)))); + } +@@ -1294,10 +1298,10 @@ class ProgramCompiler extends Object + + if (emitMetadata) { + var constructors = []; +- var allConstructors = [ +- ...c.constructors, +- ...c.procedures.where((p) => p.isFactory), +- ]; ++ var allConstructors = [ ]; ++ allConstructors.addAll(c.constructors); ++ allConstructors.addAll(c.procedures.where((p) => p.isFactory)); ++ + for (var ctor in allConstructors) { + var memberName = _constructorName(ctor.name.name); + var type = _emitAnnotatedFunctionType( +@@ -3032,10 +3036,13 @@ class ProgramCompiler extends Object + // (sync*/async/async*). Our code generator assumes it can emit names for + // named argument initialization, and sync* functions also emit locally + // modified parameters into the function's scope. +- var parameterNames = { +- for (var p in f.positionalParameters) p.name, +- for (var p in f.namedParameters) p.name, +- }; ++ var parameterNames = Set(); ++ for (var p in f.positionalParameters) { ++ parameterNames.add(p.name); ++ } ++ for (var p in f.namedParameters) { ++ parameterNames.add(p.name); ++ } + + return jsBody.toScopedBlock(parameterNames); + } +@@ -3205,23 +3212,27 @@ class ProgramCompiler extends Object + } + + var encodedConditionSource = node +- .enclosingComponent.uriToSource[node.location.file].source +- .sublist(node.conditionStartOffset, node.conditionEndOffset); ++ .enclosingComponent.uriToSource[node.location.file].source ++ .sublist(node.conditionStartOffset, node.conditionEndOffset); + var conditionSource = utf8.decode(encodedConditionSource); + var location = _getLocation(node.conditionStartOffset); +- return js.statement(' if (!#) #.assertFailed(#, #, #, #, #);', [ ++ var newvar = [ + jsCondition, + runtimeModule, +- if (node.message == null) +- JS.LiteralNull() +- else +- _visitExpression(node.message), +- js.escapedString(location.sourceUrl.toString()), +- // Lines and columns are typically printed with 1 based indexing. +- js.number(location.line + 1), +- js.number(location.column + 1), +- js.escapedString(conditionSource), +- ]); ++ ]; ++ if (node.message == null) { ++ newvar.add(JS.LiteralNull()); ++ } else { ++ newvar.add(_visitExpression(node.message)); ++ } ++ newvar.addAll([ ++ js.escapedString(location.sourceUrl.toString()), ++ // Lines and columns are typically printed with 1 based indexing. ++ js.number(location.line + 1), ++ js.number(location.column + 1), ++ js.escapedString(conditionSource)]); ++ ++ return js.statement(' if (!#) #.assertFailed(#, #, #, #, #);', newvar); + } + + static bool isBreakable(Statement stmt) { +@@ -3624,15 +3635,17 @@ class ProgramCompiler extends Object + _emitVariableDef(exceptionParameter), + runtimeModule, + _emitVariableRef(caughtError) +- ]), +- if (stackTraceParameter != null) +- js.statement('let # = #.stackTrace(#)', [ ++ ]) ]; ++ ++ if (stackTraceParameter != null) { ++ catchStatements.add(js.statement('let # = #.stackTrace(#)', [ + _emitVariableDef(stackTraceParameter), + runtimeModule, + _emitVariableRef(caughtError) +- ]), +- catchBody, +- ]; ++ ])); ++ } ++ catchStatements.add(catchBody); ++ + _rethrowParameter = savedRethrow; + return JS.Catch(_emitVariableDef(caughtError), JS.Block(catchStatements)); + } +@@ -4425,12 +4438,14 @@ class ProgramCompiler extends Object + isGetter: !setter, isSetter: setter); + } else { + var function = member.function; +- var params = [ +- ..._emitTypeFormals(function.typeParameters), +- for (var param in function.positionalParameters) +- JS.Identifier(param.name), +- if (function.namedParameters.isNotEmpty) namedArgumentTemp, +- ]; ++ var params = [ ]..addAll(_emitTypeFormals(function.typeParameters)); ++ for (var param in function.positionalParameters) { ++ params.add(JS.Identifier(param.name)); ++ } ++ ++ if (function.namedParameters.isNotEmpty) { ++ params.add(namedArgumentTemp); ++ } + + var fn = js.fun( + 'function(#) { return super[#](#); }', [params, jsName, params]); +@@ -4543,18 +4558,24 @@ class ProgramCompiler extends Object + List _emitArgumentList(Arguments node, + {bool types = true, Member target}) { + types = types && _reifyGenericFunction(target); +- return [ +- if (types) for (var typeArg in node.types) _emitType(typeArg), +- for (var arg in node.positional) +- if (arg is StaticInvocation && +- isJSSpreadInvocation(arg.target) && +- arg.arguments.positional.length == 1) +- JS.Spread(_visitExpression(arg.arguments.positional[0])) +- else +- _visitExpression(arg), +- if (node.named.isNotEmpty) +- JS.ObjectInitializer(node.named.map(_emitNamedExpression).toList()), +- ]; ++ var newvar = []; ++ if (types) { ++ for (var typeArg in node.types) { ++ newvar.add(_emitType(typeArg)); ++ } ++ } ++ for (var arg in node.positional) { ++ if (arg is StaticInvocation && isJSSpreadInvocation(arg.target) && ++ arg.arguments.positional.length == 1) { ++ newvar.add(JS.Spread(_visitExpression(arg.arguments.positional[0]))); ++ } else { ++ newvar.add(_visitExpression(arg)); ++ } ++ } ++ if (node.named.isNotEmpty) { ++ newvar.add(JS.ObjectInitializer(node.named.map(_emitNamedExpression).toList())); ++ } ++ return newvar; + } + + JS.Property _emitNamedExpression(NamedExpression arg) { +@@ -5052,12 +5073,14 @@ class ProgramCompiler extends Object + + @override + JS.Expression visitMapLiteral(MapLiteral node) { +- var entries = [ +- for (var e in node.entries) ...[ +- _visitExpression(e.key), +- _visitExpression(e.value), +- ], +- ]; ++ var entries = [ ]; ++ ++ for (var e in node.entries) { ++ entries.addAll([ ++ _visitExpression(e.key), ++ _visitExpression(e.value), ++ ]); ++ } + + // TODO(markzipan): remove const check when we use front-end const eval + if (!node.isConst) { +@@ -5152,10 +5175,12 @@ class ProgramCompiler extends Object + @override + JS.Expression visitBlockExpression(BlockExpression node) { + var jsExpr = _visitExpression(node.value); +- var jsStmts = [ +- for (var s in node.body.statements) _visitStatement(s), +- JS.Return(jsExpr), +- ]; ++ var jsStmts = [ ]; ++ for (var s in node.body.statements) { ++ jsStmts.add(_visitStatement(s)); ++ } ++ jsStmts.add(JS.Return(jsExpr)); ++ + var jsBlock = JS.Block(jsStmts); + // BlockExpressions with async operations must be constructed + // with a generator instead of a lambda. +@@ -5277,12 +5302,14 @@ class ProgramCompiler extends Object + + @override + JS.Expression visitMapConstant(MapConstant node) { +- var entries = [ +- for (var e in node.entries) ...[ +- visitConstant(e.key), +- visitConstant(e.value), +- ], +- ]; ++ var entries = [ ]; ++ for (var e in node.entries) { ++ entries.addAll([ ++ visitConstant(e.key), ++ visitConstant(e.value), ++ ]); ++ } ++ + return _emitConstMap(node.keyType, node.valueType, entries); + } + +@@ -5305,10 +5332,10 @@ class ProgramCompiler extends Object + + var type = visitInterfaceType(node.getType(types) as InterfaceType); + var prototype = js.call("#.prototype", [type]); +- var properties = [ +- JS.Property(propertyName("__proto__"), prototype), +- for (var e in node.fieldValues.entries) entryToProperty(e), +- ]; ++ var properties = [ JS.Property(propertyName("__proto__"), prototype) ]; ++ for (var e in node.fieldValues.entries) { ++ properties.add(entryToProperty(e)); ++ } + return canonicalizeConstObject( + JS.ObjectInitializer(properties, multiline: true)); + } +-- +2.29.2 + -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0017-gnu-Add-dart-2.5.0.patch >From 51ba123e0e4f46dbd055dbe6d8503c914d2d5e9d Mon Sep 17 00:00:00 2001 From: nixo Date: Fri, 27 Nov 2020 23:06:41 +0100 Subject: [PATCH 17/20] gnu: Add dart-2.5.0. * gnu/packages/dart.scm (dart-2.5.0): New variable. --- gnu/packages/dart.scm | 94 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index eaa02bf5fd..309f960bb9 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -1127,3 +1127,97 @@ (alist-replace "dart" `(,dart-2.1.0-dev.6.0) (alist-replace "gcc" `(,gcc-8) (package-native-inputs dart-2.1.0-dev.6.0)))))) + +(define-public dart-2.5.0 + (package + (inherit dart-2.4.0) + (version "2.5.0") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "1xwrj7hj9a28w2ymykmfd7c2bi7b68ssbhkkb7p62yhn4m504vh1")))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.4.0) + ((#:phases phases) + `(modify-phases ,phases + (add-before 'configure 'create-gclient-args + (lambda _ + (with-output-to-file "build/config/gclient_args.gni" + (lambda () + ;; taken from their release, available at + ;; commondatastorage.googleapis.com/dart-archive/channels/ + ;; stable/raw/2.5.0/src/dart-2.5.0.tar.gz + (display "checkout_llvm = false"))))) + (add-before 'configure 'patch-dart-action + (lambda* (#:key inputs propagated-inputs #:allow-other-keys) + (substitute* "build/dart/dart_action.gni" + ;; FIX: assignment had no effect + (("dfe =") "# dfe =") + (("\"\\$_dart_root/tools/sdks/\\$host_os/.*service.dart.snapshot\"") + "")))) + (add-before 'configure 'disable-language-model + ;; the language_model is a 200Mb tensor flow binary image, which + ;; should be downloaded from + ;; https://chrome-infra-packages.appspot.com/p/dart/language_model/ + ;; It seems to be used for code completition + (lambda _ + (substitute* "sdk/BUILD.gn" + ;; definition and use of ftlite/language model are after a + ;; conditional, make it false + (("target_cpu == \"x64\"") "false")))) + (add-before 'configure 'add-missing-includes + (lambda _ + (substitute* "runtime/bin/ffi_test/ffi_test_functions.cc" + ;; compilation fails because of mutex, condition variable and + ;; function not declared + (("#include " all) + (string-join + `(,all + "#include " "#include " + "#include ") + "\n"))))))))) + (inputs + (append + `(("dart-pkg-tflite-native" + ,(dart-pkg "tflite-native" "06e533a9747306d1114c53427cc67eda080f51f9" + "1ibd66l1hq0b04cbnxm9k968h0ijqzi1sfslcxx9w45zcnmhk63n")) + ("dart-pkg-mustache" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/xxgreg/mustache") + (commit "5e81b12215566dbe2473b2afd01a8a8aedd56ad9"))) + (sha256 + (base32 + "03k614d3njlw06n2ff6g4yf252xnwj5fb83aizs3dz1awmkhygk2"))))) + (replace-inputs + dart-2.4.0 + `(("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "0.28.4" + "0p9b60nrfqmgbngzsabgh7byrp0p1lwfc9rh77z3gjphmi16ydxf")) + ("dart-pkg-fixnum" + ,(dart-pkg "fixnum" "0.10.9" + "0vicw7jprch4pd949j0b4h695i5wzk1njg4ffhcz4jrc40l2p0gn")) + ("dart-pkg-http" + ,(dart-pkg "http" "0.12.0+2" + "0psffnp9lmyklbz06687hkm8ywnspr9ai5bpa33jw0m24zz4znc7")) + ("dart-pkg-http-io" + ,(dart-pkg "http-io" "2fa188caf7937e313026557713f7feffedd4978b" + "1wfp984n8wykx1n6niwxfhxzr2cq95qdvk47majxizwlzbqv989x")) + ("dart-pkg-http-multi-server" + ,(dart-pkg "http_multi_server" "2.0.5" + "11szb0by7yn7kdcp9pbd6igy2kxilmpsnvwdm3ds8bp7l1ysgpwk")) + ("dart-pkg-http-parser" + ,(dart-pkg "http-parser" "3.1.3" + "0g71a2bgws4nv0vllidyvf1ncbrxry81dy98vy0p8lz3h8r7irpx")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.96" + "13fd9yfv6ww2yg2bhv0x01bgx4cl2vx12cy485ls2m16jwyjf1di")))))) + (native-inputs + (alist-replace "dart" `(,dart-2.4.0) + (package-native-inputs dart-2.4.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0018-gnu-Add-dart-2.6.1.patch >From ad443d16e94268d4641f2ae6e25533ce74989678 Mon Sep 17 00:00:00 2001 From: nixo Date: Sat, 28 Nov 2020 13:41:41 +0100 Subject: [PATCH 18/20] gnu: Add dart-2.6.1. * gnu/packages/dart.scm (dart-2.6.1): New variable. --- gnu/packages/dart.scm | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 309f960bb9..88ecfffe78 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -1221,3 +1221,75 @@ (native-inputs (alist-replace "dart" `(,dart-2.4.0) (package-native-inputs dart-2.4.0))))) + +(define-public dart-2.6.1 + (package + (inherit dart-2.5.0) + (version "2.6.1") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "0h8y5bs809hzappm7xx4xz45kzp28qvbkjp55wwq9gc2mznfmz8b")))) + (arguments + ;; Inheriting from the previous, as we don't want the patched phases + (substitute-keyword-arguments (package-arguments dart-2.5.0) + ((#:phases phases) + `(modify-phases ,phases + (add-before 'configure 'fix-linker-flags + (lambda _ + (substitute* "build/config/linux/BUILD.gn" + (("\"-lc\\+\\+\",") "") + ;; Fixes "undefined reference to std::cout" + (("\"-nodefaultlibs\",") "") + ;; we are not using clang + (("\"-lclang_rt.*") "\"-fpermissive\",")))) + (add-before 'configure 'gcc-permissive + (lambda _ + (substitute* "runtime/BUILD.gn" + ;; gcc complains with "declaration of method changes meaning + ;; of", add -fpermissive + (("-fno-exceptions\",") + "-fno-exceptions\", \"-fpermissive\",")))))))) + (inputs + (append + `(("dart-pkg-ffi" + ,(dart-pkg "ffi" "ea88d71b043ee14b268c3aedff14e9eb32e20959" + "13jvj0i58cb02k1xj1wlx3r5q5krfwj4r71p6jgkacvphm9pfjll"))) + (replace-inputs + dart-2.5.0 + `(("gperftools" + ,(origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/gperftools/gperftools.git") + (commit "e9ab4c53041ac62feefbbb076d326e9a77dd1567"))) + (sha256 + (base32 + "052ldhvaaijw0yvqb3pdir68cz6idaaaq31nagrqkzjilgllisfh")))) + ("dart-pkgtested-package-config" + ,(dart-pkg "package-config" "v1.9.2" + "0gaws9v3w95fmgn74wiyif0fdjx0dvivwpzk6a3gmqjp0jrr1rqh")) + ("dart-pkg-args" + ,(dart-pkg "args" "1.5.2" + "0vqx908x8278hf4j4abd4mmsk409qmi0al3wyn3ym5sr9mrlxnsa")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.28.8" + "0dckzhw6gm6w723277ykwr5wws3i4hhkcbnal8n55s0yajk6q5l3")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.101" + "011ja9n35vs26w6mr0mn53mfgp0rx6pispf1pd7wvbm1jlvpcv32")) + ("dart-pkg-markdown" + ,(dart-pkg "markdown" "2.1.1" + "1c5mg6z2saszjpxncgkkakwnfr36ki98mivssrv3kaj9n6sagr84")) + ("dart-pkg-tflite-native" + ,(dart-pkg "tflite-native" "3c777c40608a2a9f1427bfe0028ab48e7116b4c1" + "13hrdd1bgdxqinxihlg2in0vfzg2l7lq7s40sj19djildrp62lh1")))))) + (native-inputs + (alist-replace + "dart" `(,dart-2.5.0) + (package-native-inputs dart-2.5.0))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0019-gnu-Add-dart-2.7.2.patch >From 0ef5241a5c0a2b29e813e77814776a1c37f5f35a Mon Sep 17 00:00:00 2001 From: nixo Date: Sat, 28 Nov 2020 15:39:25 +0100 Subject: [PATCH 19/20] gnu: Add dart-2.7.2. * gnu/packages/dart.scm (dart-2.7.2): New variable. --- gnu/packages/dart.scm | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index 88ecfffe78..d706825d76 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -1293,3 +1293,64 @@ (alist-replace "dart" `(,dart-2.5.0) (package-native-inputs dart-2.5.0))))) + +(define-public dart-2.7.2 + (package + (inherit dart-2.6.1) + (version "2.7.2") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "1gyi76rwznxxr09kslr3glhw1l76qc25a2y4pwqqg9rgpl52pcbd")))) + (arguments + (substitute-keyword-arguments (package-arguments dart-2.6.1) + ((#:phases phases) + `(modify-phases ,phases + (add-before 'configure 'link-pthread + (lambda* _ + (substitute* "build/toolchain/gcc_toolchain.gni" + (("\\$libs_section_postfix") + "$libs_section_postfix -lpthread")))))))) + (inputs + (append + `(("dart-pkg-pedantic" + ,(dart-pkg "pedantic" "v1.8.0" + "0bmdmf1bgxclh365ca7c05cpz7wabyis1ax65r3pj7ksjg4p8hp9"))) + (replace-inputs + dart-2.6.1 + `(("dart-pkgtested-package-config" + ,(dart-pkg "package-config" "2453cd2e78c2db56ee2669ced17ce70dd00bf576" + "0wg5dgrk584zmxkcla88641i6w4ba7fbpw8l5ghzqv1v8azqvr7i")) + ("dart-pkgtested-dart-style" + ,(dart-pkg "dart-style" "1.3.2" + "0a9vgidqxva8prw00mig2irlyj9a4swcwyw0j9n5yxjhg006j43v")) + ("dart-pkg-bazel-worker" + ,(dart-pkg "bazel-worker" "v0.1.22" + "09wmwvz3vlm9x103i6hy6jrz6rvldwnf8ii1cyj95sx05qam5csz")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.29.1" + "0aambr3588m1aqsafm0anqbbn3ajvzj3jgkjvb7qgxi9ahx3hw9j")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.104" + "1wdqdwjh3r4aiadcaf9qd5hyx6krclx397riy8f5xcravm1kn9jg")) + ("dart-pkg-protobuf" + ,(dart-pkg "protobuf" "3746c8fd3f2b0147623a8e3db89c3ff4330de760" + "09zgplljiyffqqnd0ylgzagf31b1dgw8qy35r4pwgmlh0xpc1aic")) + ("dart-pkg-pub" + ,(dart-pkg "pub" "d15067931a6b671a1c9dcc98b5923347676269cf" + "0h8lfyzhz0misgfg8hxg72rvm68miscqfr1h4nmjix9rzw76d0vw")) + ("dart-pkg-watcher" + ,(dart-pkg "watcher" "0.9.7+13" + "1ilzh97l60srga2j2iiv0ybzjxjdy166vsignp62smjbxhl0p2p9")) + ("dart-pkg-yaml" + ,(dart-pkg "yaml" "2.2.0" + "1y5xwps838yys9aw72n2300p2r5jjvz6v4klsp38y55f9kfh2dax")))))) + (native-inputs + (alist-replace + "dart" `(,dart-2.6.1) + (package-native-inputs dart-2.6.1))))) -- 2.29.2 --=-=-= Content-Type: text/x-patch Content-Disposition: attachment; filename=0020-gnu-Add-dart-2.8.4.patch >From b75b8f98be9e565d78100e201414cf204b8ef197 Mon Sep 17 00:00:00 2001 From: nixo Date: Sat, 28 Nov 2020 16:59:58 +0100 Subject: [PATCH 20/20] gnu: Add dart-2.8.4. * gnu/packages/dart.scm (dart-2.8.4): New variable. --- gnu/packages/dart.scm | 81 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/gnu/packages/dart.scm b/gnu/packages/dart.scm index d706825d76..1ab0c1e82b 100644 --- a/gnu/packages/dart.scm +++ b/gnu/packages/dart.scm @@ -1354,3 +1354,84 @@ (alist-replace "dart" `(,dart-2.6.1) (package-native-inputs dart-2.6.1))))) + +(define-public dart-2.8.4 + (package + (inherit dart-2.7.2) + (version "2.8.4") + (source + (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/dart-lang/sdk.git") + (commit version))) + (sha256 + (base32 + "0wgchkqplx6bjgb901rm583iqbmi7fy29c1xzhlddgmnz1x7yh6c")))) + (inputs + (append + `(("dart-pkg-stagehand" + ,(dart-pkg "stagehand" "v3.3.7" + "0xwssdfcl3isrfycazqhar52dms20zvg9g4zn8pmifc86zfmkcfh"))) + (replace-inputs + dart-2.7.2 + `(("dart-pkgtested-package-config" + ,(dart-pkg "package-config" "v1.9.2" + "0gaws9v3w95fmgn74wiyif0fdjx0dvivwpzk6a3gmqjp0jrr1rqh")) + ("dart-pkg-args" + ,(dart-pkg "args" "1.6.0" + "0lwms9wysfwk1dbzrgas3qfjmxrz07n2hlzvyb21dr5scjmvm8sx")) + ("dart-pkg-async" + ,(dart-pkg "async" "2.4.1" + "0447x7v58y8fqj3zfykbpy4lmp5w39p3psxa7kk3idjvq3rdqf53")) + ("dart-pkg-cli-util" + ,(dart-pkg "cli-util" "4ad7ccbe3195fd2583b30f86a86697ef61e80f41" + "1hgnck9g39z1vcnf0lysmb5sj4917l51p7hqwvkkf475nwdhfnxm")) + ("dart-pkg-dartdoc" + ,(dart-pkg "dartdoc" "v0.30.3" + "0xks7srhg0zwl6q9rzj9ralh91144yvhi378m144ydma4b9c3vac")) + ("dart-pkg-http-multi-server" + ,(dart-pkg "http_multi_server" "ea269f79321d659208402088f3297e8920a88ee6" + "0lfkw7kkghdm29h78hafjxyp01aj9whc6s9z0dhyyc56aar4jfhf")) + ("dart-pkg-intl" + ,(dart-pkg "intl" "0.16.1" + "0a87y8vy8zm2cpyq83f7anpfq0a6kgpphcl7cq3s96b0k9dvfpkl")) + ("dart-pkg-linter" + ,(dart-pkg "linter" "0.1.114" + "1cpkqb4pzks3xphx1vilplfmmlsxhs28pfzb9k0c70wgzm4biw91")) + ("dart-pkg-matcher" + ,(dart-pkg "matcher" "0.12.5" + "0y0qnx96sxrqfw92zy9ln678isbb6cl1gfk6lisgpch3q5d7q7f1")) + ("dart-pkg-path" + ,(dart-pkg "path" "1.6.2" + "0ag6bplqw7rpysgv77nsgx86758add9jszrp4v68xhld69vn5pvd")) + ("dart-pkg-pub" + ,(dart-pkg "pub" "3606265962da4248d34d352aa3d170aae4496a90" + "0sa9yvb4zx20v1h85d3i3hv917hp5hwcghrvzcl1r9afsprkjdln")) + ("dart-pkg-pub-semver" + ,(dart-pkg "pub-semver" "v1.4.4" + "1yg9fl7ynnrp8c8iax070zx6dyakj8fbghzrxmx4rnblak63ijsj")) + ("dart-pkg-shelf-packages-handler" + ,(dart-pkg "shelf-packages-handler" "2.0.0" + "1nhvj92kjag6ids8y4ld99p3v8qk6fgygc89yyi98xf3v6ijr01b")) + ("dart-pkg-source-map-stack-trace" + ,(dart-pkg "source-map-stack-trace" "2.0.0" + "0vq22isaypcfgrajfv0f6ww74cskbl8m171kq65rg9syxs50a96g")) + ("dart-pkg-source-span" + ,(dart-pkg "source-span" "1.7.0" + "055lw4x27am90shz4wa4xlnv44ndk12gd0965ffidys705xfk1cg")) + ("dart-pkg-stream-channel" + ,(dart-pkg "stream-channel" "2.0.0" + "02hs73jj4yg9sqqw2wjrrf179svdgrzamiaqmpncz3n3x12jk0hl")) + ("dart-pkg-watcher" + ,(dart-pkg "watcher" "0.9.7+14" + "1kgxisvfbhvr5q30776plh3xn7iy0ckhy4wpzsvp2pbd63kmi2wa")) + ("dart-pkg-web-socket-channel" + ,(dart-pkg "web-socket-channel" "1.0.15" + "1dcc91f1q6fl6jzyqaplg6cc5k67wcczb93z7gqnk6lijlqlmy6g")) + ("dart-pkg-yaml" + ,(dart-pkg "yaml" "2.2.0" + "1y5xwps838yys9aw72n2300p2r5jjvz6v4klsp38y55f9kfh2dax")))))) + (native-inputs + (alist-replace "dart" `(,dart-2.7.2) + (package-native-inputs dart-2.7.2))))) -- 2.29.2 --=-=-=--