1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef Tokenizer_h__
8 #define Tokenizer_h__
9 
10 #include <type_traits>
11 
12 #include "nsString.h"
13 #include "mozilla/CheckedInt.h"
14 #include "mozilla/ScopeExit.h"
15 #include "mozilla/UniquePtr.h"
16 #include "nsTArray.h"
17 
18 namespace mozilla {
19 
20 template <typename TChar>
21 class TokenizerBase {
22  public:
23   typedef nsTSubstring<TChar> TAString;
24   typedef nsTString<TChar> TString;
25   typedef nsTDependentString<TChar> TDependentString;
26   typedef nsTDependentSubstring<TChar> TDependentSubstring;
27 
28   static TChar const sWhitespaces[];
29 
30   /**
31    * The analyzer works with elements in the input cut to a sequence of token
32    * where each token has an elementary type
33    */
34   enum TokenType : uint32_t {
35     TOKEN_UNKNOWN,
36     TOKEN_RAW,
37     TOKEN_ERROR,
38     TOKEN_INTEGER,
39     TOKEN_WORD,
40     TOKEN_CHAR,
41     TOKEN_WS,
42     TOKEN_EOL,
43     TOKEN_EOF,
44     TOKEN_CUSTOM0 = 1000
45   };
46 
47   enum ECaseSensitivity { CASE_SENSITIVE, CASE_INSENSITIVE };
48 
49   /**
50    * Class holding the type and the value of a token.  It can be manually
51    * created to allow checks against it via methods of TTokenizer or are results
52    * of some of the TTokenizer's methods.
53    */
54   class Token {
55     TokenType mType;
56     TDependentSubstring mWord;
57     TString mCustom;
58     TChar mChar;
59     uint64_t mInteger;
60     ECaseSensitivity mCustomCaseInsensitivity;
61     bool mCustomEnabled;
62 
63     // If this token is a result of the parsing process, this member is
64     // referencing a sub-string in the input buffer.  If this is externally
65     // created Token this member is left an empty string.
66     TDependentSubstring mFragment;
67 
68     friend class TokenizerBase<TChar>;
69     void AssignFragment(typename TAString::const_char_iterator begin,
70                         typename TAString::const_char_iterator end);
71 
72     static Token Raw();
73 
74    public:
75     Token();
76     Token(const Token& aOther);
77     Token& operator=(const Token& aOther);
78 
79     // Static constructors of tokens by type and value
80     static Token Word(TAString const& aWord);
81     static Token Char(TChar const aChar);
82     static Token Number(uint64_t const aNumber);
83     static Token Whitespace();
84     static Token NewLine();
85     static Token EndOfFile();
86     static Token Error();
87 
88     // Compares the two tokens, type must be identical and value
89     // of one of the tokens must be 'any' or equal.
90     bool Equals(const Token& aOther) const;
91 
Type()92     TokenType Type() const { return mType; }
93     TChar AsChar() const;
94     TDependentSubstring AsString() const;
95     uint64_t AsInteger() const;
96 
Fragment()97     TDependentSubstring Fragment() const { return mFragment; }
98   };
99 
100   /**
101    * Consumers may register a custom string that, when found in the input, is
102    * considered a token and returned by Next*() and accepted by Check*()
103    * methods. AddCustomToken() returns a reference to a token that can then be
104    * comapred using Token::Equals() againts the output from Next*() or be passed
105    * to Check*().
106    */
107   Token AddCustomToken(const TAString& aValue,
108                        ECaseSensitivity aCaseInsensitivity,
109                        bool aEnabled = true);
110   template <uint32_t N>
111   Token AddCustomToken(const TChar (&aValue)[N],
112                        ECaseSensitivity aCaseInsensitivity,
113                        bool aEnabled = true) {
114     return AddCustomToken(TDependentSubstring(aValue, N - 1),
115                           aCaseInsensitivity, aEnabled);
116   }
117   void RemoveCustomToken(Token& aToken);
118   /**
119    * Only applies to a custom type of a Token (see AddCustomToken above.)
120    * This turns on and off token recognition.  When a custom token is disabled,
121    * it's ignored as never added as a custom token.
122    */
123   void EnableCustomToken(Token const& aToken, bool aEnable);
124 
125   /**
126    * Mode of tokenization.
127    * FULL tokenization, the default, recognizes built-in tokens and any custom
128    * tokens, if added. CUSTOM_ONLY will only recognize custom tokens, the rest
129    * is seen as 'raw'. This mode can be understood as a 'binary' mode.
130    */
131   enum class Mode { FULL, CUSTOM_ONLY };
132   void SetTokenizingMode(Mode aMode);
133 
134   /**
135    * Return false iff the last Check*() call has returned false or when we've
136    * read past the end of the input string.
137    */
138   [[nodiscard]] bool HasFailed() const;
139 
140  protected:
141   explicit TokenizerBase(const TChar* aWhitespaces = nullptr,
142                          const TChar* aAdditionalWordChars = nullptr);
143 
144   // false if we have already read the EOF token.
145   bool HasInput() const;
146   // Main parsing function, it doesn't shift the read cursor, just returns the
147   // next token position.
148   typename TAString::const_char_iterator Parse(Token& aToken) const;
149   // Is read cursor at the end?
150   bool IsEnd(const typename TAString::const_char_iterator& caret) const;
151   // True, when we are at the end of the input data, but it has not been marked
152   // as complete yet.  In that case we cannot proceed with providing a
153   // multi-TChar token.
154   bool IsPending(const typename TAString::const_char_iterator& caret) const;
155   // Is read cursor on a character that is a word start?
156   bool IsWordFirst(const TChar aInput) const;
157   // Is read cursor on a character that is an in-word letter?
158   bool IsWord(const TChar aInput) const;
159   // Is read cursor on a character that is a valid number?
160   // TODO - support multiple radix
161   bool IsNumber(const TChar aInput) const;
162   // Is equal to the given custom token?
163   bool IsCustom(const typename TAString::const_char_iterator& caret,
164                 const Token& aCustomToken, uint32_t* aLongest = nullptr) const;
165 
166   // Friendly helper to assign a fragment on a Token
167   static void AssignFragment(Token& aToken,
168                              typename TAString::const_char_iterator begin,
169                              typename TAString::const_char_iterator end);
170 
171   // true iff we have already read the EOF token
172   bool mPastEof;
173   // true iff the last Check*() call has returned false, reverts to true on
174   // Rollback() call
175   bool mHasFailed;
176   // true if the input string is final (finished), false when we expect more
177   // data yet to be fed to the tokenizer (see IncrementalTokenizer derived
178   // class).
179   bool mInputFinished;
180   // custom only vs full tokenizing mode, see the Parse() method
181   Mode mMode;
182   // minimal raw data chunked delivery during incremental feed
183   uint32_t mMinRawDelivery;
184 
185   // Customizable list of whitespaces
186   const TChar* mWhitespaces;
187   // Additinal custom word characters
188   const TChar* mAdditionalWordChars;
189 
190   // All these point to the original buffer passed to the constructor or to the
191   // incremental buffer after FeedInput.
192   typename TAString::const_char_iterator
193       mCursor;  // Position of the current (actually next to read) token start
194   typename TAString::const_char_iterator mEnd;  // End of the input position
195 
196   // This is the list of tokens user has registered with AddCustomToken()
197   nsTArray<UniquePtr<Token>> mCustomTokens;
198   uint32_t mNextCustomTokenID;
199 
200  private:
201   TokenizerBase() = delete;
202   TokenizerBase(const TokenizerBase&) = delete;
203   TokenizerBase(TokenizerBase&&) = delete;
204   TokenizerBase(const TokenizerBase&&) = delete;
205   TokenizerBase& operator=(const TokenizerBase&) = delete;
206 };
207 
208 /**
209  * This is a simple implementation of a lexical analyzer or maybe better
210  * called a tokenizer.
211  *
212  * Please use Tokenizer or Tokenizer16 classes, that are specializations
213  * of this template class.  Tokenizer is for ASCII input, Tokenizer16 may
214  * handle char16_t input, but doesn't recognize whitespaces or numbers
215  * other than standard `char` specialized Tokenizer class.
216  */
217 template <typename TChar>
218 class TTokenizer : public TokenizerBase<TChar> {
219  public:
220   typedef TokenizerBase<TChar> base;
221 
222   /**
223    * @param aSource
224    *    The string to parse.
225    *    IMPORTANT NOTE: TTokenizer doesn't ensure the input string buffer
226    * lifetime. It's up to the consumer to make sure the string's buffer outlives
227    * the TTokenizer!
228    * @param aWhitespaces
229    *    If non-null TTokenizer will use this custom set of whitespaces for
230    * CheckWhite() and SkipWhites() calls. By default the list consists of space
231    * and tab.
232    * @param aAdditionalWordChars
233    *    If non-null it will be added to the list of characters that consist a
234    * word. This is useful when you want to accept e.g. '-' in HTTP headers. By
235    * default a word character is consider any character for which upper case
236    *    is different from lower case.
237    *
238    * If there is an overlap between aWhitespaces and aAdditionalWordChars, the
239    * check for word characters is made first.
240    */
241   explicit TTokenizer(const typename base::TAString& aSource,
242                       const TChar* aWhitespaces = nullptr,
243                       const TChar* aAdditionalWordChars = nullptr);
244   explicit TTokenizer(const TChar* aSource, const TChar* aWhitespaces = nullptr,
245                       const TChar* aAdditionalWordChars = nullptr);
246 
247   /**
248    * When there is still anything to read from the input, tokenize it, store the
249    * token type and value to aToken result and shift the cursor past this just
250    * parsed token.  Each call to Next() reads another token from the input and
251    * shifts the cursor. Returns false if we have passed the end of the input.
252    */
253   [[nodiscard]] bool Next(typename base::Token& aToken);
254 
255   /**
256    * Parse the token on the input read cursor position, check its type is equal
257    * to aTokenType and if so, put it into aResult, shift the cursor and return
258    * true.  Otherwise, leave the input read cursor position intact and return
259    * false.
260    */
261   [[nodiscard]] bool Check(const typename base::TokenType aTokenType,
262                            typename base::Token& aResult);
263   /**
264    * Same as above method, just compares both token type and token value passed
265    * in aToken. When both the type and the value equals, shift the cursor and
266    * return true.  Otherwise return false.
267    */
268   [[nodiscard]] bool Check(const typename base::Token& aToken);
269 
270   /**
271    * SkipWhites method (below) may also skip new line characters automatically.
272    */
273   enum WhiteSkipping {
274     /**
275      * SkipWhites will only skip what is defined as a white space (default).
276      */
277     DONT_INCLUDE_NEW_LINE = 0,
278     /**
279      * SkipWhites will skip definited white spaces as well as new lines
280      * automatically.
281      */
282     INCLUDE_NEW_LINE = 1
283   };
284 
285   /**
286    * Skips any occurence of whitespaces specified in mWhitespaces member,
287    * optionally skip also new lines.
288    */
289   void SkipWhites(WhiteSkipping aIncludeNewLines = DONT_INCLUDE_NEW_LINE);
290 
291   /**
292    * Skips all tokens until the given one is found or EOF is hit.  The token
293    * or EOF are next to read.
294    */
295   void SkipUntil(typename base::Token const& aToken);
296 
297   // These are mostly shortcuts for the Check() methods above.
298 
299   /**
300    * Check whitespace character is present.
301    */
CheckWhite()302   [[nodiscard]] bool CheckWhite() { return Check(base::Token::Whitespace()); }
303   /**
304    * Check there is a single character on the read cursor position.  If so,
305    * shift the read cursor position and return true.  Otherwise false.
306    */
CheckChar(const TChar aChar)307   [[nodiscard]] bool CheckChar(const TChar aChar) {
308     return Check(base::Token::Char(aChar));
309   }
310   /**
311    * This is a customizable version of CheckChar.  aClassifier is a function
312    * called with value of the character on the current input read position.  If
313    * this user function returns true, read cursor is shifted and true returned.
314    * Otherwise false. The user classifiction function is not called when we are
315    * at or past the end and false is immediately returned.
316    */
317   [[nodiscard]] bool CheckChar(bool (*aClassifier)(const TChar aChar));
318   /**
319    * Check for a whole expected word.
320    */
CheckWord(const typename base::TAString & aWord)321   [[nodiscard]] bool CheckWord(const typename base::TAString& aWord) {
322     return Check(base::Token::Word(aWord));
323   }
324   /**
325    * Shortcut for literal const word check with compile time length calculation.
326    */
327   template <uint32_t N>
CheckWord(const TChar (& aWord)[N])328   [[nodiscard]] bool CheckWord(const TChar (&aWord)[N]) {
329     return Check(
330         base::Token::Word(typename base::TDependentString(aWord, N - 1)));
331   }
332   /**
333    * Checks \r, \n or \r\n.
334    */
CheckEOL()335   [[nodiscard]] bool CheckEOL() { return Check(base::Token::NewLine()); }
336   /**
337    * Checks we are at the end of the input string reading.  If so, shift past
338    * the end and returns true.  Otherwise does nothing and returns false.
339    */
CheckEOF()340   [[nodiscard]] bool CheckEOF() { return Check(base::Token::EndOfFile()); }
341 
342   /**
343    * These are shortcuts to obtain the value immediately when the token type
344    * matches.
345    */
346   [[nodiscard]] bool ReadChar(TChar* aValue);
347   [[nodiscard]] bool ReadChar(bool (*aClassifier)(const TChar aChar),
348                               TChar* aValue);
349   [[nodiscard]] bool ReadWord(typename base::TAString& aValue);
350   [[nodiscard]] bool ReadWord(typename base::TDependentSubstring& aValue);
351 
352   /**
353    * This is an integer read helper.  It returns false and doesn't move the read
354    * cursor when any of the following happens:
355    *  - the token at the read cursor is not an integer
356    *  - the final number doesn't fit the T type
357    * Otherwise true is returned, aValue is filled with the integral number
358    * and the cursor is moved forward.
359    */
360   template <typename T>
ReadInteger(T * aValue)361   [[nodiscard]] bool ReadInteger(T* aValue) {
362     MOZ_RELEASE_ASSERT(aValue);
363 
364     typename base::TAString::const_char_iterator rollback = mRollback;
365     typename base::TAString::const_char_iterator cursor = base::mCursor;
366     typename base::Token t;
367     if (!Check(base::TOKEN_INTEGER, t)) {
368       return false;
369     }
370 
371     mozilla::CheckedInt<T> checked(t.AsInteger());
372     if (!checked.isValid()) {
373       // Move to a state as if Check() call has failed
374       mRollback = rollback;
375       base::mCursor = cursor;
376       base::mHasFailed = true;
377       return false;
378     }
379 
380     *aValue = checked.value();
381     return true;
382   }
383 
384   /**
385    * Same as above, but accepts an integer with an optional minus sign.
386    */
387   template <typename T, typename V = std::enable_if_t<
388                             std::is_signed_v<std::remove_pointer_t<T>>,
389                             std::remove_pointer_t<T>>>
ReadSignedInteger(T * aValue)390   [[nodiscard]] bool ReadSignedInteger(T* aValue) {
391     MOZ_RELEASE_ASSERT(aValue);
392 
393     typename base::TAString::const_char_iterator rollback = mRollback;
394     typename base::TAString::const_char_iterator cursor = base::mCursor;
395     auto revert = MakeScopeExit([&] {
396       // Move to a state as if Check() call has failed
397       mRollback = rollback;
398       base::mCursor = cursor;
399       base::mHasFailed = true;
400     });
401 
402     // Using functional raw access because '-' could be part of the word set
403     // making CheckChar('-') not work.
404     bool minus = CheckChar([](const TChar aChar) { return aChar == '-'; });
405 
406     typename base::Token t;
407     if (!Check(base::TOKEN_INTEGER, t)) {
408       return false;
409     }
410 
411     mozilla::CheckedInt<T> checked(t.AsInteger());
412     if (minus) {
413       checked *= -1;
414     }
415 
416     if (!checked.isValid()) {
417       return false;
418     }
419 
420     *aValue = checked.value();
421     revert.release();
422     return true;
423   }
424 
425   /**
426    * Returns the read cursor position back as it was before the last call of any
427    * parsing method of TTokenizer (Next, Check*, Skip*, Read*) so that the last
428    * operation can be repeated. Rollback cannot be used multiple times, it only
429    * reverts the last successfull parse operation.  It also cannot be used
430    * before any parsing operation has been called on the TTokenizer.
431    */
432   void Rollback();
433 
434   /**
435    * Record() and Claim() are collecting the input as it is being parsed to
436    * obtain a substring between particular syntax bounderies defined by any
437    * recursive descent parser or simple parser the TTokenizer is used to read
438    * the input for. Inlucsion of a token that has just been parsed can be
439    * controlled using an arguemnt.
440    */
441   enum ClaimInclusion {
442     /**
443      * Include resulting (or passed) token of the last lexical analyzer
444      * operation in the result.
445      */
446     INCLUDE_LAST,
447     /**
448      * Do not include it.
449      */
450     EXCLUDE_LAST
451   };
452 
453   /**
454    * Start the process of recording.  Based on aInclude value the begining of
455    * the recorded sub-string is at the current position (EXCLUDE_LAST) or at the
456    * position before the last parsed token (INCLUDE_LAST).
457    */
458   void Record(ClaimInclusion aInclude = EXCLUDE_LAST);
459   /**
460    * Claim result of the record started with Record() call before.  Depending on
461    * aInclude the ending of the sub-string result includes or excludes the last
462    * parsed or checked token.
463    */
464   void Claim(typename base::TAString& aResult,
465              ClaimInclusion aInclude = EXCLUDE_LAST);
466   void Claim(typename base::TDependentSubstring& aResult,
467              ClaimInclusion aInclude = EXCLUDE_LAST);
468 
469   /**
470    * If aToken is found, aResult is set to the substring between the current
471    * position and the position of aToken, potentially including aToken depending
472    * on aInclude.
473    * If aToken isn't found aResult is set to the substring between the current
474    * position and the end of the string.
475    * If aToken is found, the method returns true. Otherwise it returns false.
476    *
477    * Calling Rollback() after ReadUntil() will return the read cursor to the
478    * position it had before ReadUntil was called.
479    */
480   [[nodiscard]] bool ReadUntil(typename base::Token const& aToken,
481                                typename base::TDependentSubstring& aResult,
482                                ClaimInclusion aInclude = EXCLUDE_LAST);
483   [[nodiscard]] bool ReadUntil(typename base::Token const& aToken,
484                                typename base::TAString& aResult,
485                                ClaimInclusion aInclude = EXCLUDE_LAST);
486 
487  protected:
488   // All these point to the original buffer passed to the TTokenizer's
489   // constructor
490   typename base::TAString::const_char_iterator
491       mRecord;  // Position where the recorded sub-string for Claim() is
492   typename base::TAString::const_char_iterator
493       mRollback;  // Position of the previous token start
494 
495  private:
496   TTokenizer() = delete;
497   TTokenizer(const TTokenizer&) = delete;
498   TTokenizer(TTokenizer&&) = delete;
499   TTokenizer(const TTokenizer&&) = delete;
500   TTokenizer& operator=(const TTokenizer&) = delete;
501 };
502 
503 typedef TTokenizer<char> Tokenizer;
504 typedef TTokenizer<char16_t> Tokenizer16;
505 
506 }  // namespace mozilla
507 
508 #endif  // Tokenizer_h__
509