package org.spoofax.jsglr.client.incremental;

import static java.lang.Math.min;
import static org.spoofax.jsglr.client.incremental.IncrementalSGLR.DEBUG;

/**
 * A helper class that expands the damage region
 * for incremental parsing if block comments
 * are involved.
 * 
 * @author Lennart Kats <lennart add lclnet.nl>
 */
public class CommentDamageHandler {
	
	public static final CommentDamageHandler C_STYLE = new CommentDamageHandler("/*", "*/");

	private final String commentStart;
	
	private final String commentEnd;

	public CommentDamageHandler(String commentStart, String commentEnd) {
		this.commentStart = commentStart;
		this.commentEnd = commentEnd;
	}
	
	public int getExpandedDamageRegionEnd(String input, int damageStart, int damageEnd) {
		// Move back to '/' if user just entered '*'
		damageStart = min(0, damageStart - commentStart.length() + 1);
		
		int commentStartOffset = input.lastIndexOf(commentStart, damageEnd);
		if (commentStartOffset >= damageStart) {
			int result = input.indexOf(commentEnd, commentStartOffset + commentStart.length() + 1);
			if (result == -1) {
				if (DEBUG) System.out.println("Unterminated comment ignored"); // try to recover locally
				return damageEnd;
			} else {
				return result;
			}
		} else {
			return damageEnd;
		}
			
	}
}

@@ -70,18 +70,18 @@
 g.Math.m
-in
+ax
 ;%0Aimport
@@ -238,16 +238,24 @@
 f block 
+or line 
 comments
@@ -455,16 +455,119 @@
 , %22*/%22);
+%0A%09%0A%09public static final CommentDamageHandler ONLY_LINE_COMMENTS = new CommentDamageHandler(null, null);
 %0A%0A%09priva
@@ -928,18 +928,18 @@
 tart = m
-in
+ax
 (0, dama
@@ -976,16 +976,195 @@
 ) + 1);%0A
+%09%09// Move to following newline, in case line comments are involved%0A%09%09damageEnd = max(damageEnd, input.indexOf('%5Cn', damageEnd));%0A%09%09%0A%09%09if (commentStart == null) return damageEnd; %0A
 %09%09%0A%09%09int

Support line comments in CommentDamageHandler.