Reapply "Make --sync-async the default for the VM."

Change-Id: I6e4da0da6c3f635d84380b384ae17fbb55587895
Reviewed-on: https://dart-review.googlesource.com/58721
Reviewed-by: Vyacheslav Egorov <vegorov@google.com>
Commit-Queue: Florian Loitsch <floitsch@google.com>
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f96790f..c8b2546 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@
 
 ### Dart VM
 
+* `async` functions now start synchronously by default.
+  Passing the `--no-sync-async` flag will produce the old behavior,
+  starting `async` functions asynchronously.
+
 ### Tool Changes
 
 #### Pub
diff --git a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
index 024e565..f47d69d 100644
--- a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
+++ b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
@@ -533,15 +533,17 @@
   }
 
   Future<E> performAnalysis<E>(int times, Completer<E> completer) async {
+    // Await a microtask. Otherwise the futures are chained and would
+    // resolve linearly using up the stack.
+    await null;
     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 themselves and
-    // would therefore not wait for microtask callbacks that are scheduled after
-    // invoking this method.
-    return new Future.delayed(
-        Duration.zero, () => performAnalysis(times - 1, completer));
+    // Future.value or Future.microtask() constructors use scheduleMicrotask
+    // themselves and would therefore not wait for microtask callbacks that
+    // are scheduled after invoking this method.
+    return new Future(() => performAnalysis(times - 1, completer));
   }
 
   void resolveSource(String path, String content) {
diff --git a/pkg/analyzer/lib/src/dart/analysis/driver.dart b/pkg/analyzer/lib/src/dart/analysis/driver.dart
index 26b49f5..1bde05f 100644
--- a/pkg/analyzer/lib/src/dart/analysis/driver.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/driver.dart
@@ -1954,6 +1954,8 @@
    * priority first.
    */
   Future<Null> _run() async {
+    // Give other microtasks the time to run before doing the analysis cycle.
+    await null;
     Stopwatch timer = new Stopwatch()..start();
     PerformanceLogSection analysisSection;
     while (true) {
diff --git a/pkg/front_end/tool/_fasta/command_line.dart b/pkg/front_end/tool/_fasta/command_line.dart
index c804b1e..b34bcdf 100644
--- a/pkg/front_end/tool/_fasta/command_line.dart
+++ b/pkg/front_end/tool/_fasta/command_line.dart
@@ -212,7 +212,7 @@
   "--sdk": Uri,
   "--strong": "--strong-mode",
   "--strong-mode": false,
-  "--sync-async": false,
+  "--sync-async": true,
   "--target": String,
   "--verbose": false,
   "--verify": false,
diff --git a/pkg/vm/bin/gen_kernel.dart b/pkg/vm/bin/gen_kernel.dart
index 16212bf..151be0e 100644
--- a/pkg/vm/bin/gen_kernel.dart
+++ b/pkg/vm/bin/gen_kernel.dart
@@ -28,7 +28,8 @@
           'Produce kernel file for AOT compilation (enables global transformations).',
       defaultsTo: false)
   ..addFlag('strong-mode', help: 'Enable strong mode', defaultsTo: true)
-  ..addFlag('sync-async', help: 'Start `async` functions synchronously')
+  ..addFlag('sync-async',
+      help: 'Start `async` functions synchronously', defaultsTo: true)
   ..addFlag('embed-sources',
       help: 'Embed source files in the generated kernel component',
       defaultsTo: true)
diff --git a/pkg/vm/lib/frontend_server.dart b/pkg/vm/lib/frontend_server.dart
index 0bf5ffb..38b2e10 100644
--- a/pkg/vm/lib/frontend_server.dart
+++ b/pkg/vm/lib/frontend_server.dart
@@ -48,7 +48,7 @@
       help: 'Run compiler in strong mode (uses strong mode semantics)',
       defaultsTo: false)
   ..addFlag('sync-async',
-      help: 'Start `async` functions synchronously.', defaultsTo: false)
+      help: 'Start `async` functions synchronously.', defaultsTo: true)
   ..addFlag('tfa',
       help:
           'Enable global type flow analysis and related transformations in AOT mode.',
diff --git a/pkg/vm/test/frontend_server_test.dart b/pkg/vm/test/frontend_server_test.dart
index bfd1219..997bdf9 100644
--- a/pkg/vm/test/frontend_server_test.dart
+++ b/pkg/vm/test/frontend_server_test.dart
@@ -69,16 +69,16 @@
       )).captured;
       expect(capturedArgs.single['sdk-root'], equals('sdkroot'));
       expect(capturedArgs.single['strong'], equals(true));
-      expect(capturedArgs.single['sync-async'], equals(false));
+      expect(capturedArgs.single['sync-async'], equals(true));
     });
 
-    test('compile from command line (sync-async)', () async {
+    test('compile from command line (no-sync-async)', () async {
       final List<String> args = <String>[
         'server.dart',
         '--sdk-root',
         'sdkroot',
         '--strong',
-        '--sync-async',
+        '--no-sync-async',
       ];
       final int exitcode = await starter(args, compiler: compiler);
       expect(exitcode, equals(0));
@@ -89,7 +89,7 @@
       )).captured;
       expect(capturedArgs.single['sdk-root'], equals('sdkroot'));
       expect(capturedArgs.single['strong'], equals(true));
-      expect(capturedArgs.single['sync-async'], equals(true));
+      expect(capturedArgs.single['sync-async'], equals(false));
     });
 
     test('compile from command line with link platform', () async {
diff --git a/runtime/observatory/tests/service/async_single_step_out_test.dart b/runtime/observatory/tests/service/async_single_step_out_test.dart
index 5f0777f..7da09fb 100644
--- a/runtime/observatory/tests/service/async_single_step_out_test.dart
+++ b/runtime/observatory/tests/service/async_single_step_out_test.dart
@@ -1,7 +1,7 @@
 // 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.
-// VMOptions=--error_on_bad_type --error_on_bad_override  --verbose_debug --async_debugger
+// VMOptions=--error_on_bad_type --error_on_bad_override  --verbose_debug --async_debugger --no-sync-async
 
 import 'dart:developer';
 import 'service_test_common.dart';
diff --git a/runtime/observatory/tests/service/service.status b/runtime/observatory/tests/service/service.status
index 8a40809..bb27eed 100644
--- a/runtime/observatory/tests/service/service.status
+++ b/runtime/observatory/tests/service/service.status
@@ -16,7 +16,8 @@
 process_service_test: Pass, Fail # Issue 24344
 
 [ $compiler == app_jit ]
-bad_reload_test: RuntimeError # Issue 27806
+async_step_out_test: RuntimeError # Issue 29158, Async debuggingbad_reload_test: RuntimeError # Issue 27806
+awaiter_async_stack_contents_test: RuntimeError # Issue 29158, Async debugging
 complex_reload_test: RuntimeError # Issue 27806
 debugger_location_second_test: Skip # Issue 28180
 evaluate_activation_test/instance: RuntimeError # Issue 27806
@@ -28,6 +29,8 @@
 next_through_for_each_loop_test: RuntimeError # Snapshots don't include source and generated source is not 1-to-1. The column offsets are thus off.
 next_through_implicit_call_test: RuntimeError # Snapshots don't include source and generated source is not 1-to-1. The column offsets are thus off.
 pause_on_unhandled_async_exceptions2_test: Pass, RuntimeError, Timeout, Crash # Issue 29178
+regress_28980_test: RuntimeError # Issue 29158, Async debugging
+set_library_debuggable_test: RuntimeError # Issue 29158, Async debugging
 set_name_rpc_test: RuntimeError # Issue 27806
 step_through_constructor_calls_test: RuntimeError # Snapshots don't include source and generated source is not 1-to-1. The column offsets are thus off.
 step_through_function_test: RuntimeError # Snapshots don't include source and generated source is not 1-to-1. The column offsets are thus off.
@@ -78,8 +81,12 @@
 *: Skip
 
 [ ($compiler == none || $compiler == precompiler) && ($runtime == dart_precompiled || $runtime == vm) ]
+async_step_out_test: RuntimeError # Issue 29158, Async debugging
+awaiter_async_stack_contents_test: RuntimeError # Issue 29158, Async debugging
 evaluate_activation_test/instance: RuntimeError # http://dartbug.com/20047
 evaluate_activation_test/scope: RuntimeError # http://dartbug.com/20047
+regress_28980_test: RuntimeError # Issue 29158, Async debugging
+set_library_debuggable_test: RuntimeError # Issue 29158, Async debugging
 
 [ $arch != ia32 || $arch != x64 || $system != linux ]
 get_native_allocation_samples_test: Skip # Unsupported.
diff --git a/runtime/vm/dart_api_impl_test.cc b/runtime/vm/dart_api_impl_test.cc
index f442629..7569556 100644
--- a/runtime/vm/dart_api_impl_test.cc
+++ b/runtime/vm/dart_api_impl_test.cc
@@ -4345,43 +4345,6 @@
   EXPECT(Dart_IsError(result));
 }
 
-TEST_CASE(DartAPI_NegativeNativeFieldInIsolateMessage) {
-  const char* kScriptChars =
-      "import 'dart:isolate';\n"
-      "import 'dart:nativewrappers';\n"
-      "echo(msg) {\n"
-      "  var data = msg[0];\n"
-      "  var reply = msg[1];\n"
-      "  reply.send('echoing ${data(1)}}');\n"
-      "}\n"
-      "class Test extends NativeFieldWrapperClass2 {\n"
-      "  Test(this.i, this.j);\n"
-      "  int i, j;\n"
-      "}\n"
-      "main() {\n"
-      "  var port = new RawReceivePort();\n"
-      "  var obj = new Test(1,2);\n"
-      "  var msg = [obj, port.sendPort];\n"
-      "  var snd = Isolate.spawn(echo, msg);\n"
-      "  port.handler = (msg) {\n"
-      "    port.close();\n"
-      "    print('from worker ${msg}');\n"
-      "  };\n"
-      "}\n";
-
-  CHECK_API_SCOPE(thread);
-  HANDLESCOPE(thread);
-
-  // Create a test library and Load up a test script in it.
-  Dart_Handle lib = TestCase::LoadTestScript(kScriptChars, NULL);
-
-  // Invoke 'main' which should spawn an isolate and try to send an
-  // object with native fields over to the spawned isolate. This
-  // should result in an unhandled exception which is checked.
-  Dart_Handle retobj = Dart_Invoke(lib, NewString("main"), 0, NULL);
-  EXPECT(Dart_IsError(retobj));
-}
-
 TEST_CASE(DartAPI_GetStaticField_RunsInitializer) {
   const char* kScriptChars =
       "class TestClass  {\n"
diff --git a/runtime/vm/flag_list.h b/runtime/vm/flag_list.h
index 9c11ed9..432e3d3 100644
--- a/runtime/vm/flag_list.h
+++ b/runtime/vm/flag_list.h
@@ -151,7 +151,7 @@
   C(stress_async_stacks, false, false, bool, false,                            \
     "Stress test async stack traces")                                          \
   P(strong, bool, false, "Enable strong mode.")                                \
-  P(sync_async, bool, false, "Start `async` functions synchronously.")         \
+  P(sync_async, bool, true, "Start `async` functions synchronously.")          \
   R(support_ast_printer, false, bool, true, "Support the AST printer.")        \
   R(support_compiler_stats, false, bool, true, "Support compiler stats.")      \
   R(support_disassembler, false, bool, true, "Support the disassembler.")      \
diff --git a/runtime/vm/kernel_isolate.cc b/runtime/vm/kernel_isolate.cc
index bdba931..f0b47d5 100644
--- a/runtime/vm/kernel_isolate.cc
+++ b/runtime/vm/kernel_isolate.cc
@@ -88,7 +88,7 @@
     api_flags.enable_error_on_bad_override = false;
     api_flags.reify_generic_functions = false;
     api_flags.strong = false;
-    api_flags.sync_async = false;
+    api_flags.sync_async = true;
 #if !defined(DART_PRECOMPILER) && !defined(TARGET_ARCH_DBC)
     api_flags.use_field_guards = true;
 #endif
diff --git a/tests/co19/co19-runtime.status b/tests/co19/co19-runtime.status
index 2dd3260..577410a 100644
--- a/tests/co19/co19-runtime.status
+++ b/tests/co19/co19-runtime.status
@@ -244,6 +244,9 @@
 LibTest/collection/ListMixin/ListMixin_class_A01_t02: Skip # Timeout
 LibTest/core/Uri/Uri_A06_t03: Skip # Timeout
 
+[ $compiler == app_jit || $compiler == none || $compiler == precompiler ]
+Language/Expressions/Function_Invocation/async_invokation_t02: RuntimeError # sync-async is on by default.
+
 [ $compiler == app_jit || $compiler == precompiler ]
 Language/Mixins/Mixin_Application/error_t01: Pass
 Language/Mixins/Mixin_Application/error_t02: Pass
diff --git a/tests/language/language.status b/tests/language/language.status
index ac2747f..6032632 100644
--- a/tests/language/language.status
+++ b/tests/language/language.status
@@ -475,6 +475,10 @@
 
 [ $runtime == dart_precompiled || $runtime == vm ]
 arithmetic_test: CompileTimeError # Large integer literal
+async_await_test: RuntimeError # sync-async is on by default
+asyncstar_throw_in_catch_test: RuntimeError # sync-async is on by default
+await_nonfuture_test: RuntimeError # sync-async is on by default
+await_not_started_immediately_test: RuntimeError # sync-async is on by default
 bit_operations_test: CompileTimeError # Large integer literal
 deopt_inlined_function_lazy_test: CompileTimeError # Large integer literal
 guess_cid_test: CompileTimeError # Large integer literal
diff --git a/tests/lib/lib.status b/tests/lib/lib.status
index 116c44e..fc51aee 100644
--- a/tests/lib/lib.status
+++ b/tests/lib/lib.status
@@ -367,6 +367,7 @@
 convert/utf85_test: Skip # Pass, Slow Issue 12644.
 
 [ $compiler == app_jit || $compiler == none || $compiler == precompiler ]
+async/async_await_sync_completer_test: RuntimeError # sync-async is on by default.
 async/timer_not_available_test: SkipByDesign # only meant to test when there is no way to implement timer (currently only in d8)
 async/timer_regress22626_test: Pass, RuntimeError # Issue 28254
 mirrors/mirrors_used*: SkipByDesign # Invalid tests. MirrorsUsed does not have a specification, and dart:mirrors is not required to hide declarations that are not covered by any MirrorsUsed annotation.
diff --git a/tests/lib_2/isolate/native_wrapper_message_test.dart b/tests/lib_2/isolate/native_wrapper_message_test.dart
new file mode 100644
index 0000000..09dcb40
--- /dev/null
+++ b/tests/lib_2/isolate/native_wrapper_message_test.dart
@@ -0,0 +1,34 @@
+// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
+// for details. 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:isolate';
+import 'dart:nativewrappers';
+import 'package:expect/expect.dart';
+import 'package:async_helper/async_helper.dart';
+
+echo(msg) {
+  var data = msg[0];
+  var reply = msg[1];
+  reply.send('echoing ${data(1)}}');
+}
+
+class Test extends NativeFieldWrapperClass2 {
+  Test(this.i, this.j);
+  int i, j;
+}
+
+main() {
+  var port = new RawReceivePort();
+  var obj = new Test(1, 2);
+  var msg = [obj, port.sendPort];
+  var snd = Isolate.spawn(echo, msg);
+
+  asyncStart();
+  snd.catchError((e) {
+    Expect.isTrue(e is ArgumentError);
+    Expect.isTrue("$e".contains("NativeWrapper"));
+    port.close();
+    asyncEnd();
+  });
+}
diff --git a/tests/lib_2/lib_2_vm.status b/tests/lib_2/lib_2_vm.status
index 16463be..6b5454d 100644
--- a/tests/lib_2/lib_2_vm.status
+++ b/tests/lib_2/lib_2_vm.status
@@ -2,6 +2,9 @@
 # for details. All rights reserved. Use of this source code is governed by a
 # BSD-style license that can be found in the LICENSE file.
 
+[ $runtime != vm ]
+isolate/native_wrapper_message_test: Skip # A VM specific test.
+
 [ $arch == arm64 && $runtime == vm ]
 mirrors/immutable_collections_test: Pass, Slow # http://dartbug.com/33057