8000 Implement correct for loop behavior by CohenArthur · Pull Request #316 · jinko-core/jinko · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
10000 Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions src/builtins.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! This module contains all builtin functions declared in the jinko interpreter

use std::collections::HashMap;
use std::io::{self, Write};
use std::path::PathBuf;

use crate::ffi;
Expand Down Expand Up @@ -35,16 +34,26 @@ fn string_concat(ctx: &mut Context, args: Args) -> Option<ObjectInstance> {

fn string_display(ctx: &mut Context, args: Args) -> Option<ObjectInstance> {
let s = JkString::from_instance(&args[0].execute(ctx).unwrap()).0;
let add_newline = JkBool::from_instance(&args[1].execute(ctx).unwrap()).0;

io::stdout().lock().write_all(s.as_bytes()).unwrap();
print!("{}", s);

if add_newline {
println!()
}

None
}

fn string_display_err(ctx: &mut Context, args: Args) -> Option<ObjectInstance> {
let s = JkString::from_instance(&args[0].execute(ctx).unwrap()).0;
let add_newline = JkBool::from_instance(&args[1].execute(ctx).unwrap()).0;

io::stderr().lock().write_all(s.as_bytes()).unwrap();
eprint!("{}", s);

if add_newline {
eprintln!()
}

None
}
Expand Down Expand Up @@ -144,8 +153,8 @@ mod tests {
jinko! {
__builtin_string_len("jk");
__builtin_string_concat("file", ".jk");
__builtin_string_display("to display");
__builtin_string_display_err("to display on err");
__builtin_string_display("to display", true);
__builtin_string_display_err("to display on err", true);
__builtin_string_equals("jin", "ko");
__builtin_string_is_empty("jinko");
};
Expand Down
7 changes: 6 additions & 1 deletion src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,12 @@ impl nom::error::ParseError<&str> for Error {

impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "{}", self.kind.as_str())
write!(f, "{}", self.kind.as_str())?;
if self.msg.is_some() {
write!(f, ": {}", self.msg.as_ref().unwrap())?;
}

Ok(())
}
}

Expand Down
184 changes: 143 additions & 41 deletions src/instruction/loop_block.rs
10BC8
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! The Loop instruction is used for repeating instructions. They can be of three
//! different kinds, `for`, `while` or `loop`.

use crate::instruction::{Block, InstrKind, Instruction, Var};
use crate::typechecker::TypeCtx;
use crate::{typechecker::CheckedType, Context, ErrKind, Error, ObjectInstance, TypeCheck};
use crate::instruction::{Block, FunctionCall, InstrKind, Instruction, Var};
use crate::typechecker::{CheckedType, TypeCtx};
use crate::{Context, FromObjectInstance, JkBool, ObjectInstance, TypeCheck};

/// What kind of loop the loop block represents: Either a for Loop, with a variable and
/// a range expression, a while loop with just an upper bound, or a loop with no bound
Expand Down Expand Up @@ -63,46 +63,125 @@ impl Instruction for Loop {
}
ctx.debug_step("WHILE EXIT");
}
LoopKind::For(_var, _range) => {
// FIXME:
LoopKind::For(var, range_expression) => {
// Let's break down the implementation for the following loop
// ```
// for i in range(0, 10) { /* exec() */ }
// ```

// We enter a scope to declare our internal variables
ctx.scope_enter();

// We create new variables in the scope, with the required iterator's
// name from the user. We can create these variables with special names
// since we are only using them from the interpreter. Here, we prefix
// them with a plus sign to make sure they do not interact with the user.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be documented. The user needs to be aware that he is not allowed to use identifier starting with a '+' sign

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if it explicitly needs to be documented, as if the user tries to do it they will simply encounter a parse error (identifiers can only be comprised of underscores, digits and letters). Here, since we are creating them directly from the interpreter, we're allowed to, but it's an "edge case" and abusing the language since we're not going through the parser

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documenting it to understand why there is a parser error is useful imao

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean in the parser or here? And do you mean by emitting an error or adding a comment? Because the user will never see those variables, ever. Think of them as the __<ident> variables we were talking about in gcc

// ```
// +inner = range(0, 10);
// +iterator = iter(+inner);
//
// +maybe_value = value(+iterator);
// if !+maybe_value.is_some() { break }
//
// i = +maybe_iter_value.unpack(); // This is our <iter_value>
//
// // We can now do our first execution, and then repeat part of the
// // above process
// /* exec() */
//
// In order to have a correct for implementation, jinko needs ranges,
// iterators, which implies the need for options, which implies the need
// for a standard library, which implies the need for code inclusion, etc
// etc etc... All of that is the goal of the 0.1.1 release.
// // FIXME: This needs to change. Ideally, we'd want to mutate
// the `+iterator` variable
// +iterator = next(+iterator);
// +maybe_value = current(+iterator);
// if !+maybe_value.is_some() { break }
//
// A possible implementation would be to execute the range, assign it
// to the var, and check that var is a valid iterator. For example,
// by calling `Iter::ok(var)` (whatever the API might be) and checking
// that that result, as a boolean, returns true. If it does, execute the
// body. If it does not, break from the for.

ctx.error(
Error::new(ErrKind::Context)
.with_msg("for loops are currently unimplemented".to_string()),
);
return None;

// FIXME: Rework that code
// ctx.debug_step("FOR ENTER");
// let var_name = var.name().to_owned();
// ctx.scope_enter();

// ctx.add_variable(var.clone())?;

// loop {
// range.execute(ctx)?;

// // We can unwrap since we added the variable right before
// if !ctx.get_variable(&var_name).unwrap().as_bool() {
// break;
// }

// self.block.execute(ctx)?;
// }

// ctx.scope_exit();
// ctx.debug_step("FOR EXIT");
// i = +maybe_iter_value.unpack();
// /* exec() */
// ```

// Let's create our names
let inner_name = String::from("+inner");
let iterator_name = String::from("+iterator");
let maybe_name = String::from("+maybe_value");

// Now, let's create our variables
let mut inner = Var::new(inner_name);
let mut iterator = Var::new(iterator_name);
let mut maybe = Var::new(maybe_name);
let mut iter_value = Var::new(var.name().to_owned());

// We execute the iterable expression
// `+inner = range(0, 10)`
inner.set_instance(range_expression.execute(ctx).unwrap());
ctx.add_variable(inner.clone()).unwrap();

// We construct the iterator from the iterable expression
// `+iterator = iter(+inner)`
let mut iter_constructor = FunctionCall::new(String::from("iter"));
iter_constructor.add_arg(Box::new(inner.clone()));
iterator.set_instance(iter_constructor.execute(ctx).unwrap());

// We fetch the first value from the iterator: `value(+iterator)`
// This call will be reused multiple times!
let mut iterator_value = FunctionCall::new(String::from("value"));
iterator_value.add_arg(Box::new(iterator.clone()));

// We check if `+maybe_value` contains `Some` or `Nothing`: `is_some(+maybe_value)`
// This call will be reused multiple times!
let mut maybe_is_some = FunctionCall::new(String::from("is_some"));
maybe_is_some.add_arg(Box::new(maybe.clone()));

// We advance the iterator: `next(+iterator)`
// This call will be reused multiple times!
let mut iterator_next = FunctionCall::new(String::from("next"));
iterator_next.add_arg(Box::new(iterator.clone()));

let mut maybe_unpack = FunctionCall::new(String::from("unpack"));
maybe_unpack.add_arg(Box::new(maybe.clone()));

// Now we can declare our variables in the context
ctx.add_variable(iterator.clone()).unwrap();
ctx.add_variable(maybe.clone()).unwrap();
ctx.add_variable(iter_value.clone()).unwrap();

maybe.set_instance(iterator_value.execute(ctx).unwrap());
ctx.replace_variable(maybe.clone()).unwrap();

let maybe_is_nothing = {
let instance = maybe_is_some.execute(ctx).unwrap();
!JkBool::from_instance(&instance).0
};

if maybe_is_nothing {
ctx.scope_exit();
return None;
}

iter_value.set_instance(maybe_unpack.execute(ctx).unwrap());
ctx.replace_variable(iter_value.clone()).unwrap();

loop {
self.block.execute(ctx);

iterator.set_instance(iterator_next.execute(ctx).unwrap());
ctx.replace_variable(iterator.clone()).unwrap();
maybe.set_instance(iterator_value.execute(ctx).unwrap());
ctx.replace_variable(maybe.clone()).unwrap();

let maybe_is_nothing = {
let instance = maybe_is_some.execute(ctx).unwrap();
!JkBool::from_instance(&instance).0
};

if maybe_is_nothing {
break;
}

iter_value.set_instance(maybe_unpack.execute(ctx).unwrap());
ctx.replace_variable(iter_value.clone()).unwrap();
}

ctx.scope_exit();
}
}

Expand All @@ -122,6 +201,7 @@ mod tests {
use super::*;
use crate::instruction::FunctionCall;
use crate::jinko;
use crate::{JkInt, ToObjectInstance};

#[test]
fn pretty_print_loop() {
Expand Down Expand Up @@ -161,4 +241,26 @@ mod tests {
l2 = loop { i = i + 1 }
};
}

#[test]
fn valid_for_block() {
let ctx = jinko! {
mut counter = 0;
for i in range(0, 15) {
counter = counter + 1;
}
};

// FIXME: Add assertion once #187 is fixed
// let counter = ctx.get_variable("counter").unwrap();
// assert_eq!(counter.instance(), JkInt::from(15).to_instance());
}

#[test]
fn valid_for_block_without_execution() {
jinko! {
for i in range(0, 0) {
}
};
}
}
7 changes: 6 additions & 1 deletion stdlib/iter.jk
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ func iter(r: Range_int) -> Iter_int {
Iter_int { inner = r }
}

func next(iter: Iter_int) -> Maybe_int {
func next(iter: Iter_int) -> Iter_int {
new_inner = advance(iter.inner);
iter(new_inner)
}

func value(iter: Iter_int) -> Maybe_int {
// FIXME: Turn to iter.inner.current() once parsing is implemented for this
// FIXME: This does not advance the inner range because we have no mutability
// yet. So the iterators are useless for now
Expand Down
18 changes: 11 additions & 7 deletions stdlib/range.jk
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@ func advance(r: Range_int) -> Range_int {
}

func current(r: Range_int) -> Maybe_int {
// FIXME: Add this once parsing can handle comparisons
// if r.current > r.end {
// nothing()
// } else {
// some(r.current)
//}
old_current = r.current;
mut old_end = r.end;
old_end = old_end - 1;
gone_past = old_current > old_end;
Comment thread
Skallwar marked this conversation as resolved.
Resolved

some(r.current)
// FIXME: Once #320 is fixed, replace
// if r.current > r.end - 1 {
if gone_past {
nothing()
} else {
some(r.current)
}
}
27 changes: 20 additions & 7 deletions stdlib/string.jk
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
ext func __builtin_string_len(s: string) -> int;
ext func __builtin_string_concat(a: string, b: string) -> string;
ext func __builtin_string_display(s: string);
ext func __builtin_string_display_err(s: string);
ext func __builtin_string_is_empty(s: string) -> bool;
ext func __builtin_string_equals(lhs: string, rhs: string) -> bool;

// FIXME: Remove `add_newline` parameter once strings with the \n character
// are handled correctly #323
ext func __builtin_string_display(s: string, add_newline: bool);
ext func __builtin_string_display_err(s: string, add_newline: bool);

/// Get the length of a given string
func len(s: string) -> int {
s.__builtin_string_len()
Expand All @@ -16,13 +19,23 @@ func concat(lhs: string, rhs: string) -> string {
}

/// Display a string on stdout
func display(s: string) {
s.__builtin_string_display()
func print(s: string) {
s.__builtin_string_display(false)
}

/// Display a string on stdout
func display_err(s: string) {
s.__builtin_string_display_err()
/// Display a string and a newline on stdout
func println(s: string) {
s.__builtin_string_display(true)
}

/// Display a string on stderr
func print_err(s: string) {
s.__builtin_string_display_err(false)
}

/// Display a string and a newline on stderr
func println_err(s: string) {
s.__builtin_string_display_err(true)
}

// FIXME: Once comparison operators are implemented, return `s.len() == 0`
Expand Down
3 changes: 3 additions & 0 deletions tests/ft/loops/for_loop.jk
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
for i in 0.range(3) {
"jk".print()
}
5 changes: 5 additions & 0 deletions tests/ft/loops/for_loop_one.jk
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
for i in range(0, 1) {
{
print("jinko");
}
}
3 changes: 3 additions & 0 deletions tests/ft/loops/for_loop_zero.jk
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
for i in range(0, 0) {
println("This shouldn't be printed")
}
16 changes: 16 additions & 0 deletions tests/ft/loops/loops.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
tests:
- name: "Iterate over range 10 times"
binary: "target/debug/jinko"
args:
- "tests/ft/loops/for_loop.jk"
stdout: "jkjkjk"
- name: "Iterate over range 0 times"
binary: "target/debug/jinko"
args:
- "tests/ft/loops/for_loop_zero.jk"
stdout: ""
- name: "Iterate over range 1 time"
binary: "target/debug/jinko"
args:
- "tests/ft/loops/for_loop_one.jk"
stdout: "jinko"
2 changes: 1 addition & 1 deletion tests/ft/stdlib/string/concat.jk
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
s = "jinko".concat(".jk")
s.display()
s.print()
0