Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Sloth - Preprocessor.cs

Preprocessor.cs

Caricato da: Totem
Scarica il programma completo

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Sloth
  7. {
  8.     public class MultipleLabelDefinitionsException : InterpreterException
  9.     {
  10.         public MultipleLabelDefinitionsException(String message, Int32 lineNumber) : base(message, lineNumber) { }
  11.     }
  12.  
  13.     public class Preprocessor
  14.     {
  15.         public TokenList Output { get; private set; }
  16.  
  17.         public Preprocessor()
  18.         {
  19.             this.Output = new TokenList();
  20.         }
  21.  
  22.         public void Process(TokenList rawTokens)
  23.         {
  24.             Dictionary<String, TokenList> substitutions = new Dictionary<String, TokenList>();
  25.             Int32 lineNumber = 1;
  26.  
  27.             for (Int32 i = 0; i < rawTokens.Count - 2; i++)
  28.             {
  29.                 if ((rawTokens[i].Type == TokenType.Label) &&
  30.                     (rawTokens[i + 1].Type == TokenType.Identifier) &&
  31.                     (rawTokens[i + 1].Lexeme.ToUpper() == "EQU"))
  32.                 {
  33.                     String label = rawTokens[i].Lexeme.TrimEnd(':');
  34.  
  35.                     if (substitutions.ContainsKey(label))
  36.                         throw new MultipleLabelDefinitionsException(String.Format("La label '{0}' è stata definita più volte.", label), lineNumber);
  37.  
  38.                     TokenList substitution = new TokenList();
  39.                     for (Int32 j = i + 2; (j < rawTokens.Count) && (rawTokens[j].Type != TokenType.NewLine); j++)
  40.                         substitution.Add(rawTokens[j]);
  41.                     substitutions.Add(label, substitution);
  42.  
  43.                     rawTokens.RemoveRange(i, substitution.Count + 2);
  44.                 }
  45.  
  46.                 if (rawTokens[i].Type == TokenType.NewLine)
  47.                     lineNumber++;
  48.             }
  49.  
  50.             this.Output.Clear();
  51.             foreach(Token token in rawTokens)
  52.                 if ((token.Type == TokenType.Identifier) &&
  53.                     (substitutions.ContainsKey(token.Lexeme)))
  54.                     this.Output.AddRange(substitutions[token.Lexeme]);
  55.                 else
  56.                     this.Output.Add(token);
  57.         }
  58.     }
  59. }