diff --git a/src/parser/parser_types.nim b/src/parser/parser_types.nim index ee6b028..797cec9 100644 --- a/src/parser/parser_types.nim +++ b/src/parser/parser_types.nim @@ -268,6 +268,24 @@ proc `$`*(x: ParserToken): string = value: {tokenStringValue(x)}, )""" +const LEFT_HIGHLIGHT_CHAR = ">>" +const RIGHT_HIGHLIGHT_CHAR = "<<" +func highlightStreamPosition(stream: string, position: int): string = + if position < 0: return stream + if position > stream.len - 1: return stream + + let aIndex = position - 1 + let a = if aIndex < 0: "" + else: stream[0..aIndex] + + let ch = stream[position] + + let bIndex = position + 1 + let b = if bIndex > stream.len - 1: "" + else: stream[bIndex..stream.len - 1] + + return a & LEFT_HIGHLIGHT_CHAR & ch & RIGHT_HIGHLIGHT_CHAR & b + proc `$`*(x: ParserState): string = &"""ParserState( stream: "{x.stream}", @@ -311,3 +329,14 @@ proc `$`*(x: ParserError): string = {errSpace}^ Expected 'EndOfString' at {index} but got {original.len - 1}""" else: "ParseError" + +when isMainModule: + block highlightStreamPosition: + let s = "abc" + # Out of bounds + assert s.highlightStreamPosition(-1) == s + assert s.highlightStreamPosition(s.len) == s + # Regular highlighting + assert s.highlightStreamPosition(0) == LEFT_HIGHLIGHT_CHAR & "a" & RIGHT_HIGHLIGHT_CHAR & "bc" + assert s.highlightStreamPosition(1) == "a" & LEFT_HIGHLIGHT_CHAR & "b" & RIGHT_HIGHLIGHT_CHAR & "c" + assert s.highlightStreamPosition(2) == "ab" & LEFT_HIGHLIGHT_CHAR & "c" & RIGHT_HIGHLIGHT_CHAR