Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support next and break in macro methods #14894

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/compiler/crystal/macros/interpreter.cr
Original file line number Diff line number Diff line change
Expand Up @@ -74,23 +74,57 @@ module Crystal

record MacroVarKey, name : String, exps : Array(ASTNode)?

class BlockScope
enum State
Continue
FoundNext
FoundBreak
end

property state : State = State::Continue
end

def initialize(@program : Program,
@scope : Type, @path_lookup : Type, @location : Location?,
@vars = {} of String => ASTNode, @block : Block? = nil, @def : Def? = nil,
@in_macro = false, @call : Call? = nil)
@str = IO::Memory.new(512) # Can't be String::Builder because of `{{debug}}`
@last = Nop.new
@block_scopes = [] of BlockScope
end

def define_var(name : String, value : ASTNode) : Nil
@vars[name] = value
end

def new_block_scope(& : BlockScope ->)
block_scope = BlockScope.new
@block_scopes << block_scope
begin
yield block_scope
ensure
@block_scopes.pop
end
end

def accept(node)
node.accept self
@last
end

def visit_any(node)
# upon encountering a `next` or `break` expression, this pauses evaluation
# until `interpret_block` in `./methods.cr` drops a pending `next`, or
# `new_block_scope` drops the innermost block scope by returning; while
# evaluation is paused, `@last` holds the argument to the most recent
# `next` or `break` expression
if block_scope = @block_scopes.last?
return false unless block_scope.state.continue?
end

true
end

def visit(node : Expressions)
node.expressions.each &.accept self
false
Expand Down Expand Up @@ -408,6 +442,36 @@ module Crystal
false
end

def visit(node : Next)
unless block_scope = @block_scopes.last?
node.raise "invalid next"
end

if exp = node.exp
exp.accept self
else
@last = Nop.new
end

block_scope.state = :found_next
false
end

def visit(node : Break)
unless block_scope = @block_scopes.last?
node.raise "invalid break"
end

if exp = node.exp
exp.accept self
else
@last = Nop.new
end

block_scope.state = :found_break
false
end

def visit(node : Path)
@last = resolve(node)
false
Expand Down
Loading
Loading