fix a number of assuptions that a long could hold an inum
[bpt/guile.git] / libguile / read.c
index 07c8d71..4a9b5ea 100644 (file)
@@ -1,4 +1,4 @@
-/* Copyright (C) 1995,1996,1997,1999,2000,2001,2003, 2004, 2006, 2007, 2008, 2009 Free Software
+/* Copyright (C) 1995,1996,1997,1999,2000,2001,2003, 2004, 2006, 2007, 2008, 2009, 2010 Free Software
  * Foundation, Inc.
  * 
  * This library is free software; you can redistribute it and/or
@@ -42,6 +42,7 @@
 #include "libguile/hashtab.h"
 #include "libguile/hash.h"
 #include "libguile/ports.h"
+#include "libguile/fports.h"
 #include "libguile/root.h"
 #include "libguile/strings.h"
 #include "libguile/strports.h"
@@ -59,6 +60,7 @@
 SCM_GLOBAL_SYMBOL (scm_sym_dot, ".");
 SCM_SYMBOL (scm_keyword_prefix, "prefix");
 SCM_SYMBOL (scm_keyword_postfix, "postfix");
+SCM_SYMBOL (sym_nil, "nil");
 
 scm_t_option scm_read_opts[] = {
   { SCM_OPTION_BOOLEAN, "copy", 0,
@@ -67,14 +69,12 @@ scm_t_option scm_read_opts[] = {
     "Record positions of source code expressions." },
   { SCM_OPTION_BOOLEAN, "case-insensitive", 0,
     "Convert symbols to lower case."},
-  { SCM_OPTION_SCM, "keywords", SCM_UNPACK (SCM_BOOL_F),
+  { SCM_OPTION_SCM, "keywords", (scm_t_bits) SCM_BOOL_F,
     "Style of keyword recognition: #f, 'prefix or 'postfix."},
-#if SCM_ENABLE_ELISP
-  { SCM_OPTION_BOOLEAN, "elisp-vectors", 0,
-    "Support Elisp vector syntax, namely `[...]'."},
-  { SCM_OPTION_BOOLEAN, "elisp-strings", 0,
-    "Support `\\(' and `\\)' in strings."},
-#endif
+  { SCM_OPTION_BOOLEAN, "r6rs-hex-escapes", 0,
+    "Use R6RS variable-length character and string hex escapes."},
+  { SCM_OPTION_BOOLEAN, "square-brackets", 1,
+    "Treat `[' and `]' as parentheses, for R6RS compatibility."},
   { 0, },
 };
 
@@ -135,9 +135,21 @@ SCM_DEFINE (scm_read_options, "read-options-interface", 0, 1, 0,
 }
 #undef FUNC_NAME
 
-/* An association list mapping extra hash characters to procedures.  */
-static SCM *scm_read_hash_procedures;
+/* A fluid referring to an association list mapping extra hash
+   characters to procedures.  */
+static SCM *scm_i_read_hash_procedures;
 
+static inline SCM
+scm_i_read_hash_procedures_ref (void)
+{
+  return scm_fluid_ref (*scm_i_read_hash_procedures);
+}
+
+static inline void
+scm_i_read_hash_procedures_set_x (SCM value)
+{
+  scm_fluid_set_x (*scm_i_read_hash_procedures, value);
+}
 
 \f
 /* Token readers.  */
@@ -170,7 +182,8 @@ static SCM *scm_read_hash_procedures;
    structure'').  */
 #define CHAR_IS_R5RS_DELIMITER(c)                              \
   (CHAR_IS_BLANK (c)                                           \
-   || (c == ')') || (c == '(') || (c == ';') || (c == '"'))
+   || (c == ')') || (c == '(') || (c == ';') || (c == '"')      \
+   || (SCM_SQUARE_BRACKETS_P && ((c == '[') || (c == ']'))))
 
 #define CHAR_IS_DELIMITER  CHAR_IS_R5RS_DELIMITER
 
@@ -181,67 +194,88 @@ static SCM *scm_read_hash_procedures;
    || ((_chr) == 'd') || ((_chr) == 'l'))
 
 /* Read an SCSH block comment.  */
-static inline SCM scm_read_scsh_block_comment (int chr, SCM port);
-static SCM scm_read_commented_expression (int chr, SCM port);
-
-/* Read from PORT until a delimiter (e.g., a whitespace) is read.  Return
-   zero if the whole token fits in BUF, non-zero otherwise.  */
+static inline SCM scm_read_scsh_block_comment (scm_t_wchar, SCM);
+static SCM scm_read_r6rs_block_comment (scm_t_wchar, SCM);
+static SCM scm_read_commented_expression (scm_t_wchar, SCM);
+static SCM scm_read_shebang (scm_t_wchar, SCM);
+static SCM scm_get_hash_procedure (int);
+
+/* Read from PORT until a delimiter (e.g., a whitespace) is read.  Put the
+   result in the pre-allocated buffer BUF.  Return zero if the whole token has
+   fewer than BUF_SIZE bytes, non-zero otherwise. READ will be set the number of
+   bytes actually read.  */
 static inline int
-read_token (SCM port, SCM buf, size_t *read)
-{
-  scm_t_wchar chr;
-  *read = 0;
+read_token (SCM port, char *buf, const size_t buf_size, size_t *read)
+ {
+   *read = 0;
 
-  buf = scm_i_string_start_writing (buf);
-  while (*read < scm_i_string_length (buf))
-    {
-      chr = scm_getc (port);
-
-      if (chr == EOF)
-       {
-         scm_i_string_stop_writing ();
-         return 0;
-       }
-
-      chr = (SCM_CASE_INSENSITIVE_P ? uc_tolower (chr) : chr);
+   while (*read < buf_size)
+     {
+       int chr;
 
-      if (CHAR_IS_DELIMITER (chr))
-       {
-         scm_i_string_stop_writing ();
-         scm_ungetc (chr, port);
-         return 0;
-       }
+       chr = scm_get_byte_or_eof (port);
 
-      scm_i_string_set_x (buf, *read, chr);
-      (*read)++;
-    }
-  scm_i_string_stop_writing ();
+       if (chr == EOF)
+        return 0;
+      else if (CHAR_IS_DELIMITER (chr))
+        {
+          scm_unget_byte (chr, port);
+          return 0;
+        }
+      else
+        {
+          *buf = (char) chr;
+          buf++, (*read)++;
+        }
+     }
 
-  return 1;
-}
+   return 1;
+ }
 
-static SCM
-read_complete_token (SCM port, size_t *read)
+/* Read from PORT until a delimiter (e.g., a whitespace) is read.  Put the
+   result in the pre-allocated buffer BUFFER, if the whole token has fewer than
+   BUFFER_SIZE bytes, or into OVERFLOW_BUFFER, allocated here to be freed by the
+   caller.  Return zero if the token fits in BUFFER, non-zero otherwise. READ
+   will be set the number of bytes actually read.  */
+static int
+read_complete_token (SCM port, char *buffer, const size_t buffer_size,
+                           char **overflow_buffer, size_t *read)
 {
-  SCM buffer, str = SCM_EOL;
-  size_t len;
-  int overflow;
+  int overflow = 0;
+  size_t bytes_read, overflow_size;
 
-  buffer = scm_i_make_string (READER_BUFFER_SIZE, NULL); 
-  overflow = read_token (port, buffer, read);
-  if (!overflow)
-    return scm_i_substring (buffer, 0, *read);
+  *overflow_buffer = NULL;
+  overflow_size = 0;
 
-  str = scm_string_copy (buffer);
   do
     {
-      overflow = read_token (port, buffer, &len);
-      str = scm_string_append (scm_list_2 (str, buffer));
-      *read += len;
+      overflow = read_token (port, buffer, buffer_size, &bytes_read);
+      if (bytes_read == 0)
+        break;
+      if (overflow || overflow_size != 0)
+        {
+          if (overflow_size == 0)
+            {
+              *overflow_buffer = scm_malloc (bytes_read);
+              memcpy (*overflow_buffer, buffer, bytes_read);
+              overflow_size = bytes_read;
+            }
+          else
+            {
+              *overflow_buffer = scm_realloc (*overflow_buffer, overflow_size + bytes_read);
+              memcpy (*overflow_buffer + overflow_size, buffer, bytes_read);
+              overflow_size += bytes_read;
+            }
+        }
     }
   while (overflow);
 
-  return scm_i_substring (str, 0, *read);
+  if (overflow_size)
+    *read = overflow_size;
+  else
+    *read = bytes_read;
+
+  return (overflow_size != 0);
 }
 
 /* Skip whitespace from PORT and return the first non-whitespace character
@@ -284,11 +318,18 @@ flush_ws (SCM port, const char *eoferr)
            eoferr = "read_sharp";
            goto goteof;
          case '!':
-           scm_read_scsh_block_comment (c, port);
+           scm_read_shebang (c, port);
            break;
          case ';':
            scm_read_commented_expression (c, port);
            break;
+         case '|':
+           if (scm_is_false (scm_get_hash_procedure (c)))
+             {
+               scm_read_r6rs_block_comment (c, port);
+               break;
+             }
+           /* fall through */
          default:
            scm_ungetc (c, port);
            return '#';
@@ -313,7 +354,6 @@ flush_ws (SCM port, const char *eoferr)
 
 static SCM scm_read_expression (SCM port);
 static SCM scm_read_sharp (int chr, SCM port);
-static SCM scm_get_hash_procedure (int c);
 static SCM recsexpr (SCM obj, long line, int column, SCM filename);
 
 
@@ -325,7 +365,7 @@ scm_read_sexp (scm_t_wchar chr, SCM port)
   register SCM tmp;
   register SCM tl, ans = SCM_EOL;
   SCM tl2 = SCM_EOL, ans2 = SCM_EOL, copy = SCM_BOOL_F;
-  static const int terminating_char = ')';
+  const int terminating_char = ((chr == '[') ? ']' : ')');
 
   /* Need to capture line and column numbers here. */
   long line = SCM_LINUM (port);
@@ -360,9 +400,15 @@ scm_read_sexp (scm_t_wchar chr, SCM port)
     {
       SCM new_tail;
 
+      if (c == ')' || (SCM_SQUARE_BRACKETS_P && c == ']'))
+        scm_i_input_error (FUNC_NAME, port,
+                           "in pair: mismatched close paren: ~A",
+                           scm_list_1 (SCM_MAKE_CHAR (c)));
+
       scm_ungetc (c, port);
-      if (scm_is_eq (scm_sym_dot,
-                    (tmp = scm_read_expression (port))))
+      tmp = scm_read_expression (port);
+
+      if (scm_is_eq (scm_sym_dot, tmp))
        {
          SCM_SETCDR (tl, tmp = scm_read_expression (port));
 
@@ -405,6 +451,41 @@ scm_read_sexp (scm_t_wchar chr, SCM port)
 }
 #undef FUNC_NAME
 
+
+/* Read a hexadecimal number NDIGITS in length.  Put its value into the variable
+   C.  If TERMINATOR is non-null, terminate early if the TERMINATOR character is
+   found.  */
+#define SCM_READ_HEX_ESCAPE(ndigits, terminator)                   \
+  do                                                               \
+    {                                                              \
+      scm_t_wchar a;                                               \
+      size_t i = 0;                                                \
+      c = 0;                                                       \
+      while (i < ndigits)                                          \
+        {                                                          \
+          a = scm_getc (port);                                     \
+          if (a == EOF)                                            \
+            goto str_eof;                                          \
+          if (terminator                                           \
+              && (a == (scm_t_wchar) terminator)                   \
+              && (i > 0))                                          \
+            break;                                                 \
+          if ('0' <= a && a <= '9')                                \
+            a -= '0';                                              \
+          else if ('A' <= a && a <= 'F')                           \
+            a = a - 'A' + 10;                                      \
+          else if ('a' <= a && a <= 'f')                           \
+            a = a - 'a' + 10;                                      \
+          else                                                     \
+            {                                                      \
+              c = a;                                               \
+              goto bad_escaped;                                    \
+            }                                                      \
+          c = c * 16 + a;                                          \
+          i ++;                                                    \
+        }                                                          \
+    } while (0)
+
 static SCM
 scm_read_string (int chr, SCM port)
 #define FUNC_NAME "scm_lreadr"
@@ -442,13 +523,6 @@ scm_read_string (int chr, SCM port)
             case '"':
             case '\\':
               break;
-#if SCM_ENABLE_ELISP
-            case '(':
-            case ')':
-              if (SCM_ESCAPED_PARENS_P)
-                break;
-              goto bad_escaped;
-#endif
             case '\n':
               continue;
             case '0':
@@ -472,90 +546,27 @@ scm_read_string (int chr, SCM port)
             case 'v':
               c = '\v';
               break;
+            case 'b':
+              c = '\010';
+              break;
             case 'x':
-              {
-                scm_t_wchar a, b;
-                a = scm_getc (port);
-                if (a == EOF)
-                  goto str_eof;
-                b = scm_getc (port);
-                if (b == EOF)
-                  goto str_eof;
-                if ('0' <= a && a <= '9')
-                  a -= '0';
-                else if ('A' <= a && a <= 'F')
-                  a = a - 'A' + 10;
-                else if ('a' <= a && a <= 'f')
-                  a = a - 'a' + 10;
-                else
-                  {
-                    c = a;
-                    goto bad_escaped;
-                  }
-                if ('0' <= b && b <= '9')
-                  b -= '0';
-                else if ('A' <= b && b <= 'F')
-                  b = b - 'A' + 10;
-                else if ('a' <= b && b <= 'f')
-                  b = b - 'a' + 10;
-                else
-                  {
-                    c = b;
-                    goto bad_escaped;
-                  }
-                c = a * 16 + b;
-                break;
-              }
+              if (SCM_R6RS_ESCAPES_P)
+                SCM_READ_HEX_ESCAPE (10, ';');
+              else
+                SCM_READ_HEX_ESCAPE (2, '\0');
+              break;
             case 'u':
-              {
-                scm_t_wchar a;
-                int i;
-                c = 0;
-                for (i = 0; i < 4; i++)
-                  {
-                    a = scm_getc (port);
-                    if (a == EOF)
-                      goto str_eof;
-                    if ('0' <= a && a <= '9')
-                      a -= '0';
-                    else if ('A' <= a && a <= 'F')
-                      a = a - 'A' + 10;
-                    else if ('a' <= a && a <= 'f')
-                      a = a - 'a' + 10;
-                    else
-                      {
-                        c = a;
-                        goto bad_escaped;
-                      }
-                    c = c * 16 + a;
-                  }
-                break;
-              }
+              if (!SCM_R6RS_ESCAPES_P)
+                {
+                  SCM_READ_HEX_ESCAPE (4, '\0');
+                  break;
+                }
             case 'U':
-              {
-                scm_t_wchar a;
-                int i;
-                c = 0;
-                for (i = 0; i < 6; i++)
-                  {
-                    a = scm_getc (port);
-                    if (a == EOF)
-                      goto str_eof;
-                    if ('0' <= a && a <= '9')
-                      a -= '0';
-                    else if ('A' <= a && a <= 'F')
-                      a = a - 'A' + 10;
-                    else if ('a' <= a && a <= 'f')
-                      a = a - 'a' + 10;
-                    else
-                      {
-                        c = a;
-                        goto bad_escaped;
-                      }
-                    c = c * 16 + a;
-                  }
-                break;
-              }
+              if (!SCM_R6RS_ESCAPES_P)
+                {
+                  SCM_READ_HEX_ESCAPE (6, '\0');
+                  break;
+                }
             default:
             bad_escaped:
               scm_i_input_error (FUNC_NAME, port,
@@ -572,7 +583,7 @@ scm_read_string (int chr, SCM port)
     {
       return scm_i_substring_copy (str, 0, c_str_len);
     }
-  
+
   return scm_nullstr;
 }
 #undef FUNC_NAME
@@ -581,17 +592,35 @@ scm_read_string (int chr, SCM port)
 static SCM
 scm_read_number (scm_t_wchar chr, SCM port)
 {
-  SCM result;
-  SCM buffer;
-  size_t read;
+  SCM result, str = SCM_EOL;
+  char buffer[READER_BUFFER_SIZE];
+  char *overflow_buffer = NULL;
+  size_t bytes_read;
+  int overflow;
+  scm_t_port *pt = SCM_PTAB_ENTRY (port);
 
   scm_ungetc (chr, port);
-  buffer = read_complete_token (port, &read);
-  result = scm_string_to_number (buffer, SCM_UNDEFINED);
+  overflow = read_complete_token (port, buffer, sizeof (buffer),
+                                  &overflow_buffer, &bytes_read);
+
+  if (!overflow)
+    str = scm_from_stringn (buffer, bytes_read, pt->encoding, pt->ilseq_handler);
+  else
+    str = scm_from_stringn (overflow_buffer, bytes_read, pt->encoding,
+                            pt->ilseq_handler);
+
+  result = scm_string_to_number (str, SCM_UNDEFINED);
   if (!scm_is_true (result))
-    /* Return a symbol instead of a number.  */
-    result = scm_string_to_symbol (buffer);
+    {
+      /* Return a symbol instead of a number */
+      if (SCM_CASE_INSENSITIVE_P)
+        str = scm_string_downcase_x (str);
+      result = scm_string_to_symbol (str);
+    }
 
+  if (overflow)
+    free (overflow_buffer);
+  SCM_COL (port) += scm_i_string_length (str);
   return result;
 }
 
@@ -600,20 +629,52 @@ scm_read_mixed_case_symbol (scm_t_wchar chr, SCM port)
 {
   SCM result;
   int ends_with_colon = 0;
-  SCM buffer;
-  size_t read = 0;
+  size_t bytes_read;
   int postfix = scm_is_eq (SCM_PACK (SCM_KEYWORD_STYLE), scm_keyword_postfix);
+  int overflow;
+  char buffer[READER_BUFFER_SIZE], *overflow_buffer;
+  scm_t_port *pt = SCM_PTAB_ENTRY (port);
+  SCM str;
 
   scm_ungetc (chr, port);
-  buffer = read_complete_token (port, &read);
-  if (read > 0)
-    ends_with_colon = scm_i_string_ref (buffer, read - 1) == ':';
+  overflow = read_complete_token (port, buffer, READER_BUFFER_SIZE,
+                                  &overflow_buffer, &bytes_read);
+  if (bytes_read > 0)
+    {
+      if (!overflow)
+        ends_with_colon = buffer[bytes_read - 1] == ':';
+      else
+        ends_with_colon = overflow_buffer[bytes_read - 1] == ':';
+    }
 
-  if (postfix && ends_with_colon && (read > 1))
-    result = scm_symbol_to_keyword (scm_string_to_symbol (scm_i_substring (buffer, 0, read - 1)));
+  if (postfix && ends_with_colon && (bytes_read > 1))
+    {
+      if (!overflow)
+        str = scm_from_stringn (buffer, bytes_read - 1, pt->encoding, pt->ilseq_handler);
+      else
+        str = scm_from_stringn (overflow_buffer, bytes_read - 1, pt->encoding,
+                                pt->ilseq_handler);
+
+      if (SCM_CASE_INSENSITIVE_P)
+        str = scm_string_downcase_x (str);
+      result = scm_symbol_to_keyword (scm_string_to_symbol (str));
+    }
   else
-    result = scm_string_to_symbol (buffer);
+    {
+      if (!overflow)
+        str = scm_from_stringn (buffer, bytes_read, pt->encoding, pt->ilseq_handler);
+      else
+        str = scm_from_stringn (overflow_buffer, bytes_read, pt->encoding,
+                                pt->ilseq_handler);
 
+      if (SCM_CASE_INSENSITIVE_P)
+        str = scm_string_downcase_x (str);
+      result = scm_string_to_symbol (str);
+    }
+
+  if (overflow)
+    free (overflow_buffer);
+  SCM_COL (port) += scm_i_string_length (str);
   return result;
 }
 
@@ -623,8 +684,11 @@ scm_read_number_and_radix (scm_t_wchar chr, SCM port)
 {
   SCM result;
   size_t read;
-  SCM buffer = scm_i_make_string (READER_BUFFER_SIZE, NULL);
+  char buffer[READER_BUFFER_SIZE], *overflow_buffer;
+  int overflow;
   unsigned int radix;
+  SCM str;
+  scm_t_port *pt;
 
   switch (chr)
     {
@@ -654,8 +718,22 @@ scm_read_number_and_radix (scm_t_wchar chr, SCM port)
       radix = 10;
     }
 
-  buffer = read_complete_token (port, &read);
-  result = scm_string_to_number (buffer, scm_from_uint (radix));
+  overflow = read_complete_token (port, buffer, sizeof (buffer),
+                                  &overflow_buffer, &read);
+
+  pt = SCM_PTAB_ENTRY (port);
+  if (!overflow)
+    str = scm_from_stringn (buffer, read, pt->encoding, pt->ilseq_handler);
+  else
+    str = scm_from_stringn (overflow_buffer, read, pt->encoding,
+                            pt->ilseq_handler);
+
+  result = scm_string_to_number (str, scm_from_uint (radix));
+
+  if (overflow)
+    free (overflow_buffer);
+
+  SCM_COL (port) += scm_i_string_length (str);
 
   if (scm_is_true (result))
     return result;
@@ -779,6 +857,19 @@ scm_read_syntax (int chr, SCM port)
   return p;
 }
 
+static inline SCM
+scm_read_nil (int chr, SCM port)
+{
+  SCM id = scm_read_mixed_case_symbol (chr, port);
+
+  if (!scm_is_eq (id, sym_nil))
+    scm_i_input_error ("scm_read_nil", port,
+                       "unexpected input while reading #nil: ~a",
+                       scm_list_1 (id));
+
+  return SCM_ELISP_NIL;
+}
+  
 static inline SCM
 scm_read_semicolon_comment (int chr, SCM port)
 {
@@ -789,7 +880,7 @@ scm_read_semicolon_comment (int chr, SCM port)
      always represents itself no matter what the encoding is.  */
   for (c = scm_get_byte_or_eof (port);
        (c != EOF) && (c != '\n');
-       c = scm_getc (port));
+       c = scm_get_byte_or_eof (port));
 
   return SCM_UNSPECIFIED;
 }
@@ -818,18 +909,18 @@ static SCM
 scm_read_character (scm_t_wchar chr, SCM port)
 #define FUNC_NAME "scm_lreadr"
 {
-  SCM charname = scm_i_make_string (READER_CHAR_NAME_MAX_SIZE, NULL);
-  size_t charname_len;
+  char buffer[READER_CHAR_NAME_MAX_SIZE];
+  SCM charname;
+  size_t charname_len, bytes_read;
   scm_t_wchar cp;
   int overflow;
+  scm_t_port *pt;
 
-  overflow = read_token (port, charname, &charname_len);
-  charname = scm_c_substring (charname, 0, charname_len);
-
+  overflow = read_token (port, buffer, READER_CHAR_NAME_MAX_SIZE, &bytes_read);
   if (overflow)
-    goto char_error;
+    scm_i_input_error (FUNC_NAME, port, "character name too long", SCM_EOL);
 
-  if (charname_len == 0)
+  if (bytes_read == 0)
     {
       chr = scm_getc (port);
       if (chr == EOF)
@@ -840,10 +931,29 @@ scm_read_character (scm_t_wchar chr, SCM port)
       return (SCM_MAKE_CHAR (chr));
     }
 
-  if (charname_len == 1)
-    return SCM_MAKE_CHAR (scm_i_string_ref (charname, 0));
+  pt = SCM_PTAB_ENTRY (port);
 
+  /* Simple ASCII characters can be processed immediately.  Also, simple
+     ISO-8859-1 characters can be processed immediately if the encoding for this
+     port is ISO-8859-1.  */
+  if (bytes_read == 1 && ((unsigned char) buffer[0] <= 127 || pt->encoding == NULL))
+    {
+      SCM_COL (port) += 1;
+      return SCM_MAKE_CHAR (buffer[0]);
+    }
+
+  /* Otherwise, convert the buffer into a proper scheme string for
+     processing.  */
+  charname = scm_from_stringn (buffer, bytes_read, pt->encoding,
+                              pt->ilseq_handler);
+  charname_len = scm_i_string_length (charname);
+  SCM_COL (port) += charname_len;
   cp = scm_i_string_ref (charname, 0);
+  if (charname_len == 1)
+    return SCM_MAKE_CHAR (cp);
+
+  /* Ignore dotted circles, which may be used to keep combining characters from
+     combining with the backslash in #\charname.  */
   if (cp == SCM_CODEPOINT_DOTTED_CIRCLE && charname_len == 2)
     return SCM_MAKE_CHAR (scm_i_string_ref (charname, 1));
 
@@ -855,16 +965,35 @@ scm_read_character (scm_t_wchar chr, SCM port)
       SCM p = scm_string_to_number (charname, scm_from_uint (8));
       if (SCM_I_INUMP (p))
         {
-          scm_t_wchar c = SCM_I_INUM (p);
+          scm_t_wchar c = scm_to_uint32 (p);
           if (SCM_IS_UNICODE_CHAR (c))
             return SCM_MAKE_CHAR (c);
           else
-            scm_i_input_error (FUNC_NAME, port, 
+            scm_i_input_error (FUNC_NAME, port,
                                "out-of-range octal character escape: ~a",
                                scm_list_1 (charname));
         }
     }
 
+  if (cp == 'x' && (charname_len > 1))
+    {
+      SCM p;
+
+      /* Convert from hex, skipping the initial 'x' character in CHARNAME */
+      p = scm_string_to_number (scm_c_substring (charname, 1, charname_len),
+                                scm_from_uint (16));
+      if (SCM_I_INUMP (p))
+        {
+          scm_t_wchar c = scm_to_uint32 (p);
+          if (SCM_IS_UNICODE_CHAR (c))
+            return SCM_MAKE_CHAR (c);
+          else
+            scm_i_input_error (FUNC_NAME, port,
+                               "out-of-range hex character escape: ~a",
+                               scm_list_1 (charname));
+        }
+    }
+
   /* The names of characters should never have non-Latin1
      characters.  */
   if (scm_i_is_narrow_string (charname)
@@ -875,7 +1004,6 @@ scm_read_character (scm_t_wchar chr, SCM port)
         return ch;
     }
 
- char_error:
   scm_i_input_error (FUNC_NAME, port, "unknown character name ~a",
                     scm_list_1 (charname));
 
@@ -990,6 +1118,79 @@ scm_read_scsh_block_comment (scm_t_wchar chr, SCM port)
   return SCM_UNSPECIFIED;
 }
 
+static inline SCM
+scm_read_shebang (scm_t_wchar chr, SCM port)
+{
+  int c = 0;
+  if ((c = scm_get_byte_or_eof (port)) != 'r')
+    {
+      scm_ungetc (c, port);
+      return scm_read_scsh_block_comment (chr, port);
+    }
+  if ((c = scm_get_byte_or_eof (port)) != '6')
+    {
+      scm_ungetc (c, port);
+      scm_ungetc ('r', port);
+      return scm_read_scsh_block_comment (chr, port);
+    }
+  if ((c = scm_get_byte_or_eof (port)) != 'r')
+    {
+      scm_ungetc (c, port);
+      scm_ungetc ('6', port);
+      scm_ungetc ('r', port);
+      return scm_read_scsh_block_comment (chr, port);
+    }
+  if ((c = scm_get_byte_or_eof (port)) != 's')
+    {
+      scm_ungetc (c, port);
+      scm_ungetc ('r', port);
+      scm_ungetc ('6', port);
+      scm_ungetc ('r', port);
+      return scm_read_scsh_block_comment (chr, port);
+    }
+  
+  return SCM_UNSPECIFIED;
+}
+
+static SCM
+scm_read_r6rs_block_comment (scm_t_wchar chr, SCM port)
+{
+  /* Unlike SCSH-style block comments, SRFI-30/R6RS block comments may be
+     nested.  So care must be taken.  */
+  int nesting_level = 1;
+  int opening_seen = 0, closing_seen = 0;
+
+  while (nesting_level > 0)
+    {
+      int c = scm_getc (port);
+
+      if (c == EOF)
+       scm_i_input_error ("scm_read_r6rs_block_comment", port,
+                          "unterminated `#| ... |#' comment", SCM_EOL);
+
+      if (opening_seen)
+       {
+         if (c == '|')
+           nesting_level++;
+         opening_seen = 0;
+       }
+      else if (closing_seen)
+       {
+         if (c == '#')
+           nesting_level--;
+         closing_seen = 0;
+       }
+      else if (c == '|')
+       closing_seen = 1;
+      else if (c == '#')
+       opening_seen = 1;
+      else
+       opening_seen = closing_seen = 0;
+    }
+
+  return SCM_UNSPECIFIED;
+}
+
 static SCM
 scm_read_commented_expression (scm_t_wchar chr, SCM port)
 {
@@ -1041,8 +1242,10 @@ scm_read_extended_symbol (scm_t_wchar chr, SCM port)
 
       if (len >= scm_i_string_length (buf) - 2)
        {
+         SCM addy;
+
          scm_i_string_stop_writing ();
-         SCM addy = scm_i_make_string (1024, NULL);
+         addy = scm_i_make_string (1024, NULL);
          buf = scm_string_append (scm_list_2 (buf, addy));
          len = 0;
          buf = scm_i_string_start_writing (buf);
@@ -1163,18 +1366,31 @@ scm_read_sharp (scm_t_wchar chr, SCM port)
     case '{':
       return (scm_read_extended_symbol (chr, port));
     case '!':
-      return (scm_read_scsh_block_comment (chr, port));
+      return (scm_read_shebang (chr, port));
     case ';':
       return (scm_read_commented_expression (chr, port));
     case '`':
     case '\'':
     case ',':
       return (scm_read_syntax (chr, port));
+    case 'n':
+      return (scm_read_nil (chr, port));
     default:
       result = scm_read_sharp_extension (chr, port);
       if (scm_is_eq (result, SCM_UNSPECIFIED))
-       scm_i_input_error (FUNC_NAME, port, "Unknown # object: ~S",
-                          scm_list_1 (SCM_MAKE_CHAR (chr)));
+       {
+         /* To remain compatible with 1.8 and earlier, the following
+            characters have lower precedence than `read-hash-extend'
+            characters.  */
+         switch (chr)
+           {
+           case '|':
+             return scm_read_r6rs_block_comment (chr, port);
+           default:
+             scm_i_input_error (FUNC_NAME, port, "Unknown # object: ~S",
+                                scm_list_1 (SCM_MAKE_CHAR (chr)));
+           }
+       }
       else
        return result;
     }
@@ -1201,6 +1417,10 @@ scm_read_expression (SCM port)
        case ';':
          (void) scm_read_semicolon_comment (chr, port);
          break;
+       case '[':
+          if (!SCM_SQUARE_BRACKETS_P)
+            return (scm_read_mixed_case_symbol (chr, port));
+          /* otherwise fall through */
        case '(':
          return (scm_read_sexp (chr, port));
        case '"':
@@ -1222,6 +1442,10 @@ scm_read_expression (SCM port)
        case ')':
          scm_i_input_error (FUNC_NAME, port, "unexpected \")\"", SCM_EOL);
          break;
+       case ']':
+          if (SCM_SQUARE_BRACKETS_P)
+            scm_i_input_error (FUNC_NAME, port, "unexpected \"]\"", SCM_EOL);
+          /* otherwise fall through */
        case EOF:
          return SCM_EOF_VAL;
        case ':':
@@ -1339,7 +1563,7 @@ SCM_DEFINE (scm_read_hash_extend, "read-hash-extend", 2, 0, 0,
              proc, SCM_ARG2, FUNC_NAME);
 
   /* Check if chr is already in the alist.  */
-  this = *scm_read_hash_procedures;
+  this = scm_i_read_hash_procedures_ref ();
   prev = SCM_BOOL_F;
   while (1)
     {
@@ -1348,8 +1572,9 @@ SCM_DEFINE (scm_read_hash_extend, "read-hash-extend", 2, 0, 0,
          /* not found, so add it to the beginning.  */
          if (scm_is_true (proc))
            {
-             *scm_read_hash_procedures = 
-               scm_cons (scm_cons (chr, proc), *scm_read_hash_procedures);
+              SCM new = scm_cons (scm_cons (chr, proc),
+                                  scm_i_read_hash_procedures_ref ());
+             scm_i_read_hash_procedures_set_x (new);
            }
          break;
        }
@@ -1361,8 +1586,8 @@ SCM_DEFINE (scm_read_hash_extend, "read-hash-extend", 2, 0, 0,
              /* remove it.  */
              if (scm_is_false (prev))
                {
-                 *scm_read_hash_procedures =
-                   SCM_CDR (*scm_read_hash_procedures);
+                  SCM rest = SCM_CDR (scm_i_read_hash_procedures_ref ());
+                 scm_i_read_hash_procedures_set_x (rest);
                }
              else
                scm_set_cdr_x (prev, SCM_CDR (this));
@@ -1386,7 +1611,7 @@ SCM_DEFINE (scm_read_hash_extend, "read-hash-extend", 2, 0, 0,
 static SCM
 scm_get_hash_procedure (int c)
 {
-  SCM rest = *scm_read_hash_procedures;
+  SCM rest = scm_i_read_hash_procedures_ref ();
 
   while (1)
     {
@@ -1402,20 +1627,27 @@ scm_get_hash_procedure (int c)
 
 #define SCM_ENCODING_SEARCH_SIZE (500)
 
-/* Search the first few hundred characters of a file for
-   an emacs-like coding declaration.  */
+/* Search the first few hundred characters of a file for an Emacs-like coding
+   declaration.  Returns either NULL or a string whose storage has been
+   allocated with `scm_gc_malloc ()'.  */
 char *
-scm_scan_for_encoding (SCM port)
+scm_i_scan_for_encoding (SCM port)
 {
   char header[SCM_ENCODING_SEARCH_SIZE+1];
-  size_t bytes_read;
+  size_t bytes_read, encoding_length, i;
   char *encoding = NULL;
   int utf8_bom = 0;
-  char *pos;
-  int i;
+  char *pos, *encoding_start;
   int in_comment;
 
-  bytes_read = scm_c_read (port, header, SCM_ENCODING_SEARCH_SIZE);  
+  if (SCM_FPORTP (port) && !SCM_FDES_RANDOM_P (SCM_FPORT_FDES (port)))
+    /* PORT is a non-seekable file port (e.g., as created by Bash when using
+       "guile <(echo '(display "hello")')") so bail out.  */
+    return NULL;
+
+  bytes_read = scm_c_read (port, header, SCM_ENCODING_SEARCH_SIZE);
+  header[bytes_read] = '\0';
+
   scm_seek (port, scm_from_int (0), scm_from_int (SEEK_SET));
 
   if (bytes_read > 3 
@@ -1444,60 +1676,59 @@ scm_scan_for_encoding (SCM port)
     pos ++;
 
   /* grab the next token */
+  encoding_start = pos;
   i = 0;
-  while (pos + i - header <= SCM_ENCODING_SEARCH_SIZE 
-         && pos + i - header < bytes_read
-        && (isalnum((int) pos[i]) || pos[i] == '_' || pos[i] == '-' 
-             || pos[i] == '.'))
+  while (encoding_start + i - header <= SCM_ENCODING_SEARCH_SIZE
+         && encoding_start + i - header < bytes_read
+        && (isalnum ((int) encoding_start[i])
+            || strchr ("_-.:/,+=()", encoding_start[i]) != NULL))
     i++;
 
-  if (i == 0)
+  encoding_length = i;
+  if (encoding_length == 0)
     return NULL;
 
-  encoding = scm_malloc (i+1);
-  memcpy (encoding, pos, i);
-  encoding[i] ='\0';
-  for (i = 0; i < strlen (encoding); i++)
+  encoding = scm_gc_strndup (encoding_start, encoding_length, "encoding");
+  for (i = 0; i < encoding_length; i++)
     encoding[i] = toupper ((int) encoding[i]);
 
   /* push backwards to make sure we were in a comment */
   in_comment = 0;
-  while (pos - i - header > 0)
+  pos = encoding_start;
+  while (pos >= header)
     {
-      if (*(pos - i) == '\n')
+      if (*pos == '\n')
        {
          /* This wasn't in a semicolon comment. Check for a
           hash-bang comment. */
          char *beg = strstr (header, "#!");
          char *end = strstr (header, "!#");
-         if (beg < pos && pos < end)
+         if (beg < encoding_start && encoding_start + encoding_length < end)
            in_comment = 1;
          break;
        }
-      if (*(pos - i) == ';')
+      if (*pos == ';')
        {
          in_comment = 1;
          break;
        }
-      i ++;
+      pos --;
     }
   if (!in_comment)
-    {
-      /* This wasn't in a comment */
-      free (encoding);
-      return NULL;
-    }
+    /* This wasn't in a comment */
+    return NULL;
+
   if (utf8_bom && strcmp(encoding, "UTF-8"))
-    scm_misc_error (NULL, 
+    scm_misc_error (NULL,
                    "the port input declares the encoding ~s but is encoded as UTF-8",
                    scm_list_1 (scm_from_locale_string (encoding)));
-      
+
   return encoding;
 }
 
 SCM_DEFINE (scm_file_encoding, "file-encoding", 1, 0, 0,
             (SCM port),
-            "Scans the port for an EMACS-like character coding declaration\n"
+            "Scans the port for an Emacs-like character coding declaration\n"
             "near the top of the contents of a port with random-acessible contents.\n"
             "The coding declaration is of the form\n"
             "@code{coding: XXXXX} and must appear in a scheme comment.\n"
@@ -1508,17 +1739,16 @@ SCM_DEFINE (scm_file_encoding, "file-encoding", 1, 0, 0,
 {
   char *enc;
   SCM s_enc;
-  
-  enc = scm_scan_for_encoding (port);
+
+  enc = scm_i_scan_for_encoding (port);
   if (enc == NULL)
     return SCM_BOOL_F;
   else
     {
       s_enc = scm_from_locale_string (enc);
-      free (enc);
       return s_enc;
     }
-  
+
   return SCM_BOOL_F;
 }
 #undef FUNC_NAME
@@ -1526,8 +1756,13 @@ SCM_DEFINE (scm_file_encoding, "file-encoding", 1, 0, 0,
 void
 scm_init_read ()
 {
-  scm_read_hash_procedures =
-    SCM_VARIABLE_LOC (scm_c_define ("read-hash-procedures", SCM_EOL));
+  SCM read_hash_procs;
+
+  read_hash_procs = scm_make_fluid ();
+  scm_fluid_set_x (read_hash_procs, SCM_EOL);
+  
+  scm_i_read_hash_procedures =
+    SCM_VARIABLE_LOC (scm_c_define ("%read-hash-procedures", read_hash_procs));
 
   scm_init_opts (scm_read_options, scm_read_opts);
 #include "libguile/read.x"