TextTokenizer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://github.com/jskeet/dotnet-protobufs/
  4. // Original C++/Java/Python code:
  5. // http://code.google.com/p/protobuf/
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following disclaimer
  15. // in the documentation and/or other materials provided with the
  16. // distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived from
  19. // this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. using System;
  33. using System.Globalization;
  34. using System.Text.RegularExpressions;
  35. namespace Google.ProtocolBuffers {
  36. /// <summary>
  37. /// Represents a stream of tokens parsed from a string.
  38. /// </summary>
  39. internal sealed class TextTokenizer {
  40. private readonly string text;
  41. private string currentToken;
  42. /// <summary>
  43. /// The character index within the text to perform the next regex match at.
  44. /// </summary>
  45. private int matchPos = 0;
  46. /// <summary>
  47. /// The character index within the text at which the current token begins.
  48. /// </summary>
  49. private int pos = 0;
  50. /// <summary>
  51. /// The line number of the current token.
  52. /// </summary>
  53. private int line = 0;
  54. /// <summary>
  55. /// The column number of the current token.
  56. /// </summary>
  57. private int column = 0;
  58. /// <summary>
  59. /// The line number of the previous token.
  60. /// </summary>
  61. private int previousLine = 0;
  62. /// <summary>
  63. /// The column number of the previous token.
  64. /// </summary>
  65. private int previousColumn = 0;
  66. // Note: atomic groups used to mimic possessive quantifiers in Java in both of these regexes
  67. internal static readonly Regex WhitespaceAndCommentPattern = new Regex("\\G(?>(\\s|(#.*$))+)",
  68. SilverlightCompatibility.CompiledRegexWhereAvailable | RegexOptions.Multiline);
  69. private static readonly Regex TokenPattern = new Regex(
  70. "\\G[a-zA-Z_](?>[0-9a-zA-Z_+-]*)|" + // an identifier
  71. "\\G[0-9+-](?>[0-9a-zA-Z_.+-]*)|" + // a number
  72. "\\G\"(?>([^\"\\\n\\\\]|\\\\.)*)(\"|\\\\?$)|" + // a double-quoted string
  73. "\\G\'(?>([^\"\\\n\\\\]|\\\\.)*)(\'|\\\\?$)", // a single-quoted string
  74. SilverlightCompatibility.CompiledRegexWhereAvailable | RegexOptions.Multiline);
  75. private static readonly Regex DoubleInfinity = new Regex("^-?inf(inity)?$",
  76. SilverlightCompatibility.CompiledRegexWhereAvailable | RegexOptions.IgnoreCase);
  77. private static readonly Regex FloatInfinity = new Regex("^-?inf(inity)?f?$",
  78. SilverlightCompatibility.CompiledRegexWhereAvailable | RegexOptions.IgnoreCase);
  79. private static readonly Regex FloatNan = new Regex("^nanf?$",
  80. SilverlightCompatibility.CompiledRegexWhereAvailable | RegexOptions.IgnoreCase);
  81. /** Construct a tokenizer that parses tokens from the given text. */
  82. public TextTokenizer(string text) {
  83. this.text = text;
  84. SkipWhitespace();
  85. NextToken();
  86. }
  87. /// <summary>
  88. /// Are we at the end of the input?
  89. /// </summary>
  90. public bool AtEnd {
  91. get { return currentToken.Length == 0; }
  92. }
  93. /// <summary>
  94. /// Advances to the next token.
  95. /// </summary>
  96. public void NextToken() {
  97. previousLine = line;
  98. previousColumn = column;
  99. // Advance the line counter to the current position.
  100. while (pos < matchPos) {
  101. if (text[pos] == '\n') {
  102. ++line;
  103. column = 0;
  104. } else {
  105. ++column;
  106. }
  107. ++pos;
  108. }
  109. // Match the next token.
  110. if (matchPos == text.Length) {
  111. // EOF
  112. currentToken = "";
  113. } else {
  114. Match match = TokenPattern.Match(text, matchPos);
  115. if (match.Success) {
  116. currentToken = match.Value;
  117. matchPos += match.Length;
  118. } else {
  119. // Take one character.
  120. currentToken = text[matchPos].ToString();
  121. matchPos++;
  122. }
  123. SkipWhitespace();
  124. }
  125. }
  126. /// <summary>
  127. /// Skip over any whitespace so that matchPos starts at the next token.
  128. /// </summary>
  129. private void SkipWhitespace() {
  130. Match match = WhitespaceAndCommentPattern.Match(text, matchPos);
  131. if (match.Success) {
  132. matchPos += match.Length;
  133. }
  134. }
  135. /// <summary>
  136. /// If the next token exactly matches the given token, consume it and return
  137. /// true. Otherwise, return false without doing anything.
  138. /// </summary>
  139. public bool TryConsume(string token) {
  140. if (currentToken == token) {
  141. NextToken();
  142. return true;
  143. }
  144. return false;
  145. }
  146. /*
  147. * If the next token exactly matches {@code token}, consume it. Otherwise,
  148. * throw a {@link ParseException}.
  149. */
  150. /// <summary>
  151. /// If the next token exactly matches the specified one, consume it.
  152. /// Otherwise, throw a FormatException.
  153. /// </summary>
  154. /// <param name="token"></param>
  155. public void Consume(string token) {
  156. if (!TryConsume(token)) {
  157. throw CreateFormatException("Expected \"" + token + "\".");
  158. }
  159. }
  160. /// <summary>
  161. /// Returns true if the next token is an integer, but does not consume it.
  162. /// </summary>
  163. public bool LookingAtInteger() {
  164. if (currentToken.Length == 0) {
  165. return false;
  166. }
  167. char c = currentToken[0];
  168. return ('0' <= c && c <= '9') || c == '-' || c == '+';
  169. }
  170. /// <summary>
  171. /// If the next token is an identifier, consume it and return its value.
  172. /// Otherwise, throw a FormatException.
  173. /// </summary>
  174. public string ConsumeIdentifier() {
  175. foreach (char c in currentToken) {
  176. if (('a' <= c && c <= 'z') ||
  177. ('A' <= c && c <= 'Z') ||
  178. ('0' <= c && c <= '9') ||
  179. (c == '_') || (c == '.')) {
  180. // OK
  181. } else {
  182. throw CreateFormatException("Expected identifier.");
  183. }
  184. }
  185. string result = currentToken;
  186. NextToken();
  187. return result;
  188. }
  189. /// <summary>
  190. /// If the next token is a 32-bit signed integer, consume it and return its
  191. /// value. Otherwise, throw a FormatException.
  192. /// </summary>
  193. public int ConsumeInt32() {
  194. try {
  195. int result = TextFormat.ParseInt32(currentToken);
  196. NextToken();
  197. return result;
  198. } catch (FormatException e) {
  199. throw CreateIntegerParseException(e);
  200. }
  201. }
  202. /// <summary>
  203. /// If the next token is a 32-bit unsigned integer, consume it and return its
  204. /// value. Otherwise, throw a FormatException.
  205. /// </summary>
  206. public uint ConsumeUInt32() {
  207. try {
  208. uint result = TextFormat.ParseUInt32(currentToken);
  209. NextToken();
  210. return result;
  211. } catch (FormatException e) {
  212. throw CreateIntegerParseException(e);
  213. }
  214. }
  215. /// <summary>
  216. /// If the next token is a 64-bit signed integer, consume it and return its
  217. /// value. Otherwise, throw a FormatException.
  218. /// </summary>
  219. public long ConsumeInt64() {
  220. try {
  221. long result = TextFormat.ParseInt64(currentToken);
  222. NextToken();
  223. return result;
  224. } catch (FormatException e) {
  225. throw CreateIntegerParseException(e);
  226. }
  227. }
  228. /// <summary>
  229. /// If the next token is a 64-bit unsigned integer, consume it and return its
  230. /// value. Otherwise, throw a FormatException.
  231. /// </summary>
  232. public ulong ConsumeUInt64() {
  233. try {
  234. ulong result = TextFormat.ParseUInt64(currentToken);
  235. NextToken();
  236. return result;
  237. } catch (FormatException e) {
  238. throw CreateIntegerParseException(e);
  239. }
  240. }
  241. /// <summary>
  242. /// If the next token is a double, consume it and return its value.
  243. /// Otherwise, throw a FormatException.
  244. /// </summary>
  245. public double ConsumeDouble() {
  246. // We need to parse infinity and nan separately because
  247. // double.Parse() does not accept "inf", "infinity", or "nan".
  248. if (DoubleInfinity.IsMatch(currentToken)) {
  249. bool negative = currentToken.StartsWith("-");
  250. NextToken();
  251. return negative ? double.NegativeInfinity : double.PositiveInfinity;
  252. }
  253. if (currentToken.Equals("nan", StringComparison.InvariantCultureIgnoreCase)) {
  254. NextToken();
  255. return Double.NaN;
  256. }
  257. try {
  258. double result = double.Parse(currentToken, CultureInfo.InvariantCulture);
  259. NextToken();
  260. return result;
  261. } catch (FormatException e) {
  262. throw CreateFloatParseException(e);
  263. } catch (OverflowException e) {
  264. throw CreateFloatParseException(e);
  265. }
  266. }
  267. /// <summary>
  268. /// If the next token is a float, consume it and return its value.
  269. /// Otherwise, throw a FormatException.
  270. /// </summary>
  271. public float ConsumeFloat() {
  272. // We need to parse infinity and nan separately because
  273. // Float.parseFloat() does not accept "inf", "infinity", or "nan".
  274. if (FloatInfinity.IsMatch(currentToken)) {
  275. bool negative = currentToken.StartsWith("-");
  276. NextToken();
  277. return negative ? float.NegativeInfinity : float.PositiveInfinity;
  278. }
  279. if (FloatNan.IsMatch(currentToken)) {
  280. NextToken();
  281. return float.NaN;
  282. }
  283. if (currentToken.EndsWith("f")) {
  284. currentToken = currentToken.TrimEnd('f');
  285. }
  286. try {
  287. float result = float.Parse(currentToken, CultureInfo.InvariantCulture);
  288. NextToken();
  289. return result;
  290. } catch (FormatException e) {
  291. throw CreateFloatParseException(e);
  292. } catch (OverflowException e) {
  293. throw CreateFloatParseException(e);
  294. }
  295. }
  296. /// <summary>
  297. /// If the next token is a Boolean, consume it and return its value.
  298. /// Otherwise, throw a FormatException.
  299. /// </summary>
  300. public bool ConsumeBoolean() {
  301. if (currentToken == "true") {
  302. NextToken();
  303. return true;
  304. }
  305. if (currentToken == "false") {
  306. NextToken();
  307. return false;
  308. }
  309. throw CreateFormatException("Expected \"true\" or \"false\".");
  310. }
  311. /// <summary>
  312. /// If the next token is a string, consume it and return its (unescaped) value.
  313. /// Otherwise, throw a FormatException.
  314. /// </summary>
  315. public string ConsumeString() {
  316. return ConsumeByteString().ToStringUtf8();
  317. }
  318. /// <summary>
  319. /// If the next token is a string, consume it, unescape it as a
  320. /// ByteString and return it. Otherwise, throw a FormatException.
  321. /// </summary>
  322. public ByteString ConsumeByteString() {
  323. char quote = currentToken.Length > 0 ? currentToken[0] : '\0';
  324. if (quote != '\"' && quote != '\'') {
  325. throw CreateFormatException("Expected string.");
  326. }
  327. if (currentToken.Length < 2 ||
  328. currentToken[currentToken.Length-1] != quote) {
  329. throw CreateFormatException("String missing ending quote.");
  330. }
  331. try {
  332. string escaped = currentToken.Substring(1, currentToken.Length - 2);
  333. ByteString result = TextFormat.UnescapeBytes(escaped);
  334. NextToken();
  335. return result;
  336. } catch (FormatException e) {
  337. throw CreateFormatException(e.Message);
  338. }
  339. }
  340. /// <summary>
  341. /// Returns a format exception with the current line and column numbers
  342. /// in the description, suitable for throwing.
  343. /// </summary>
  344. public FormatException CreateFormatException(string description) {
  345. // Note: People generally prefer one-based line and column numbers.
  346. return new FormatException((line + 1) + ":" + (column + 1) + ": " + description);
  347. }
  348. /// <summary>
  349. /// Returns a format exception with the line and column numbers of the
  350. /// previous token in the description, suitable for throwing.
  351. /// </summary>
  352. public FormatException CreateFormatExceptionPreviousToken(string description) {
  353. // Note: People generally prefer one-based line and column numbers.
  354. return new FormatException((previousLine + 1) + ":" + (previousColumn + 1) + ": " + description);
  355. }
  356. /// <summary>
  357. /// Constructs an appropriate FormatException for the given existing exception
  358. /// when trying to parse an integer.
  359. /// </summary>
  360. private FormatException CreateIntegerParseException(FormatException e) {
  361. return CreateFormatException("Couldn't parse integer: " + e.Message);
  362. }
  363. /// <summary>
  364. /// Constructs an appropriate FormatException for the given existing exception
  365. /// when trying to parse a float or double.
  366. /// </summary>
  367. private FormatException CreateFloatParseException(Exception e) {
  368. return CreateFormatException("Couldn't parse number: " + e.Message);
  369. }
  370. }
  371. }