Do not try to fetch more tokens if the stream end is encountered.
diff --git a/pkgs/yaml/lib/src/scanner.dart b/pkgs/yaml/lib/src/scanner.dart
index 15b0219..47efd38 100644
--- a/pkgs/yaml/lib/src/scanner.dart
+++ b/pkgs/yaml/lib/src/scanner.dart
@@ -324,6 +324,9 @@
       if (_tokens.isNotEmpty) {
         _staleSimpleKeys();
 
+        // If there are no more tokens to fetch, break.
+        if (_tokens.last.type == TokenType.STREAM_END) break;
+
         // If the current token could be a simple key, we need to scan more
         // tokens until we determine whether it is or not. Otherwise we might
         // not emit the `KEY` token before we emit the value of the key.
diff --git a/pkgs/yaml/test/yaml_test.dart b/pkgs/yaml/test/yaml_test.dart
index 153af5e..053f6be 100644
--- a/pkgs/yaml/test/yaml_test.dart
+++ b/pkgs/yaml/test/yaml_test.dart
@@ -29,26 +29,33 @@
     });
   });
 
-  group("refuses documents that declare version", () {
-    test("1.0", () {
-      expectYamlFails("""
+  group("refuses", () {
+    test("invalid contents", () {
+      // This caused the scanner to hang in an infinite loop.
+      expectYamlFails("{");
+    });
+
+    group("documents that declare version", () {
+      test("1.0", () {
+        expectYamlFails("""
          %YAML 1.0
          --- text
          """);
-    });
+      });
 
-    test("1.3", () {
-      expectYamlFails("""
-         %YAML 1.3
-         --- text
-         """);
-    });
+      test("1.3", () {
+        expectYamlFails("""
+           %YAML 1.3
+           --- text
+           """);
+      });
 
-    test("2.0", () {
-      expectYamlFails("""
-         %YAML 2.0
-         --- text
-         """);
+      test("2.0", () {
+        expectYamlFails("""
+           %YAML 2.0
+           --- text
+           """);
+      });
     });
   });