source: trunk/yao/share/antlr-2.7.7/lib/csharp/antlr.runtime/antlr/CharScanner.cs @ 1

Last change on this file since 1 was 1, checked in by lnalod, 15 years ago

Initial import of YAO sources

File size: 19.4 KB
Line 
1using System;
2using Stream                    = System.IO.Stream;
3using TextReader                = System.IO.TextReader;
4using StringBuilder             = System.Text.StringBuilder;
5using Hashtable                 = System.Collections.Hashtable;
6using Assembly                  = System.Reflection.Assembly;
7using EventHandlerList  = System.ComponentModel.EventHandlerList;
8
9using BitSet                    = antlr.collections.impl.BitSet;
10using antlr.debug;
11
12namespace antlr
13{
14        /*ANTLR Translator Generator
15        * Project led by Terence Parr at http://www.jGuru.com
16        * Software rights: http://www.antlr.org/license.html
17        *
18        * $Id:$
19        */
20
21        //
22        // ANTLR C# Code Generator by Micheal Jordan
23        //                            Kunle Odutola       : kunle UNDERSCORE odutola AT hotmail DOT com
24        //                            Anthony Oguntimehin
25        //
26        // With many thanks to Eric V. Smith from the ANTLR list.
27        //
28       
29        public abstract class CharScanner : TokenStream, ICharScannerDebugSubject
30        {
31                internal const char NO_CHAR = (char) (0);
32                public static readonly char EOF_CHAR = Char.MaxValue;
33
34                // Used to store event delegates
35                private EventHandlerList events_ = new EventHandlerList();
36
37                protected internal EventHandlerList Events
38                {
39                        get     { return events_;       }
40                }
41
42                // The unique keys for each event that CharScanner [objects] can generate
43                internal static readonly object EnterRuleEventKey                       = new object();
44                internal static readonly object ExitRuleEventKey                        = new object();
45                internal static readonly object DoneEventKey                            = new object();
46                internal static readonly object ReportErrorEventKey                     = new object();
47                internal static readonly object ReportWarningEventKey           = new object();
48                internal static readonly object NewLineEventKey                         = new object();
49                internal static readonly object MatchEventKey                           = new object();
50                internal static readonly object MatchNotEventKey                        = new object();
51                internal static readonly object MisMatchEventKey                        = new object();
52                internal static readonly object MisMatchNotEventKey                     = new object();
53                internal static readonly object ConsumeEventKey                         = new object();
54                internal static readonly object LAEventKey                                      = new object();
55                internal static readonly object SemPredEvaluatedEventKey        = new object();
56                internal static readonly object SynPredStartedEventKey          = new object();
57                internal static readonly object SynPredFailedEventKey           = new object();
58                internal static readonly object SynPredSucceededEventKey        = new object();
59
60                protected internal StringBuilder text;                          // text of current token
61               
62                protected bool saveConsumedInput = true;        // does consume() save characters?
63
64                /// <summary>Used for creating Token instances.</summary>
65                protected TokenCreator  tokenCreator;
66
67                /// <summary>Used for caching lookahead characters.</summary>
68                protected char                  cached_LA1;
69                protected char                  cached_LA2;
70
71                protected bool caseSensitive = true;
72                protected bool caseSensitiveLiterals = true;
73                protected Hashtable literals; // set by subclass
74               
75                /*Tab chars are handled by tab() according to this value; override
76                *  method to do anything weird with tabs.
77                */
78                protected internal int tabsize = 8;
79               
80                protected internal IToken returnToken_ = null; // used to return tokens w/o using return val.
81               
82                protected internal LexerSharedInputState inputState;
83               
84                /*Used during filter mode to indicate that path is desired.
85                *  A subsequent scan error will report an error as usual if
86                *  acceptPath=true;
87                */
88                protected internal bool commitToPath = false;
89               
90                /*Used to keep track of indentdepth for traceIn/Out */
91                protected internal int traceDepth = 0;
92               
93                public CharScanner()
94                {
95                        text = new StringBuilder();
96                        setTokenCreator(new CommonToken.CommonTokenCreator());
97                }
98               
99                public CharScanner(InputBuffer cb) : this()
100                {
101                        inputState = new LexerSharedInputState(cb);
102                        cached_LA2 = inputState.input.LA(2);
103                        cached_LA1 = inputState.input.LA(1);
104                }
105               
106                public CharScanner(LexerSharedInputState sharedState) : this()
107                {
108                        inputState = sharedState;
109                        if (inputState != null)
110                        {
111                                cached_LA2 = inputState.input.LA(2);
112                                cached_LA1 = inputState.input.LA(1);
113                }
114        }
115               
116
117                public event TraceEventHandler EnterRule
118                {
119                        add             {       Events.AddHandler(EnterRuleEventKey, value);    }
120                        remove  {       Events.RemoveHandler(EnterRuleEventKey, value); }
121                }
122
123                public event TraceEventHandler ExitRule
124                {
125                        add             {       Events.AddHandler(ExitRuleEventKey, value);             }
126                        remove  {       Events.RemoveHandler(ExitRuleEventKey, value);  }
127                }
128
129                public event TraceEventHandler Done
130                {
131                        add             {       Events.AddHandler(DoneEventKey, value);         }
132                        remove  {       Events.RemoveHandler(DoneEventKey, value);      }
133                }
134
135                public event MessageEventHandler ErrorReported
136                {
137                        add             {       Events.AddHandler(ReportErrorEventKey, value);          }
138                        remove  {       Events.RemoveHandler(ReportErrorEventKey, value);       }
139                }
140
141                public event MessageEventHandler WarningReported
142                {
143                        add             {       Events.AddHandler(ReportWarningEventKey, value);        }
144                        remove  {       Events.RemoveHandler(ReportWarningEventKey, value);     }
145                }
146
147                public event NewLineEventHandler HitNewLine
148                {
149                        add             {       Events.AddHandler(NewLineEventKey, value);              }
150                        remove  {       Events.RemoveHandler(NewLineEventKey, value);   }
151                }
152
153                public event MatchEventHandler MatchedChar
154                {
155                        add             {       Events.AddHandler(MatchEventKey, value);        }
156                        remove  {       Events.RemoveHandler(MatchEventKey, value);     }
157                }
158
159                public event MatchEventHandler MatchedNotChar
160                {
161                        add             {       Events.AddHandler(MatchNotEventKey, value);             }
162                        remove  {       Events.RemoveHandler(MatchNotEventKey, value);  }
163                }
164
165                public event MatchEventHandler MisMatchedChar
166                {
167                        add             {       Events.AddHandler(MisMatchEventKey, value);             }
168                        remove  {       Events.RemoveHandler(MisMatchEventKey, value);  }
169                }
170
171                public event MatchEventHandler MisMatchedNotChar
172                {
173                        add             {       Events.AddHandler(MisMatchNotEventKey, value);          }
174                        remove  {       Events.RemoveHandler(MisMatchNotEventKey, value);       }
175                }
176
177                public event TokenEventHandler ConsumedChar
178                {
179                        add             {       Events.AddHandler(ConsumeEventKey, value);              }
180                        remove  {       Events.RemoveHandler(ConsumeEventKey, value);   }
181                }
182
183                public event TokenEventHandler CharLA
184                {
185                        add             {       Events.AddHandler(LAEventKey, value);           }
186                        remove  {       Events.RemoveHandler(LAEventKey, value);        }
187                }
188
189                public event SemanticPredicateEventHandler SemPredEvaluated
190                {
191                        add             {       Events.AddHandler(SemPredEvaluatedEventKey, value);             }
192                        remove  {       Events.RemoveHandler(SemPredEvaluatedEventKey, value);  }
193                }
194
195                public event SyntacticPredicateEventHandler SynPredStarted
196                {
197                        add             {       Events.AddHandler(SynPredStartedEventKey, value);               }
198                        remove  {       Events.RemoveHandler(SynPredStartedEventKey, value);    }
199                }
200
201                public event SyntacticPredicateEventHandler SynPredFailed
202                {
203                        add             {       Events.AddHandler(SynPredFailedEventKey, value);        }
204                        remove  {       Events.RemoveHandler(SynPredFailedEventKey, value);     }
205                }
206
207                public event SyntacticPredicateEventHandler SynPredSucceeded
208                {
209                        add             {       Events.AddHandler(SynPredSucceededEventKey, value);             }
210                        remove  {       Events.RemoveHandler(SynPredSucceededEventKey, value);  }
211                }
212
213                // From interface TokenStream
214                public virtual IToken nextToken() { return null; }
215
216                public virtual void  append(char c)
217                {
218                        if (saveConsumedInput)
219                        {
220                                text.Append(c);
221                        }
222                }
223               
224                public virtual void  append(string s)
225                {
226                        if (saveConsumedInput)
227                        {
228                                text.Append(s);
229                        }
230                }
231               
232                public virtual void  commit()
233                {
234                        inputState.input.commit();
235                }
236               
237                public virtual void recover(RecognitionException ex, BitSet tokenSet)
238                {
239                        consume();
240                        consumeUntil(tokenSet);
241                }
242               
243                public virtual void  consume()
244                {
245                        if (inputState.guessing == 0)
246                        {
247                                if (caseSensitive)
248                                {
249                                        append(cached_LA1);
250                                }
251                                else
252                                {
253                                        // use input.LA(), not LA(), to get original case
254                                        // CharScanner.LA() would toLower it.
255                                        append(inputState.input.LA(1));
256                                }
257                                if (cached_LA1 == '\t')
258                                {
259                                        tab();
260                                }
261                                else
262                                {
263                                        inputState.column++;
264                                }
265                        }
266                        if (caseSensitive)
267                        {
268                                cached_LA1 = inputState.input.consume();
269                                cached_LA2 = inputState.input.LA(2);
270                        }
271                        else
272                        {
273                                cached_LA1 = toLower(inputState.input.consume());
274                                cached_LA2 = toLower(inputState.input.LA(2));
275                        }
276                }
277               
278                /*Consume chars until one matches the given char */
279                public virtual void  consumeUntil(int c)
280                {
281                        while ((EOF_CHAR != cached_LA1) && (c != cached_LA1))
282                        {
283                                consume();
284                        }
285                }
286               
287                /*Consume chars until one matches the given set */
288                public virtual void  consumeUntil(BitSet bset)
289                {
290                        while (cached_LA1 != EOF_CHAR && !bset.member(cached_LA1))
291                        {
292                                consume();
293                        }
294                }
295               
296                public virtual bool getCaseSensitive()
297                {
298                        return caseSensitive;
299                }
300               
301                public bool getCaseSensitiveLiterals()
302                {
303                        return caseSensitiveLiterals;
304                }
305               
306                public virtual int getColumn()
307                {
308                        return inputState.column;
309                }
310               
311                public virtual void  setColumn(int c)
312                {
313                        inputState.column = c;
314                }
315               
316                public virtual bool getCommitToPath()
317                {
318                        return commitToPath;
319                }
320               
321                public virtual string getFilename()
322                {
323                        return inputState.filename;
324                }
325               
326                public virtual InputBuffer getInputBuffer()
327                {
328                        return inputState.input;
329                }
330               
331                public virtual LexerSharedInputState getInputState()
332                {
333                        return inputState;
334                }
335               
336                public virtual void  setInputState(LexerSharedInputState state)
337                {
338                        inputState = state;
339                }
340               
341                public virtual int getLine()
342                {
343                        return inputState.line;
344                }
345               
346                /*return a copy of the current text buffer */
347                public virtual string getText()
348                {
349                        return text.ToString();
350                }
351               
352                public virtual IToken getTokenObject()
353                {
354                        return returnToken_;
355                }
356               
357                public virtual char LA(int i)
358                {
359                        if (i == 1)
360                        {
361                                return cached_LA1;
362                        }
363                        if (i == 2)
364                        {
365                                return cached_LA2;
366                        }
367                        if (caseSensitive)
368                        {
369                                return inputState.input.LA(i);
370                        }
371                        else
372                        {
373                                return toLower(inputState.input.LA(i));
374                        }
375                }
376               
377                protected internal virtual IToken makeToken(int t)
378                {
379                        IToken  newToken        = null;
380                        bool    typeCreated;
381
382                        try
383                        {
384                                newToken = tokenCreator.Create();
385                                if (newToken != null)
386                                {
387                                        newToken.Type = t;
388                                        newToken.setColumn(inputState.tokenStartColumn);
389                                        newToken.setLine(inputState.tokenStartLine);
390                                        // tracking real start line now: newToken.setLine(inputState.line);
391                                        newToken.setFilename(inputState.filename);
392                                }
393                                typeCreated     = true;
394                        }
395                        catch
396                        {
397                                typeCreated = false;
398                        }
399
400                        if (!typeCreated)
401                        {
402                                panic("Can't create Token object '" + tokenCreator.TokenTypeName + "'");
403                                newToken = Token.badToken;
404                        }
405                        return newToken;
406                }
407               
408                public virtual int mark()
409                {
410                        return inputState.input.mark();
411                }
412               
413                public virtual void  match(char c)
414                {
415                        match((int) c);
416                }
417
418                public virtual void  match(int c)
419                {
420                        if (cached_LA1 != c)
421                        {
422                                throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), false, this);
423                        }
424                        consume();
425                }
426               
427                public virtual void  match(BitSet b)
428                {
429                        if (!b.member(cached_LA1))
430                        {
431                                throw new MismatchedCharException(cached_LA1, b, false, this);
432                        }
433                        consume();
434                }
435               
436                public virtual void  match(string s)
437                {
438                        int len = s.Length;
439                         for (int i = 0; i < len; i++)
440                        {
441                                if (cached_LA1 != s[i])
442                                {
443                                        throw new MismatchedCharException(cached_LA1, s[i], false, this);
444                                }
445                                consume();
446                        }
447                }
448               
449                public virtual void  matchNot(char c)
450                {
451                        matchNot((int) c);
452                }
453               
454                public virtual void  matchNot(int c)
455                {
456                        if (cached_LA1 == c)
457                        {
458                                throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), true, this);
459                        }
460                        consume();
461                }
462               
463                public virtual void  matchRange(int c1, int c2)
464                {
465                        if (cached_LA1 < c1 || cached_LA1 > c2)
466                        {
467                                throw new MismatchedCharException(cached_LA1, Convert.ToChar(c1), Convert.ToChar(c2), false, this);
468                        }
469                        consume();
470                }
471               
472                public virtual void  matchRange(char c1, char c2)
473                {
474                        matchRange((int) c1, (int) c2);
475                }
476               
477                public virtual void  newline()
478                {
479                        inputState.line++;
480                        inputState.column = 1;
481                }
482               
483                /*advance the current column number by an appropriate amount
484                *  according to tab size. This method is called from consume().
485                */
486                public virtual void  tab()
487                {
488                        int c = getColumn();
489                        int nc = (((c - 1) / tabsize) + 1) * tabsize + 1; // calculate tab stop
490                        setColumn(nc);
491                }
492               
493                public virtual void  setTabSize(int size)
494                {
495                        tabsize = size;
496                }
497               
498                public virtual int getTabSize()
499                {
500                        return tabsize;
501                }
502               
503                public virtual void panic()
504                {
505                        //Console.Error.WriteLine("CharScanner: panic");
506                        //Environment.Exit(1);
507                        panic("");
508
509                }
510               
511                /// <summary>
512                /// This method is executed by ANTLR internally when it detected an illegal
513                /// state that cannot be recovered from.
514                /// The previous implementation of this method called <see cref="Environment.Exit"/>
515                /// and writes directly to <see cref="Console.Error"/>, which is usually not
516                /// appropriate when a translator is embedded into a larger application.
517                /// </summary>
518                /// <param name="s">Error message.</param>
519                public virtual void panic(string s)
520                {
521                        //Console.Error.WriteLine("CharScanner; panic: " + s);
522                        //Environment.Exit(1);
523                        throw new ANTLRPanicException("CharScanner::panic: " + s);
524                }
525               
526                /*Parser error-reporting function can be overridden in subclass */
527                public virtual void  reportError(RecognitionException ex)
528                {
529                        Console.Error.WriteLine(ex);
530                }
531               
532                /*Parser error-reporting function can be overridden in subclass */
533                public virtual void  reportError(string s)
534                {
535                        if (getFilename() == null)
536                        {
537                                Console.Error.WriteLine("error: " + s);
538                        }
539                        else
540                        {
541                                Console.Error.WriteLine(getFilename() + ": error: " + s);
542                        }
543                }
544               
545                /*Parser warning-reporting function can be overridden in subclass */
546                public virtual void  reportWarning(string s)
547                {
548                        if (getFilename() == null)
549                        {
550                                Console.Error.WriteLine("warning: " + s);
551                        }
552                        else
553                        {
554                                Console.Error.WriteLine(getFilename() + ": warning: " + s);
555                        }
556                }
557               
558                public virtual void refresh()
559                {
560                        if (caseSensitive)
561                        {
562                                cached_LA2 = inputState.input.LA(2);
563                                cached_LA1 = inputState.input.LA(1);
564                        }
565                        else
566                        {
567                                cached_LA2 = toLower(inputState.input.LA(2));
568                                cached_LA1 = toLower(inputState.input.LA(1));
569                        }
570                }
571
572                public virtual void resetState(InputBuffer ib)
573                {
574                        text.Length = 0;
575                        traceDepth = 0;
576                        inputState.resetInput(ib);
577                        refresh();
578                }
579
580                public void resetState(Stream s)
581                {
582                        resetState(new ByteBuffer(s));
583                }
584
585                public void resetState(TextReader tr)
586                {
587                        resetState(new CharBuffer(tr));
588                }
589
590                public virtual void  resetText()
591                {
592                        text.Length = 0;
593                        inputState.tokenStartColumn = inputState.column;
594                        inputState.tokenStartLine = inputState.line;
595                }
596               
597                public virtual void  rewind(int pos)
598                {
599                        inputState.input.rewind(pos);
600                        //setColumn(inputState.tokenStartColumn);
601                        if (caseSensitive)
602                        {
603                                cached_LA2 = inputState.input.LA(2);
604                                cached_LA1 = inputState.input.LA(1);
605                        }
606                        else
607                        {
608                                cached_LA2 = toLower(inputState.input.LA(2));
609                                cached_LA1 = toLower(inputState.input.LA(1));
610                        }
611                }
612               
613                public virtual void  setCaseSensitive(bool t)
614                {
615                        caseSensitive = t;
616                        if (caseSensitive)
617                        {
618                                cached_LA2 = inputState.input.LA(2);
619                                cached_LA1 = inputState.input.LA(1);
620                        }
621                        else
622                        {
623                                cached_LA2 = toLower(inputState.input.LA(2));
624                                cached_LA1 = toLower(inputState.input.LA(1));
625                        }
626                }
627               
628                public virtual void  setCommitToPath(bool commit)
629                {
630                        commitToPath = commit;
631                }
632               
633                public virtual void  setFilename(string f)
634                {
635                        inputState.filename = f;
636                }
637               
638                public virtual void  setLine(int line)
639                {
640                        inputState.line = line;
641                }
642               
643                public virtual void  setText(string s)
644                {
645                        resetText();
646                        text.Append(s);
647                }
648               
649                public virtual void  setTokenObjectClass(string cl)
650                {
651                        this.tokenCreator = new ReflectionBasedTokenCreator(this, cl);
652                }
653               
654                public virtual void  setTokenCreator(TokenCreator tokenCreator)
655                {
656                        this.tokenCreator = tokenCreator;
657                }
658               
659                // Test the token text against the literals table
660                // Override this method to perform a different literals test
661                public virtual int testLiteralsTable(int ttype)
662                {
663                        string tokenText = text.ToString();
664
665                        if ( (tokenText == null) || (tokenText == string.Empty) )
666                                return ttype;
667                        else
668                        {
669                                object typeAsObject = literals[tokenText];
670                                return (typeAsObject == null) ? ttype : ((int) typeAsObject);
671                        }
672                }
673               
674                /*Test the text passed in against the literals table
675                * Override this method to perform a different literals test
676                * This is used primarily when you want to test a portion of
677                * a token.
678                */
679                public virtual int testLiteralsTable(string someText, int ttype)
680                {
681                        if ( (someText == null) || (someText == string.Empty) )
682                                return ttype;
683                        else
684                        {
685                                object typeAsObject = literals[someText];
686                                return (typeAsObject == null) ? ttype : ((int) typeAsObject);
687                        }
688                }
689               
690                // Override this method to get more specific case handling
691                public virtual char toLower(int c)
692                {
693                        return Char.ToLower(Convert.ToChar(c), System.Globalization.CultureInfo.InvariantCulture);
694                }
695               
696                public virtual void  traceIndent()
697                {
698                         for (int i = 0; i < traceDepth; i++)
699                                Console.Out.Write(" ");
700                }
701               
702                public virtual void  traceIn(string rname)
703                {
704                        traceDepth += 1;
705                        traceIndent();
706                        Console.Out.WriteLine("> lexer " + rname + "; c==" + LA(1));
707                }
708               
709                public virtual void  traceOut(string rname)
710                {
711                        traceIndent();
712                        Console.Out.WriteLine("< lexer " + rname + "; c==" + LA(1));
713                        traceDepth -= 1;
714                }
715               
716                /*This method is called by YourLexer.nextToken() when the lexer has
717                *  hit EOF condition.  EOF is NOT a character.
718                *  This method is not called if EOF is reached during
719                *  syntactic predicate evaluation or during evaluation
720                *  of normal lexical rules, which presumably would be
721                *  an IOException.  This traps the "normal" EOF condition.
722                *
723                *  uponEOF() is called after the complete evaluation of
724                *  the previous token and only if your parser asks
725                *  for another token beyond that last non-EOF token.
726                *
727                *  You might want to throw token or char stream exceptions
728                *  like: "Heh, premature eof" or a retry stream exception
729                *  ("I found the end of this file, go back to referencing file").
730                */
731                public virtual void  uponEOF()
732                {
733                }
734
735                private class ReflectionBasedTokenCreator : TokenCreator
736                {
737                        protected ReflectionBasedTokenCreator() {}
738
739                        public ReflectionBasedTokenCreator(CharScanner owner, string tokenTypeName)
740                        {
741                                this.owner = owner;
742                                SetTokenType(tokenTypeName);
743                        }
744
745                        private CharScanner owner;
746
747                        /// <summary>
748                        /// The fully qualified name of the Token type to create.
749                        /// </summary>
750                        private string tokenTypeName;
751
752                        /// <summary>
753                        /// Type object used as a template for creating tokens by reflection.
754                        /// </summary>
755                        private Type tokenTypeObject;
756
757                        /// <summary>
758                        /// Returns the fully qualified name of the Token type that this
759                        /// class creates.
760                        /// </summary>
761                        private void SetTokenType(string tokenTypeName)
762                        {
763                                this.tokenTypeName = tokenTypeName;
764                                foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies())
765                                {
766                                        try
767                                        {
768                                                tokenTypeObject = assem.GetType(tokenTypeName);
769                                                if (tokenTypeObject != null)
770                                                {
771                                                        break;
772                                                }
773                                        }
774                                        catch
775                                        {
776                                                throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'");
777                                        }
778                                }
779                                if (tokenTypeObject==null)
780                                        throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'");
781                        }
782
783                        /// <summary>
784                        /// Returns the fully qualified name of the Token type that this
785                        /// class creates.
786                        /// </summary>
787                        public override string TokenTypeName
788                        {
789                                get
790                                { 
791                                        return tokenTypeName; 
792                                }
793                        }
794
795                        /// <summary>
796                        /// Constructs a <see cref="Token"/> instance.
797                        /// </summary>
798                        public override IToken Create()
799                        {
800                                IToken newToken = null;
801
802                                try
803                                {
804                                        newToken = (Token) Activator.CreateInstance(tokenTypeObject);
805                                }
806                                catch
807                                {
808                                        // supress exception
809                                }
810                                return newToken;
811                        }
812                }
813        }
814}
Note: See TracBrowser for help on using the repository browser.