]> git.ipfire.org Git - thirdparty/bird.git/blobdiff - filter/f-util.c
Filter: The for loop uses the method system for type dispatch
[thirdparty/bird.git] / filter / f-util.c
index d814493ea9e0da9014c576dde10766397fd08a3d..ab5b909437994d1bb8190ef2cdff8e5ece1ef5a2 100644 (file)
@@ -41,6 +41,40 @@ struct filter *f_new_where(struct f_inst *where)
   return f;
 }
 
+struct f_inst *
+f_for_cycle(struct symbol *var, struct f_inst *term, struct f_inst *block)
+{
+  ASSERT((var->class & ~0xff) == SYM_VARIABLE);
+  ASSERT(term->next == NULL);
+
+  /* Static type check */
+  if (term->type == T_VOID)
+    cf_error("Couldn't infer the type of FOR expression, please assign it to a variable.");
+
+  enum f_type el_type = f_type_element_type(term->type);
+  struct sym_scope *scope = el_type ? f_type_method_scope(term->type) : NULL;
+  struct symbol *ms = scope ? cf_find_symbol_scope(scope, "!for_next") : NULL;
+
+  if (!ms)
+    cf_error("Type %s is not iterable, can't be used in FOR", f_type_name(term->type));
+
+  if (var->class != (SYM_VARIABLE | el_type))
+    cf_error("Loop variable '%s' in FOR must be of type %s, got %s",
+       var->name, f_type_name(el_type), f_type_name(var->class & 0xff));
+
+  /* Push the iterator auxiliary value onto stack */
+  struct f_inst *iter = term->next = f_new_inst(FI_CONSTANT, (struct f_val) {});
+
+  /* Initialize the iterator variable */
+  iter->next = f_new_inst(FI_CONSTANT, (struct f_val) { .type = el_type });
+
+  /* Prepend the loop block with loop beginning instruction */
+  struct f_inst *loop_start = f_new_inst(FI_FOR_LOOP_START, var);
+  loop_start->next = block;
+
+  return ms->method->new_inst(term, loop_start);
+}
+
 #define CA_KEY(n)      n->name, n->fda.type
 #define CA_NEXT(n)     n->next
 #define CA_EQ(na,ta,nb,tb)     (!strcmp(na,nb) && (ta == tb))