lexer: Factor some token inspectors out into new token functions.
[pspp] / src / language / lexer / token.c
index 89a5cf0102baf5fa77347ef8051469a8fde8dc77..ec64bbfb4a431cfcf0044cf0dd9a05b31755569f 100644 (file)
@@ -25,6 +25,8 @@
 #include "data/identifier.h"
 #include "libpspp/assertion.h"
 #include "libpspp/cast.h"
+#include "libpspp/misc.h"
+
 
 #include "gl/ftoastr.h"
 #include "gl/xalloc.h"
@@ -40,7 +42,7 @@ token_init (struct token *token)
 
 /* Frees the string that TOKEN contains. */
 void
-token_destroy (struct token *token)
+token_uninit (struct token *token)
 {
   if (token != NULL)
     ss_dealloc (&token->string);
@@ -51,7 +53,7 @@ number_token_to_string (const struct token *token)
 {
   char buffer[DBL_BUFSIZE_BOUND];
 
-  dtoastr (buffer, sizeof buffer, 0, 0, fabs (token->number));
+  c_dtoastr (buffer, sizeof buffer, 0, 0, fabs (token->number));
   return (token->type == T_POS_NUM
           ? xstrdup (buffer)
           : xasprintf ("-%s", buffer));
@@ -133,8 +135,6 @@ string_representation (struct substring ss)
 char *
 token_to_string (const struct token *token)
 {
-  const char *name;
-
   switch (token->type)
     {
     case T_POS_NUM:
@@ -142,14 +142,15 @@ token_to_string (const struct token *token)
       return number_token_to_string (token);
 
     case T_ID:
+    case T_MACRO_ID:
+    case T_MACRO_PUNCT:
       return ss_xstrdup (token->string);
 
     case T_STRING:
       return string_representation (token->string);
 
     default:
-      name = token_type_to_name (token->type);
-      return name != NULL ? xstrdup (name) : NULL;
+      return xstrdup_if_nonnull (token_type_to_name (token->type));
     }
 }
 
@@ -163,7 +164,7 @@ token_print (const struct token *token, FILE *stream)
     {
       char s[DBL_BUFSIZE_BOUND];
 
-      dtoastr (s, sizeof s, 0, 0, token->number);
+      c_dtoastr (s, sizeof s, 0, 0, token->number);
       fprintf (stream, "\t%s", s);
     }
   if (token->type == T_ID || token->type == T_STRING || token->string.length)
@@ -171,3 +172,19 @@ token_print (const struct token *token, FILE *stream)
              (int) token->string.length, token->string.string);
   putc ('\n', stream);
 }
+
+bool
+token_is_integer (const struct token *t)
+{
+  return (token_is_number (t)
+          && t->number > LONG_MIN
+          && t->number <= LONG_MAX
+          && floor (t->number) == t->number);
+}
+
+long
+token_integer (const struct token *t)
+{
+  assert (token_is_integer (t));
+  return t->number;
+}