`LanguageParser.Parse` infinite loops on malformed input

Abierto Apto para principiantes
#48 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
72/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
csharp
Área
compilers

Línea de trabajo

Empieza en ColorCode.Parsing.LanguageParser.Parse, el bucle que impulsa Match.NextMatch() y supone que la posición de escaneo avanza. Ejecuta el fragmento de consola de repro mínimo del issue con el lenguaje json para ver que se cuelga, y luego añade una guarda de no progreso (sal del bucle cuando el índice y la longitud de la coincidencia no cambian) para que la entrada malformada degrade en lugar de girar indefinidamente. Terminado cuando el repro regrese y las pruebas existentes del parser sigan pasando.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

AI Disclosure: The bug report below is being co-written by AI.


ColorCode.Core 2.0.15 (CommunityToolkit/ColorCode-Universal)

ColorCode.Parsing.LanguageParser.Parse enters a non-terminating loop for certain malformed source strings, burning a CPU core forever on the calling thread. In our case this was on the UI thread, so the entire app froze.

Why is this important

There are many cases where there can be invalid input passed into the library. For example, AI chat rendering that AI writes the code that need to be syntax highlighted.

Reproduction

Highlighting the following source with the json language:

state.status = "completed"
state.metadata = { "status": "running", "shellID": "sh_1df528…", "pid": 133242 }
content = [
  "Command moved to the background (shell ID: sh_1df528…).…\nOutput is streaming to: …/sh_1df528…out",
  "You will be notified automatically when the command finishes.…"
]

The body is not valid JSON. LanguageParser.Parse does not return.

Minimal repro:

using System;
using System.Collections.Generic;
using System.Threading;
using ColorCode;
using ColorCode.Common;
using ColorCode.Compilation;
using ColorCode.Parsing;

var malformed = """
    state.status = "completed"
    state.metadata = { "status": "running", "shellID": "sh_1df528…", "pid": 133242 }
    content = [
      "Command moved to the background (shell ID: sh_1df528…).…\nOutput is streaming to: …/sh_1df528…out",
      "You will be notified automatically when the command finishes.…"
    ]
    """;

var compiler = new LanguageCompiler(new Dictionary<string, CompiledLanguage>(), new ReaderWriterLockSlim());
var repo = new LanguageRepository(new Dictionary<string, ILanguage> { ["json"] = Languages.FindById("json") });
var parser = new LanguageParser(compiler, repo);

parser.Parse(malformed, Languages.FindById("json"), (parsed, scopes) => { }); // never returns
Expected behavior

Parse returns (the input is simply malformed; highlighting should degrade gracefully or throw a parse error, not hang).

Actual behavior

Parse spins forever in Regex.Match.NextMatch() and never terminates. The thread is unkillable and consumes 100% CPU indefinitely.

Stack trace (from a real hang)
System.Text.RegularExpressions.RegexInterpreter.TryMatchAtCurrentPosition
System.Text.RegularExpressions.RegexInterpreter.Scan
System.Text.RegularExpressions.Regex.ScanInternal
System.Text.RegularExpressions.Regex.RunSingleMatch
System.Text.RegularExpressions.Match.NextMatch        // non-terminating loop
ColorCode.Parsing.LanguageParser.Parse
Root-cause hypothesis

A language rule matches without advancing the scan position, so Match.NextMatch() keeps returning matches at the same position forever. I suspect one of the json language's regex rules can produce a zero-width match on this input, causing the loop in LanguageParser.Parse (which drives the regex and relies on position advancing) to never make progress.

Suggested fix area
  • LanguageParser.Parse: guard against no-progress iterations (e.g. bail if match.Index / match length doesn't advance), or add a safety bound on iterations.
  • Alternatively, consider a timeout/token the caller can use — though note .NET has no way to abort a non-terminating regex, so a prevention guard (zero-width match detection) is more robust than cancellation.
Lenguaje dominante
C#
Estrellas
267
Forks
59
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de CommunityToolkit/ColorCode-Universal

Todos los issues de CommunityToolkit/ColorCode-Universal

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.