Skip to content

Commit

Permalink
for-generator example
Browse files Browse the repository at this point in the history
  • Loading branch information
kuviman committed Nov 22, 2024
1 parent ceb0d04 commit 432097c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
19 changes: 19 additions & 0 deletions examples/for-generator.ks
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std.*;

let generator = fn(()) {
print "yielding 1";
yield "1";
print "yielding 2";
yield "2";
print "yielding stop";
yield "stop";
print "yielding 3";
yield "3";
};

for value in generator() {
print value;
#if value == "stop" {
#break;
#}
};
14 changes: 14 additions & 0 deletions std/lib.ks
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,17 @@ impl float64 as Parse = (
const parse = forall[T] {
(T as Parse).parse
};

const generator_handler = forall[T] {
(.handle = T -> () with ()) :: type
};

impl syntax @"syntax".for_loop = macro (.value_pattern, .generator, .body) => `(
with (.handle = $value_pattern => $body) :: generator_handler[_];
$generator
);

impl syntax @"syntax".@"yield" = macro (.value) => `(
(current generator_handler[_]).handle $value
);

3 changes: 2 additions & 1 deletion std/syntax.ks
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ syntax_module {
# syntax break_with_value <- 2 = "break" value;
# syntax break_without_value <- 2 = "break";
# syntax continue_impl <- 2 = "continue";
syntax yield <- 2 = "yield" value;

# syntax loop_impl <- 3 = "loop" "{" body "}";
# syntax for_loop <- 3 = "for" value_pattern "in" generator "{" body "}";
syntax for_loop <- 3 = "for" value_pattern "in" generator "{" body "}";
syntax @"builtin macro impl_cast" <- 4 = "impl" value "as" target "=" impl;
syntax @"builtin macro impl_syntax" <- 4 = "impl" "syntax" def "=" impl;
syntax @"builtin macro let" <- 4 = "let" pattern "=" value;
Expand Down

0 comments on commit 432097c

Please sign in to comment.