Skip to content

Commit 44db12b

Browse files
committed
type_checkers: await
1 parent 92a2e65 commit 44db12b

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

src/type_checkers/array_literal.cr

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# -----------------------------------------------------------------------
2+
# This file is part of MoonScript
3+
#
4+
# MoonSript is free software: you can redistribute it and/or modify
5+
# it under the terms of the GNU General Public License as published by
6+
# the Free Software Foundation, either version 3 of the License, or
7+
# (at your option) any later version.
8+
#
9+
# MoonSript is distributed in the hope that it will be useful,
10+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
# GNU General Public License for more details.
13+
#
14+
# You should have received a copy of the GNU General Public License
15+
# along with MoonSript. If not, see <https://www.gnu.org/licenses/>.
16+
#
17+
# Copyright (C) 2025 Krisna Pranav, MoonScript Developers
18+
# -----------------------------------------------------------------------
19+
20+
module MoonScript
21+
class TypeChecker
22+
def check(node : Ast::ArrayLiteral) : Checkable
23+
defined_type =
24+
node.type.try do |type|
25+
Type.new("Array", [resolve(type).as(Checkable)])
26+
end
27+
28+
if node.items.empty?
29+
defined_type || Type.new("Array", [Variable.new("a").as(Checkable)])
30+
else
31+
first =
32+
resolve node.items.first
33+
34+
rest =
35+
node.items[1..node.items.size]
36+
37+
rest.each_with_index do |item, index|
38+
type = resolve item
39+
40+
return error! :array_not_matches do
41+
block do
42+
text "The"
43+
bold "#{ordinal(index + 2)} item"
44+
text "of an array does not match the type of the 1st item."
45+
end
46+
47+
snippet "I was expecting the type of the 1st item:", first
48+
snippet "Instead it is:", type
49+
snippet "The item in question is here:", item
50+
end unless Comparer.compare(type, first)
51+
end
52+
53+
inferred_type =
54+
Comparer.normalize(Type.new("Array", [first]))
55+
56+
if defined_type
57+
final_type =
58+
Comparer.compare(inferred_type, defined_type)
59+
60+
error! :array_not_matches_defined_type do
61+
block do
62+
text "The"
63+
bold "defined type"
64+
text "of an array does not matches"
65+
end
66+
67+
expected defined_type, inferred_type
68+
snippet "The array in question is here:", node.type.not_nil!
69+
end unless final_type
70+
71+
final_type
72+
else
73+
inferred_type
74+
end
75+
end
76+
end
77+
end
78+
end

0 commit comments

Comments
 (0)