Commit 9de90f63

9de90f639f53Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 1 file · +1 added

Description

feat: implement Spinel v2 codegen backend (Phases 1-4)

Implement the Spinel v2 compiler backend in the Spinel Ruby subset. Uses parallel arrays for all data structures (no arrays of objects) to ensure compatibility with Spinel v1 self-compilation.

Phase 1 (fib): Fully working - integer arithmetic, if/else, recursion, puts, top-level def with parameters.

Phases 2-4: Partial implementation of strings, control flow, classes, arrays, hashes. CRuby pipeline works for basic tests (bm_strings, bm_control). More complex tests need additional fixes.

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
9de90f639f53
Parent
eda5ca27a501

spinel_codegen.rbaddedView file

1+# Spinel v2 Codegen - Ruby subset AOT compiler backend
2+#
3+# Reads text AST from spinel_parse.rb, generates standalone C code.
4+# Written in Spinel-compilable Ruby subset.
5+#
6+# Usage: ruby spinel_codegen.rb ast.txt output.c
7+#
8+# All data structures use parallel arrays (no arrays of objects).
9+# Node fields stored as parallel arrays indexed by integer node ID.
10+
11+class Compiler
12+ attr_accessor :out
13+
14+ def initialize
15+ @out = ""
16+ @indent = 0
17+ @temp_counter = 0
18+ @label_counter = 0
19+
20+ # ---- AST node storage (parallel arrays by node ID) ----
21+ # Use "".split(",") for StrArray init (v1 infers StrArray from split)
22+ @nd_type = "".split(",")
23+ @nd_name = "".split(",")
24+ @nd_value = []
25+ @nd_content = "".split(",")
26+ @nd_flags = []
27+ @nd_operator = "".split(",")
28+ @nd_binop = "".split(",")
29+ @nd_callop = "".split(",")
30+ @nd_unescaped = "".split(",")
31+
32+ # Node references (integer node IDs, -1 = nil)
33+ @nd_receiver = []
34+ @nd_arguments = []
35+ @nd_body = []
36+ @nd_block = []
37+ @nd_parameters = []
38+ @nd_predicate = []
39+ @nd_subsequent = []
40+ @nd_else_clause = []
41+ @nd_left = []
42+ @nd_right = []
43+ @nd_constant_path = []
44+ @nd_superclass = []
45+ @nd_rest = []
46+ @nd_rescue_clause = []
47+ @nd_ensure_clause = []
48+ @nd_expression = []
49+ @nd_target = []
50+ @nd_pattern = []
51+ @nd_key = []
52+ @nd_reference = []
53+ @nd_collection = []
54+
55+ # Node array fields: stored as comma-separated ID strings
56+ @nd_stmts = "".split(",")
57+ @nd_args = "".split(",")
58+ @nd_requireds = "".split(",")
59+ @nd_optionals = "".split(",")
60+ @nd_keywords = "".split(",")
61+ @nd_elements = "".split(",")
62+ @nd_parts = "".split(",")
63+ @nd_conditions = "".split(",")
64+ @nd_exceptions = "".split(",")
65+ @nd_targets = "".split(",")
66+
67+ @nd_count = 0
68+ @root_id = 0
69+
70+ # ---- Top-level methods (parallel arrays) ----
71+ @meth_names = "".split(",")
72+ @meth_param_names = "".split(",")
73+ @meth_param_types = "".split(",")
74+ @meth_return_types = "".split(",")
75+ @meth_body_ids = []
76+ @meth_has_defaults = "".split(",")
77+
78+ # ---- Classes (parallel arrays) ----
79+ @cls_names = "".split(",")
80+ @cls_parents = "".split(",")
81+ @cls_ivar_names = "".split(",")
82+ @cls_ivar_types = "".split(",")
83+ @cls_meth_names = "".split(",")
84+ @cls_meth_params = "".split(",")
85+ @cls_meth_ptypes = "".split(",")
86+ @cls_meth_returns = "".split(",")
87+ @cls_meth_bodies = "".split(",")
88+ @cls_meth_defaults = "".split(",")
89+ @cls_attr_readers = "".split(",")
90+ @cls_attr_writers = "".split(",")
91+ @cls_cmeth_names = "".split(",")
92+ @cls_cmeth_params = "".split(",")
93+ @cls_cmeth_ptypes = "".split(",")
94+ @cls_cmeth_returns = "".split(",")
95+ @cls_cmeth_bodies = "".split(",")
96+
97+ # ---- Constants (parallel arrays) ----
98+ @const_names = "".split(",")
99+ @const_types = "".split(",")
100+ @const_expr_ids = []
101+
102+ # ---- Scope stack for local variables ----
103+ @scope_names = "".split(",")
104+ @scope_types = "".split(",")
105+
106+ @current_class_idx = -1
107+ @current_method_name = ""
108+ @current_method_return = ""
109+ @in_main = 0
110+ @in_loop = 0
111+
112+ # Feature flags
113+ @needs_gc = 0
114+ @needs_int_array = 0
115+ @needs_str_array = 0
116+ @needs_str_int_hash = 0
117+ @needs_str_str_hash = 0
118+ @needs_string_helpers = 0
119+ end
120+
121+ def join_sep(arr, sep)
122+ result = ""
123+ i = 0
124+ while i < arr.length
125+ if i > 0
126+ result = result + sep
127+ end
128+ result = result + arr[i]
129+ i = i + 1
130+ end
131+ result
132+ end
133+
134+ # Parse comma-sep node IDs into IntArray
135+ def parse_id_list(s)
136+ if s == ""
137+ return []
138+ end
139+ parts = s.split(",")
140+ result = []
141+ i = 0
142+ while i < parts.length
143+ result.push(parts[i].to_i)
144+ i = i + 1
145+ end
146+ result
147+ end
148+
149+ def new_temp
150+ @temp_counter = @temp_counter + 1
151+ "_t" + @temp_counter.to_s
152+ end
153+
154+ def new_label
155+ @label_counter = @label_counter + 1
156+ "_L" + @label_counter.to_s
157+ end
158+
159+ # ---- AST reader ----
160+ def alloc_node
161+ nid = @nd_count
162+ @nd_type.push("")
163+ @nd_name.push("")
164+ @nd_value.push(0)
165+ @nd_content.push("")
166+ @nd_flags.push(0)
167+ @nd_operator.push("")
168+ @nd_binop.push("")
169+ @nd_callop.push("")
170+ @nd_unescaped.push("")
171+ @nd_receiver.push(-1)
172+ @nd_arguments.push(-1)
173+ @nd_body.push(-1)
174+ @nd_block.push(-1)
175+ @nd_parameters.push(-1)
176+ @nd_predicate.push(-1)
177+ @nd_subsequent.push(-1)
178+ @nd_else_clause.push(-1)
179+ @nd_left.push(-1)
180+ @nd_right.push(-1)
181+ @nd_constant_path.push(-1)
182+ @nd_superclass.push(-1)
183+ @nd_rest.push(-1)
184+ @nd_rescue_clause.push(-1)
185+ @nd_ensure_clause.push(-1)
186+ @nd_expression.push(-1)
187+ @nd_target.push(-1)
188+ @nd_pattern.push(-1)
189+ @nd_key.push(-1)
190+ @nd_reference.push(-1)
191+ @nd_collection.push(-1)
192+ @nd_stmts.push("")
193+ @nd_args.push("")
194+ @nd_requireds.push("")
195+ @nd_optionals.push("")
196+ @nd_keywords.push("")
197+ @nd_elements.push("")
198+ @nd_parts.push("")
199+ @nd_conditions.push("")
200+ @nd_exceptions.push("")
201+ @nd_targets.push("")
202+ @nd_count = @nd_count + 1
203+ nid
204+ end
205+
206+ def read_text_ast(data)
207+ lines = data.split("\n")
208+ # First pass: find max node ID
209+ max_id = 0
210+ i = 0
211+ while i < lines.length
212+ line = lines[i]
213+ if line.length > 0
214+ parts = line.split(" ")
215+ if parts.length >= 2
216+ if parts[0] == "ROOT"
217+ @root_id = parts[1].to_i
218+ end
219+ if parts[0] == "N"
220+ nid = parts[1].to_i
221+ if nid > max_id
222+ max_id = nid
223+ end
224+ end
225+ end
226+ end
227+ i = i + 1
228+ end
229+
230+ # Allocate all nodes
231+ j = 0
232+ while j <= max_id
233+ alloc_node
234+ j = j + 1
235+ end
236+
237+ # Second pass: populate fields
238+ i = 0
239+ while i < lines.length
240+ line = lines[i]
241+ if line.length > 0
242+ parts = line.split(" ")
243+ if parts.length >= 3
244+ tag = parts[0]
245+ nid = parts[1].to_i
246+ if tag == "N"
247+ @nd_type[nid] = parts[2]
248+ end
249+ if tag == "S"
250+ field = parts[2]
251+ val = ""
252+ if parts.length >= 4
253+ val = unescape_str(parts[3])
254+ end
255+ set_string_field(nid, field, val)
256+ end
257+ if tag == "I"
258+ field = parts[2]
259+ val = 0
260+ if parts.length >= 4
261+ val = parts[3].to_i
262+ end
263+ set_int_field(nid, field, val)
264+ end
265+ if tag == "F"
266+ field = parts[2]
267+ if parts.length >= 4
268+ @nd_content[nid] = parts[3]
269+ end
270+ end
271+ if tag == "R"
272+ field = parts[2]
273+ ref_id = -1
274+ if parts.length >= 4
275+ ref_id = parts[3].to_i
276+ end
277+ set_ref_field(nid, field, ref_id)
278+ end
279+ if tag == "A"
280+ field = parts[2]
281+ ids_str = ""
282+ if parts.length >= 4
283+ ids_str = parts[3]
284+ end
285+ set_array_field(nid, field, ids_str)
286+ end
287+ end
288+ end
289+ i = i + 1
290+ end
291+ end
292+
293+ def unescape_str(s)
294+ result = ""
295+ i = 0
296+ while i < s.length
297+ ch = s[i]
298+ if ch == "%"
299+ if i + 2 < s.length
300+ hex = s[i + 1] + s[i + 2]
301+ if hex == "0A"
302+ result = result + "\n"
303+ i = i + 3
304+ else
305+ if hex == "0D"
306+ result = result + "\r"
307+ i = i + 3
308+ else
309+ if hex == "09"
310+ result = result + "\t"
311+ i = i + 3
312+ else
313+ if hex == "20"
314+ result = result + " "
315+ i = i + 3
316+ else
317+ if hex == "25"
318+ result = result + "%"
319+ i = i + 3
320+ else
321+ result = result + "%" + hex
322+ i = i + 3
323+ end
324+ end
325+ end
326+ end
327+ end
328+ else
329+ result = result + ch
330+ i = i + 1
331+ end
332+ else
333+ result = result + ch
334+ i = i + 1
335+ end
336+ end
337+ result
338+ end
339+
340+ def set_string_field(nid, field, val)
341+ if field == "name"
342+ @nd_name[nid] = val
343+ end
344+ if field == "content"
345+ @nd_content[nid] = val
346+ end
347+ if field == "value"
348+ @nd_content[nid] = val
349+ end
350+ if field == "operator"
351+ @nd_operator[nid] = val
352+ end
353+ if field == "binary_operator"
354+ @nd_binop[nid] = val
355+ end
356+ if field == "call_operator"
357+ @nd_callop[nid] = val
358+ end
359+ if field == "unescaped"
360+ @nd_unescaped[nid] = val
361+ end
362+ end
363+
364+ def set_int_field(nid, field, val)
365+ if field == "value"
366+ @nd_value[nid] = val
367+ end
368+ if field == "flags"
369+ @nd_flags[nid] = val
370+ end
371+ if field == "number"
372+ @nd_value[nid] = val
373+ end
374+ if field == "maximum"
375+ @nd_value[nid] = val
376+ end
377+ if field == "start_line"
378+ @nd_value[nid] = val
379+ end
380+ end
381+
382+ def set_ref_field(nid, field, ref_id)
383+ if field == "receiver"
384+ @nd_receiver[nid] = ref_id
385+ end
386+ if field == "arguments"
387+ @nd_arguments[nid] = ref_id
388+ end
389+ if field == "body"
390+ @nd_body[nid] = ref_id
391+ end
392+ if field == "block"
393+ @nd_block[nid] = ref_id
394+ end
395+ if field == "parameters"
396+ @nd_parameters[nid] = ref_id
397+ end
398+ if field == "predicate"
399+ @nd_predicate[nid] = ref_id
400+ end
401+ if field == "subsequent"
402+ @nd_subsequent[nid] = ref_id
403+ end
404+ if field == "else_clause"
405+ @nd_else_clause[nid] = ref_id
406+ end
407+ if field == "left"
408+ @nd_left[nid] = ref_id
409+ end
410+ if field == "right"
411+ @nd_right[nid] = ref_id
412+ end
413+ if field == "constant_path"
414+ @nd_constant_path[nid] = ref_id
415+ end
416+ if field == "superclass"
417+ @nd_superclass[nid] = ref_id
418+ end
419+ if field == "rest"
420+ @nd_rest[nid] = ref_id
421+ end
422+ if field == "rescue_clause"
423+ @nd_rescue_clause[nid] = ref_id
424+ end
425+ if field == "ensure_clause"
426+ @nd_ensure_clause[nid] = ref_id
427+ end
428+ if field == "expression"
429+ @nd_expression[nid] = ref_id
430+ end
431+ if field == "target"
432+ @nd_target[nid] = ref_id
433+ end
434+ if field == "pattern"
435+ @nd_pattern[nid] = ref_id
436+ end
437+ if field == "key"
438+ @nd_key[nid] = ref_id
439+ end
440+ if field == "reference"
441+ @nd_reference[nid] = ref_id
442+ end
443+ if field == "collection"
444+ @nd_collection[nid] = ref_id
445+ end
446+ if field == "statements"
447+ @nd_body[nid] = ref_id
448+ end
449+ if field == "value"
450+ @nd_expression[nid] = ref_id
451+ end
452+ if field == "index"
453+ @nd_target[nid] = ref_id
454+ end
455+ if field == "parent"
456+ @nd_receiver[nid] = ref_id
457+ end
458+ if field == "rescue_expression"
459+ @nd_else_clause[nid] = ref_id
460+ end
461+ if field == "call"
462+ @nd_receiver[nid] = ref_id
463+ end
464+ end
465+
466+ def set_array_field(nid, field, ids_str)
467+ if field == "body"
468+ @nd_stmts[nid] = ids_str
469+ end
470+ if field == "arguments"
471+ @nd_args[nid] = ids_str
472+ end
473+ if field == "requireds"
474+ @nd_requireds[nid] = ids_str
475+ end
476+ if field == "optionals"
477+ @nd_optionals[nid] = ids_str
478+ end
479+ if field == "keywords"
480+ @nd_keywords[nid] = ids_str
481+ end
482+ if field == "elements"
483+ @nd_elements[nid] = ids_str
484+ end
485+ if field == "parts"
486+ @nd_parts[nid] = ids_str
487+ end
488+ if field == "conditions"
489+ @nd_conditions[nid] = ids_str
490+ end
491+ if field == "exceptions"
492+ @nd_exceptions[nid] = ids_str
493+ end
494+ if field == "lefts"
495+ @nd_targets[nid] = ids_str
496+ end
497+ if field == "targets"
498+ @nd_targets[nid] = ids_str
499+ end
500+ end
501+
502+ # ---- Convenience: get stmts of a body node ----
503+ def get_stmts(nid)
504+ if nid < 0
505+ return []
506+ end
507+ # If it's a StatementsNode, return its stmts
508+ if @nd_type[nid] == "StatementsNode"
509+ return parse_id_list(@nd_stmts[nid])
510+ end
511+ # Otherwise return single-element array
512+ result = []
513+ result.push(nid)
514+ result
515+ end
516+
517+ def get_body_stmts(nid)
518+ body = @nd_body[nid]
519+ if body < 0
520+ return []
521+ end
522+ get_stmts(body)
523+ end
524+
525+ def get_args(nid)
526+ # nid is an ArgumentsNode
527+ if nid < 0
528+ return []
529+ end
530+ if @nd_type[nid] == "ArgumentsNode"
531+ return parse_id_list(@nd_args[nid])
532+ end
533+ result = []
534+ result.push(nid)
535+ result
536+ end
537+
538+ # ---- Scope management ----
539+ def push_scope
540+ @scope_names.push("---")
541+ @scope_types.push("---")
542+ end
543+
544+ def pop_scope
545+ while @scope_names.length > 0
546+ last = @scope_names[@scope_names.length - 1]
547+ if last == "---"
548+ @scope_names.pop
549+ @scope_types.pop
550+ return
551+ end
552+ @scope_names.pop
553+ @scope_types.pop
554+ end
555+ end
556+
557+ def declare_var(name, vtype)
558+ @scope_names.push(name)
559+ @scope_types.push(vtype)
560+ end
561+
562+ def find_var_type(name)
563+ i = @scope_names.length - 1
564+ while i >= 0
565+ if @scope_names[i] == name
566+ return @scope_types[i]
567+ end
568+ i = i - 1
569+ end
570+ ""
571+ end
572+
573+ def set_var_type(name, vtype)
574+ i = @scope_names.length - 1
575+ while i >= 0
576+ if @scope_names[i] == name
577+ @scope_types[i] = vtype
578+ return
579+ end
580+ i = i - 1
581+ end
582+ end
583+
584+ # ---- Class/Method lookup (all parallel arrays) ----
585+ def find_class_idx(name)
586+ i = 0
587+ while i < @cls_names.length
588+ if @cls_names[i] == name
589+ return i
590+ end
591+ i = i + 1
592+ end
593+ -1
594+ end
595+
596+ def find_method_idx(name)
597+ i = 0
598+ while i < @meth_names.length
599+ if @meth_names[i] == name
600+ return i
601+ end
602+ i = i + 1
603+ end
604+ -1
605+ end
606+
607+ def find_const_idx(name)
608+ i = 0
609+ while i < @const_names.length
610+ if @const_names[i] == name
611+ return i
612+ end
613+ i = i + 1
614+ end
615+ -1
616+ end
617+
618+ # Find method in class (search parent chain)
619+ def cls_find_method(ci, mname)
620+ names = @cls_meth_names[ci].split(";")
621+ j = 0
622+ while j < names.length
623+ if names[j] == mname
624+ return j
625+ end
626+ j = j + 1
627+ end
628+ # Check parent
629+ if @cls_parents[ci] != ""
630+ pi = find_class_idx(@cls_parents[ci])
631+ if pi >= 0
632+ return cls_find_method(pi, mname)
633+ end
634+ end
635+ -1
636+ end
637+
638+ # Get method return type from class
639+ def cls_method_return(ci, mname)
640+ names = @cls_meth_names[ci].split(";")
641+ returns = @cls_meth_returns[ci].split(";")
642+ j = 0
643+ while j < names.length
644+ if names[j] == mname
645+ if j < returns.length
646+ return returns[j]
647+ end
648+ return "int"
649+ end
650+ j = j + 1
651+ end
652+ if @cls_parents[ci] != ""
653+ pi = find_class_idx(@cls_parents[ci])
654+ if pi >= 0
655+ return cls_method_return(pi, mname)
656+ end
657+ end
658+ "int"
659+ end
660+
661+ # Get ivar type from class
662+ def cls_ivar_type(ci, iname)
663+ names = @cls_ivar_names[ci].split(";")
664+ types = @cls_ivar_types[ci].split(";")
665+ j = 0
666+ while j < names.length
667+ if names[j] == iname
668+ if j < types.length
669+ return types[j]
670+ end
671+ return "int"
672+ end
673+ j = j + 1
674+ end
675+ if @cls_parents[ci] != ""
676+ pi = find_class_idx(@cls_parents[ci])
677+ if pi >= 0
678+ return cls_ivar_type(pi, iname)
679+ end
680+ end
681+ "int"
682+ end
683+
684+ # ---- Emit helpers ----
685+ def emit(s)
686+ ind = ""
687+ j = 0
688+ while j < @indent
689+ ind = ind + " "
690+ j = j + 1
691+ end
692+ @out = @out + ind + s + "\n"
693+ end
694+
695+ def emit_raw(s)
696+ @out = @out + s + "\n"
697+ end
698+
699+ # ---- Type inference ----
700+ def infer_type(nid)
701+ if nid < 0
702+ return "void"
703+ end
704+ t = @nd_type[nid]
705+ if t == "IntegerNode"
706+ return "int"
707+ end
708+ if t == "FloatNode"
709+ return "float"
710+ end
711+ if t == "StringNode"
712+ return "string"
713+ end
714+ if t == "SymbolNode"
715+ return "string"
716+ end
717+ if t == "InterpolatedStringNode"
718+ return "string"
719+ end
720+ if t == "TrueNode"
721+ return "bool"
722+ end
723+ if t == "FalseNode"
724+ return "bool"
725+ end
726+ if t == "NilNode"
727+ return "nil"
728+ end
729+ if t == "ArrayNode"
730+ return infer_array_elem_type(nid)
731+ end
732+ if t == "HashNode"
733+ return infer_hash_val_type(nid)
734+ end
735+ if t == "RangeNode"
736+ return "range"
737+ end
738+ if t == "LocalVariableReadNode"
739+ vt = find_var_type(@nd_name[nid])
740+ if vt != ""
741+ return vt
742+ end
743+ return "int"
744+ end
745+ if t == "InstanceVariableReadNode"
746+ if @current_class_idx >= 0
747+ return cls_ivar_type(@current_class_idx, @nd_name[nid])
748+ end
749+ return "int"
750+ end
751+ if t == "ConstantReadNode"
752+ ci = find_const_idx(@nd_name[nid])
753+ if ci >= 0
754+ return @const_types[ci]
755+ end
756+ cx = find_class_idx(@nd_name[nid])
757+ if cx >= 0
758+ return "class_" + @nd_name[nid]
759+ end
760+ return "int"
761+ end
762+ if t == "CallNode"
763+ return infer_call_type(nid)
764+ end
765+ if t == "IfNode"
766+ body = @nd_body[nid]
767+ if body >= 0
768+ stmts = get_stmts(body)
769+ if stmts.length > 0
770+ return infer_type(stmts[stmts.length - 1])
771+ end
772+ end
773+ return "void"
774+ end
775+ if t == "AndNode"
776+ return "bool"
777+ end
778+ if t == "OrNode"
779+ return infer_type(@nd_left[nid])
780+ end
781+ if t == "ParenthesesNode"
782+ body = @nd_body[nid]
783+ if body >= 0
784+ stmts = get_stmts(body)
785+ if stmts.length > 0
786+ return infer_type(stmts[stmts.length - 1])
787+ end
788+ end
789+ return "void"
790+ end
791+ if t == "SelfNode"
792+ if @current_class_idx >= 0
793+ return "obj_" + @cls_names[@current_class_idx]
794+ end
795+ return "int"
796+ end
797+ "int"
798+ end
799+
800+ def infer_array_elem_type(nid)
801+ elems = parse_id_list(@nd_elements[nid])
802+ if elems.length > 0
803+ et = infer_type(elems[0])
804+ if et == "string"
805+ return "str_array"
806+ end
807+ end
808+ "int_array"
809+ end
810+
811+ def infer_hash_val_type(nid)
812+ elems = parse_id_list(@nd_elements[nid])
813+ if elems.length > 0
814+ eid = elems[0]
815+ if @nd_type[eid] == "AssocNode"
816+ vt = infer_type(@nd_expression[eid])
817+ if vt == "string"
818+ return "str_str_hash"
819+ end
820+ end
821+ end
822+ "str_int_hash"
823+ end
824+
825+ def infer_call_type(nid)
826+ mname = @nd_name[nid]
827+ recv = @nd_receiver[nid]
828+
829+ if mname == "+"
830+ if recv >= 0
831+ lt = infer_type(recv)
832+ if lt == "string"
833+ return "string"
834+ end
835+ if lt == "float"
836+ return "float"
837+ end
838+ end
839+ return "int"
840+ end
841+ if mname == "-"
842+ if recv >= 0
843+ lt = infer_type(recv)
844+ if lt == "float"
845+ return "float"
846+ end
847+ end
848+ return "int"
849+ end
850+ if mname == "*"
851+ if recv >= 0
852+ lt = infer_type(recv)
853+ if lt == "float"
854+ return "float"
855+ end
856+ end
857+ return "int"
858+ end
859+ if mname == "/"
860+ if recv >= 0
861+ lt = infer_type(recv)
862+ if lt == "float"
863+ return "float"
864+ end
865+ end
866+ return "int"
867+ end
868+ if mname == "%"
869+ return "int"
870+ end
871+ if mname == "<"
872+ return "bool"
873+ end
874+ if mname == ">"
875+ return "bool"
876+ end
877+ if mname == "<="
878+ return "bool"
879+ end
880+ if mname == ">="
881+ return "bool"
882+ end
883+ if mname == "=="
884+ return "bool"
885+ end
886+ if mname == "!="
887+ return "bool"
888+ end
889+ if mname == "!"
890+ return "bool"
891+ end
892+ if mname == "length"
893+ return "int"
894+ end
895+ if mname == "to_s"
896+ return "string"
897+ end
898+ if mname == "to_i"
899+ return "int"
900+ end
901+ if mname == "to_f"
902+ return "float"
903+ end
904+ if mname == "upcase"
905+ return "string"
906+ end
907+ if mname == "downcase"
908+ return "string"
909+ end
910+ if mname == "strip"
911+ return "string"
912+ end
913+ if mname == "chomp"
914+ return "string"
915+ end
916+ if mname == "include?"
917+ return "bool"
918+ end
919+ if mname == "start_with?"
920+ return "bool"
921+ end
922+ if mname == "end_with?"
923+ return "bool"
924+ end
925+ if mname == "empty?"
926+ return "bool"
927+ end
928+ if mname == "has_key?"
929+ return "bool"
930+ end
931+ if mname == "split"
932+ return "str_array"
933+ end
934+ if mname == "gsub"
935+ return "string"
936+ end
937+ if mname == "sub"
938+ return "string"
939+ end
940+ if mname == "index"
941+ return "int"
942+ end
943+ if mname == "keys"
944+ return "str_array"
945+ end
946+ if mname == "push"
947+ if recv >= 0
948+ return infer_type(recv)
949+ end
950+ return "int_array"
951+ end
952+ if mname == "pop"
953+ if recv >= 0
954+ rt = infer_type(recv)
955+ if rt == "str_array"
956+ return "string"
957+ end
958+ end
959+ return "int"
960+ end
961+ if mname == "sort"
962+ if recv >= 0
963+ return infer_type(recv)
964+ end
965+ return "int_array"
966+ end
967+ if mname == "first"
968+ if recv >= 0
969+ rt = infer_type(recv)
970+ if rt == "str_array"
971+ return "string"
972+ end
973+ end
974+ return "int"
975+ end
976+ if mname == "last"
977+ if recv >= 0
978+ rt = infer_type(recv)
979+ if rt == "str_array"
980+ return "string"
981+ end
982+ end
983+ return "int"
984+ end
985+ if mname == "min"
986+ return "int"
987+ end
988+ if mname == "max"
989+ return "int"
990+ end
991+ if mname == "sum"
992+ return "int"
993+ end
994+ if mname == "reverse"
995+ if recv >= 0
996+ return infer_type(recv)
997+ end
998+ return "int_array"
999+ end
1000+ if mname == "[]"
1001+ if recv >= 0
1002+ rt = infer_type(recv)
1003+ if rt == "string"
1004+ return "string"
1005+ end
1006+ if rt == "int_array"
1007+ return "int"
1008+ end
1009+ if rt == "str_array"
1010+ return "string"
1011+ end
1012+ if rt == "str_int_hash"
1013+ return "int"
1014+ end
1015+ if rt == "str_str_hash"
1016+ return "string"
1017+ end
1018+ end
1019+ return "int"
1020+ end
1021+ if mname == "puts"
1022+ return "void"
1023+ end
1024+ if mname == "print"
1025+ return "void"
1026+ end
1027+ if mname == "new"
1028+ if recv >= 0
1029+ if @nd_type[recv] == "ConstantReadNode"
1030+ return "obj_" + @nd_name[recv]
1031+ end
1032+ end
1033+ end
1034+ if mname == "sqrt"
1035+ return "float"
1036+ end
1037+ if mname == "freeze"
1038+ if recv >= 0
1039+ return infer_type(recv)
1040+ end
1041+ return "string"
1042+ end
1043+
1044+ # Method call on object
1045+ if recv >= 0
1046+ rt = infer_type(recv)
1047+ if is_obj_type(rt) == 1
1048+ cname = rt[4, rt.length - 4]
1049+ ci = find_class_idx(cname)
1050+ if ci >= 0
1051+ # Check attr_reader
1052+ readers = @cls_attr_readers[ci].split(";")
1053+ j = 0
1054+ while j < readers.length
1055+ if readers[j] == mname
1056+ return cls_ivar_type(ci, "@" + mname)
1057+ end
1058+ j = j + 1
1059+ end
1060+ # Check method
1061+ mr = cls_method_return(ci, mname)
1062+ if mr != "int"
1063+ return mr
1064+ end
1065+ # If method exists, return its return type
1066+ mi = cls_find_method(ci, mname)
1067+ if mi >= 0
1068+ return cls_method_return(ci, mname)
1069+ end
1070+ end
1071+ end
1072+ end
1073+
1074+ # Top-level method
1075+ mi = find_method_idx(mname)
1076+ if mi >= 0
1077+ return @meth_return_types[mi]
1078+ end
1079+
1080+ # Bare method call in class context
1081+ if @current_class_idx >= 0
1082+ mr = cls_method_return(@current_class_idx, mname)
1083+ return mr
1084+ end
1085+
1086+ "int"
1087+ end
1088+
1089+ def is_obj_type(t)
1090+ if t.length > 4
1091+ if t[0] == "o"
1092+ if t[1] == "b"
1093+ if t[2] == "j"
1094+ if t[3] == "_"
1095+ return 1
1096+ end
1097+ end
1098+ end
1099+ end
1100+ end
1101+ 0
1102+ end
1103+
1104+ def type_is_pointer(t)
1105+ if t == "int_array"
1106+ return 1
1107+ end
1108+ if t == "str_array"
1109+ return 1
1110+ end
1111+ if t == "str_int_hash"
1112+ return 1
1113+ end
1114+ if t == "str_str_hash"
1115+ return 1
1116+ end
1117+ if is_obj_type(t) == 1
1118+ return 1
1119+ end
1120+ 0
1121+ end
1122+
1123+ # ---- C type mapping ----
1124+ def c_type(t)
1125+ if t == "int"
1126+ return "mrb_int"
1127+ end
1128+ if t == "float"
1129+ return "mrb_float"
1130+ end
1131+ if t == "bool"
1132+ return "mrb_bool"
1133+ end
1134+ if t == "string"
1135+ return "const char *"
1136+ end
1137+ if t == "void"
1138+ return "mrb_int"
1139+ end
1140+ if t == "nil"
1141+ return "mrb_int"
1142+ end
1143+ if t == "int_array"
1144+ return "sp_IntArray *"
1145+ end
1146+ if t == "str_array"
1147+ return "sp_StrArray *"
1148+ end
1149+ if t == "str_int_hash"
1150+ return "sp_StrIntHash *"
1151+ end
1152+ if t == "str_str_hash"
1153+ return "sp_StrStrHash *"
1154+ end
1155+ if is_obj_type(t) == 1
1156+ cname = t[4, t.length - 4]
1157+ return "sp_" + cname + " *"
1158+ end
1159+ "mrb_int"
1160+ end
1161+
1162+ def c_default_val(t)
1163+ if t == "int"
1164+ return "0"
1165+ end
1166+ if t == "float"
1167+ return "0.0"
1168+ end
1169+ if t == "bool"
1170+ return "FALSE"
1171+ end
1172+ if t == "string"
1173+ return "\"\""
1174+ end
1175+ if t == "void"
1176+ return "0"
1177+ end
1178+ if t == "nil"
1179+ return "0"
1180+ end
1181+ if type_is_pointer(t) == 1
1182+ return "NULL"
1183+ end
1184+ "0"
1185+ end
1186+
1187+ def sanitize_name(name)
1188+ result = ""
1189+ i = 0
1190+ while i < name.length
1191+ ch = name[i]
1192+ if ch == "?"
1193+ result = result + "_p"
1194+ else
1195+ if ch == "!"
1196+ result = result + "_bang"
1197+ else
1198+ if ch == "="
1199+ result = result + "_eq"
1200+ else
1201+ result = result + ch
1202+ end
1203+ end
1204+ end
1205+ i = i + 1
1206+ end
1207+ result
1208+ end
1209+
1210+ def sanitize_ivar(name)
1211+ if name.length > 0
1212+ if name[0] == "@"
1213+ return name[1, name.length - 1]
1214+ end
1215+ end
1216+ name
1217+ end
1218+
1219+ # ---- Collection pass ----
1220+ def collect_all
1221+ root = @root_id
1222+ if @nd_type[root] != "ProgramNode"
1223+ return
1224+ end
1225+ stmts = get_body_stmts(root)
1226+
1227+ # Pass 1: classes
1228+ i = 0
1229+ while i < stmts.length
1230+ sid = stmts[i]
1231+ if @nd_type[sid] == "ClassNode"
1232+ collect_class(sid)
1233+ end
1234+ i = i + 1
1235+ end
1236+
1237+ # Pass 2: top-level methods and constants
1238+ i = 0
1239+ while i < stmts.length
1240+ sid = stmts[i]
1241+ if @nd_type[sid] == "DefNode"
1242+ collect_toplevel_method(sid)
1243+ end
1244+ if @nd_type[sid] == "ConstantWriteNode"
1245+ collect_constant(sid)
1246+ end
1247+ i = i + 1
1248+ end
1249+
1250+ # Pass 3: infer return types
1251+ infer_all_returns
1252+ end
1253+
1254+ def collect_class(nid)
1255+ ci = @cls_names.length
1256+ cname = ""
1257+ cp = @nd_constant_path[nid]
1258+ if cp >= 0
1259+ cname = @nd_name[cp]
1260+ end
1261+ parent = ""
1262+ sp = @nd_superclass[nid]
1263+ if sp >= 0
1264+ parent = @nd_name[sp]
1265+ end
1266+
1267+ @cls_names.push(cname)
1268+ @cls_parents.push(parent)
1269+ @cls_ivar_names.push("")
1270+ @cls_ivar_types.push("")
1271+ @cls_meth_names.push("")
1272+ @cls_meth_params.push("")
1273+ @cls_meth_ptypes.push("")
1274+ @cls_meth_returns.push("")
1275+ @cls_meth_bodies.push("")
1276+ @cls_meth_defaults.push("")
1277+ @cls_attr_readers.push("")
1278+ @cls_attr_writers.push("")
1279+ @cls_cmeth_names.push("")
1280+ @cls_cmeth_params.push("")
1281+ @cls_cmeth_ptypes.push("")
1282+ @cls_cmeth_returns.push("")
1283+ @cls_cmeth_bodies.push("")
1284+ @needs_gc = 1
1285+
1286+ # Collect class body
1287+ body = @nd_body[nid]
1288+ if body < 0
1289+ return
1290+ end
1291+ body_stmts = get_stmts(body)
1292+ j = 0
1293+ while j < body_stmts.length
1294+ sid = body_stmts[j]
1295+ if @nd_type[sid] == "DefNode"
1296+ collect_class_method(ci, sid)
1297+ end
1298+ if @nd_type[sid] == "CallNode"
1299+ collect_attr_call(ci, sid)
1300+ end
1301+ j = j + 1
1302+ end
1303+
1304+ # Collect ivars
1305+ collect_ivars(ci)
1306+ end
1307+
1308+ def collect_class_method(ci, nid)
1309+ mname = @nd_name[nid]
1310+ body_id = @nd_body[nid]
1311+
1312+ # Check for class method (def self.xxx)
1313+ if @nd_receiver[nid] >= 0
1314+ if @nd_type[@nd_receiver[nid]] == "SelfNode"
1315+ # Class method
1316+ params_str = collect_params_str(nid)
1317+ ptypes_str = collect_ptypes_str(nid, ci)
1318+ defaults_str = collect_defaults_str(nid)
1319+ append_cls_cmeth(ci, mname, params_str, ptypes_str, "int", body_id)
1320+ return
1321+ end
1322+ end
1323+
1324+ params_str = collect_params_str(nid)
1325+ ptypes_str = collect_ptypes_str(nid, ci)
1326+ defaults_str = collect_defaults_str(nid)
1327+ append_cls_meth(ci, mname, params_str, ptypes_str, "int", body_id, defaults_str)
1328+ end
1329+
1330+ def collect_params_str(nid)
1331+ params = @nd_parameters[nid]
1332+ if params < 0
1333+ return ""
1334+ end
1335+ reqs = parse_id_list(@nd_requireds[params])
1336+ opts = parse_id_list(@nd_optionals[params])
1337+ result = ""
1338+ k = 0
1339+ while k < reqs.length
1340+ if result != ""
1341+ result = result + ","
1342+ end
1343+ result = result + @nd_name[reqs[k]]
1344+ k = k + 1
1345+ end
1346+ k = 0
1347+ while k < opts.length
1348+ if result != ""
1349+ result = result + ","
1350+ end
1351+ result = result + @nd_name[opts[k]]
1352+ k = k + 1
1353+ end
1354+ result
1355+ end
1356+
1357+ def collect_ptypes_str(nid, ci)
1358+ params = @nd_parameters[nid]
1359+ if params < 0
1360+ return ""
1361+ end
1362+ reqs = parse_id_list(@nd_requireds[params])
1363+ opts = parse_id_list(@nd_optionals[params])
1364+ result = ""
1365+ k = 0
1366+ while k < reqs.length
1367+ if result != ""
1368+ result = result + ","
1369+ end
1370+ result = result + "int"
1371+ k = k + 1
1372+ end
1373+ k = 0
1374+ while k < opts.length
1375+ if result != ""
1376+ result = result + ","
1377+ end
1378+ # Infer from default value
1379+ def_id = @nd_expression[opts[k]]
1380+ if def_id >= 0
1381+ result = result + infer_type(def_id)
1382+ else
1383+ result = result + "int"
1384+ end
1385+ k = k + 1
1386+ end
1387+ result
1388+ end
1389+
1390+ def collect_defaults_str(nid)
1391+ params = @nd_parameters[nid]
1392+ if params < 0
1393+ return ""
1394+ end
1395+ reqs = parse_id_list(@nd_requireds[params])
1396+ opts = parse_id_list(@nd_optionals[params])
1397+ result = ""
1398+ k = 0
1399+ while k < reqs.length
1400+ if result != ""
1401+ result = result + ","
1402+ end
1403+ result = result + "-1"
1404+ k = k + 1
1405+ end
1406+ k = 0
1407+ while k < opts.length
1408+ if result != ""
1409+ result = result + ","
1410+ end
1411+ def_id = @nd_expression[opts[k]]
1412+ if def_id >= 0
1413+ result = result + def_id.to_s
1414+ else
1415+ result = result + "-1"
1416+ end
1417+ k = k + 1
1418+ end
1419+ result
1420+ end
1421+
1422+ def append_cls_meth(ci, name, params, ptypes, ret, body_id, defaults)
1423+ if @cls_meth_names[ci] != ""
1424+ @cls_meth_names[ci] = @cls_meth_names[ci] + ";" + name
1425+ @cls_meth_params[ci] = @cls_meth_params[ci] + "|" + params
1426+ @cls_meth_ptypes[ci] = @cls_meth_ptypes[ci] + "|" + ptypes
1427+ @cls_meth_returns[ci] = @cls_meth_returns[ci] + ";" + ret
1428+ @cls_meth_bodies[ci] = @cls_meth_bodies[ci] + ";" + body_id.to_s
1429+ @cls_meth_defaults[ci] = @cls_meth_defaults[ci] + "|" + defaults
1430+ else
1431+ @cls_meth_names[ci] = name
1432+ @cls_meth_params[ci] = params
1433+ @cls_meth_ptypes[ci] = ptypes
1434+ @cls_meth_returns[ci] = ret
1435+ @cls_meth_bodies[ci] = body_id.to_s
1436+ @cls_meth_defaults[ci] = defaults
1437+ end
1438+ end
1439+
1440+ def append_cls_cmeth(ci, name, params, ptypes, ret, body_id)
1441+ if @cls_cmeth_names[ci] != ""
1442+ @cls_cmeth_names[ci] = @cls_cmeth_names[ci] + ";" + name
1443+ @cls_cmeth_params[ci] = @cls_cmeth_params[ci] + "|" + params
1444+ @cls_cmeth_ptypes[ci] = @cls_cmeth_ptypes[ci] + "|" + ptypes
1445+ @cls_cmeth_returns[ci] = @cls_cmeth_returns[ci] + ";" + ret
1446+ @cls_cmeth_bodies[ci] = @cls_cmeth_bodies[ci] + ";" + body_id.to_s
1447+ else
1448+ @cls_cmeth_names[ci] = name
1449+ @cls_cmeth_params[ci] = params
1450+ @cls_cmeth_ptypes[ci] = ptypes
1451+ @cls_cmeth_returns[ci] = ret
1452+ @cls_cmeth_bodies[ci] = body_id.to_s
1453+ end
1454+ end
1455+
1456+ def collect_attr_call(ci, nid)
1457+ mname = @nd_name[nid]
1458+ args_id = @nd_arguments[nid]
1459+ if args_id < 0
1460+ return
1461+ end
1462+ arg_ids = get_args(args_id)
1463+ if mname == "attr_accessor"
1464+ k = 0
1465+ while k < arg_ids.length
1466+ aname = @nd_content[arg_ids[k]]
1467+ append_attr_reader(ci, aname)
1468+ append_attr_writer(ci, aname)
1469+ k = k + 1
1470+ end
1471+ end
1472+ if mname == "attr_reader"
1473+ k = 0
1474+ while k < arg_ids.length
1475+ aname = @nd_content[arg_ids[k]]
1476+ append_attr_reader(ci, aname)
1477+ k = k + 1
1478+ end
1479+ end
1480+ if mname == "attr_writer"
1481+ k = 0
1482+ while k < arg_ids.length
1483+ aname = @nd_content[arg_ids[k]]
1484+ append_attr_writer(ci, aname)
1485+ k = k + 1
1486+ end
1487+ end
1488+ end
1489+
1490+ def append_attr_reader(ci, name)
1491+ if @cls_attr_readers[ci] != ""
1492+ @cls_attr_readers[ci] = @cls_attr_readers[ci] + ";" + name
1493+ else
1494+ @cls_attr_readers[ci] = name
1495+ end
1496+ end
1497+
1498+ def append_attr_writer(ci, name)
1499+ if @cls_attr_writers[ci] != ""
1500+ @cls_attr_writers[ci] = @cls_attr_writers[ci] + ";" + name
1501+ else
1502+ @cls_attr_writers[ci] = name
1503+ end
1504+ end
1505+
1506+ def collect_ivars(ci)
1507+ # Scan all methods for ivar writes
1508+ meths = @cls_meth_bodies[ci].split(";")
1509+ j = 0
1510+ while j < meths.length
1511+ bid = meths[j].to_i
1512+ if bid >= 0
1513+ scan_ivars(ci, bid)
1514+ end
1515+ j = j + 1
1516+ end
1517+ # Add ivars from attr_readers/writers that might not have explicit writes
1518+ readers = @cls_attr_readers[ci].split(";")
1519+ j = 0
1520+ while j < readers.length
1521+ iname = "@" + readers[j]
1522+ if ivar_exists(ci, iname) == 0
1523+ add_ivar(ci, iname, "int")
1524+ end
1525+ j = j + 1
1526+ end
1527+ writers = @cls_attr_writers[ci].split(";")
1528+ j = 0
1529+ while j < writers.length
1530+ iname = "@" + writers[j]
1531+ if ivar_exists(ci, iname) == 0
1532+ add_ivar(ci, iname, "int")
1533+ end
1534+ j = j + 1
1535+ end
1536+ end
1537+
1538+ def ivar_exists(ci, iname)
1539+ names = @cls_ivar_names[ci].split(";")
1540+ k = 0
1541+ while k < names.length
1542+ if names[k] == iname
1543+ return 1
1544+ end
1545+ k = k + 1
1546+ end
1547+ 0
1548+ end
1549+
1550+ def add_ivar(ci, iname, itype)
1551+ if @cls_ivar_names[ci] != ""
1552+ @cls_ivar_names[ci] = @cls_ivar_names[ci] + ";" + iname
1553+ @cls_ivar_types[ci] = @cls_ivar_types[ci] + ";" + itype
1554+ else
1555+ @cls_ivar_names[ci] = iname
1556+ @cls_ivar_types[ci] = itype
1557+ end
1558+ end
1559+
1560+ def scan_ivars(ci, nid)
1561+ if nid < 0
1562+ return
1563+ end
1564+ if @nd_type[nid] == "InstanceVariableWriteNode"
1565+ iname = @nd_name[nid]
1566+ if ivar_exists(ci, iname) == 0
1567+ vtype = infer_ivar_init_type(@nd_expression[nid])
1568+ add_ivar(ci, iname, vtype)
1569+ end
1570+ end
1571+ if @nd_type[nid] == "InstanceVariableOperatorWriteNode"
1572+ iname = @nd_name[nid]
1573+ if ivar_exists(ci, iname) == 0
1574+ add_ivar(ci, iname, "int")
1575+ end
1576+ end
1577+ # Recurse into children
1578+ scan_ivars_children(ci, nid)
1579+ end
1580+
1581+ def scan_ivars_children(ci, nid)
1582+ if @nd_body[nid] >= 0
1583+ scan_ivars(ci, @nd_body[nid])
1584+ end
1585+ stmts = parse_id_list(@nd_stmts[nid])
1586+ k = 0
1587+ while k < stmts.length
1588+ scan_ivars(ci, stmts[k])
1589+ k = k + 1
1590+ end
1591+ if @nd_expression[nid] >= 0
1592+ scan_ivars(ci, @nd_expression[nid])
1593+ end
1594+ if @nd_predicate[nid] >= 0
1595+ scan_ivars(ci, @nd_predicate[nid])
1596+ end
1597+ if @nd_subsequent[nid] >= 0
1598+ scan_ivars(ci, @nd_subsequent[nid])
1599+ end
1600+ if @nd_else_clause[nid] >= 0
1601+ scan_ivars(ci, @nd_else_clause[nid])
1602+ end
1603+ if @nd_receiver[nid] >= 0
1604+ scan_ivars(ci, @nd_receiver[nid])
1605+ end
1606+ if @nd_arguments[nid] >= 0
1607+ scan_ivars(ci, @nd_arguments[nid])
1608+ end
1609+ args = parse_id_list(@nd_args[nid])
1610+ k = 0
1611+ while k < args.length
1612+ scan_ivars(ci, args[k])
1613+ k = k + 1
1614+ end
1615+ conds = parse_id_list(@nd_conditions[nid])
1616+ k = 0
1617+ while k < conds.length
1618+ scan_ivars(ci, conds[k])
1619+ k = k + 1
1620+ end
1621+ if @nd_left[nid] >= 0
1622+ scan_ivars(ci, @nd_left[nid])
1623+ end
1624+ if @nd_right[nid] >= 0
1625+ scan_ivars(ci, @nd_right[nid])
1626+ end
1627+ if @nd_block[nid] >= 0
1628+ scan_ivars(ci, @nd_block[nid])
1629+ end
1630+ elems = parse_id_list(@nd_elements[nid])
1631+ k = 0
1632+ while k < elems.length
1633+ scan_ivars(ci, elems[k])
1634+ k = k + 1
1635+ end
1636+ end
1637+
1638+ def infer_ivar_init_type(nid)
1639+ if nid < 0
1640+ return "int"
1641+ end
1642+ t = @nd_type[nid]
1643+ if t == "IntegerNode"
1644+ return "int"
1645+ end
1646+ if t == "FloatNode"
1647+ return "float"
1648+ end
1649+ if t == "StringNode"
1650+ return "string"
1651+ end
1652+ if t == "SymbolNode"
1653+ return "string"
1654+ end
1655+ if t == "TrueNode"
1656+ return "bool"
1657+ end
1658+ if t == "FalseNode"
1659+ return "bool"
1660+ end
1661+ if t == "ArrayNode"
1662+ return infer_array_elem_type(nid)
1663+ end
1664+ if t == "HashNode"
1665+ return infer_hash_val_type(nid)
1666+ end
1667+ if t == "CallNode"
1668+ if @nd_name[nid] == "new"
1669+ r = @nd_receiver[nid]
1670+ if r >= 0
1671+ if @nd_type[r] == "ConstantReadNode"
1672+ return "obj_" + @nd_name[r]
1673+ end
1674+ end
1675+ end
1676+ end
1677+ if t == "LocalVariableReadNode"
1678+ vt = find_var_type(@nd_name[nid])
1679+ if vt != ""
1680+ return vt
1681+ end
1682+ end
1683+ "int"
1684+ end
1685+
1686+ def collect_toplevel_method(nid)
1687+ mname = @nd_name[nid]
1688+ body_id = @nd_body[nid]
1689+ params_str = collect_params_str(nid)
1690+ ptypes_str = ""
1691+ defaults_str = collect_defaults_str(nid)
1692+
1693+ # Infer param types from defaults
1694+ params = @nd_parameters[nid]
1695+ if params >= 0
1696+ reqs = parse_id_list(@nd_requireds[params])
1697+ opts = parse_id_list(@nd_optionals[params])
1698+ k = 0
1699+ while k < reqs.length
1700+ if ptypes_str != ""
1701+ ptypes_str = ptypes_str + ","
1702+ end
1703+ ptypes_str = ptypes_str + "int"
1704+ k = k + 1
1705+ end
1706+ k = 0
1707+ while k < opts.length
1708+ if ptypes_str != ""
1709+ ptypes_str = ptypes_str + ","
1710+ end
1711+ def_id = @nd_expression[opts[k]]
1712+ if def_id >= 0
1713+ ptypes_str = ptypes_str + infer_type(def_id)
1714+ else
1715+ ptypes_str = ptypes_str + "int"
1716+ end
1717+ k = k + 1
1718+ end
1719+ end
1720+
1721+ @meth_names.push(mname)
1722+ @meth_param_names.push(params_str)
1723+ @meth_param_types.push(ptypes_str)
1724+ @meth_return_types.push("int")
1725+ @meth_body_ids.push(body_id)
1726+ @meth_has_defaults.push(defaults_str)
1727+ end
1728+
1729+ def collect_constant(nid)
1730+ @const_names.push(@nd_name[nid])
1731+ expr_id = @nd_expression[nid]
1732+ ct = "int"
1733+ if expr_id >= 0
1734+ ct = infer_type(expr_id)
1735+ end
1736+ @const_types.push(ct)
1737+ @const_expr_ids.push(expr_id)
1738+ end
1739+
1740+ # ---- Return type inference ----
1741+ def infer_all_returns
1742+ # Top-level methods
1743+ i = 0
1744+ while i < @meth_names.length
1745+ push_scope
1746+ pnames = @meth_param_names[i].split(",")
1747+ ptypes = @meth_param_types[i].split(",")
1748+ j = 0
1749+ while j < pnames.length
1750+ pt = "int"
1751+ if j < ptypes.length
1752+ pt = ptypes[j]
1753+ end
1754+ declare_var(pnames[j], pt)
1755+ j = j + 1
1756+ end
1757+ rt = infer_body_return(@meth_body_ids[i])
1758+ @meth_return_types[i] = rt
1759+ pop_scope
1760+ i = i + 1
1761+ end
1762+
1763+ # Class methods
1764+ i = 0
1765+ while i < @cls_names.length
1766+ @current_class_idx = i
1767+ mnames = @cls_meth_names[i].split(";")
1768+ all_params = @cls_meth_params[i].split("|")
1769+ all_ptypes = @cls_meth_ptypes[i].split("|")
1770+ bodies = @cls_meth_bodies[i].split(";")
1771+ returns = @cls_meth_returns[i].split(";")
1772+
1773+ j = 0
1774+ while j < mnames.length
1775+ push_scope
1776+ pnames = []
1777+ ptypes = []
1778+ if j < all_params.length
1779+ pnames = all_params[j].split(",")
1780+ end
1781+ if j < all_ptypes.length
1782+ ptypes = all_ptypes[j].split(",")
1783+ end
1784+
1785+ # Infer param types for initialize
1786+ if mnames[j] == "initialize"
1787+ k = 0
1788+ while k < pnames.length
1789+ pt = infer_init_param_type(i, pnames[k])
1790+ if k < ptypes.length
1791+ ptypes[k] = pt
1792+ end
1793+ declare_var(pnames[k], pt)
1794+ k = k + 1
1795+ end
1796+ # Update ptypes in class storage
1797+ new_ptypes = join_sep(ptypes, ",")
1798+ if j < all_ptypes.length
1799+ all_ptypes[j] = new_ptypes
1800+ end
1801+ @cls_meth_ptypes[i] = join_sep(all_ptypes, "|")
1802+ else
1803+ k = 0
1804+ while k < pnames.length
1805+ pt = "int"
1806+ if k < ptypes.length
1807+ pt = ptypes[k]
1808+ end
1809+ declare_var(pnames[k], pt)
1810+ k = k + 1
1811+ end
1812+ end
1813+
1814+ bid = -1
1815+ if j < bodies.length
1816+ bid = bodies[j].to_i
1817+ end
1818+ rt = "int"
1819+ if mnames[j] == "initialize"
1820+ rt = "void"
1821+ else
1822+ if mnames[j] == "to_s"
1823+ rt = "string"
1824+ else
1825+ rt = infer_body_return(bid)
1826+ end
1827+ end
1828+ if j < returns.length
1829+ returns[j] = rt
1830+ end
1831+ pop_scope
1832+ j = j + 1
1833+ end
1834+ @cls_meth_returns[i] = join_sep(returns, ";")
1835+
1836+ # Class methods
1837+ cmnames = @cls_cmeth_names[i].split(";")
1838+ cm_bodies = @cls_cmeth_bodies[i].split(";")
1839+ cm_returns = @cls_cmeth_returns[i].split(";")
1840+ j = 0
1841+ while j < cmnames.length
1842+ push_scope
1843+ bid = -1
1844+ if j < cm_bodies.length
1845+ bid = cm_bodies[j].to_i
1846+ end
1847+ rt = infer_body_return(bid)
1848+ if j < cm_returns.length
1849+ cm_returns[j] = rt
1850+ end
1851+ pop_scope
1852+ j = j + 1
1853+ end
1854+ @cls_cmeth_returns[i] = join_sep(cm_returns, ";")
1855+ @current_class_idx = -1
1856+ i = i + 1
1857+ end
1858+ end
1859+
1860+ def infer_init_param_type(ci, pname)
1861+ # Check if param is assigned to an ivar in initialize
1862+ mnames = @cls_meth_names[ci].split(";")
1863+ bodies = @cls_meth_bodies[ci].split(";")
1864+ j = 0
1865+ while j < mnames.length
1866+ if mnames[j] == "initialize"
1867+ bid = -1
1868+ if j < bodies.length
1869+ bid = bodies[j].to_i
1870+ end
1871+ if bid >= 0
1872+ stmts = get_stmts(bid)
1873+ k = 0
1874+ while k < stmts.length
1875+ sid = stmts[k]
1876+ if @nd_type[sid] == "InstanceVariableWriteNode"
1877+ expr = @nd_expression[sid]
1878+ if expr >= 0
1879+ if @nd_type[expr] == "LocalVariableReadNode"
1880+ if @nd_name[expr] == pname
1881+ return cls_ivar_type(ci, @nd_name[sid])
1882+ end
1883+ end
1884+ end
1885+ end
1886+ k = k + 1
1887+ end
1888+ end
1889+ end
1890+ j = j + 1
1891+ end
1892+ "int"
1893+ end
1894+
1895+ def infer_body_return(body_id)
1896+ if body_id < 0
1897+ return "void"
1898+ end
1899+ stmts = get_stmts(body_id)
1900+ if stmts.length == 0
1901+ return "void"
1902+ end
1903+ # Check for explicit returns
1904+ rt = scan_return_type_list(stmts)
1905+ if rt != ""
1906+ return rt
1907+ end
1908+ # Last expression
1909+ infer_type(stmts[stmts.length - 1])
1910+ end
1911+
1912+ def scan_return_type_list(stmts)
1913+ i = 0
1914+ while i < stmts.length
1915+ rt = scan_return_type(stmts[i])
1916+ if rt != ""
1917+ return rt
1918+ end
1919+ i = i + 1
1920+ end
1921+ ""
1922+ end
1923+
1924+ def scan_return_type(nid)
1925+ if nid < 0
1926+ return ""
1927+ end
1928+ if @nd_type[nid] == "ReturnNode"
1929+ args_id = @nd_arguments[nid]
1930+ if args_id >= 0
1931+ arg_ids = get_args(args_id)
1932+ if arg_ids.length > 0
1933+ return infer_type(arg_ids[0])
1934+ end
1935+ end
1936+ return "void"
1937+ end
1938+ if @nd_type[nid] == "IfNode"
1939+ r1 = ""
1940+ body = @nd_body[nid]
1941+ if body >= 0
1942+ stmts = get_stmts(body)
1943+ r1 = scan_return_type_list(stmts)
1944+ end
1945+ sub = @nd_subsequent[nid]
1946+ if sub >= 0
1947+ r2 = scan_return_type(sub)
1948+ if r2 != ""
1949+ r1 = r2
1950+ end
1951+ end
1952+ return r1
1953+ end
1954+ if @nd_type[nid] == "ElseNode"
1955+ body = @nd_body[nid]
1956+ if body >= 0
1957+ stmts = get_stmts(body)
1958+ return scan_return_type_list(stmts)
1959+ end
1960+ end
1961+ if @nd_type[nid] == "WhileNode"
1962+ body = @nd_body[nid]
1963+ if body >= 0
1964+ stmts = get_stmts(body)
1965+ return scan_return_type_list(stmts)
1966+ end
1967+ end
1968+ ""
1969+ end
1970+
1971+ # ---- Feature detection ----
1972+ def detect_features
1973+ scan_features(@root_id)
1974+ end
1975+
1976+ def scan_features(nid)
1977+ if nid < 0
1978+ return
1979+ end
1980+ t = @nd_type[nid]
1981+ if t == "ArrayNode"
1982+ et = infer_array_elem_type(nid)
1983+ if et == "str_array"
1984+ @needs_str_array = 1
1985+ else
1986+ @needs_int_array = 1
1987+ end
1988+ @needs_gc = 1
1989+ end
1990+ if t == "HashNode"
1991+ ht = infer_hash_val_type(nid)
1992+ if ht == "str_str_hash"
1993+ @needs_str_str_hash = 1
1994+ else
1995+ @needs_str_int_hash = 1
1996+ end
1997+ @needs_gc = 1
1998+ @needs_str_array = 1
1999+ end
2000+ if t == "InterpolatedStringNode"
2001+ @needs_string_helpers = 1
2002+ end
2003+ if t == "SymbolNode"
2004+ @needs_string_helpers = 1
2005+ end
2006+ if t == "CallNode"
2007+ mname = @nd_name[nid]
2008+ if mname == "to_s"
2009+ @needs_string_helpers = 1
2010+ end
2011+ if mname == "+"
2012+ if @nd_receiver[nid] >= 0
2013+ rt = infer_type(@nd_receiver[nid])
2014+ if rt == "string"
2015+ @needs_string_helpers = 1
2016+ end
2017+ end
2018+ end
2019+ if mname == "upcase"
2020+ @needs_string_helpers = 1
2021+ end
2022+ if mname == "downcase"
2023+ @needs_string_helpers = 1
2024+ end
2025+ if mname == "strip"
2026+ @needs_string_helpers = 1
2027+ end
2028+ if mname == "chomp"
2029+ @needs_string_helpers = 1
2030+ end
2031+ if mname == "include?"
2032+ @needs_string_helpers = 1
2033+ end
2034+ if mname == "start_with?"
2035+ @needs_string_helpers = 1
2036+ end
2037+ if mname == "end_with?"
2038+ @needs_string_helpers = 1
2039+ end
2040+ if mname == "split"
2041+ @needs_string_helpers = 1
2042+ @needs_str_array = 1
2043+ @needs_gc = 1
2044+ end
2045+ if mname == "gsub"
2046+ @needs_string_helpers = 1
2047+ end
2048+ if mname == "index"
2049+ @needs_string_helpers = 1
2050+ end
2051+ if mname == "new"
2052+ if @nd_receiver[nid] >= 0
2053+ if @nd_type[@nd_receiver[nid]] == "ConstantReadNode"
2054+ @needs_gc = 1
2055+ end
2056+ end
2057+ end
2058+ if mname == "to_a"
2059+ if @nd_receiver[nid] >= 0
2060+ if @nd_type[@nd_receiver[nid]] == "RangeNode"
2061+ @needs_int_array = 1
2062+ @needs_gc = 1
2063+ end
2064+ end
2065+ end
2066+ if mname == "sort"
2067+ @needs_int_array = 1
2068+ @needs_gc = 1
2069+ end
2070+ if mname == "reduce"
2071+ @needs_int_array = 1
2072+ @needs_gc = 1
2073+ end
2074+ if mname == "inject"
2075+ @needs_int_array = 1
2076+ @needs_gc = 1
2077+ end
2078+ if mname == "reject"
2079+ @needs_int_array = 1
2080+ @needs_gc = 1
2081+ end
2082+ if mname == "keys"
2083+ @needs_str_array = 1
2084+ @needs_gc = 1
2085+ end
2086+ if mname == "each"
2087+ if @nd_receiver[nid] >= 0
2088+ rt = infer_type(@nd_receiver[nid])
2089+ if rt == "str_int_hash"
2090+ @needs_str_int_hash = 1
2091+ end
2092+ if rt == "str_str_hash"
2093+ @needs_str_str_hash = 1
2094+ end
2095+ end
2096+ end
2097+ end
2098+ # Recurse
2099+ scan_features_children(nid)
2100+ end
2101+
2102+ def scan_features_children(nid)
2103+ if @nd_body[nid] >= 0
2104+ scan_features(@nd_body[nid])
2105+ end
2106+ stmts = parse_id_list(@nd_stmts[nid])
2107+ k = 0
2108+ while k < stmts.length
2109+ scan_features(stmts[k])
2110+ k = k + 1
2111+ end
2112+ if @nd_expression[nid] >= 0
2113+ scan_features(@nd_expression[nid])
2114+ end
2115+ if @nd_predicate[nid] >= 0
2116+ scan_features(@nd_predicate[nid])
2117+ end
2118+ if @nd_subsequent[nid] >= 0
2119+ scan_features(@nd_subsequent[nid])
2120+ end
2121+ if @nd_else_clause[nid] >= 0
2122+ scan_features(@nd_else_clause[nid])
2123+ end
2124+ if @nd_receiver[nid] >= 0
2125+ scan_features(@nd_receiver[nid])
2126+ end
2127+ if @nd_arguments[nid] >= 0
2128+ scan_features(@nd_arguments[nid])
2129+ end
2130+ args = parse_id_list(@nd_args[nid])
2131+ k = 0
2132+ while k < args.length
2133+ scan_features(args[k])
2134+ k = k + 1
2135+ end
2136+ conds = parse_id_list(@nd_conditions[nid])
2137+ k = 0
2138+ while k < conds.length
2139+ scan_features(conds[k])
2140+ k = k + 1
2141+ end
2142+ elems = parse_id_list(@nd_elements[nid])
2143+ k = 0
2144+ while k < elems.length
2145+ scan_features(elems[k])
2146+ k = k + 1
2147+ end
2148+ parts = parse_id_list(@nd_parts[nid])
2149+ k = 0
2150+ while k < parts.length
2151+ scan_features(parts[k])
2152+ k = k + 1
2153+ end
2154+ if @nd_left[nid] >= 0
2155+ scan_features(@nd_left[nid])
2156+ end
2157+ if @nd_right[nid] >= 0
2158+ scan_features(@nd_right[nid])
2159+ end
2160+ if @nd_block[nid] >= 0
2161+ scan_features(@nd_block[nid])
2162+ end
2163+ if @nd_key[nid] >= 0
2164+ scan_features(@nd_key[nid])
2165+ end
2166+ if @nd_collection[nid] >= 0
2167+ scan_features(@nd_collection[nid])
2168+ end
2169+ if @nd_target[nid] >= 0
2170+ scan_features(@nd_target[nid])
2171+ end
2172+ if @nd_parameters[nid] >= 0
2173+ scan_features(@nd_parameters[nid])
2174+ end
2175+ reqs = parse_id_list(@nd_requireds[nid])
2176+ k = 0
2177+ while k < reqs.length
2178+ scan_features(reqs[k])
2179+ k = k + 1
2180+ end
2181+ opts = parse_id_list(@nd_optionals[nid])
2182+ k = 0
2183+ while k < opts.length
2184+ scan_features(opts[k])
2185+ k = k + 1
2186+ end
2187+ end
2188+
2189+ # ---- Code generation ----
2190+ def compile
2191+ collect_all
2192+ detect_features
2193+ generate_code
2194+ end
2195+
2196+ def generate_code
2197+ stmts = get_body_stmts(@root_id)
2198+
2199+ emit_header
2200+ if @needs_gc == 1
2201+ emit_gc_runtime
2202+ end
2203+ if @needs_int_array == 1
2204+ emit_int_array_runtime
2205+ end
2206+ if @needs_str_array == 1
2207+ emit_str_array_runtime
2208+ end
2209+ if @needs_str_int_hash == 1
2210+ emit_str_int_hash_runtime
2211+ end
2212+ if @needs_str_str_hash == 1
2213+ emit_str_str_hash_runtime
2214+ end
2215+ if @needs_string_helpers == 1
2216+ # String helpers need StrArray (for split) and GC
2217+ if @needs_gc == 0
2218+ @needs_gc = 1
2219+ emit_gc_runtime
2220+ end
2221+ if @needs_str_array == 0
2222+ @needs_str_array = 1
2223+ emit_str_array_runtime
2224+ end
2225+ emit_string_helpers
2226+ end
2227+ emit_class_structs
2228+ emit_forward_decls
2229+ emit_class_methods
2230+ emit_toplevel_methods
2231+ emit_main(stmts)
2232+ end
2233+
2234+ def emit_header
2235+ emit_raw("/* Generated by Spinel v2 AOT compiler */")
2236+ emit_raw("#include <stdio.h>")
2237+ emit_raw("#include <stdlib.h>")
2238+ emit_raw("#include <string.h>")
2239+ emit_raw("#include <math.h>")
2240+ emit_raw("#include <stdbool.h>")
2241+ emit_raw("#include <stdint.h>")
2242+ emit_raw("#include <ctype.h>")
2243+ emit_raw("#include <stdarg.h>")
2244+ emit_raw("")
2245+ emit_raw("typedef int64_t mrb_int;")
2246+ emit_raw("typedef double mrb_float;")
2247+ emit_raw("typedef bool mrb_bool;")
2248+ emit_raw("#ifndef TRUE")
2249+ emit_raw("#define TRUE true")
2250+ emit_raw("#endif")
2251+ emit_raw("#ifndef FALSE")
2252+ emit_raw("#define FALSE false")
2253+ emit_raw("#endif")
2254+ emit_raw("")
2255+ emit_raw("static inline mrb_int sp_idiv(mrb_int a, mrb_int b) {")
2256+ emit_raw(" mrb_int q = a / b; mrb_int r = a % b;")
2257+ emit_raw(" if ((r != 0) && ((r ^ b) < 0)) q--;")
2258+ emit_raw(" return q;")
2259+ emit_raw("}")
2260+ emit_raw("static inline mrb_int sp_imod(mrb_int a, mrb_int b) {")
2261+ emit_raw(" mrb_int r = a % b;")
2262+ emit_raw(" if ((r != 0) && ((r ^ b) < 0)) r += b;")
2263+ emit_raw(" return r;")
2264+ emit_raw("}")
2265+ emit_raw("")
2266+ emit_raw("static int sp_last_status = 0;")
2267+ emit_raw("")
2268+ end
2269+
2270+ def emit_gc_runtime
2271+ emit_raw("typedef struct sp_gc_hdr { struct sp_gc_hdr *next; void (*finalize)(void *); void (*scan)(void *); unsigned marked : 1; } sp_gc_hdr;")
2272+ emit_raw("static sp_gc_hdr *sp_gc_heap = NULL; static size_t sp_gc_bytes = 0; static size_t sp_gc_threshold = 256*1024;")
2273+ emit_raw("#define SP_GC_STACK_MAX 8192")
2274+ emit_raw("static void **sp_gc_roots[SP_GC_STACK_MAX]; static int sp_gc_nroots = 0;")
2275+ emit_raw("#define SP_GC_SAVE() int _gc_saved = sp_gc_nroots")
2276+ emit_raw("#define SP_GC_ROOT(v) do{if(sp_gc_nroots<SP_GC_STACK_MAX)sp_gc_roots[sp_gc_nroots++]=(void**)&(v);}while(0)")
2277+ emit_raw("#define SP_GC_RESTORE() sp_gc_nroots = _gc_saved")
2278+ emit_raw("static void sp_gc_mark(void*obj){if(!obj)return;sp_gc_hdr*h=(sp_gc_hdr*)((char*)obj-sizeof(sp_gc_hdr));if(h->marked)return;h->marked=1;if(h->scan)h->scan(obj);}")
2279+ emit_raw("static void sp_gc_collect(void){for(int i=0;i<sp_gc_nroots;i++){void*obj=*sp_gc_roots[i];if(obj)sp_gc_mark(obj);}sp_gc_hdr**pp=&sp_gc_heap;sp_gc_bytes=0;while(*pp){sp_gc_hdr*h=*pp;if(!h->marked){*pp=h->next;if(h->finalize)h->finalize((char*)h+sizeof(sp_gc_hdr));free(h);}else{h->marked=0;sp_gc_bytes+=sizeof(sp_gc_hdr);pp=&h->next;}}}")
2280+ emit_raw("static void*sp_gc_alloc(size_t sz,void(*fin)(void*),void(*scn)(void*)){if(sp_gc_bytes>sp_gc_threshold){sp_gc_collect();if(sp_gc_bytes>sp_gc_threshold/2)sp_gc_threshold*=2;}sp_gc_hdr*h=(sp_gc_hdr*)calloc(1,sizeof(sp_gc_hdr)+sz);h->finalize=fin;h->scan=scn;h->next=sp_gc_heap;sp_gc_heap=h;sp_gc_bytes+=sizeof(sp_gc_hdr)+sz;return(char*)h+sizeof(sp_gc_hdr);}")
2281+ emit_raw("")
2282+ end
2283+
2284+ def emit_int_array_runtime
2285+ emit_raw("typedef struct{mrb_int*data;mrb_int start;mrb_int len;mrb_int cap;}sp_IntArray;")
2286+ emit_raw("static void sp_IntArray_fin(void*p){free(((sp_IntArray*)p)->data);}")
2287+ emit_raw("static sp_IntArray*sp_IntArray_new(void){sp_IntArray*a=(sp_IntArray*)sp_gc_alloc(sizeof(sp_IntArray),sp_IntArray_fin,NULL);a->cap=16;a->data=(mrb_int*)malloc(sizeof(mrb_int)*a->cap);a->start=0;a->len=0;return a;}")
2288+ emit_raw("static sp_IntArray*sp_IntArray_from_range(mrb_int s,mrb_int e){sp_IntArray*a=sp_IntArray_new();mrb_int n=e-s+1;if(n<0)n=0;if(n>a->cap){a->cap=n;a->data=(mrb_int*)realloc(a->data,sizeof(mrb_int)*a->cap);}for(mrb_int i=0;i<n;i++)a->data[i]=s+i;a->len=n;return a;}")
2289+ emit_raw("static sp_IntArray*sp_IntArray_dup(sp_IntArray*a){sp_IntArray*b=sp_IntArray_new();if(a->len>b->cap){b->cap=a->len;b->data=(mrb_int*)realloc(b->data,sizeof(mrb_int)*b->cap);}memcpy(b->data,a->data+a->start,sizeof(mrb_int)*a->len);b->len=a->len;return b;}")
2290+ emit_raw("static void sp_IntArray_push(sp_IntArray*a,mrb_int v){mrb_int e=a->start+a->len;if(e>=a->cap){if(a->start>0){memmove(a->data,a->data+a->start,sizeof(mrb_int)*a->len);a->start=0;e=a->len;}if(e>=a->cap){a->cap=a->cap*2+1;a->data=(mrb_int*)realloc(a->data,sizeof(mrb_int)*a->cap);}}a->data[e]=v;a->len++;}")
2291+ emit_raw("static mrb_int sp_IntArray_pop(sp_IntArray*a){return a->data[a->start+--a->len];}")
2292+ emit_raw("static mrb_int sp_IntArray_length(sp_IntArray*a){return a->len;}")
2293+ emit_raw("static mrb_bool sp_IntArray_empty(sp_IntArray*a){return a->len==0;}")
2294+ emit_raw("static mrb_int sp_IntArray_get(sp_IntArray*a,mrb_int i){if(i<0)i+=a->len;return a->data[a->start+i];}")
2295+ emit_raw("static void sp_IntArray_set(sp_IntArray*a,mrb_int i,mrb_int v){if(i<0)i+=a->len;while(a->start+i>=a->cap){a->cap=a->cap*2+1;a->data=(mrb_int*)realloc(a->data,sizeof(mrb_int)*a->cap);}while(i>=a->len){a->data[a->start+a->len]=0;a->len++;}a->data[a->start+i]=v;}")
2296+ emit_raw("static void sp_IntArray_reverse_bang(sp_IntArray*a){for(mrb_int i=0,j=a->len-1;i<j;i++,j--){mrb_int t=a->data[a->start+i];a->data[a->start+i]=a->data[a->start+j];a->data[a->start+j]=t;}}")
2297+ emit_raw("static int _sp_int_cmp(const void*a,const void*b){mrb_int va=*(const mrb_int*)a,vb=*(const mrb_int*)b;return(va>vb)-(va<vb);}")
2298+ emit_raw("static sp_IntArray*sp_IntArray_sort(sp_IntArray*a){sp_IntArray*b=sp_IntArray_dup(a);qsort(b->data+b->start,b->len,sizeof(mrb_int),_sp_int_cmp);return b;}")
2299+ emit_raw("static void sp_IntArray_sort_bang(sp_IntArray*a){qsort(a->data+a->start,a->len,sizeof(mrb_int),_sp_int_cmp);}")
2300+ emit_raw("static mrb_int sp_IntArray_min(sp_IntArray*a){mrb_int m=a->data[a->start];for(mrb_int i=1;i<a->len;i++)if(a->data[a->start+i]<m)m=a->data[a->start+i];return m;}")
2301+ emit_raw("static mrb_int sp_IntArray_max(sp_IntArray*a){mrb_int m=a->data[a->start];for(mrb_int i=1;i<a->len;i++)if(a->data[a->start+i]>m)m=a->data[a->start+i];return m;}")
2302+ emit_raw("static mrb_int sp_IntArray_sum(sp_IntArray*a){mrb_int s=0;for(mrb_int i=0;i<a->len;i++)s+=a->data[a->start+i];return s;}")
2303+ emit_raw("static mrb_bool sp_IntArray_include(sp_IntArray*a,mrb_int v){for(mrb_int i=0;i<a->len;i++)if(a->data[a->start+i]==v)return TRUE;return FALSE;}")
2304+ emit_raw("")
2305+ end
2306+
2307+ def emit_str_array_runtime
2308+ emit_raw("typedef struct{const char**data;mrb_int len;mrb_int cap;}sp_StrArray;")
2309+ emit_raw("static void sp_StrArray_fin(void*p){free(((sp_StrArray*)p)->data);}")
2310+ emit_raw("static sp_StrArray*sp_StrArray_new(void){sp_StrArray*a=(sp_StrArray*)sp_gc_alloc(sizeof(sp_StrArray),sp_StrArray_fin,NULL);a->cap=16;a->data=(const char**)malloc(sizeof(const char*)*a->cap);a->len=0;return a;}")
2311+ emit_raw("static void sp_StrArray_push(sp_StrArray*a,const char*v){if(a->len>=a->cap){a->cap=a->cap*2+1;a->data=(const char**)realloc(a->data,sizeof(const char*)*a->cap);}a->data[a->len++]=v;}")
2312+ emit_raw("static const char*sp_StrArray_pop(sp_StrArray*a){return a->data[--a->len];}")
2313+ emit_raw("static mrb_int sp_StrArray_length(sp_StrArray*a){return a->len;}")
2314+ emit_raw("static mrb_bool sp_StrArray_empty(sp_StrArray*a){return a->len==0;}")
2315+ emit_raw("static const char*sp_StrArray_get(sp_StrArray*a,mrb_int i){if(i<0)i+=a->len;return a->data[i];}")
2316+ emit_raw("static void sp_StrArray_set(sp_StrArray*a,mrb_int i,const char*v){if(i<0)i+=a->len;while(i>=a->len)sp_StrArray_push(a,\"\");a->data[i]=v;}")
2317+ emit_raw("")
2318+ end
2319+
2320+ def emit_str_int_hash_runtime
2321+ emit_raw("typedef struct{const char**keys;mrb_int*vals;mrb_int len;mrb_int cap;}sp_StrIntHash;")
2322+ emit_raw("static void sp_StrIntHash_fin(void*p){sp_StrIntHash*h=(sp_StrIntHash*)p;free(h->keys);free(h->vals);}")
2323+ emit_raw("static sp_StrIntHash*sp_StrIntHash_new(void){sp_StrIntHash*h=(sp_StrIntHash*)sp_gc_alloc(sizeof(sp_StrIntHash),sp_StrIntHash_fin,NULL);h->cap=16;h->keys=(const char**)malloc(sizeof(const char*)*h->cap);h->vals=(mrb_int*)malloc(sizeof(mrb_int)*h->cap);h->len=0;return h;}")
2324+ emit_raw("static mrb_int sp_StrIntHash_get(sp_StrIntHash*h,const char*k){for(mrb_int i=0;i<h->len;i++)if(strcmp(h->keys[i],k)==0)return h->vals[i];return 0;}")
2325+ emit_raw("static void sp_StrIntHash_set(sp_StrIntHash*h,const char*k,mrb_int v){for(mrb_int i=0;i<h->len;i++){if(strcmp(h->keys[i],k)==0){h->vals[i]=v;return;}}if(h->len>=h->cap){h->cap*=2;h->keys=(const char**)realloc(h->keys,sizeof(const char*)*h->cap);h->vals=(mrb_int*)realloc(h->vals,sizeof(mrb_int)*h->cap);}h->keys[h->len]=k;h->vals[h->len]=v;h->len++;}")
2326+ emit_raw("static mrb_bool sp_StrIntHash_has_key(sp_StrIntHash*h,const char*k){for(mrb_int i=0;i<h->len;i++)if(strcmp(h->keys[i],k)==0)return TRUE;return FALSE;}")
2327+ emit_raw("static mrb_int sp_StrIntHash_length(sp_StrIntHash*h){return h->len;}")
2328+ emit_raw("static void sp_StrIntHash_delete(sp_StrIntHash*h,const char*k){for(mrb_int i=0;i<h->len;i++){if(strcmp(h->keys[i],k)==0){for(mrb_int j=i;j<h->len-1;j++){h->keys[j]=h->keys[j+1];h->vals[j]=h->vals[j+1];}h->len--;return;}}}")
2329+ emit_raw("static sp_StrArray*sp_StrIntHash_keys(sp_StrIntHash*h){sp_StrArray*a=sp_StrArray_new();for(mrb_int i=0;i<h->len;i++)sp_StrArray_push(a,h->keys[i]);return a;}")
2330+ emit_raw("")
2331+ end
2332+
2333+ def emit_str_str_hash_runtime
2334+ emit_raw("typedef struct{const char**keys;const char**vals;mrb_int len;mrb_int cap;}sp_StrStrHash;")
2335+ emit_raw("static void sp_StrStrHash_fin(void*p){sp_StrStrHash*h=(sp_StrStrHash*)p;free(h->keys);free(h->vals);}")
2336+ emit_raw("static sp_StrStrHash*sp_StrStrHash_new(void){sp_StrStrHash*h=(sp_StrStrHash*)sp_gc_alloc(sizeof(sp_StrStrHash),sp_StrStrHash_fin,NULL);h->cap=16;h->keys=(const char**)malloc(sizeof(const char*)*h->cap);h->vals=(const char**)malloc(sizeof(const char*)*h->cap);h->len=0;return h;}")
2337+ emit_raw("static const char*sp_StrStrHash_get(sp_StrStrHash*h,const char*k){for(mrb_int i=0;i<h->len;i++)if(strcmp(h->keys[i],k)==0)return h->vals[i];return\"\";}")
2338+ emit_raw("static void sp_StrStrHash_set(sp_StrStrHash*h,const char*k,const char*v){for(mrb_int i=0;i<h->len;i++){if(strcmp(h->keys[i],k)==0){h->vals[i]=v;return;}}if(h->len>=h->cap){h->cap*=2;h->keys=(const char**)realloc(h->keys,sizeof(const char*)*h->cap);h->vals=(const char**)realloc(h->vals,sizeof(const char*)*h->cap);}h->keys[h->len]=k;h->vals[h->len]=v;h->len++;}")
2339+ emit_raw("static mrb_bool sp_StrStrHash_has_key(sp_StrStrHash*h,const char*k){for(mrb_int i=0;i<h->len;i++)if(strcmp(h->keys[i],k)==0)return TRUE;return FALSE;}")
2340+ emit_raw("static mrb_int sp_StrStrHash_length(sp_StrStrHash*h){return h->len;}")
2341+ emit_raw("static void sp_StrStrHash_delete(sp_StrStrHash*h,const char*k){for(mrb_int i=0;i<h->len;i++){if(strcmp(h->keys[i],k)==0){for(mrb_int j=i;j<h->len-1;j++){h->keys[j]=h->keys[j+1];h->vals[j]=h->vals[j+1];}h->len--;return;}}}")
2342+ emit_raw("static sp_StrArray*sp_StrStrHash_keys(sp_StrStrHash*h){sp_StrArray*a=sp_StrArray_new();for(mrb_int i=0;i<h->len;i++)sp_StrArray_push(a,h->keys[i]);return a;}")
2343+ emit_raw("")
2344+ end
2345+
2346+ def emit_string_helpers
2347+ emit_raw("static const char*sp_str_concat(const char*a,const char*b){size_t la=strlen(a),lb=strlen(b);char*r=(char*)malloc(la+lb+1);memcpy(r,a,la);memcpy(r+la,b,lb+1);return r;}")
2348+ emit_raw("static const char*sp_int_to_s(mrb_int n){char*b=(char*)malloc(32);snprintf(b,32,\"%lld\",(long long)n);return b;}")
2349+ emit_raw("static const char*sp_float_to_s(mrb_float f){char*b=(char*)malloc(64);snprintf(b,64,\"%g\",f);return b;}")
2350+ emit_raw("static const char*sp_str_upcase(const char*s){size_t l=strlen(s);char*r=(char*)malloc(l+1);for(size_t i=0;i<=l;i++)r[i]=toupper((unsigned char)s[i]);return r;}")
2351+ emit_raw("static const char*sp_str_downcase(const char*s){size_t l=strlen(s);char*r=(char*)malloc(l+1);for(size_t i=0;i<=l;i++)r[i]=tolower((unsigned char)s[i]);return r;}")
2352+ emit_raw("static const char*sp_str_strip(const char*s){while(*s&&isspace((unsigned char)*s))s++;size_t l=strlen(s);while(l>0&&isspace((unsigned char)s[l-1]))l--;char*r=(char*)malloc(l+1);memcpy(r,s,l);r[l]=0;return r;}")
2353+ emit_raw("static const char*sp_str_chomp(const char*s){size_t l=strlen(s);while(l>0&&(s[l-1]=='\\n'||s[l-1]=='\\r'))l--;char*r=(char*)malloc(l+1);memcpy(r,s,l);r[l]=0;return r;}")
2354+ emit_raw("static mrb_bool sp_str_include(const char*s,const char*sub){return strstr(s,sub)!=NULL;}")
2355+ emit_raw("static mrb_bool sp_str_start_with(const char*s,const char*p){return strncmp(s,p,strlen(p))==0;}")
2356+ emit_raw("static mrb_bool sp_str_end_with(const char*s,const char*suf){size_t ls=strlen(s),lsuf=strlen(suf);if(lsuf>ls)return FALSE;return strcmp(s+ls-lsuf,suf)==0;}")
2357+ emit_raw("static sp_StrArray*sp_str_split(const char*s,const char*sep){sp_StrArray*a=sp_StrArray_new();size_t sl=strlen(sep);if(sl==0){for(size_t i=0;s[i];i++){char*c=(char*)malloc(2);c[0]=s[i];c[1]=0;sp_StrArray_push(a,c);}return a;}const char*p=s;while(1){const char*f=strstr(p,sep);if(!f){char*r=(char*)malloc(strlen(p)+1);strcpy(r,p);sp_StrArray_push(a,r);break;}size_t n=f-p;char*r=(char*)malloc(n+1);memcpy(r,p,n);r[n]=0;sp_StrArray_push(a,r);p=f+sl;}return a;}")
2358+ emit_raw("static const char*sp_str_gsub(const char*s,const char*pat,const char*rep){size_t pl=strlen(pat),rl=strlen(rep),sl=strlen(s);if(pl==0)return s;size_t cap=sl*2+1;char*out=(char*)malloc(cap);size_t ol=0;const char*p=s;while(*p){const char*f=strstr(p,pat);if(!f){size_t n=strlen(p);if(ol+n>=cap){cap=(ol+n)*2+1;out=(char*)realloc(out,cap);}memcpy(out+ol,p,n);ol+=n;break;}size_t n=f-p;if(ol+n+rl>=cap){cap=(ol+n+rl)*2+1;out=(char*)realloc(out,cap);}memcpy(out+ol,p,n);ol+=n;memcpy(out+ol,rep,rl);ol+=rl;p=f+pl;}out[ol]=0;return out;}")
2359+ emit_raw("static mrb_int sp_str_index(const char*s,const char*sub){const char*f=strstr(s,sub);if(!f)return -1;return(mrb_int)(f-s);}")
2360+ emit_raw("static const char*sp_str_sub_range(const char*s,mrb_int start,mrb_int len){mrb_int sl=(mrb_int)strlen(s);if(start<0)start+=sl;if(start<0)start=0;if(start>=sl)return\"\";if(len<0)len=0;if(start+len>sl)len=sl-start;char*r=(char*)malloc(len+1);memcpy(r,s+start,len);r[len]=0;return r;}")
2361+ emit_raw("static const char*sp_sprintf(const char*fmt,...){char*b=(char*)malloc(4096);va_list ap;va_start(ap,fmt);vsnprintf(b,4096,fmt,ap);va_end(ap);return b;}")
2362+ emit_raw("")
2363+ end
2364+
2365+ # ---- Struct emission ----
2366+ def emit_class_structs
2367+ # Forward declare typedefs
2368+ i = 0
2369+ while i < @cls_names.length
2370+ emit_raw("typedef struct sp_" + @cls_names[i] + "_s sp_" + @cls_names[i] + ";")
2371+ i = i + 1
2372+ end
2373+ if @cls_names.length > 0
2374+ emit_raw("")
2375+ end
2376+ # Struct definitions
2377+ i = 0
2378+ while i < @cls_names.length
2379+ emit_raw("struct sp_" + @cls_names[i] + "_s {")
2380+ emit_class_fields(i)
2381+ emit_raw("};")
2382+ emit_raw("")
2383+ i = i + 1
2384+ end
2385+ end
2386+
2387+ def emit_class_fields(ci)
2388+ # Parent fields first
2389+ if @cls_parents[ci] != ""
2390+ pi = find_class_idx(@cls_parents[ci])
2391+ if pi >= 0
2392+ emit_parent_fields(pi)
2393+ end
2394+ end
2395+ # Own fields (skip those inherited from parent)
2396+ names = @cls_ivar_names[ci].split(";")
2397+ types = @cls_ivar_types[ci].split(";")
2398+ j = 0
2399+ while j < names.length
2400+ iname = names[j]
2401+ itype = "int"
2402+ if j < types.length
2403+ itype = types[j]
2404+ end
2405+ # Skip if in parent chain
2406+ if @cls_parents[ci] != ""
2407+ pi = find_class_idx(@cls_parents[ci])
2408+ if pi >= 0
2409+ if ivar_in_chain(pi, iname) == 1
2410+ j = j + 1
2411+ next
2412+ end
2413+ end
2414+ end
2415+ fname = sanitize_ivar(iname)
2416+ emit_raw(" " + c_type(itype) + " " + fname + ";")
2417+ j = j + 1
2418+ end
2419+ end
2420+
2421+ def emit_parent_fields(ci)
2422+ if @cls_parents[ci] != ""
2423+ pi = find_class_idx(@cls_parents[ci])
2424+ if pi >= 0
2425+ emit_parent_fields(pi)
2426+ end
2427+ end
2428+ names = @cls_ivar_names[ci].split(";")
2429+ types = @cls_ivar_types[ci].split(";")
2430+ j = 0
2431+ while j < names.length
2432+ iname = names[j]
2433+ itype = "int"
2434+ if j < types.length
2435+ itype = types[j]
2436+ end
2437+ if @cls_parents[ci] != ""
2438+ pi = find_class_idx(@cls_parents[ci])
2439+ if pi >= 0
2440+ if ivar_in_chain(pi, iname) == 1
2441+ j = j + 1
2442+ next
2443+ end
2444+ end
2445+ end
2446+ fname = sanitize_ivar(iname)
2447+ emit_raw(" " + c_type(itype) + " " + fname + ";")
2448+ j = j + 1
2449+ end
2450+ end
2451+
2452+ def ivar_in_chain(ci, iname)
2453+ names = @cls_ivar_names[ci].split(";")
2454+ k = 0
2455+ while k < names.length
2456+ if names[k] == iname
2457+ return 1
2458+ end
2459+ k = k + 1
2460+ end
2461+ if @cls_parents[ci] != ""
2462+ pi = find_class_idx(@cls_parents[ci])
2463+ if pi >= 0
2464+ return ivar_in_chain(pi, iname)
2465+ end
2466+ end
2467+ 0
2468+ end
2469+
2470+ # ---- Forward declarations ----
2471+ def emit_forward_decls
2472+ # Top-level methods
2473+ i = 0
2474+ while i < @meth_names.length
2475+ emit_raw("static " + c_type(@meth_return_types[i]) + " sp_" + sanitize_name(@meth_names[i]) + "(" + method_params_decl(i) + ");")
2476+ i = i + 1
2477+ end
2478+ # Class methods
2479+ i = 0
2480+ while i < @cls_names.length
2481+ cname = @cls_names[i]
2482+ # Constructor
2483+ init_idx = cls_find_method_direct(i, "initialize")
2484+ emit_raw("static sp_" + cname + " *sp_" + cname + "_new(" + constructor_params_decl(i) + ");")
2485+ if init_idx >= 0
2486+ emit_raw("static void sp_" + cname + "_initialize(sp_" + cname + " *self" + init_params_decl(i) + ");")
2487+ end
2488+ # Instance methods
2489+ mnames = @cls_meth_names[i].split(";")
2490+ returns = @cls_meth_returns[i].split(";")
2491+ all_params = @cls_meth_params[i].split("|")
2492+ all_ptypes = @cls_meth_ptypes[i].split("|")
2493+ j = 0
2494+ while j < mnames.length
2495+ if mnames[j] != "initialize"
2496+ rt = "int"
2497+ if j < returns.length
2498+ rt = returns[j]
2499+ end
2500+ emit_raw("static " + c_type(rt) + " sp_" + cname + "_" + sanitize_name(mnames[j]) + "(sp_" + cname + " *self" + method_with_self_params(j, all_params, all_ptypes) + ");")
2501+ end
2502+ j = j + 1
2503+ end
2504+ # Class methods
2505+ cmnames = @cls_cmeth_names[i].split(";")
2506+ cm_returns = @cls_cmeth_returns[i].split(";")
2507+ cm_params = @cls_cmeth_params[i].split("|")
2508+ cm_ptypes = @cls_cmeth_ptypes[i].split("|")
2509+ j = 0
2510+ while j < cmnames.length
2511+ rt = "int"
2512+ if j < cm_returns.length
2513+ rt = cm_returns[j]
2514+ end
2515+ emit_raw("static " + c_type(rt) + " sp_" + cname + "_cls_" + sanitize_name(cmnames[j]) + "(" + cls_method_params_decl(j, cm_params, cm_ptypes) + ");")
2516+ j = j + 1
2517+ end
2518+ i = i + 1
2519+ end
2520+ emit_raw("")
2521+ end
2522+
2523+ def cls_find_method_direct(ci, mname)
2524+ mnames = @cls_meth_names[ci].split(";")
2525+ j = 0
2526+ while j < mnames.length
2527+ if mnames[j] == mname
2528+ return j
2529+ end
2530+ j = j + 1
2531+ end
2532+ -1
2533+ end
2534+
2535+ def method_params_decl(mi)
2536+ pnames = @meth_param_names[mi].split(",")
2537+ ptypes = @meth_param_types[mi].split(",")
2538+ if pnames.length == 0
2539+ return "void"
2540+ end
2541+ result = ""
2542+ j = 0
2543+ while j < pnames.length
2544+ if j > 0
2545+ result = result + ", "
2546+ end
2547+ pt = "int"
2548+ if j < ptypes.length
2549+ pt = ptypes[j]
2550+ end
2551+ result = result + c_type(pt) + " lv_" + pnames[j]
2552+ j = j + 1
2553+ end
2554+ result
2555+ end
2556+
2557+ def find_init_class(ci)
2558+ # Find which class in the chain has initialize
2559+ init_idx = cls_find_method_direct(ci, "initialize")
2560+ if init_idx >= 0
2561+ return ci
2562+ end
2563+ if @cls_parents[ci] != ""
2564+ pi = find_class_idx(@cls_parents[ci])
2565+ if pi >= 0
2566+ return find_init_class(pi)
2567+ end
2568+ end
2569+ -1
2570+ end
2571+
2572+ def constructor_params_decl(ci)
2573+ init_ci = find_init_class(ci)
2574+ if init_ci < 0
2575+ return "void"
2576+ end
2577+ init_idx = cls_find_method_direct(init_ci, "initialize")
2578+ all_params = @cls_meth_params[init_ci].split("|")
2579+ all_ptypes = @cls_meth_ptypes[init_ci].split("|")
2580+ pnames = []
2581+ ptypes = []
2582+ if init_idx < all_params.length
2583+ pnames = all_params[init_idx].split(",")
2584+ end
2585+ if init_idx < all_ptypes.length
2586+ ptypes = all_ptypes[init_idx].split(",")
2587+ end
2588+ if pnames.length == 0
2589+ return "void"
2590+ end
2591+ result = ""
2592+ j = 0
2593+ while j < pnames.length
2594+ if j > 0
2595+ result = result + ", "
2596+ end
2597+ pt = "int"
2598+ if j < ptypes.length
2599+ pt = ptypes[j]
2600+ end
2601+ result = result + c_type(pt) + " lv_" + pnames[j]
2602+ j = j + 1
2603+ end
2604+ result
2605+ end
2606+
2607+ def init_params_decl(ci)
2608+ init_ci = find_init_class(ci)
2609+ if init_ci < 0
2610+ return ""
2611+ end
2612+ init_idx = cls_find_method_direct(init_ci, "initialize")
2613+ if init_idx < 0
2614+ return ""
2615+ end
2616+ all_params = @cls_meth_params[init_ci].split("|")
2617+ all_ptypes = @cls_meth_ptypes[init_ci].split("|")
2618+ pnames = []
2619+ ptypes = []
2620+ if init_idx < all_params.length
2621+ pnames = all_params[init_idx].split(",")
2622+ end
2623+ if init_idx < all_ptypes.length
2624+ ptypes = all_ptypes[init_idx].split(",")
2625+ end
2626+ result = ""
2627+ j = 0
2628+ while j < pnames.length
2629+ pt = "int"
2630+ if j < ptypes.length
2631+ pt = ptypes[j]
2632+ end
2633+ result = result + ", " + c_type(pt) + " lv_" + pnames[j]
2634+ j = j + 1
2635+ end
2636+ result
2637+ end
2638+
2639+ def method_with_self_params(midx, all_params, all_ptypes)
2640+ pnames = []
2641+ ptypes = []
2642+ if midx < all_params.length
2643+ pnames = all_params[midx].split(",")
2644+ end
2645+ if midx < all_ptypes.length
2646+ ptypes = all_ptypes[midx].split(",")
2647+ end
2648+ result = ""
2649+ j = 0
2650+ while j < pnames.length
2651+ pt = "int"
2652+ if j < ptypes.length
2653+ pt = ptypes[j]
2654+ end
2655+ result = result + ", " + c_type(pt) + " lv_" + pnames[j]
2656+ j = j + 1
2657+ end
2658+ result
2659+ end
2660+
2661+ def cls_method_params_decl(midx, all_params, all_ptypes)
2662+ pnames = []
2663+ ptypes = []
2664+ if midx < all_params.length
2665+ pnames = all_params[midx].split(",")
2666+ end
2667+ if midx < all_ptypes.length
2668+ ptypes = all_ptypes[midx].split(",")
2669+ end
2670+ if pnames.length == 0
2671+ return "void"
2672+ end
2673+ result = ""
2674+ j = 0
2675+ while j < pnames.length
2676+ if j > 0
2677+ result = result + ", "
2678+ end
2679+ pt = "int"
2680+ if j < ptypes.length
2681+ pt = ptypes[j]
2682+ end
2683+ result = result + c_type(pt) + " lv_" + pnames[j]
2684+ j = j + 1
2685+ end
2686+ result
2687+ end
2688+
2689+ # ---- Emit class methods ----
2690+ def emit_class_methods
2691+ i = 0
2692+ while i < @cls_names.length
2693+ emit_constructor(i)
2694+ mnames = @cls_meth_names[i].split(";")
2695+ returns = @cls_meth_returns[i].split(";")
2696+ all_params = @cls_meth_params[i].split("|")
2697+ all_ptypes = @cls_meth_ptypes[i].split("|")
2698+ bodies = @cls_meth_bodies[i].split(";")
2699+ j = 0
2700+ while j < mnames.length
2701+ if mnames[j] != "initialize"
2702+ rt = "int"
2703+ if j < returns.length
2704+ rt = returns[j]
2705+ end
2706+ bid = -1
2707+ if j < bodies.length
2708+ bid = bodies[j].to_i
2709+ end
2710+ pnames = []
2711+ ptypes = []
2712+ if j < all_params.length
2713+ pnames = all_params[j].split(",")
2714+ end
2715+ if j < all_ptypes.length
2716+ ptypes = all_ptypes[j].split(",")
2717+ end
2718+ emit_instance_method(i, mnames[j], pnames, ptypes, rt, bid)
2719+ end
2720+ j = j + 1
2721+ end
2722+ # Class methods
2723+ cmnames = @cls_cmeth_names[i].split(";")
2724+ cm_returns = @cls_cmeth_returns[i].split(";")
2725+ cm_params = @cls_cmeth_params[i].split("|")
2726+ cm_ptypes = @cls_cmeth_ptypes[i].split("|")
2727+ cm_bodies = @cls_cmeth_bodies[i].split(";")
2728+ j = 0
2729+ while j < cmnames.length
2730+ rt = "int"
2731+ if j < cm_returns.length
2732+ rt = cm_returns[j]
2733+ end
2734+ bid = -1
2735+ if j < cm_bodies.length
2736+ bid = cm_bodies[j].to_i
2737+ end
2738+ pnames = []
2739+ ptypes = []
2740+ if j < cm_params.length
2741+ pnames = cm_params[j].split(",")
2742+ end
2743+ if j < cm_ptypes.length
2744+ ptypes = cm_ptypes[j].split(",")
2745+ end
2746+ emit_class_level_method(i, cmnames[j], pnames, ptypes, rt, bid)
2747+ j = j + 1
2748+ end
2749+ i = i + 1
2750+ end
2751+ end
2752+
2753+ def emit_constructor(ci)
2754+ cname = @cls_names[ci]
2755+ init_idx = cls_find_method_direct(ci, "initialize")
2756+ emit_raw("static sp_" + cname + " *sp_" + cname + "_new(" + constructor_params_decl(ci) + ") {")
2757+ emit_raw(" SP_GC_SAVE();")
2758+ emit_raw(" sp_" + cname + " *self = (sp_" + cname + " *)sp_gc_alloc(sizeof(sp_" + cname + "), NULL, NULL);")
2759+ emit_raw(" SP_GC_ROOT(self);")
2760+
2761+ init_ci = find_init_class(ci)
2762+ actual_init_idx = -1
2763+ if init_ci >= 0
2764+ actual_init_idx = cls_find_method_direct(init_ci, "initialize")
2765+ end
2766+
2767+ if init_idx >= 0
2768+ bodies = @cls_meth_bodies[ci].split(";")
2769+ bid = -1
2770+ if init_idx < bodies.length
2771+ bid = bodies[init_idx].to_i
2772+ end
2773+ if bid >= 0
2774+ @current_class_idx = ci
2775+ all_params = @cls_meth_params[ci].split("|")
2776+ all_ptypes = @cls_meth_ptypes[ci].split("|")
2777+ pnames = []
2778+ ptypes = []
2779+ if init_idx < all_params.length
2780+ pnames = all_params[init_idx].split(",")
2781+ end
2782+ if init_idx < all_ptypes.length
2783+ ptypes = all_ptypes[init_idx].split(",")
2784+ end
2785+ push_scope
2786+ k = 0
2787+ while k < pnames.length
2788+ pt = "int"
2789+ if k < ptypes.length
2790+ pt = ptypes[k]
2791+ end
2792+ declare_var(pnames[k], pt)
2793+ k = k + 1
2794+ end
2795+ stmts = get_stmts(bid)
2796+ k = 0
2797+ while k < stmts.length
2798+ sid = stmts[k]
2799+ if @nd_type[sid] == "SuperNode"
2800+ # Call parent initialize
2801+ if @cls_parents[ci] != ""
2802+ pi = find_class_idx(@cls_parents[ci])
2803+ if pi >= 0
2804+ super_args = ""
2805+ args_id = @nd_arguments[sid]
2806+ if args_id >= 0
2807+ arg_ids = get_args(args_id)
2808+ ak = 0
2809+ while ak < arg_ids.length
2810+ if ak > 0
2811+ super_args = super_args + ", "
2812+ end
2813+ super_args = super_args + compile_expr(arg_ids[ak])
2814+ ak = ak + 1
2815+ end
2816+ end
2817+ emit_raw(" sp_" + @cls_parents[ci] + "_initialize((sp_" + @cls_parents[ci] + " *)self" + (super_args != "" ? ", " + super_args : "") + ");")
2818+ end
2819+ end
2820+ end
2821+ if @nd_type[sid] == "InstanceVariableWriteNode"
2822+ ivar = sanitize_ivar(@nd_name[sid])
2823+ val = compile_expr(@nd_expression[sid])
2824+ emit_raw(" self->" + ivar + " = " + val + ";")
2825+ end
2826+ k = k + 1
2827+ end
2828+ pop_scope
2829+ @current_class_idx = -1
2830+ end
2831+ else
2832+ # No own initialize - call parent's if it exists
2833+ if init_ci >= 0
2834+ if init_ci != ci
2835+ parent_name = @cls_names[init_ci]
2836+ # Build param forwarding: forward all constructor params to parent init
2837+ pi_params = @cls_meth_params[init_ci].split("|")
2838+ pi_idx = cls_find_method_direct(init_ci, "initialize")
2839+ pnames = []
2840+ if pi_idx >= 0
2841+ if pi_idx < pi_params.length
2842+ pnames = pi_params[pi_idx].split(",")
2843+ end
2844+ end
2845+ fwd = ""
2846+ pk = 0
2847+ while pk < pnames.length
2848+ if pk > 0
2849+ fwd = fwd + ", "
2850+ end
2851+ fwd = fwd + "lv_" + pnames[pk]
2852+ pk = pk + 1
2853+ end
2854+ emit_raw(" sp_" + parent_name + "_initialize((sp_" + parent_name + " *)self" + (fwd != "" ? ", " + fwd : "") + ");")
2855+ end
2856+ end
2857+ end
2858+
2859+ emit_raw(" SP_GC_RESTORE();")
2860+ emit_raw(" return self;")
2861+ emit_raw("}")
2862+ emit_raw("")
2863+
2864+ # Initialize function (for super calls)
2865+ if init_idx >= 0
2866+ emit_raw("static void sp_" + cname + "_initialize(sp_" + cname + " *self" + init_params_decl(ci) + ") {")
2867+ bodies = @cls_meth_bodies[ci].split(";")
2868+ bid = -1
2869+ if init_idx < bodies.length
2870+ bid = bodies[init_idx].to_i
2871+ end
2872+ if bid >= 0
2873+ @current_class_idx = ci
2874+ all_params = @cls_meth_params[ci].split("|")
2875+ all_ptypes = @cls_meth_ptypes[ci].split("|")
2876+ pnames = []
2877+ ptypes = []
2878+ if init_idx < all_params.length
2879+ pnames = all_params[init_idx].split(",")
2880+ end
2881+ if init_idx < all_ptypes.length
2882+ ptypes = all_ptypes[init_idx].split(",")
2883+ end
2884+ push_scope
2885+ k = 0
2886+ while k < pnames.length
2887+ pt = "int"
2888+ if k < ptypes.length
2889+ pt = ptypes[k]
2890+ end
2891+ declare_var(pnames[k], pt)
2892+ k = k + 1
2893+ end
2894+ stmts = get_stmts(bid)
2895+ k = 0
2896+ while k < stmts.length
2897+ sid = stmts[k]
2898+ if @nd_type[sid] == "InstanceVariableWriteNode"
2899+ ivar = sanitize_ivar(@nd_name[sid])
2900+ val = compile_expr(@nd_expression[sid])
2901+ emit_raw(" self->" + ivar + " = " + val + ";")
2902+ end
2903+ k = k + 1
2904+ end
2905+ pop_scope
2906+ @current_class_idx = -1
2907+ end
2908+ emit_raw("}")
2909+ emit_raw("")
2910+ end
2911+ end
2912+
2913+ def emit_instance_method(ci, mname, pnames, ptypes, rt, bid)
2914+ cname = @cls_names[ci]
2915+ @current_class_idx = ci
2916+ @current_method_name = mname
2917+ @current_method_return = rt
2918+ @indent = 1
2919+
2920+ emit_raw("static " + c_type(rt) + " sp_" + cname + "_" + sanitize_name(mname) + "(sp_" + cname + " *self" + build_params_str(pnames, ptypes) + ") {")
2921+
2922+ push_scope
2923+ j = 0
2924+ while j < pnames.length
2925+ pt = "int"
2926+ if j < ptypes.length
2927+ pt = ptypes[j]
2928+ end
2929+ declare_var(pnames[j], pt)
2930+ j = j + 1
2931+ end
2932+
2933+ if bid >= 0
2934+ declare_method_locals(bid, pnames)
2935+ compile_body_return(bid, rt)
2936+ end
2937+
2938+ pop_scope
2939+ @current_class_idx = -1
2940+ @current_method_name = ""
2941+ @indent = 0
2942+ emit_raw("}")
2943+ emit_raw("")
2944+ end
2945+
2946+ def emit_class_level_method(ci, mname, pnames, ptypes, rt, bid)
2947+ cname = @cls_names[ci]
2948+ @current_class_idx = ci
2949+ @current_method_name = mname
2950+ @current_method_return = rt
2951+ @indent = 1
2952+
2953+ emit_raw("static " + c_type(rt) + " sp_" + cname + "_cls_" + sanitize_name(mname) + "(" + build_params_decl(pnames, ptypes) + ") {")
2954+
2955+ push_scope
2956+ j = 0
2957+ while j < pnames.length
2958+ pt = "int"
2959+ if j < ptypes.length
2960+ pt = ptypes[j]
2961+ end
2962+ declare_var(pnames[j], pt)
2963+ j = j + 1
2964+ end
2965+
2966+ if bid >= 0
2967+ declare_method_locals(bid, pnames)
2968+ compile_body_return(bid, rt)
2969+ end
2970+
2971+ pop_scope
2972+ @current_class_idx = -1
2973+ @current_method_name = ""
2974+ @indent = 0
2975+ emit_raw("}")
2976+ emit_raw("")
2977+ end
2978+
2979+ def build_params_str(pnames, ptypes)
2980+ result = ""
2981+ j = 0
2982+ while j < pnames.length
2983+ pt = "int"
2984+ if j < ptypes.length
2985+ pt = ptypes[j]
2986+ end
2987+ result = result + ", " + c_type(pt) + " lv_" + pnames[j]
2988+ j = j + 1
2989+ end
2990+ result
2991+ end
2992+
2993+ def build_params_decl(pnames, ptypes)
2994+ if pnames.length == 0
2995+ return "void"
2996+ end
2997+ result = ""
2998+ j = 0
2999+ while j < pnames.length
3000+ if j > 0
3001+ result = result + ", "
3002+ end
3003+ pt = "int"
3004+ if j < ptypes.length
3005+ pt = ptypes[j]
3006+ end
3007+ result = result + c_type(pt) + " lv_" + pnames[j]
3008+ j = j + 1
3009+ end
3010+ result
3011+ end
3012+
3013+ # ---- Emit top-level methods ----
3014+ def emit_toplevel_methods
3015+ i = 0
3016+ while i < @meth_names.length
3017+ emit_toplevel_method(i)
3018+ i = i + 1
3019+ end
3020+ end
3021+
3022+ def emit_toplevel_method(mi)
3023+ @current_method_name = @meth_names[mi]
3024+ @current_method_return = @meth_return_types[mi]
3025+ @indent = 1
3026+ @in_main = 0
3027+
3028+ pnames = @meth_param_names[mi].split(",")
3029+ ptypes = @meth_param_types[mi].split(",")
3030+
3031+ emit_raw("static " + c_type(@meth_return_types[mi]) + " sp_" + sanitize_name(@meth_names[mi]) + "(" + method_params_decl(mi) + ") {")
3032+
3033+ push_scope
3034+ j = 0
3035+ while j < pnames.length
3036+ pt = "int"
3037+ if j < ptypes.length
3038+ pt = ptypes[j]
3039+ end
3040+ declare_var(pnames[j], pt)
3041+ j = j + 1
3042+ end
3043+
3044+ bid = @meth_body_ids[mi]
3045+ if bid >= 0
3046+ declare_method_locals(bid, pnames)
3047+ compile_body_return(bid, @meth_return_types[mi])
3048+ end
3049+
3050+ pop_scope
3051+ @current_method_name = ""
3052+ @indent = 0
3053+ emit_raw("}")
3054+ emit_raw("")
3055+ end
3056+
3057+ def declare_method_locals(bid, params)
3058+ lnames = []
3059+ ltypes = []
3060+ scan_locals(bid, lnames, ltypes, params)
3061+ j = 0
3062+ while j < lnames.length
3063+ declare_var(lnames[j], ltypes[j])
3064+ emit(" " + c_type(ltypes[j]) + " lv_" + lnames[j] + " = " + c_default_val(ltypes[j]) + ";")
3065+ j = j + 1
3066+ end
3067+ end
3068+
3069+ def scan_locals(nid, names, types, params)
3070+ if nid < 0
3071+ return
3072+ end
3073+ if @nd_type[nid] == "LocalVariableWriteNode"
3074+ lname = @nd_name[nid]
3075+ if not_in(lname, names) == 1
3076+ if not_in(lname, params) == 1
3077+ names.push(lname)
3078+ types.push(infer_type(@nd_expression[nid]))
3079+ end
3080+ end
3081+ end
3082+ if @nd_type[nid] == "LocalVariableOperatorWriteNode"
3083+ lname = @nd_name[nid]
3084+ if not_in(lname, names) == 1
3085+ if not_in(lname, params) == 1
3086+ names.push(lname)
3087+ types.push("int")
3088+ end
3089+ end
3090+ end
3091+ if @nd_type[nid] == "ForNode"
3092+ tgt = @nd_target[nid]
3093+ if tgt >= 0
3094+ if @nd_type[tgt] == "LocalVariableTargetNode"
3095+ lname = @nd_name[tgt]
3096+ if not_in(lname, names) == 1
3097+ if not_in(lname, params) == 1
3098+ names.push(lname)
3099+ types.push("int")
3100+ end
3101+ end
3102+ end
3103+ end
3104+ end
3105+ # Block parameters need to be declared as locals
3106+ if @nd_type[nid] == "CallNode"
3107+ blk = @nd_block[nid]
3108+ if blk >= 0
3109+ bp = @nd_parameters[blk]
3110+ if bp >= 0
3111+ inner = @nd_parameters[bp]
3112+ if inner >= 0
3113+ reqs = parse_id_list(@nd_requireds[inner])
3114+ bk = 0
3115+ while bk < reqs.length
3116+ bname = @nd_name[reqs[bk]]
3117+ if not_in(bname, names) == 1
3118+ if not_in(bname, params) == 1
3119+ names.push(bname)
3120+ # Infer type from receiver context
3121+ recv_type = ""
3122+ if @nd_receiver[nid] >= 0
3123+ recv_type = infer_type(@nd_receiver[nid])
3124+ end
3125+ mname = @nd_name[nid]
3126+ if mname == "each"
3127+ if recv_type == "int_array"
3128+ if bk == 0
3129+ types.push("int")
3130+ else
3131+ types.push("int")
3132+ end
3133+ else
3134+ if recv_type == "str_array"
3135+ types.push("string")
3136+ else
3137+ if recv_type == "str_int_hash"
3138+ if bk == 0
3139+ types.push("string")
3140+ else
3141+ types.push("int")
3142+ end
3143+ else
3144+ if recv_type == "str_str_hash"
3145+ types.push("string")
3146+ else
3147+ types.push("int")
3148+ end
3149+ end
3150+ end
3151+ end
3152+ else
3153+ if mname == "times"
3154+ types.push("int")
3155+ else
3156+ if mname == "upto"
3157+ types.push("int")
3158+ else
3159+ if mname == "downto"
3160+ types.push("int")
3161+ else
3162+ if mname == "reduce"
3163+ types.push("int")
3164+ else
3165+ if mname == "inject"
3166+ types.push("int")
3167+ else
3168+ if mname == "reject"
3169+ types.push("int")
3170+ else
3171+ types.push("int")
3172+ end
3173+ end
3174+ end
3175+ end
3176+ end
3177+ end
3178+ end
3179+ end
3180+ end
3181+ bk = bk + 1
3182+ end
3183+ end
3184+ end
3185+ end
3186+ end
3187+ # Recurse
3188+ scan_locals_children(nid, names, types, params)
3189+ end
3190+
3191+ def scan_locals_children(nid, names, types, params)
3192+ if @nd_body[nid] >= 0
3193+ scan_locals(@nd_body[nid], names, types, params)
3194+ end
3195+ stmts = parse_id_list(@nd_stmts[nid])
3196+ k = 0
3197+ while k < stmts.length
3198+ scan_locals(stmts[k], names, types, params)
3199+ k = k + 1
3200+ end
3201+ if @nd_expression[nid] >= 0
3202+ scan_locals(@nd_expression[nid], names, types, params)
3203+ end
3204+ if @nd_predicate[nid] >= 0
3205+ scan_locals(@nd_predicate[nid], names, types, params)
3206+ end
3207+ if @nd_subsequent[nid] >= 0
3208+ scan_locals(@nd_subsequent[nid], names, types, params)
3209+ end
3210+ if @nd_else_clause[nid] >= 0
3211+ scan_locals(@nd_else_clause[nid], names, types, params)
3212+ end
3213+ if @nd_arguments[nid] >= 0
3214+ scan_locals(@nd_arguments[nid], names, types, params)
3215+ end
3216+ args = parse_id_list(@nd_args[nid])
3217+ k = 0
3218+ while k < args.length
3219+ scan_locals(args[k], names, types, params)
3220+ k = k + 1
3221+ end
3222+ conds = parse_id_list(@nd_conditions[nid])
3223+ k = 0
3224+ while k < conds.length
3225+ scan_locals(conds[k], names, types, params)
3226+ k = k + 1
3227+ end
3228+ elems = parse_id_list(@nd_elements[nid])
3229+ k = 0
3230+ while k < elems.length
3231+ scan_locals(elems[k], names, types, params)
3232+ k = k + 1
3233+ end
3234+ if @nd_left[nid] >= 0
3235+ scan_locals(@nd_left[nid], names, types, params)
3236+ end
3237+ if @nd_right[nid] >= 0
3238+ scan_locals(@nd_right[nid], names, types, params)
3239+ end
3240+ if @nd_block[nid] >= 0
3241+ scan_locals(@nd_block[nid], names, types, params)
3242+ end
3243+ if @nd_receiver[nid] >= 0
3244+ scan_locals(@nd_receiver[nid], names, types, params)
3245+ end
3246+ if @nd_collection[nid] >= 0
3247+ scan_locals(@nd_collection[nid], names, types, params)
3248+ end
3249+ end
3250+
3251+ def not_in(name, arr)
3252+ k = 0
3253+ while k < arr.length
3254+ if arr[k] == name
3255+ return 0
3256+ end
3257+ k = k + 1
3258+ end
3259+ 1
3260+ end
3261+
3262+ # ---- Main emission ----
3263+ def emit_main(stmts)
3264+ emit_raw("typedef struct{const char**data;mrb_int len;}sp_Argv;")
3265+ emit_raw("static sp_Argv sp_argv;")
3266+ emit_raw("")
3267+ emit_raw("int main(int argc,char**argv){")
3268+ emit_raw(" sp_argv.data=(const char**)(argv+1);sp_argv.len=argc-1;")
3269+
3270+ @in_main = 1
3271+ @indent = 1
3272+ push_scope
3273+
3274+ # Pre-declare main locals
3275+ lnames = []
3276+ ltypes = []
3277+ empty_params = []
3278+ i = 0
3279+ while i < stmts.length
3280+ sid = stmts[i]
3281+ if @nd_type[sid] != "DefNode"
3282+ if @nd_type[sid] != "ClassNode"
3283+ if @nd_type[sid] != "ConstantWriteNode"
3284+ scan_locals(sid, lnames, ltypes, empty_params)
3285+ end
3286+ end
3287+ end
3288+ i = i + 1
3289+ end
3290+
3291+ j = 0
3292+ while j < lnames.length
3293+ declare_var(lnames[j], ltypes[j])
3294+ ctp = c_type(ltypes[j])
3295+ if type_is_pointer(ltypes[j]) == 1
3296+ emit(" " + ctp + "lv_" + lnames[j] + " = NULL;")
3297+ emit(" SP_GC_ROOT(lv_" + lnames[j] + ");")
3298+ else
3299+ emit(" " + ctp + " lv_" + lnames[j] + " = " + c_default_val(ltypes[j]) + ";")
3300+ end
3301+ j = j + 1
3302+ end
3303+
3304+ # Constants
3305+ i = 0
3306+ while i < @const_names.length
3307+ ctp = c_type(@const_types[i])
3308+ val = compile_expr(@const_expr_ids[i])
3309+ emit(" " + ctp + " cst_" + @const_names[i] + " = " + val + ";")
3310+ i = i + 1
3311+ end
3312+
3313+ emit_raw("")
3314+
3315+ # Compile main statements
3316+ i = 0
3317+ while i < stmts.length
3318+ sid = stmts[i]
3319+ if @nd_type[sid] != "DefNode"
3320+ if @nd_type[sid] != "ClassNode"
3321+ if @nd_type[sid] != "ConstantWriteNode"
3322+ compile_stmt(sid)
3323+ end
3324+ end
3325+ end
3326+ i = i + 1
3327+ end
3328+
3329+ emit_raw(" return 0;")
3330+ emit_raw("}")
3331+
3332+ pop_scope
3333+ @in_main = 0
3334+ end
3335+
3336+ # ---- Expression compiler ----
3337+ def compile_expr(nid)
3338+ if nid < 0
3339+ return "0"
3340+ end
3341+ t = @nd_type[nid]
3342+ if t == "IntegerNode"
3343+ return @nd_value[nid].to_s
3344+ end
3345+ if t == "FloatNode"
3346+ return @nd_content[nid]
3347+ end
3348+ if t == "StringNode"
3349+ return c_string_literal(@nd_content[nid])
3350+ end
3351+ if t == "SymbolNode"
3352+ return c_string_literal(@nd_content[nid])
3353+ end
3354+ if t == "InterpolatedStringNode"
3355+ return compile_interpolated(nid)
3356+ end
3357+ if t == "TrueNode"
3358+ return "TRUE"
3359+ end
3360+ if t == "FalseNode"
3361+ return "FALSE"
3362+ end
3363+ if t == "NilNode"
3364+ return "0"
3365+ end
3366+ if t == "SelfNode"
3367+ return "self"
3368+ end
3369+ if t == "LocalVariableReadNode"
3370+ return "lv_" + @nd_name[nid]
3371+ end
3372+ if t == "InstanceVariableReadNode"
3373+ return "self->" + sanitize_ivar(@nd_name[nid])
3374+ end
3375+ if t == "ConstantReadNode"
3376+ ci = find_const_idx(@nd_name[nid])
3377+ if ci >= 0
3378+ return "cst_" + @nd_name[nid]
3379+ end
3380+ return @nd_name[nid]
3381+ end
3382+ if t == "ConstantPathNode"
3383+ if @nd_receiver[nid] >= 0
3384+ return @nd_name[@nd_receiver[nid]] + "_" + @nd_name[nid]
3385+ end
3386+ return @nd_name[nid]
3387+ end
3388+ if t == "CallNode"
3389+ return compile_call_expr(nid)
3390+ end
3391+ if t == "IfNode"
3392+ return compile_if_expr(nid)
3393+ end
3394+ if t == "UnlessNode"
3395+ return compile_unless_expr(nid)
3396+ end
3397+ if t == "AndNode"
3398+ return "(" + compile_expr(@nd_left[nid]) + " && " + compile_expr(@nd_right[nid]) + ")"
3399+ end
3400+ if t == "OrNode"
3401+ return "(" + compile_expr(@nd_left[nid]) + " || " + compile_expr(@nd_right[nid]) + ")"
3402+ end
3403+ if t == "ParenthesesNode"
3404+ body = @nd_body[nid]
3405+ if body >= 0
3406+ stmts = get_stmts(body)
3407+ if stmts.length > 0
3408+ return compile_expr(stmts[stmts.length - 1])
3409+ end
3410+ end
3411+ return "0"
3412+ end
3413+ if t == "ArrayNode"
3414+ return compile_array_literal(nid)
3415+ end
3416+ if t == "HashNode"
3417+ return compile_hash_literal(nid)
3418+ end
3419+ if t == "RangeNode"
3420+ return compile_expr(@nd_left[nid])
3421+ end
3422+ if t == "DefinedNode"
3423+ return "\"expression\""
3424+ end
3425+ if t == "SourceLineNode"
3426+ return @nd_value[nid].to_s
3427+ end
3428+ if t == "ArgumentsNode"
3429+ arg_ids = parse_id_list(@nd_args[nid])
3430+ if arg_ids.length > 0
3431+ return compile_expr(arg_ids[0])
3432+ end
3433+ return "0"
3434+ end
3435+ if t == "StatementsNode"
3436+ stmts = parse_id_list(@nd_stmts[nid])
3437+ if stmts.length > 0
3438+ return compile_expr(stmts[stmts.length - 1])
3439+ end
3440+ return "0"
3441+ end
3442+ if t == "EmbeddedStatementsNode"
3443+ body = @nd_body[nid]
3444+ if body >= 0
3445+ stmts = get_stmts(body)
3446+ if stmts.length > 0
3447+ return compile_expr(stmts[0])
3448+ end
3449+ end
3450+ return "0"
3451+ end
3452+ "0"
3453+ end
3454+
3455+ def c_string_literal(s)
3456+ result = "\""
3457+ i = 0
3458+ while i < s.length
3459+ ch = s[i]
3460+ if ch == "\\"
3461+ result = result + "\\\\"
3462+ else
3463+ if ch == "\""
3464+ result = result + "\\\""
3465+ else
3466+ if ch == "\n"
3467+ result = result + "\\n"
3468+ else
3469+ if ch == "\r"
3470+ result = result + "\\r"
3471+ else
3472+ if ch == "\t"
3473+ result = result + "\\t"
3474+ else
3475+ result = result + ch
3476+ end
3477+ end
3478+ end
3479+ end
3480+ end
3481+ i = i + 1
3482+ end
3483+ result + "\""
3484+ end
3485+
3486+ def compile_interpolated(nid)
3487+ @needs_string_helpers = 1
3488+ parts = parse_id_list(@nd_parts[nid])
3489+ if parts.length == 0
3490+ return "\"\""
3491+ end
3492+ fmt = ""
3493+ arg_exprs = []
3494+ i = 0
3495+ while i < parts.length
3496+ pid = parts[i]
3497+ if @nd_type[pid] == "StringNode"
3498+ fmt = fmt + escape_c_format(@nd_content[pid])
3499+ else
3500+ if @nd_type[pid] == "EmbeddedStatementsNode"
3501+ body = @nd_body[pid]
3502+ if body >= 0
3503+ stmts = get_stmts(body)
3504+ if stmts.length > 0
3505+ inner = stmts[0]
3506+ it = infer_type(inner)
3507+ if it == "int"
3508+ fmt = fmt + "%lld"
3509+ arg_exprs.push("(long long)" + compile_expr(inner))
3510+ else
3511+ if it == "float"
3512+ fmt = fmt + "%g"
3513+ arg_exprs.push(compile_expr(inner))
3514+ else
3515+ if it == "string"
3516+ fmt = fmt + "%s"
3517+ arg_exprs.push(compile_expr(inner))
3518+ else
3519+ if it == "bool"
3520+ fmt = fmt + "%s"
3521+ arg_exprs.push("(" + compile_expr(inner) + " ? \"true\" : \"false\")")
3522+ else
3523+ fmt = fmt + "%lld"
3524+ arg_exprs.push("(long long)" + compile_expr(inner))
3525+ end
3526+ end
3527+ end
3528+ end
3529+ end
3530+ end
3531+ end
3532+ end
3533+ i = i + 1
3534+ end
3535+ result = "sp_sprintf(\"" + fmt + "\""
3536+ j = 0
3537+ while j < arg_exprs.length
3538+ result = result + ", " + arg_exprs[j]
3539+ j = j + 1
3540+ end
3541+ result + ")"
3542+ end
3543+
3544+ def escape_c_format(s)
3545+ result = ""
3546+ i = 0
3547+ while i < s.length
3548+ ch = s[i]
3549+ if ch == "%"
3550+ result = result + "%%"
3551+ else
3552+ if ch == "\\"
3553+ result = result + "\\\\"
3554+ else
3555+ if ch == "\""
3556+ result = result + "\\\""
3557+ else
3558+ if ch == "\n"
3559+ result = result + "\\n"
3560+ else
3561+ if ch == "\t"
3562+ result = result + "\\t"
3563+ else
3564+ result = result + ch
3565+ end
3566+ end
3567+ end
3568+ end
3569+ end
3570+ i = i + 1
3571+ end
3572+ result
3573+ end
3574+
3575+ def compile_arg0(nid)
3576+ args_id = @nd_arguments[nid]
3577+ if args_id >= 0
3578+ arg_ids = get_args(args_id)
3579+ if arg_ids.length > 0
3580+ return compile_expr(arg_ids[0])
3581+ end
3582+ end
3583+ "0"
3584+ end
3585+
3586+ def compile_call_expr(nid)
3587+ mname = @nd_name[nid]
3588+ recv = @nd_receiver[nid]
3589+
3590+ # No receiver
3591+ if recv < 0
3592+ mi = find_method_idx(mname)
3593+ if mi >= 0
3594+ return "sp_" + sanitize_name(mname) + "(" + compile_call_args(nid) + ")"
3595+ end
3596+ if @current_class_idx >= 0
3597+ cidx = cls_find_method(@current_class_idx, mname)
3598+ if cidx >= 0
3599+ ca = compile_call_args(nid)
3600+ cname = @cls_names[@current_class_idx]
3601+ owner = find_method_owner(@current_class_idx, mname)
3602+ if ca != ""
3603+ return "sp_" + owner + "_" + sanitize_name(mname) + "(self, " + ca + ")"
3604+ else
3605+ return "sp_" + owner + "_" + sanitize_name(mname) + "(self)"
3606+ end
3607+ end
3608+ end
3609+ return "0"
3610+ end
3611+
3612+ # Operators
3613+ if mname == "+"
3614+ lt = infer_type(recv)
3615+ if lt == "string"
3616+ @needs_string_helpers = 1
3617+ return "sp_str_concat(" + compile_expr(recv) + ", " + compile_arg0(nid) + ")"
3618+ end
3619+ return "(" + compile_expr(recv) + " + " + compile_arg0(nid) + ")"
3620+ end
3621+ if mname == "-"
3622+ args_id = @nd_arguments[nid]
3623+ if args_id < 0
3624+ return "(-" + compile_expr(recv) + ")"
3625+ end
3626+ return "(" + compile_expr(recv) + " - " + compile_arg0(nid) + ")"
3627+ end
3628+ if mname == "*"
3629+ return "(" + compile_expr(recv) + " * " + compile_arg0(nid) + ")"
3630+ end
3631+ if mname == "/"
3632+ lt = infer_type(recv)
3633+ if lt == "float"
3634+ return "(" + compile_expr(recv) + " / " + compile_arg0(nid) + ")"
3635+ end
3636+ return "sp_idiv(" + compile_expr(recv) + ", " + compile_arg0(nid) + ")"
3637+ end
3638+ if mname == "%"
3639+ return "sp_imod(" + compile_expr(recv) + ", " + compile_arg0(nid) + ")"
3640+ end
3641+ if mname == "<"
3642+ return "(" + compile_expr(recv) + " < " + compile_arg0(nid) + ")"
3643+ end
3644+ if mname == ">"
3645+ return "(" + compile_expr(recv) + " > " + compile_arg0(nid) + ")"
3646+ end
3647+ if mname == "<="
3648+ return "(" + compile_expr(recv) + " <= " + compile_arg0(nid) + ")"
3649+ end
3650+ if mname == ">="
3651+ return "(" + compile_expr(recv) + " >= " + compile_arg0(nid) + ")"
3652+ end
3653+ if mname == "=="
3654+ return compile_eq(nid, "==")
3655+ end
3656+ if mname == "!="
3657+ return compile_eq(nid, "!=")
3658+ end
3659+ if mname == "!"
3660+ return "(!" + compile_expr(recv) + ")"
3661+ end
3662+ if mname == "<<"
3663+ return "(" + compile_expr(recv) + " << " + compile_arg0(nid) + ")"
3664+ end
3665+ if mname == ">>"
3666+ return "(" + compile_expr(recv) + " >> " + compile_arg0(nid) + ")"
3667+ end
3668+ if mname == "&"
3669+ return "(" + compile_expr(recv) + " & " + compile_arg0(nid) + ")"
3670+ end
3671+ if mname == "|"
3672+ return "(" + compile_expr(recv) + " | " + compile_arg0(nid) + ")"
3673+ end
3674+ if mname == "^"
3675+ return "(" + compile_expr(recv) + " ^ " + compile_arg0(nid) + ")"
3676+ end
3677+ if mname == "~"
3678+ return "(~" + compile_expr(recv) + ")"
3679+ end
3680+
3681+ # .new
3682+ if mname == "new"
3683+ if @nd_type[recv] == "ConstantReadNode"
3684+ cname = @nd_name[recv]
3685+ ci = find_class_idx(cname)
3686+ if ci >= 0
3687+ return "sp_" + cname + "_new(" + compile_call_args(nid) + ")"
3688+ end
3689+ end
3690+ end
3691+
3692+ recv_type = infer_type(recv)
3693+ rc = compile_expr(recv)
3694+
3695+ # String methods
3696+ if recv_type == "string"
3697+ @needs_string_helpers = 1
3698+ if mname == "length"
3699+ return "(mrb_int)strlen(" + rc + ")"
3700+ end
3701+ if mname == "to_i"
3702+ return "((mrb_int)atoll(" + rc + "))"
3703+ end
3704+ if mname == "to_f"
3705+ return "atof(" + rc + ")"
3706+ end
3707+ if mname == "upcase"
3708+ return "sp_str_upcase(" + rc + ")"
3709+ end
3710+ if mname == "downcase"
3711+ return "sp_str_downcase(" + rc + ")"
3712+ end
3713+ if mname == "strip"
3714+ return "sp_str_strip(" + rc + ")"
3715+ end
3716+ if mname == "chomp"
3717+ return "sp_str_chomp(" + rc + ")"
3718+ end
3719+ if mname == "include?"
3720+ return "sp_str_include(" + rc + ", " + compile_arg0(nid) + ")"
3721+ end
3722+ if mname == "start_with?"
3723+ return "sp_str_start_with(" + rc + ", " + compile_arg0(nid) + ")"
3724+ end
3725+ if mname == "end_with?"
3726+ return "sp_str_end_with(" + rc + ", " + compile_arg0(nid) + ")"
3727+ end
3728+ if mname == "split"
3729+ @needs_str_array = 1
3730+ return "sp_str_split(" + rc + ", " + compile_arg0(nid) + ")"
3731+ end
3732+ if mname == "gsub"
3733+ args_id = @nd_arguments[nid]
3734+ arg1 = "\"\""
3735+ if args_id >= 0
3736+ a = get_args(args_id)
3737+ if a.length >= 2
3738+ arg1 = compile_expr(a[1])
3739+ end
3740+ end
3741+ return "sp_str_gsub(" + rc + ", " + compile_arg0(nid) + ", " + arg1 + ")"
3742+ end
3743+ if mname == "index"
3744+ return "sp_str_index(" + rc + ", " + compile_arg0(nid) + ")"
3745+ end
3746+ if mname == "[]"
3747+ return "sp_str_sub_range(" + rc + ", " + compile_arg0(nid) + ", 1)"
3748+ end
3749+ if mname == "freeze"
3750+ return rc
3751+ end
3752+ end
3753+
3754+ # Integer methods
3755+ if recv_type == "int"
3756+ if mname == "to_s"
3757+ @needs_string_helpers = 1
3758+ return "sp_int_to_s(" + rc + ")"
3759+ end
3760+ if mname == "to_f"
3761+ return "(mrb_float)(" + rc + ")"
3762+ end
3763+ if mname == "abs"
3764+ return "((" + rc + ") < 0 ? -(" + rc + ") : (" + rc + "))"
3765+ end
3766+ end
3767+
3768+ if recv_type == "float"
3769+ if mname == "to_s"
3770+ @needs_string_helpers = 1
3771+ return "sp_float_to_s(" + rc + ")"
3772+ end
3773+ if mname == "to_i"
3774+ return "(mrb_int)(" + rc + ")"
3775+ end
3776+ end
3777+
3778+ if recv_type == "bool"
3779+ if mname == "to_s"
3780+ return "(" + rc + " ? \"true\" : \"false\")"
3781+ end
3782+ end
3783+
3784+ # Array methods
3785+ if recv_type == "int_array"
3786+ if mname == "length"
3787+ return "sp_IntArray_length(" + rc + ")"
3788+ end
3789+ if mname == "[]"
3790+ return "sp_IntArray_get(" + rc + ", " + compile_arg0(nid) + ")"
3791+ end
3792+ if mname == "push"
3793+ return "(sp_IntArray_push(" + rc + ", " + compile_arg0(nid) + "), 0)"
3794+ end
3795+ if mname == "pop"
3796+ return "sp_IntArray_pop(" + rc + ")"
3797+ end
3798+ if mname == "empty?"
3799+ return "sp_IntArray_empty(" + rc + ")"
3800+ end
3801+ if mname == "include?"
3802+ return "sp_IntArray_include(" + rc + ", " + compile_arg0(nid) + ")"
3803+ end
3804+ if mname == "sort"
3805+ return "sp_IntArray_sort(" + rc + ")"
3806+ end
3807+ if mname == "first"
3808+ return "sp_IntArray_get(" + rc + ", 0)"
3809+ end
3810+ if mname == "last"
3811+ return "sp_IntArray_get(" + rc + ", sp_IntArray_length(" + rc + ") - 1)"
3812+ end
3813+ if mname == "min"
3814+ return "sp_IntArray_min(" + rc + ")"
3815+ end
3816+ if mname == "max"
3817+ return "sp_IntArray_max(" + rc + ")"
3818+ end
3819+ if mname == "sum"
3820+ return "sp_IntArray_sum(" + rc + ")"
3821+ end
3822+ if mname == "to_a"
3823+ return "sp_IntArray_dup(" + rc + ")"
3824+ end
3825+ end
3826+ if recv_type == "str_array"
3827+ if mname == "length"
3828+ return "sp_StrArray_length(" + rc + ")"
3829+ end
3830+ if mname == "[]"
3831+ return "sp_StrArray_get(" + rc + ", " + compile_arg0(nid) + ")"
3832+ end
3833+ if mname == "first"
3834+ return "sp_StrArray_get(" + rc + ", 0)"
3835+ end
3836+ if mname == "last"
3837+ return "sp_StrArray_get(" + rc + ", sp_StrArray_length(" + rc + ") - 1)"
3838+ end
3839+ end
3840+
3841+ # Hash methods
3842+ if recv_type == "str_int_hash"
3843+ if mname == "[]"
3844+ return "sp_StrIntHash_get(" + rc + ", " + compile_arg0(nid) + ")"
3845+ end
3846+ if mname == "has_key?"
3847+ return "sp_StrIntHash_has_key(" + rc + ", " + compile_arg0(nid) + ")"
3848+ end
3849+ if mname == "length"
3850+ return "sp_StrIntHash_length(" + rc + ")"
3851+ end
3852+ if mname == "keys"
3853+ return "sp_StrIntHash_keys(" + rc + ")"
3854+ end
3855+ end
3856+ if recv_type == "str_str_hash"
3857+ if mname == "[]"
3858+ return "sp_StrStrHash_get(" + rc + ", " + compile_arg0(nid) + ")"
3859+ end
3860+ if mname == "has_key?"
3861+ return "sp_StrStrHash_has_key(" + rc + ", " + compile_arg0(nid) + ")"
3862+ end
3863+ if mname == "length"
3864+ return "sp_StrStrHash_length(" + rc + ")"
3865+ end
3866+ if mname == "keys"
3867+ return "sp_StrStrHash_keys(" + rc + ")"
3868+ end
3869+ end
3870+
3871+ # Math
3872+ if @nd_type[recv] == "ConstantReadNode"
3873+ if @nd_name[recv] == "Math"
3874+ if mname == "sqrt"
3875+ return "sqrt(" + compile_arg0(nid) + ")"
3876+ end
3877+ end
3878+ end
3879+
3880+ # to_a on range
3881+ if mname == "to_a"
3882+ if @nd_type[recv] == "RangeNode"
3883+ @needs_int_array = 1
3884+ @needs_gc = 1
3885+ return "sp_IntArray_from_range(" + compile_expr(@nd_left[recv]) + ", " + compile_expr(@nd_right[recv]) + ")"
3886+ end
3887+ end
3888+
3889+ # Object method calls
3890+ if is_obj_type(recv_type) == 1
3891+ cname = recv_type[4, recv_type.length - 4]
3892+ ci = find_class_idx(cname)
3893+ if ci >= 0
3894+ # attr_reader
3895+ readers = @cls_attr_readers[ci].split(";")
3896+ j = 0
3897+ while j < readers.length
3898+ if readers[j] == mname
3899+ return rc + "->" + mname
3900+ end
3901+ j = j + 1
3902+ end
3903+ # attr_writer
3904+ if mname.length > 1
3905+ if mname[mname.length - 1] == "="
3906+ bname = mname[0, mname.length - 1]
3907+ writers = @cls_attr_writers[ci].split(";")
3908+ j = 0
3909+ while j < writers.length
3910+ if writers[j] == bname
3911+ return "(" + rc + "->" + bname + " = " + compile_arg0(nid) + ")"
3912+ end
3913+ j = j + 1
3914+ end
3915+ end
3916+ end
3917+ # Method call
3918+ owner = find_method_owner(ci, mname)
3919+ if owner != ""
3920+ ca = compile_call_args(nid)
3921+ if owner == cname
3922+ if ca != ""
3923+ return "sp_" + owner + "_" + sanitize_name(mname) + "(" + rc + ", " + ca + ")"
3924+ else
3925+ return "sp_" + owner + "_" + sanitize_name(mname) + "(" + rc + ")"
3926+ end
3927+ else
3928+ if ca != ""
3929+ return "sp_" + owner + "_" + sanitize_name(mname) + "((sp_" + owner + " *)" + rc + ", " + ca + ")"
3930+ else
3931+ return "sp_" + owner + "_" + sanitize_name(mname) + "((sp_" + owner + " *)" + rc + ")"
3932+ end
3933+ end
3934+ end
3935+ end
3936+ end
3937+
3938+ "0"
3939+ end
3940+
3941+ def compile_eq(nid, op)
3942+ recv = @nd_receiver[nid]
3943+ lt = infer_type(recv)
3944+ args_id = @nd_arguments[nid]
3945+ arg_id = -1
3946+ if args_id >= 0
3947+ a = get_args(args_id)
3948+ if a.length > 0
3949+ arg_id = a[0]
3950+ end
3951+ end
3952+ at = "int"
3953+ if arg_id >= 0
3954+ at = infer_type(arg_id)
3955+ end
3956+ lc = compile_expr(recv)
3957+ rc = "0"
3958+ if arg_id >= 0
3959+ rc = compile_expr(arg_id)
3960+ end
3961+ if lt == "string"
3962+ if at == "nil"
3963+ if op == "=="
3964+ return "(" + lc + " == NULL)"
3965+ else
3966+ return "(" + lc + " != NULL)"
3967+ end
3968+ end
3969+ if op == "=="
3970+ return "(strcmp(" + lc + ", " + rc + ") == 0)"
3971+ else
3972+ return "(strcmp(" + lc + ", " + rc + ") != 0)"
3973+ end
3974+ end
3975+ if at == "nil"
3976+ if type_is_pointer(lt) == 1
3977+ if op == "=="
3978+ return "(" + lc + " == NULL)"
3979+ else
3980+ return "(" + lc + " != NULL)"
3981+ end
3982+ end
3983+ end
3984+ "(" + lc + " " + op + " " + rc + ")"
3985+ end
3986+
3987+ def compile_call_args(nid)
3988+ args_id = @nd_arguments[nid]
3989+ if args_id < 0
3990+ return ""
3991+ end
3992+ arg_ids = get_args(args_id)
3993+ result = ""
3994+ k = 0
3995+ while k < arg_ids.length
3996+ if k > 0
3997+ result = result + ", "
3998+ end
3999+ result = result + compile_expr(arg_ids[k])
4000+ k = k + 1
4001+ end
4002+ result
4003+ end
4004+
4005+ def find_method_owner(ci, mname)
4006+ if ci < 0
4007+ return ""
4008+ end
4009+ mnames = @cls_meth_names[ci].split(";")
4010+ j = 0
4011+ while j < mnames.length
4012+ if mnames[j] == mname
4013+ return @cls_names[ci]
4014+ end
4015+ j = j + 1
4016+ end
4017+ if @cls_parents[ci] != ""
4018+ pi = find_class_idx(@cls_parents[ci])
4019+ if pi >= 0
4020+ return find_method_owner(pi, mname)
4021+ end
4022+ end
4023+ ""
4024+ end
4025+
4026+ def compile_if_expr(nid)
4027+ cond = compile_expr(@nd_predicate[nid])
4028+ then_val = "0"
4029+ body = @nd_body[nid]
4030+ if body >= 0
4031+ stmts = get_stmts(body)
4032+ if stmts.length > 0
4033+ then_val = compile_expr(stmts[stmts.length - 1])
4034+ end
4035+ end
4036+ else_val = "0"
4037+ sub = @nd_subsequent[nid]
4038+ if sub >= 0
4039+ if @nd_type[sub] == "ElseNode"
4040+ eb = @nd_body[sub]
4041+ if eb >= 0
4042+ es = get_stmts(eb)
4043+ if es.length > 0
4044+ else_val = compile_expr(es[es.length - 1])
4045+ end
4046+ end
4047+ else
4048+ else_val = compile_if_expr(sub)
4049+ end
4050+ end
4051+ "(" + cond + " ? " + then_val + " : " + else_val + ")"
4052+ end
4053+
4054+ def compile_unless_expr(nid)
4055+ cond = compile_expr(@nd_predicate[nid])
4056+ then_val = "0"
4057+ body = @nd_body[nid]
4058+ if body >= 0
4059+ stmts = get_stmts(body)
4060+ if stmts.length > 0
4061+ then_val = compile_expr(stmts[stmts.length - 1])
4062+ end
4063+ end
4064+ "(!" + cond + " ? " + then_val + " : 0)"
4065+ end
4066+
4067+ def compile_array_literal(nid)
4068+ @needs_gc = 1
4069+ elems = parse_id_list(@nd_elements[nid])
4070+ if elems.length == 0
4071+ @needs_int_array = 1
4072+ return "sp_IntArray_new()"
4073+ end
4074+ et = infer_type(elems[0])
4075+ if et == "string"
4076+ @needs_str_array = 1
4077+ tmp = new_temp
4078+ emit(" sp_StrArray *" + tmp + " = sp_StrArray_new();")
4079+ k = 0
4080+ while k < elems.length
4081+ emit(" sp_StrArray_push(" + tmp + ", " + compile_expr(elems[k]) + ");")
4082+ k = k + 1
4083+ end
4084+ return tmp
4085+ end
4086+ @needs_int_array = 1
4087+ tmp = new_temp
4088+ emit(" sp_IntArray *" + tmp + " = sp_IntArray_new();")
4089+ k = 0
4090+ while k < elems.length
4091+ emit(" sp_IntArray_push(" + tmp + ", " + compile_expr(elems[k]) + ");")
4092+ k = k + 1
4093+ end
4094+ tmp
4095+ end
4096+
4097+ def compile_hash_literal(nid)
4098+ @needs_gc = 1
4099+ elems = parse_id_list(@nd_elements[nid])
4100+ if elems.length == 0
4101+ @needs_str_int_hash = 1
4102+ return "sp_StrIntHash_new()"
4103+ end
4104+ vtype = "int"
4105+ eid = elems[0]
4106+ if @nd_type[eid] == "AssocNode"
4107+ vtype = infer_type(@nd_expression[eid])
4108+ end
4109+ if vtype == "string"
4110+ @needs_str_str_hash = 1
4111+ tmp = new_temp
4112+ emit(" sp_StrStrHash *" + tmp + " = sp_StrStrHash_new();")
4113+ k = 0
4114+ while k < elems.length
4115+ el = elems[k]
4116+ if @nd_type[el] == "AssocNode"
4117+ emit(" sp_StrStrHash_set(" + tmp + ", " + compile_expr(@nd_key[el]) + ", " + compile_expr(@nd_expression[el]) + ");")
4118+ end
4119+ k = k + 1
4120+ end
4121+ return tmp
4122+ end
4123+ @needs_str_int_hash = 1
4124+ tmp = new_temp
4125+ emit(" sp_StrIntHash *" + tmp + " = sp_StrIntHash_new();")
4126+ k = 0
4127+ while k < elems.length
4128+ el = elems[k]
4129+ if @nd_type[el] == "AssocNode"
4130+ emit(" sp_StrIntHash_set(" + tmp + ", " + compile_expr(@nd_key[el]) + ", " + compile_expr(@nd_expression[el]) + ");")
4131+ end
4132+ k = k + 1
4133+ end
4134+ tmp
4135+ end
4136+
4137+ # ---- Statement compiler ----
4138+ def compile_stmt(nid)
4139+ if nid < 0
4140+ return
4141+ end
4142+ t = @nd_type[nid]
4143+ if t == "LocalVariableWriteNode"
4144+ val = compile_expr(@nd_expression[nid])
4145+ emit(" lv_" + @nd_name[nid] + " = " + val + ";")
4146+ set_var_type(@nd_name[nid], infer_type(@nd_expression[nid]))
4147+ return
4148+ end
4149+ if t == "LocalVariableOperatorWriteNode"
4150+ op = @nd_binop[nid]
4151+ val = compile_expr(@nd_expression[nid])
4152+ if op == "+"
4153+ emit(" lv_" + @nd_name[nid] + " += " + val + ";")
4154+ end
4155+ if op == "-"
4156+ emit(" lv_" + @nd_name[nid] + " -= " + val + ";")
4157+ end
4158+ if op == "*"
4159+ emit(" lv_" + @nd_name[nid] + " *= " + val + ";")
4160+ end
4161+ if op == "/"
4162+ emit(" lv_" + @nd_name[nid] + " /= " + val + ";")
4163+ end
4164+ if op == "%"
4165+ emit(" lv_" + @nd_name[nid] + " = sp_imod(lv_" + @nd_name[nid] + ", " + val + ");")
4166+ end
4167+ return
4168+ end
4169+ if t == "InstanceVariableWriteNode"
4170+ val = compile_expr(@nd_expression[nid])
4171+ emit(" self->" + sanitize_ivar(@nd_name[nid]) + " = " + val + ";")
4172+ return
4173+ end
4174+ if t == "InstanceVariableOperatorWriteNode"
4175+ op = @nd_binop[nid]
4176+ val = compile_expr(@nd_expression[nid])
4177+ ivar = sanitize_ivar(@nd_name[nid])
4178+ if op == "+"
4179+ emit(" self->" + ivar + " += " + val + ";")
4180+ end
4181+ if op == "-"
4182+ emit(" self->" + ivar + " -= " + val + ";")
4183+ end
4184+ return
4185+ end
4186+ if t == "IfNode"
4187+ compile_if_stmt(nid)
4188+ return
4189+ end
4190+ if t == "UnlessNode"
4191+ compile_unless_stmt(nid)
4192+ return
4193+ end
4194+ if t == "WhileNode"
4195+ compile_while_stmt(nid)
4196+ return
4197+ end
4198+ if t == "UntilNode"
4199+ compile_until_stmt(nid)
4200+ return
4201+ end
4202+ if t == "ForNode"
4203+ compile_for_stmt(nid)
4204+ return
4205+ end
4206+ if t == "CaseNode"
4207+ compile_case_stmt(nid)
4208+ return
4209+ end
4210+ if t == "ReturnNode"
4211+ compile_return_stmt(nid)
4212+ return
4213+ end
4214+ if t == "BreakNode"
4215+ emit(" break;")
4216+ return
4217+ end
4218+ if t == "NextNode"
4219+ emit(" continue;")
4220+ return
4221+ end
4222+ if t == "CallNode"
4223+ compile_call_stmt(nid)
4224+ return
4225+ end
4226+ if t == "StatementsNode"
4227+ stmts = parse_id_list(@nd_stmts[nid])
4228+ k = 0
4229+ while k < stmts.length
4230+ compile_stmt(stmts[k])
4231+ k = k + 1
4232+ end
4233+ return
4234+ end
4235+ expr = compile_expr(nid)
4236+ if expr != "0"
4237+ emit(" " + expr + ";")
4238+ end
4239+ end
4240+
4241+ def compile_if_stmt(nid)
4242+ cond = compile_expr(@nd_predicate[nid])
4243+ emit(" if (" + cond + ") {")
4244+ @indent = @indent + 1
4245+ compile_stmts_body(@nd_body[nid])
4246+ @indent = @indent - 1
4247+ sub = @nd_subsequent[nid]
4248+ if sub >= 0
4249+ if @nd_type[sub] == "ElseNode"
4250+ emit(" } else {")
4251+ @indent = @indent + 1
4252+ compile_stmts_body(@nd_body[sub])
4253+ @indent = @indent - 1
4254+ else
4255+ emit(" } else")
4256+ compile_if_stmt(sub)
4257+ return
4258+ end
4259+ end
4260+ emit(" }")
4261+ end
4262+
4263+ def compile_unless_stmt(nid)
4264+ cond = compile_expr(@nd_predicate[nid])
4265+ emit(" if (!(" + cond + ")) {")
4266+ @indent = @indent + 1
4267+ compile_stmts_body(@nd_body[nid])
4268+ @indent = @indent - 1
4269+ ec = @nd_else_clause[nid]
4270+ if ec >= 0
4271+ emit(" } else {")
4272+ @indent = @indent + 1
4273+ compile_stmts_body(@nd_body[ec])
4274+ @indent = @indent - 1
4275+ end
4276+ emit(" }")
4277+ end
4278+
4279+ def compile_while_stmt(nid)
4280+ old = @in_loop
4281+ @in_loop = 1
4282+ cond = compile_expr(@nd_predicate[nid])
4283+ emit(" while (" + cond + ") {")
4284+ @indent = @indent + 1
4285+ compile_stmts_body(@nd_body[nid])
4286+ @indent = @indent - 1
4287+ emit(" }")
4288+ @in_loop = old
4289+ end
4290+
4291+ def compile_until_stmt(nid)
4292+ old = @in_loop
4293+ @in_loop = 1
4294+ cond = compile_expr(@nd_predicate[nid])
4295+ emit(" while (!(" + cond + ")) {")
4296+ @indent = @indent + 1
4297+ compile_stmts_body(@nd_body[nid])
4298+ @indent = @indent - 1
4299+ emit(" }")
4300+ @in_loop = old
4301+ end
4302+
4303+ def compile_for_stmt(nid)
4304+ old = @in_loop
4305+ @in_loop = 1
4306+ coll = @nd_collection[nid]
4307+ if coll >= 0
4308+ if @nd_type[coll] == "RangeNode"
4309+ vname = "i"
4310+ tgt = @nd_target[nid]
4311+ if tgt >= 0
4312+ if @nd_type[tgt] == "LocalVariableTargetNode"
4313+ vname = @nd_name[tgt]
4314+ end
4315+ end
4316+ left = compile_expr(@nd_left[coll])
4317+ right = compile_expr(@nd_right[coll])
4318+ emit(" for (lv_" + vname + " = " + left + "; lv_" + vname + " <= " + right + "; lv_" + vname + "++) {")
4319+ @indent = @indent + 1
4320+ compile_stmts_body(@nd_body[nid])
4321+ @indent = @indent - 1
4322+ emit(" }")
4323+ end
4324+ end
4325+ @in_loop = old
4326+ end
4327+
4328+ def compile_case_stmt(nid)
4329+ pred = @nd_predicate[nid]
4330+ if pred < 0
4331+ compile_case_no_pred(nid)
4332+ return
4333+ end
4334+ pred_type = infer_type(pred)
4335+ pred_val = compile_expr(pred)
4336+ tmp = new_temp
4337+ if pred_type == "string"
4338+ emit(" const char *" + tmp + " = " + pred_val + ";")
4339+ else
4340+ emit(" mrb_int " + tmp + " = " + pred_val + ";")
4341+ end
4342+ conds = parse_id_list(@nd_conditions[nid])
4343+ k = 0
4344+ while k < conds.length
4345+ wid = conds[k]
4346+ if @nd_type[wid] == "WhenNode"
4347+ kw = "if"
4348+ if k > 0
4349+ kw = "} else if"
4350+ end
4351+ cond_str = compile_when_conds(wid, tmp, pred_type)
4352+ emit(" " + kw + " (" + cond_str + ") {")
4353+ @indent = @indent + 1
4354+ compile_stmts_body(@nd_body[wid])
4355+ @indent = @indent - 1
4356+ end
4357+ k = k + 1
4358+ end
4359+ ec = @nd_else_clause[nid]
4360+ if ec >= 0
4361+ emit(" } else {")
4362+ @indent = @indent + 1
4363+ compile_stmts_body(@nd_body[ec])
4364+ @indent = @indent - 1
4365+ end
4366+ emit(" }")
4367+ end
4368+
4369+ def compile_case_no_pred(nid)
4370+ conds = parse_id_list(@nd_conditions[nid])
4371+ k = 0
4372+ while k < conds.length
4373+ wid = conds[k]
4374+ if @nd_type[wid] == "WhenNode"
4375+ kw = "if"
4376+ if k > 0
4377+ kw = "} else if"
4378+ end
4379+ wconds = parse_id_list(@nd_conditions[wid])
4380+ cexpr = "0"
4381+ if wconds.length > 0
4382+ cexpr = compile_expr(wconds[0])
4383+ end
4384+ emit(" " + kw + " (" + cexpr + ") {")
4385+ @indent = @indent + 1
4386+ compile_stmts_body(@nd_body[wid])
4387+ @indent = @indent - 1
4388+ end
4389+ k = k + 1
4390+ end
4391+ ec = @nd_else_clause[nid]
4392+ if ec >= 0
4393+ emit(" } else {")
4394+ @indent = @indent + 1
4395+ compile_stmts_body(@nd_body[ec])
4396+ @indent = @indent - 1
4397+ end
4398+ emit(" }")
4399+ end
4400+
4401+ def compile_when_conds(wid, tmp, pred_type)
4402+ wconds = parse_id_list(@nd_conditions[wid])
4403+ result = ""
4404+ k = 0
4405+ while k < wconds.length
4406+ if k > 0
4407+ result = result + " || "
4408+ end
4409+ cid = wconds[k]
4410+ if @nd_type[cid] == "RangeNode"
4411+ left = compile_expr(@nd_left[cid])
4412+ right = compile_expr(@nd_right[cid])
4413+ result = result + "(" + tmp + " >= " + left + " && " + tmp + " <= " + right + ")"
4414+ else
4415+ if pred_type == "string"
4416+ result = result + "strcmp(" + tmp + ", " + compile_expr(cid) + ") == 0"
4417+ else
4418+ result = result + tmp + " == " + compile_expr(cid)
4419+ end
4420+ end
4421+ k = k + 1
4422+ end
4423+ result
4424+ end
4425+
4426+ def compile_return_stmt(nid)
4427+ args_id = @nd_arguments[nid]
4428+ if args_id >= 0
4429+ arg_ids = get_args(args_id)
4430+ if arg_ids.length > 0
4431+ emit(" return " + compile_expr(arg_ids[0]) + ";")
4432+ return
4433+ end
4434+ end
4435+ emit(" return 0;")
4436+ end
4437+
4438+ def compile_call_stmt(nid)
4439+ mname = @nd_name[nid]
4440+ recv = @nd_receiver[nid]
4441+
4442+ if mname == "puts"
4443+ if recv < 0
4444+ compile_puts(nid)
4445+ return
4446+ end
4447+ if recv >= 0
4448+ if @nd_type[recv] == "GlobalVariableReadNode"
4449+ if @nd_name[recv] == "$stderr"
4450+ compile_stderr_puts(nid)
4451+ return
4452+ end
4453+ end
4454+ end
4455+ end
4456+ if mname == "print"
4457+ if recv < 0
4458+ compile_print(nid)
4459+ return
4460+ end
4461+ end
4462+
4463+ # []=
4464+ if mname == "[]="
4465+ if recv >= 0
4466+ compile_bracket_assign(nid)
4467+ return
4468+ end
4469+ end
4470+
4471+ # delete
4472+ if mname == "delete"
4473+ if recv >= 0
4474+ rt = infer_type(recv)
4475+ rc = compile_expr(recv)
4476+ if rt == "str_int_hash"
4477+ emit(" sp_StrIntHash_delete(" + rc + ", " + compile_arg0(nid) + ");")
4478+ return
4479+ end
4480+ if rt == "str_str_hash"
4481+ emit(" sp_StrStrHash_delete(" + rc + ", " + compile_arg0(nid) + ");")
4482+ return
4483+ end
4484+ end
4485+ end
4486+
4487+ # push
4488+ if mname == "push"
4489+ if recv >= 0
4490+ rt = infer_type(recv)
4491+ rc = compile_expr(recv)
4492+ if rt == "int_array"
4493+ emit(" sp_IntArray_push(" + rc + ", " + compile_arg0(nid) + ");")
4494+ return
4495+ end
4496+ if rt == "str_array"
4497+ emit(" sp_StrArray_push(" + rc + ", " + compile_arg0(nid) + ");")
4498+ return
4499+ end
4500+ end
4501+ end
4502+
4503+ # reverse! / sort!
4504+ if mname == "reverse!"
4505+ if recv >= 0
4506+ rt = infer_type(recv)
4507+ rc = compile_expr(recv)
4508+ if rt == "int_array"
4509+ emit(" sp_IntArray_reverse_bang(" + rc + ");")
4510+ return
4511+ end
4512+ end
4513+ end
4514+ if mname == "sort!"
4515+ if recv >= 0
4516+ rt = infer_type(recv)
4517+ rc = compile_expr(recv)
4518+ if rt == "int_array"
4519+ emit(" sp_IntArray_sort_bang(" + rc + ");")
4520+ return
4521+ end
4522+ end
4523+ end
4524+
4525+ # each with block
4526+ if mname == "each"
4527+ if @nd_block[nid] >= 0
4528+ compile_each_block(nid)
4529+ return
4530+ end
4531+ end
4532+
4533+ # times/upto/downto with block
4534+ if mname == "times"
4535+ if @nd_block[nid] >= 0
4536+ compile_times_block(nid)
4537+ return
4538+ end
4539+ end
4540+ if mname == "upto"
4541+ if @nd_block[nid] >= 0
4542+ compile_upto_block(nid)
4543+ return
4544+ end
4545+ end
4546+ if mname == "downto"
4547+ if @nd_block[nid] >= 0
4548+ compile_downto_block(nid)
4549+ return
4550+ end
4551+ end
4552+
4553+ # reduce/inject
4554+ if mname == "reduce"
4555+ if @nd_block[nid] >= 0
4556+ compile_reduce_block(nid)
4557+ return
4558+ end
4559+ end
4560+ if mname == "inject"
4561+ if @nd_block[nid] >= 0
4562+ compile_reduce_block(nid)
4563+ return
4564+ end
4565+ end
4566+
4567+ # reject
4568+ if mname == "reject"
4569+ if @nd_block[nid] >= 0
4570+ compile_reject_block(nid)
4571+ return
4572+ end
4573+ end
4574+
4575+ # loop
4576+ if mname == "loop"
4577+ if @nd_block[nid] >= 0
4578+ old = @in_loop
4579+ @in_loop = 1
4580+ emit(" while (1) {")
4581+ @indent = @indent + 1
4582+ compile_stmts_body(@nd_body[@nd_block[nid]])
4583+ @indent = @indent - 1
4584+ emit(" }")
4585+ @in_loop = old
4586+ return
4587+ end
4588+ end
4589+
4590+ # exit
4591+ if mname == "exit"
4592+ if recv < 0
4593+ val = compile_arg0(nid)
4594+ emit(" exit(" + val + ");")
4595+ return
4596+ end
4597+ end
4598+
4599+ # attr_writer: obj.x = val
4600+ if recv >= 0
4601+ if mname.length > 1
4602+ if mname[mname.length - 1] == "="
4603+ bname = mname[0, mname.length - 1]
4604+ rt = infer_type(recv)
4605+ if is_obj_type(rt) == 1
4606+ rc = compile_expr(recv)
4607+ emit(" " + rc + "->" + bname + " = " + compile_arg0(nid) + ";")
4608+ return
4609+ end
4610+ end
4611+ end
4612+ end
4613+
4614+ # General
4615+ val = compile_expr(nid)
4616+ if val != "0"
4617+ emit(" " + val + ";")
4618+ end
4619+ end
4620+
4621+ def compile_bracket_assign(nid)
4622+ recv = @nd_receiver[nid]
4623+ rt = infer_type(recv)
4624+ rc = compile_expr(recv)
4625+ args_id = @nd_arguments[nid]
4626+ arg_ids = []
4627+ if args_id >= 0
4628+ arg_ids = get_args(args_id)
4629+ end
4630+ idx = "0"
4631+ val = "0"
4632+ if arg_ids.length >= 1
4633+ idx = compile_expr(arg_ids[0])
4634+ end
4635+ if arg_ids.length >= 2
4636+ val = compile_expr(arg_ids[1])
4637+ end
4638+ if rt == "int_array"
4639+ emit(" sp_IntArray_set(" + rc + ", " + idx + ", " + val + ");")
4640+ return
4641+ end
4642+ if rt == "str_array"
4643+ emit(" sp_StrArray_set(" + rc + ", " + idx + ", " + val + ");")
4644+ return
4645+ end
4646+ if rt == "str_int_hash"
4647+ emit(" sp_StrIntHash_set(" + rc + ", " + idx + ", " + val + ");")
4648+ return
4649+ end
4650+ if rt == "str_str_hash"
4651+ emit(" sp_StrStrHash_set(" + rc + ", " + idx + ", " + val + ");")
4652+ return
4653+ end
4654+ end
4655+
4656+ def compile_puts(nid)
4657+ args_id = @nd_arguments[nid]
4658+ if args_id < 0
4659+ emit(" putchar('\\n');")
4660+ return
4661+ end
4662+ arg_ids = get_args(args_id)
4663+ if arg_ids.length == 0
4664+ emit(" putchar('\\n');")
4665+ return
4666+ end
4667+ k = 0
4668+ while k < arg_ids.length
4669+ aid = arg_ids[k]
4670+ at = infer_type(aid)
4671+ val = compile_expr(aid)
4672+ if at == "int"
4673+ emit(" printf(\"%lld\\n\", (long long)" + val + ");")
4674+ else
4675+ if at == "float"
4676+ emit(" printf(\"%g\\n\", " + val + ");")
4677+ else
4678+ if at == "string"
4679+ emit(" { const char *_ps = " + val + "; if (_ps) { fputs(_ps, stdout); if (!*_ps || _ps[strlen(_ps)-1] != '\\n') putchar('\\n'); } else putchar('\\n'); }")
4680+ else
4681+ if at == "bool"
4682+ emit(" puts(" + val + " ? \"true\" : \"false\");")
4683+ else
4684+ if is_obj_type(at) == 1
4685+ cname = at[4, at.length - 4]
4686+ owner = find_method_owner(find_class_idx(cname), "to_s")
4687+ if owner != ""
4688+ sv = "sp_" + owner + "_to_s(" + (owner == cname ? val : "(sp_" + owner + " *)" + val) + ")"
4689+ emit(" { const char *_ps = " + sv + "; if (_ps) { fputs(_ps, stdout); if (!*_ps || _ps[strlen(_ps)-1] != '\\n') putchar('\\n'); } else putchar('\\n'); }")
4690+ else
4691+ emit(" printf(\"%lld\\n\", (long long)(mrb_int)" + val + ");")
4692+ end
4693+ else
4694+ emit(" printf(\"%lld\\n\", (long long)" + val + ");")
4695+ end
4696+ end
4697+ end
4698+ end
4699+ end
4700+ k = k + 1
4701+ end
4702+ end
4703+
4704+ def compile_stderr_puts(nid)
4705+ args_id = @nd_arguments[nid]
4706+ if args_id < 0
4707+ emit(" fputc('\\n', stderr);")
4708+ return
4709+ end
4710+ arg_ids = get_args(args_id)
4711+ k = 0
4712+ while k < arg_ids.length
4713+ at = infer_type(arg_ids[k])
4714+ val = compile_expr(arg_ids[k])
4715+ if at == "string"
4716+ emit(" fprintf(stderr, \"%s\\n\", " + val + ");")
4717+ else
4718+ emit(" fprintf(stderr, \"%lld\\n\", (long long)" + val + ");")
4719+ end
4720+ k = k + 1
4721+ end
4722+ end
4723+
4724+ def compile_print(nid)
4725+ args_id = @nd_arguments[nid]
4726+ if args_id < 0
4727+ return
4728+ end
4729+ arg_ids = get_args(args_id)
4730+ k = 0
4731+ while k < arg_ids.length
4732+ at = infer_type(arg_ids[k])
4733+ val = compile_expr(arg_ids[k])
4734+ if at == "int"
4735+ emit(" printf(\"%lld\", (long long)" + val + ");")
4736+ else
4737+ if at == "string"
4738+ emit(" fputs(" + val + ", stdout);")
4739+ else
4740+ emit(" printf(\"%lld\", (long long)" + val + ");")
4741+ end
4742+ end
4743+ k = k + 1
4744+ end
4745+ end
4746+
4747+ def get_block_param(nid, idx)
4748+ blk = @nd_block[nid]
4749+ if blk < 0
4750+ return ""
4751+ end
4752+ params = @nd_parameters[blk]
4753+ if params < 0
4754+ return ""
4755+ end
4756+ inner = @nd_parameters[params]
4757+ if inner < 0
4758+ return ""
4759+ end
4760+ reqs = parse_id_list(@nd_requireds[inner])
4761+ if idx < reqs.length
4762+ return @nd_name[reqs[idx]]
4763+ end
4764+ ""
4765+ end
4766+
4767+ def compile_each_block(nid)
4768+ old = @in_loop
4769+ @in_loop = 1
4770+ rt = infer_type(@nd_receiver[nid])
4771+ rc = compile_expr(@nd_receiver[nid])
4772+ bp1 = get_block_param(nid, 0)
4773+ bp2 = get_block_param(nid, 1)
4774+ if bp1 == ""
4775+ bp1 = "_x"
4776+ end
4777+
4778+ if rt == "int_array"
4779+ tmp = new_temp
4780+ emit(" for (mrb_int " + tmp + " = 0; " + tmp + " < sp_IntArray_length(" + rc + "); " + tmp + "++) {")
4781+ emit(" lv_" + bp1 + " = sp_IntArray_get(" + rc + ", " + tmp + ");")
4782+ @indent = @indent + 1
4783+ compile_stmts_body(@nd_body[@nd_block[nid]])
4784+ @indent = @indent - 1
4785+ emit(" }")
4786+ end
4787+ if rt == "str_array"
4788+ tmp = new_temp
4789+ emit(" for (mrb_int " + tmp + " = 0; " + tmp + " < sp_StrArray_length(" + rc + "); " + tmp + "++) {")
4790+ emit(" lv_" + bp1 + " = sp_StrArray_get(" + rc + ", " + tmp + ");")
4791+ @indent = @indent + 1
4792+ compile_stmts_body(@nd_body[@nd_block[nid]])
4793+ @indent = @indent - 1
4794+ emit(" }")
4795+ end
4796+ if rt == "str_int_hash"
4797+ tmp = new_temp
4798+ emit(" for (mrb_int " + tmp + " = 0; " + tmp + " < " + rc + "->len; " + tmp + "++) {")
4799+ emit(" lv_" + bp1 + " = " + rc + "->keys[" + tmp + "];")
4800+ if bp2 != ""
4801+ emit(" lv_" + bp2 + " = " + rc + "->vals[" + tmp + "];")
4802+ end
4803+ @indent = @indent + 1
4804+ compile_stmts_body(@nd_body[@nd_block[nid]])
4805+ @indent = @indent - 1
4806+ emit(" }")
4807+ end
4808+ if rt == "str_str_hash"
4809+ tmp = new_temp
4810+ emit(" for (mrb_int " + tmp + " = 0; " + tmp + " < " + rc + "->len; " + tmp + "++) {")
4811+ emit(" lv_" + bp1 + " = " + rc + "->keys[" + tmp + "];")
4812+ if bp2 != ""
4813+ emit(" lv_" + bp2 + " = " + rc + "->vals[" + tmp + "];")
4814+ end
4815+ @indent = @indent + 1
4816+ compile_stmts_body(@nd_body[@nd_block[nid]])
4817+ @indent = @indent - 1
4818+ emit(" }")
4819+ end
4820+ @in_loop = old
4821+ end
4822+
4823+ def compile_times_block(nid)
4824+ old = @in_loop
4825+ @in_loop = 1
4826+ rc = compile_expr(@nd_receiver[nid])
4827+ bp1 = get_block_param(nid, 0)
4828+ tmp = new_temp
4829+ emit(" for (mrb_int " + tmp + " = 0; " + tmp + " < " + rc + "; " + tmp + "++) {")
4830+ if bp1 != ""
4831+ emit(" lv_" + bp1 + " = " + tmp + ";")
4832+ end
4833+ @indent = @indent + 1
4834+ compile_stmts_body(@nd_body[@nd_block[nid]])
4835+ @indent = @indent - 1
4836+ emit(" }")
4837+ @in_loop = old
4838+ end
4839+
4840+ def compile_upto_block(nid)
4841+ old = @in_loop
4842+ @in_loop = 1
4843+ rc = compile_expr(@nd_receiver[nid])
4844+ lim = compile_arg0(nid)
4845+ bp1 = get_block_param(nid, 0)
4846+ tmp = new_temp
4847+ emit(" for (mrb_int " + tmp + " = " + rc + "; " + tmp + " <= " + lim + "; " + tmp + "++) {")
4848+ if bp1 != ""
4849+ emit(" lv_" + bp1 + " = " + tmp + ";")
4850+ end
4851+ @indent = @indent + 1
4852+ compile_stmts_body(@nd_body[@nd_block[nid]])
4853+ @indent = @indent - 1
4854+ emit(" }")
4855+ @in_loop = old
4856+ end
4857+
4858+ def compile_downto_block(nid)
4859+ old = @in_loop
4860+ @in_loop = 1
4861+ rc = compile_expr(@nd_receiver[nid])
4862+ lim = compile_arg0(nid)
4863+ bp1 = get_block_param(nid, 0)
4864+ tmp = new_temp
4865+ emit(" for (mrb_int " + tmp + " = " + rc + "; " + tmp + " >= " + lim + "; " + tmp + "--) {")
4866+ if bp1 != ""
4867+ emit(" lv_" + bp1 + " = " + tmp + ";")
4868+ end
4869+ @indent = @indent + 1
4870+ compile_stmts_body(@nd_body[@nd_block[nid]])
4871+ @indent = @indent - 1
4872+ emit(" }")
4873+ @in_loop = old
4874+ end
4875+
4876+ def compile_reduce_block(nid)
4877+ rc = compile_expr(@nd_receiver[nid])
4878+ init_val = compile_arg0(nid)
4879+ bp1 = get_block_param(nid, 0)
4880+ bp2 = get_block_param(nid, 1)
4881+ if bp1 == ""
4882+ bp1 = "_acc"
4883+ end
4884+ if bp2 == ""
4885+ bp2 = "_x"
4886+ end
4887+ emit(" lv_" + bp1 + " = " + init_val + ";")
4888+ rt = infer_type(@nd_receiver[nid])
4889+ if rt == "int_array"
4890+ tmp = new_temp
4891+ emit(" for (mrb_int " + tmp + " = 0; " + tmp + " < sp_IntArray_length(" + rc + "); " + tmp + "++) {")
4892+ emit(" lv_" + bp2 + " = sp_IntArray_get(" + rc + ", " + tmp + ");")
4893+ @indent = @indent + 1
4894+ blk = @nd_block[nid]
4895+ if blk >= 0
4896+ body = @nd_body[blk]
4897+ if body >= 0
4898+ stmts = get_stmts(body)
4899+ if stmts.length > 0
4900+ last = stmts[stmts.length - 1]
4901+ val = compile_expr(last)
4902+ emit(" lv_" + bp1 + " = " + val + ";")
4903+ end
4904+ end
4905+ end
4906+ @indent = @indent - 1
4907+ emit(" }")
4908+ end
4909+ end
4910+
4911+ def compile_reject_block(nid)
4912+ rc = compile_expr(@nd_receiver[nid])
4913+ bp1 = get_block_param(nid, 0)
4914+ if bp1 == ""
4915+ bp1 = "_x"
4916+ end
4917+ rt = infer_type(@nd_receiver[nid])
4918+ if rt == "int_array"
4919+ @needs_int_array = 1
4920+ tmp_arr = new_temp
4921+ emit(" sp_IntArray *" + tmp_arr + " = sp_IntArray_new();")
4922+ tmp_i = new_temp
4923+ emit(" for (mrb_int " + tmp_i + " = 0; " + tmp_i + " < sp_IntArray_length(" + rc + "); " + tmp_i + "++) {")
4924+ emit(" lv_" + bp1 + " = sp_IntArray_get(" + rc + ", " + tmp_i + ");")
4925+ @indent = @indent + 1
4926+ blk = @nd_block[nid]
4927+ if blk >= 0
4928+ body = @nd_body[blk]
4929+ if body >= 0
4930+ stmts = get_stmts(body)
4931+ if stmts.length > 0
4932+ last = stmts[stmts.length - 1]
4933+ cond = compile_expr(last)
4934+ emit(" if (!(" + cond + ")) sp_IntArray_push(" + tmp_arr + ", lv_" + bp1 + ");")
4935+ end
4936+ end
4937+ end
4938+ @indent = @indent - 1
4939+ emit(" }")
4940+ end
4941+ end
4942+
4943+ def compile_stmts_body(nid)
4944+ if nid < 0
4945+ return
4946+ end
4947+ stmts = get_stmts(nid)
4948+ k = 0
4949+ while k < stmts.length
4950+ compile_stmt(stmts[k])
4951+ k = k + 1
4952+ end
4953+ end
4954+
4955+ def compile_body_return(body_id, return_type)
4956+ if body_id < 0
4957+ if return_type != "void"
4958+ emit(" return " + c_default_val(return_type) + ";")
4959+ end
4960+ return
4961+ end
4962+ stmts = get_stmts(body_id)
4963+ if stmts.length == 0
4964+ if return_type != "void"
4965+ emit(" return " + c_default_val(return_type) + ";")
4966+ end
4967+ return
4968+ end
4969+ # All but last
4970+ i = 0
4971+ while i < stmts.length - 1
4972+ compile_stmt(stmts[i])
4973+ i = i + 1
4974+ end
4975+ last = stmts[stmts.length - 1]
4976+ if @nd_type[last] == "ReturnNode"
4977+ compile_return_stmt(last)
4978+ return
4979+ end
4980+ if @nd_type[last] == "IfNode"
4981+ compile_if_return(last, return_type)
4982+ return
4983+ end
4984+ if @nd_type[last] == "CaseNode"
4985+ compile_case_return(last, return_type)
4986+ return
4987+ end
4988+ if @nd_type[last] == "WhileNode"
4989+ compile_while_stmt(last)
4990+ if return_type != "void"
4991+ emit(" return " + c_default_val(return_type) + ";")
4992+ end
4993+ return
4994+ end
4995+ if return_type != "void"
4996+ emit(" return " + compile_expr(last) + ";")
4997+ else
4998+ compile_stmt(last)
4999+ end
5000+ end
5001+
5002+ def compile_if_return(nid, rt)
5003+ cond = compile_expr(@nd_predicate[nid])
5004+ emit(" if (" + cond + ") {")
5005+ @indent = @indent + 1
5006+ body = @nd_body[nid]
5007+ if body >= 0
5008+ compile_body_return(body, rt)
5009+ else
5010+ if rt != "void"
5011+ emit(" return " + c_default_val(rt) + ";")
5012+ end
5013+ end
5014+ @indent = @indent - 1
5015+ sub = @nd_subsequent[nid]
5016+ if sub >= 0
5017+ if @nd_type[sub] == "ElseNode"
5018+ emit(" } else {")
5019+ @indent = @indent + 1
5020+ eb = @nd_body[sub]
5021+ if eb >= 0
5022+ compile_body_return(eb, rt)
5023+ else
5024+ if rt != "void"
5025+ emit(" return " + c_default_val(rt) + ";")
5026+ end
5027+ end
5028+ @indent = @indent - 1
5029+ else
5030+ emit(" } else")
5031+ compile_if_return(sub, rt)
5032+ return
5033+ end
5034+ else
5035+ if rt != "void"
5036+ emit(" } else {")
5037+ emit(" return " + c_default_val(rt) + ";")
5038+ end
5039+ end
5040+ emit(" }")
5041+ end
5042+
5043+ def compile_case_return(nid, rt)
5044+ pred = @nd_predicate[nid]
5045+ if pred >= 0
5046+ pred_type = infer_type(pred)
5047+ pred_val = compile_expr(pred)
5048+ tmp = new_temp
5049+ if pred_type == "string"
5050+ emit(" const char *" + tmp + " = " + pred_val + ";")
5051+ else
5052+ emit(" mrb_int " + tmp + " = " + pred_val + ";")
5053+ end
5054+ conds = parse_id_list(@nd_conditions[nid])
5055+ k = 0
5056+ while k < conds.length
5057+ wid = conds[k]
5058+ if @nd_type[wid] == "WhenNode"
5059+ kw = "if"
5060+ if k > 0
5061+ kw = "} else if"
5062+ end
5063+ cond_str = compile_when_conds(wid, tmp, pred_type)
5064+ emit(" " + kw + " (" + cond_str + ") {")
5065+ @indent = @indent + 1
5066+ compile_body_return(@nd_body[wid], rt)
5067+ @indent = @indent - 1
5068+ end
5069+ k = k + 1
5070+ end
5071+ else
5072+ conds = parse_id_list(@nd_conditions[nid])
5073+ k = 0
5074+ while k < conds.length
5075+ wid = conds[k]
5076+ kw = "if"
5077+ if k > 0
5078+ kw = "} else if"
5079+ end
5080+ wconds = parse_id_list(@nd_conditions[wid])
5081+ cexpr = "0"
5082+ if wconds.length > 0
5083+ cexpr = compile_expr(wconds[0])
5084+ end
5085+ emit(" " + kw + " (" + cexpr + ") {")
5086+ @indent = @indent + 1
5087+ compile_body_return(@nd_body[wid], rt)
5088+ @indent = @indent - 1
5089+ k = k + 1
5090+ end
5091+ end
5092+ ec = @nd_else_clause[nid]
5093+ if ec >= 0
5094+ emit(" } else {")
5095+ @indent = @indent + 1
5096+ compile_body_return(@nd_body[ec], rt)
5097+ @indent = @indent - 1
5098+ end
5099+ emit(" }")
5100+ end
5101+end
5102+
5103+# ---- Main ----
5104+ast_file = ARGV[0]
5105+out_file = ARGV[1]
5106+
5107+if ast_file == nil
5108+ $stderr.puts "Usage: ruby spinel_codegen.rb ast.txt output.c"
5109+ exit(1)
5110+end
5111+
5112+data = File.read(ast_file)
5113+compiler = Compiler.new
5114+compiler.read_text_ast(data)
5115+compiler.compile
5116+
5117+if out_file != nil
5118+ File.write(out_file, compiler.out)
5119+else
5120+ print compiler.out
5121+end