From e07b94fd18c7099caa7850bccf3dcd32d648d16e Mon Sep 17 00:00:00 2001 From: "Michael D. Lowis" Date: Wed, 12 Jun 2024 22:58:59 -0400 Subject: [PATCH] finished code generation for hash literals --- cerise-c.m | 14 ++++++++++++++ cerise-c.rb | 44 ++++++++++++++++++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/cerise-c.m b/cerise-c.m index d8d91c4..832155a 100644 --- a/cerise-c.m +++ b/cerise-c.m @@ -86,6 +86,20 @@ TestStringOps() # assert length("foo") == 3 } +TestArrayOps() +{ + def array = [1,2,3] + set item = array[0] +# set array[0] = item +} + +TestHashOps() +{ + def hash = {foo: "bar", "baz": "boo"} + set item = hash["foo"] +# set hash["foo"] = item +} + Main() { def foo = [1,2,3] diff --git a/cerise-c.rb b/cerise-c.rb index 6f1b1c6..c7245b5 100755 --- a/cerise-c.rb +++ b/cerise-c.rb @@ -532,19 +532,33 @@ class Parser expect(",") if !matches("]") end expect("]") - exprs IR::Const.new(loc, nil, exprs) end def hash_literal() - exprs = {} + dict = {} expect("{") -# while !matches("}") -# exprs << expression() -# expect(",") if !matches("}") -# end + loc = location() + while !matches("}") + key = string_or_ident() + expect(":") + val = expression() + dict[key] = val + expect(",") if !matches("}") + end expect("}") - exprs + IR::Const.new(loc, nil, dict) + end + + def string_or_ident() + tok = consume() + if tok.type == :string + IR::Const.new(tok.pos, Value::String, tok.text) + elsif tok.type == :ident + IR::Const.new(tok.pos, Value::String, "\"#{tok.text}\"") + else + error("not a string or identifier: #{tok}") + end end end @@ -1121,7 +1135,21 @@ module Codegen end elsif v.value.is_a? Hash - putln state, "Value #{var} = MakeHash(#{v.value});" +# putln state, "Value #{var} = MakeHash(#{v.value});" + + putln state, "Value #{var} = MakeHashOfLength(#{v.value.length});" + v.value.each do |k, v| + val = emit(state, v) + putln state, "Hash_SetIndex(#{var}, MakeString(#{k.value}), #{val});" +# +# +# pp k +# val = emit(state, e) +# putln state, "Array_SetIndex(#{var}, #{i}, #{val});" +# + end + + else raise "code emitting constants of this type not implemented" end -- 2.54.0