picrin/src/symbol.c

106 lines
2.0 KiB
C
Raw Normal View History

2014-01-17 06:58:31 -05:00
/**
* See Copyright Notice in picrin.h
*/
2013-10-10 04:22:25 -04:00
#include <string.h>
2013-10-13 03:01:40 -04:00
#include <stdlib.h>
2014-01-12 02:03:36 -05:00
#include <math.h>
2013-10-10 04:22:25 -04:00
#include "picrin.h"
#include "picrin/string.h"
2013-10-20 01:05:35 -04:00
2013-10-28 13:11:31 -04:00
pic_sym
pic_intern_cstr(pic_state *pic, const char *str)
2013-10-20 01:05:35 -04:00
{
xh_entry *e;
2013-10-28 13:11:31 -04:00
pic_sym id;
2013-10-20 01:05:35 -04:00
2014-02-12 10:14:03 -05:00
e = xh_get(pic->syms, str);
2013-10-28 13:11:31 -04:00
if (e) {
return e->val;
2013-10-20 01:05:35 -04:00
}
str = pic_strdup(pic, str);
2014-02-12 10:14:03 -05:00
id = pic->sym_cnt++;
xh_put(pic->syms, str, id);
xh_put_int(pic->sym_names, id, (long)str);
2013-10-28 13:11:31 -04:00
return id;
2013-10-20 01:05:35 -04:00
}
2014-01-12 02:03:36 -05:00
pic_sym
pic_gensym(pic_state *pic, pic_sym base)
{
2014-02-12 23:53:56 -05:00
int id;
2014-01-12 02:03:36 -05:00
char *str;
pic_sym uniq;
2014-02-12 23:53:56 -05:00
id = ++pic->uniq_sym_cnt;
str = (char *)pic_alloc(pic, strlen(pic_symbol_name(pic, base)) + (int)log10(id) + 3);
sprintf(str, "%s@%d", pic_symbol_name(pic, base), id);
2014-01-12 02:03:36 -05:00
2014-02-12 23:52:11 -05:00
/* don't put the symbol to pic->syms to keep it uninterned */
2014-02-12 10:14:03 -05:00
uniq = pic->sym_cnt++;
xh_put_int(pic->sym_names, uniq, (long)str);
2014-01-12 02:03:36 -05:00
return uniq;
}
bool
pic_interned_p(pic_state *pic, pic_sym sym)
{
return sym == pic_intern_cstr(pic, pic_symbol_name(pic, sym));
}
2013-10-28 13:11:31 -04:00
const char *
pic_symbol_name(pic_state *pic, pic_sym sym)
2013-10-20 01:05:35 -04:00
{
2014-02-12 10:14:03 -05:00
return (const char *)xh_get_int(pic->sym_names, sym)->val;
2013-10-10 04:22:25 -04:00
}
2013-10-28 13:49:38 -04:00
static pic_value
pic_symbol_symbol_p(pic_state *pic)
{
pic_value v;
pic_get_args(pic, "o", &v);
2014-01-30 13:03:36 -05:00
return pic_bool_value(pic_sym_p(v));
2013-10-28 13:49:38 -04:00
}
static pic_value
pic_symbol_symbol_to_string(pic_state *pic)
{
pic_value v;
pic_get_args(pic, "o", &v);
2014-01-30 13:03:36 -05:00
if (! pic_sym_p(v)) {
2013-10-28 13:49:38 -04:00
pic_error(pic, "symbol->string: expected symbol");
}
return pic_obj_value(pic_str_new_cstr(pic, pic_symbol_name(pic, pic_sym(v))));
2013-10-28 13:49:38 -04:00
}
static pic_value
pic_symbol_string_to_symbol(pic_state *pic)
{
pic_value v;
pic_get_args(pic, "o", &v);
if (! pic_str_p(v)) {
pic_error(pic, "string->symbol: expected string");
}
return pic_symbol_value(pic_intern_cstr(pic, pic_str_cstr(pic_str_ptr(v))));
2013-10-28 13:49:38 -04:00
}
void
pic_init_symbol(pic_state *pic)
{
pic_defun(pic, "symbol?", pic_symbol_symbol_p);
pic_defun(pic, "symbol->string", pic_symbol_symbol_to_string);
pic_defun(pic, "string->symbol", pic_symbol_string_to_symbol);
}