1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
| unit CodeToImage.CleanPas;
interface
uses
{Winapi}
Winapi.Windows,
{System}
System.SysUtils, System.Classes, System.Generics.Collections, System.Types;
procedure CleanPas(const IntSrc: TStrings; OutScr: TStrings);
implementation
type
// État du parseur pour gérer les chaînes, commentaires et directives
TState = (stNormal, stString, stCommentBrace, stDirective);
var
// Dictionnaire de normalisation :
// clé = nom en minuscules, valeur = forme canonique
FormattedMap: TDictionary<string, string>;
{ Charge la liste canonique depuis la ressource RCDATA. }
procedure LoadFormattedNamesFromResource(const ResName: string);
var
RS: TResourceStream;
SL: TStringList;
I: Integer;
key: string;
begin
if Assigned(FormattedMap) then
Exit;
// Création du dictionnaire
FormattedMap := TDictionary<string, string>.Create;
RS := nil;
SL := TStringList.Create;
try
// Lecture de la ressource RCDATA dans un TStringList
RS := TResourceStream.Create(HInstance, ResName, RT_RCDATA);
SL.LoadFromStream(RS, TEncoding.UTF8);
// Remplissage du dictionnaire
for I := 0 to SL.Count - 1 do
begin
if SL[I].Trim = '' then
Continue;
key := LowerCase(SL[I].Trim);
if not FormattedMap.ContainsKey(key) then
FormattedMap.Add(key, SL[I].Trim);
end;
finally
RS.Free;
SL.Free;
end;
end;
{ Renvoie la forme canonique d'un identifiant si elle existe dans FormattedMap,
sinon renvoie l'identifiant tel quel. }
function NormalizeIdentifier(const Ident: string): string;
var
key: string;
begin
key := LowerCase(Ident);
if Assigned(FormattedMap) and FormattedMap.TryGetValue(key, Result) then
Exit
else
Result := Ident;
end;
{ Retourne vrai si le caractère peut faire partie d'un opérateur (utilisé pour la mise en forme des espaces) }
function IsOpChar(Ch: Char): Boolean; inline;
begin
Result := CharInSet(Ch, [':', '+', '-', '*', '/', '=', '<', '>', '.']);
end;
{ Renvoie le caractère à la position sPos dans la chaîne S, ou #0 si hors limites }
function PeekCharAt(const S: string; sPos: Integer): Char; inline;
begin
if (sPos >= 1) and (sPos <= Length(S)) then
Result := S[sPos]
else
Result := #0;
end;
{ Tente de reconnaître un opérateur multi-caractères à partir de sPos.
Retourne True et place l'opérateur dans sOp si trouvé. }
function MatchOpInLine(const S: string; sPos: Integer; out sOp: string)
: Boolean;
begin
sOp := '';
if sPos > Length(S) then
Exit(False);
if (sPos + 1 <= Length(S)) and (Copy(S, sPos, 2) = ':=') then
begin
sOp := ':=';
Exit(True);
end;
if (sPos + 1 <= Length(S)) and (Copy(S, sPos, 2) = '<=') then
begin
sOp := '<=';
Exit(True);
end;
if (sPos + 1 <= Length(S)) and (Copy(S, sPos, 2) = '>=') then
begin
sOp := '>=';
Exit(True);
end;
if (sPos + 1 <= Length(S)) and (Copy(S, sPos, 2) = '<>') then
begin
sOp := '<>';
Exit(True);
end;
if (sPos + 1 <= Length(S)) and (Copy(S, sPos, 2) = '..') then
begin
sOp := '..';
Exit(True);
end;
if CharInSet(S[sPos], ['+', '-', '*', '/', '=', '<', '>']) then
begin
sOp := S[sPos];
Exit(True);
end;
Result := False;
end;
{ Procédure principale : nettoie et formate le code.
- Normalise les identifiants en utilisant FormattedMap (chargée depuis la ressource)
- Gère les espaces, ponctuation, opérateurs, chaînes, commentaires et directives
- Traite les génériques (TDictionary<string,string>) }
procedure CleanPas(const IntSrc: TStrings; OutScr: TStrings);
var
I, L, Idx, IndentLen: Integer;
LineStr, LeadingIndent, FinalLine, Op: string;
Ch, NextCh: Char;
State: TState;
SpacePending: Boolean;
Sb: TStringBuilder;
TempLines: TStringList;
BlankCount: Integer;
// Profondeur de générique (< ... >) ; 0 = hors générique
GenericDepth: Integer;
{ Ajoute un espace en attente si SpacePending est vrai }
procedure AppendPendingSpace;
begin
if SpacePending then
begin
Sb.Append(' ');
SpacePending := False;
end;
end;
{ Assure qu'il y a exactement un espace final (utilisé après certains tokens) }
procedure EnsureSingleTrailingSpace;
begin
if (Sb.Length = 0) then
Sb.Append(' ')
else if Sb.Chars[Sb.Length - 1] <> ' ' then
Sb.Append(' ');
end;
begin
if OutScr = nil then
Exit;
LoadFormattedNamesFromResource('NormalizeIdent');
OutScr.BeginUpdate;
try
OutScr.Clear;
if (IntSrc = nil) or (IntSrc.Count = 0) then
Exit;
Sb := TStringBuilder.Create;
TempLines := TStringList.Create;
try
// Parcours ligne par ligne
for I := 0 to IntSrc.Count - 1 do
begin
LineStr := IntSrc[I];
IndentLen := 0;
// Conserver l'indentation initiale (tabs et espaces)
while (IndentLen < Length(LineStr)) and
CharInSet(LineStr[IndentLen + 1], [#9, ' ']) do
Inc(IndentLen);
LeadingIndent := Copy(LineStr, 1, IndentLen);
Sb.Clear;
Sb.Append(LeadingIndent);
State := stNormal;
SpacePending := False;
GenericDepth := 0;
L := Length(LineStr);
Idx := IndentLen + 1;
// Parcours caractère par caractère
while Idx <= L do
begin
Ch := LineStr[Idx];
NextCh := PeekCharAt(LineStr, Idx + 1);
case State of
stNormal:
begin
// Début de chaîne littérale
if Ch = '''' then
begin
AppendPendingSpace;
Sb.Append('''');
State := stString;
Inc(Idx);
Continue;
end;
// Commentaire // jusqu'à la fin de la ligne
if (Ch = '/') and (NextCh = '/') then
begin
AppendPendingSpace;
Sb.Append(Copy(LineStr, Idx, L - Idx + 1));
Break; // fin de la ligne
end;
// Commentaire ou directive entre accolades { ... }
if Ch = '{' then
begin
var
j := Idx + 1;
while (j <= L) and (LineStr[j] = ' ') do
Inc(j);
if (j <= L) and (LineStr[j] = '$') then
begin
// directive du compilateur {$...}
AppendPendingSpace;
Sb.Append('{');
State := stDirective;
Inc(Idx);
Continue;
end
else
begin
// commentaire normal { ... }
AppendPendingSpace;
Sb.Append('{');
State := stCommentBrace;
Inc(Idx);
Continue;
end;
end;
// Espaces : on marque qu'un espace est en attente et on l'ajoute au prochain token significatif
if CharInSet(Ch, [' ']) then
begin
SpacePending := True;
Inc(Idx);
Continue;
end;
// Point-virgule : fin d'instruction ; on gère la coupure de ligne si nécessaire
if Ch = ';' then
begin
SpacePending := False;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
Sb.Append(';');
Inc(Idx);
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
if Idx <= L then
begin
// Si la ligne continue après le ; on ajoute la ligne courante à TempLines et on recommence
FinalLine := Sb.ToString;
while (Length(FinalLine) > 0) and
(FinalLine[Length(FinalLine)] = ' ') do
SetLength(FinalLine, Length(FinalLine) - 1);
TempLines.Add(FinalLine);
Sb.Clear;
Sb.Append(LeadingIndent);
SpacePending := False;
Continue;
end
else
begin
// fin de ligne : assurer un espace final unique
EnsureSingleTrailingSpace;
Continue;
end;
end;
// --- Gestion des génériques : '<', '>' et virgule interne ---
if Ch = '<' then
begin
// Annule tout espace en attente et supprime un espace déjà ajouté avant '<'
SpacePending := False;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
// Entrée en générique : pas d'espace avant '<'
Sb.Append('<');
Inc(GenericDepth);
Inc(Idx);
// Supprimer les espaces immédiatement après '<' dans la source
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
Continue;
end;
if Ch = '>' then
begin
if GenericDepth > 0 then
begin
// Supprimer les espaces avant '>' dans le résultat si présents
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
Sb.Append('>');
Dec(GenericDepth);
Inc(Idx);
// Supprimer les espaces immédiatement après '>' dans la source
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
Continue;
end;
end;
// Virgule : si on est dans un générique, ne pas forcer d'espace après la virgule
if Ch = ',' then
begin
SpacePending := False;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
Sb.Append(',');
Inc(Idx);
if GenericDepth > 0 then
begin
// supprimer les espaces après la virgule dans un générique
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
end
else
begin
EnsureSingleTrailingSpace;
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
end;
Continue;
end;
// --- Gestion spécifique du point '.' et de l'opérateur '..' ---
if Ch = '.' then
begin
// opérateur intervalle '..'
if NextCh = '.' then
begin
AppendPendingSpace;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] <> ' ') then
Sb.Append(' ');
Sb.Append('..');
Inc(Idx, 2);
if (Idx <= L) and not CharInSet(LineStr[Idx],
[' ', ';', ',', ')', ']', ':']) then
Sb.Append(' ');
Continue;
end
else
begin
// séparateur '.' : AUCUN espace avant ni après
SpacePending := False;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
Sb.Append('.');
Inc(Idx);
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
Continue;
end;
end;
// Deux points : gestion spéciale pour ':=' sinon formatage normal
if Ch = ':' then
begin
if (NextCh = '=') then
begin
AppendPendingSpace;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] <> ' ') then
Sb.Append(' ');
Sb.Append(':=');
Inc(Idx, 2);
if (Idx <= L) and not CharInSet(LineStr[Idx],
[' ', ';', ',', ')', ']', ':']) then
Sb.Append(' ');
Continue;
end
else
begin
SpacePending := False;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
Sb.Append(':');
EnsureSingleTrailingSpace;
Inc(Idx);
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
Continue;
end;
end;
// Fermeture de parenthèse ou crochet : pas d'espace avant, espace après
if CharInSet(Ch, [')', ']']) then
begin
SpacePending := False;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] = ' ') then
Sb.Length := Sb.Length - 1;
Sb.Append(Ch);
EnsureSingleTrailingSpace;
Inc(Idx);
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
Continue;
end;
// Ouverture de parenthèse ou crochet : espace avant si nécessaire, pas d'espace après
if CharInSet(Ch, ['(', '[']) then
begin
AppendPendingSpace;
Sb.Append(Ch);
Inc(Idx);
while (Idx <= L) and CharInSet(LineStr[Idx], [' ']) do
Inc(Idx);
Continue;
end;
// Opérateurs : si on est dans un générique, on ignore la détection d'opérateurs pour '<' et '>'
if IsOpChar(Ch) then
begin
if GenericDepth = 0 then
begin
if MatchOpInLine(LineStr, Idx, Op) then
begin
AppendPendingSpace;
if (Sb.Length > 0) and (Sb.Chars[Sb.Length - 1] <> ' ')
then
Sb.Append(' ');
Sb.Append(Op);
Inc(Idx, Length(Op));
if (Idx <= L) and not CharInSet(LineStr[Idx],
[' ', ';', ',', ')', ']', ':']) then
Sb.Append(' ');
Continue;
end;
end;
end;
// Détection d'un identifiant complet (lettre ou underscore suivi de lettres/chiffres/_)
// On normalise l'identifiant via NormalizeIdentifier avant de l'ajouter
if CharInSet(Ch, ['A' .. 'Z', 'a' .. 'z', '_']) then
begin
var
startIdx := Idx;
Inc(Idx);
while (Idx <= L) and CharInSet(LineStr[Idx],
['A' .. 'Z', 'a' .. 'z', '0' .. '9', '_']) do
Inc(Idx);
var
Ident := Copy(LineStr, startIdx, Idx - startIdx);
AppendPendingSpace;
Sb.Append(NormalizeIdentifier(Ident));
Continue;
end;
// Par défaut : caractère isolé (ponctuation non traitée, etc.)
AppendPendingSpace;
Sb.Append(Ch);
Inc(Idx);
end;
stString:
begin
// Dans une chaîne : on copie tout tel quel, en gérant les quotes doubles ('')
Sb.Append(Ch);
if Ch = '''' then
begin
if (Idx < L) and (LineStr[Idx + 1] = '''') then
begin
// quote échappée : '' -> on ajoute la seconde quote et on avance de 2
Sb.Append('''');
Inc(Idx, 2);
Continue;
end
else
begin
// fin de chaîne
State := stNormal;
Inc(Idx);
Continue;
end;
end
else
Inc(Idx);
end;
stCommentBrace:
begin
// Dans un commentaire { ... } : on copie jusqu'à '}' et on revient à stNormal
Sb.Append(Ch);
if Ch = '}' then
State := stNormal;
Inc(Idx);
end;
stDirective:
begin
// Directive {$ ... } : on copie jusqu'à '}' et on revient à stNormal
Sb.Append(Ch);
if Ch = '}' then
State := stNormal;
Inc(Idx);
end;
end;
end;
// Nettoyage des espaces de fin de ligne
FinalLine := Sb.ToString;
L := Length(FinalLine);
while (L > 0) and (FinalLine[L] = ' ') do
Dec(L);
FinalLine := Copy(FinalLine, 1, L);
TempLines.Add(FinalLine);
end;
// Élimination des lignes vides consécutives : on garde au plus une ligne vide
BlankCount := 0;
for I := 0 to TempLines.Count - 1 do
begin
if Trim(TempLines[I]) = '' then
begin
Inc(BlankCount);
if BlankCount = 1 then
OutScr.Add('');
end
else
begin
BlankCount := 0;
OutScr.Add(TempLines[I]);
end;
end;
finally
// Libération des ressources temporaires
Sb.Free;
TempLines.Free;
end;
// Libération de la table de correspondance chargée depuis la ressource
if Assigned(FormattedMap) then
begin
FormattedMap.Free;
FormattedMap := nil;
end;
finally
OutScr.EndUpdate;
end;
end;
end. |
Partager