Forum | Documentation | Website | Blog

Skip to content
Snippets Groups Projects
Commit febeab77 authored by Ary Borenszweig's avatar Ary Borenszweig
Browse files

Added some array methods in macros: [] and length. Also: String#split with char

parent 5d6f6e73
Branches
Tags
No related merge requests found
......@@ -134,10 +134,14 @@ describe "MacroExpander" do
assert_macro "", %({{"1 2 3".split}}), [] of ASTNode, %(["1", "2", "3"])
end
it "executes string split with arguments" do
it "executes string split with string argument" do
assert_macro "", %({{"1-2-3".split("-")}}), [] of ASTNode, %(["1", "2", "3"])
end
it "executes string split with char argument" do
assert_macro "", %({{"1-2-3".split('-')}}), [] of ASTNode, %(["1", "2", "3"])
end
it "executes string strip" do
assert_macro "", %({{" hello ".strip}}), [] of ASTNode, "hello"
end
......@@ -153,4 +157,16 @@ describe "MacroExpander" do
it "executes string lines" do
assert_macro "x", %({{x.lines}}), [StringLiteral.new("1\n2\n3")] of ASTNode, %(["1", "2", "3"])
end
it "executes array index 0" do
assert_macro "", %({{[1, 2, 3][0]}}), [] of ASTNode, "1"
end
it "executes array index 1" do
assert_macro "", %({{[1, 2, 3][1]}}), [] of ASTNode, "2"
end
it "executes array length" do
assert_macro "", %({{[1, 2, 3].length}}), [] of ASTNode, "3"
end
end
......@@ -304,7 +304,12 @@ module Crystal
when 0
create_array_literal_from_values(@value.split)
when 1
create_array_literal_from_values(@value.split(args.first.to_macro_id))
first_arg = args.first
if first_arg.is_a?(CharLiteral)
create_array_literal_from_values(@value.split(first_arg.value))
else
create_array_literal_from_values(@value.split(first_arg.to_macro_id))
end
else
raise "wrong number of arguments for split (#{args.length} for 0, 1)"
end
......@@ -322,6 +327,35 @@ module Crystal
end
end
class ArrayLiteral
def interpret(method, args)
case method
when "length"
interpret_argumentless_method(method, args) { NumberLiteral.new(elements.length, :i32) }
when "[]"
case args.length
when 1
arg = args.first
unless arg.is_a?(NumberLiteral)
arg.raise "argument to [] must be a number, not #{arg}"
end
index = arg.to_number.to_i
value = elements[index]?
if value
value
else
raise "array index out of bounds: #{index} in #{self}"
end
else
raise "wrong number of arguments for [] (#{args.length} for 1)"
end
else
super
end
end
end
class SymbolLiteral
def to_macro_id
@value
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment