`LanguageParser.Parse` infinite loops on malformed input

Ouverte Adaptée aux débutants
#48 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Évaluation

Difficulté
2/5
Temps estimé
1-3 heures
Accessibilité débutants
72/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
csharp
Domaine
compilers

Piste de recherche

Commencez à ColorCode.Parsing.LanguageParser.Parse, la boucle qui pilote Match.NextMatch() et suppose que la position de scan avance. Exécutez l’extrait de console de repro minimal de l’issue avec le langage json pour observer qu’il se bloque, puis ajoutez une garde de non-progression (sortir de la boucle lorsque l’index et la longueur de la correspondance ne bougent pas) afin que l’entrée malformée se dégrade au lieu de tourner en boucle. Terminé lorsque le repro revient et que les tests existants du parser passent toujours.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

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.
Langage dominant
C#
Étoiles
267
Forks
59
Métriques de merge des PR
Aucune PR mergée en 30 j

Préparer son environnement

Ce projet ne fournit ni conteneur de développement, ni Dockerfile, ni guide de contribution : l'installation est à votre charge. Commencez par son README, et consultez notre guide de la première contribution pour les étapes générales.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de CommunityToolkit/ColorCode-Universal

Toutes les issues de CommunityToolkit/ColorCode-Universal

Issues similaires

Plus d'issues C#

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.