Changes from PR review
Add assertions to ensure that the comment regions and the type regions are suitable nested.
@@ -122,30 +122,34 @@ function translator.translate(input, prog_ast)
local instance = Translator.new(input)
instance:add_forward_declarations(prog_ast)
- local j = 1 -- The index of the current comment region.
+ -- Erase all type regions, while preserving comments
+ -- As a sanity check, assert that the comment regions are either inside or outside the type
+ -- regions, not crossing the boundaries.
+ local j = 1
+ local comments = prog_ast.comment_regions
for _, region in ipairs(prog_ast.regions) do
local start_index = region[1]
+ local end_index = region[2]
- -- Ignore the comments before the current region.
- while j <= #prog_ast.comment_regions and start_index > prog_ast.comment_regions[j][1] do
+ -- Skip over the comments before the current region.
+ while j <= #comments and comments[j][2] < start_index do
j = j + 1
end
- -- Multiple comment regions can span within a single region.
- while j <= #prog_ast.comment_regions do
- local comment = prog_ast.comment_regions[j]
- -- Ensure that the current comment does not appear before the current region.
- assert(start_index <= comment[1])
- -- Determine if the comment appears within the current region.
- if comment[2] <= region[2] then
- instance:erase_region(start_index, comment[1] - 1)
- start_index = comment[2] + 1
+ -- Preserve the comments inside the current region
+ while j <= #comments and comments[j][2] <= end_index do
+ assert(start_index < comments[j][1])
+ instance:erase_region(start_index, comments[j][1] - 1)
+ start_index = comments[j][2] + 1
j = j + 1
- else
- break
end
+
+ -- Ensure that the next comment is outside the current region
+ if j <= #comments then
+ assert(end_index < comments[j][1])
end
- instance:erase_region(start_index, region[2])
+
+ instance:erase_region(start_index, end_index)
end
-- Whatever characters that were not included in the partials should be added.
