obj_typing.c
1 #include <string.h>
2 #include <kuroko/vm.h>
3 #include <kuroko/value.h>
4 #include <kuroko/util.h>
5 
23 static KrkValue typeToString(KrkValue val) {
24  if (IS_CLASS(val)) {
25  return OBJECT_VAL(AS_CLASS(val)->name);
26  } else if (IS_STRING(val)) {
27  return val;
28  } else if (IS_TUPLE(val)) {
29  /* Form a string by concatenating typeToString with ',' */
30  struct StringBuilder sb = {0};
31 
32  for (size_t i = 0; i < AS_TUPLE(val)->values.count; ++i) {
33  krk_push(typeToString(AS_TUPLE(val)->values.values[i]));
34  pushStringBuilderStr(&sb, AS_CSTRING(krk_peek(0)), AS_STRING(krk_peek(0))->length);
35  krk_pop();
36  if (i < AS_TUPLE(val)->values.count - 1) {
37  pushStringBuilder(&sb,',');
38  }
39  }
40 
41  return finishStringBuilder(&sb);
42  } else {
43  /* Just repr it. */
44  KrkClass * type = krk_getType(val);
45  krk_push(val);
46  return krk_callDirect(type->_reprer, 1);
47  }
48 }
49 
50 KRK_Function(__class_getitem__) {
51  FUNCTION_TAKES_EXACTLY(2);
52  if (!IS_CLASS(argv[0])) return TYPE_ERROR(class,argv[0]);
53 
54  struct StringBuilder sb = {0};
55 
56  /* First lets look at the class. */
57  pushStringBuilderStr(&sb, AS_CLASS(argv[0])->name->chars, AS_CLASS(argv[0])->name->length);
58  pushStringBuilder(&sb,'[');
59 
60  krk_push(typeToString(argv[1]));
61  pushStringBuilderStr(&sb, AS_CSTRING(krk_peek(0)), AS_STRING(krk_peek(0))->length);
62  krk_pop();
63  pushStringBuilder(&sb,']');
64  return finishStringBuilder(&sb);
65 }
66 
67 NativeFn krk_GenericAlias = FUNC_NAME(krk,__class_getitem__);
NativeFn krk_GenericAlias
Special value for type hint expressions.
Definition: obj_typing.c:67
Type object.
Definition: object.h:215
KrkObj * _reprer
__repr__ Called to create a reproducible string representation of an instance
Definition: object.h:229
Stack reference or primative value.
KrkClass * krk_getType(KrkValue value)
Get the class representing a value.
Definition: vm.c:240
Inline flexible string array.
Definition: util.h:162
Utilities for creating native bindings.
Definitions for primitive stack references.
Core API for the bytecode virtual machine.
KrkValue krk_pop(void)
Pop the top of the stack.
Definition: vm.c:131
void krk_push(KrkValue value)
Push a stack value.
Definition: vm.c:118
KrkValue krk_callDirect(KrkObj *callable, int argCount)
Call a closure or native function with argCount arguments.
Definition: vm.c:740
KrkValue krk_peek(int distance)
Peek down from the top of the stack.
Definition: vm.c:139