OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 /// A library for broadly-useful functions and regular expressions for scanning |
| 6 /// HTTP entities. |
| 7 /// |
| 8 /// Many of the regular expressions come from [section 2.2 of the HTTP |
| 9 /// spec][spec]. |
| 10 /// |
| 11 /// [spec]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html |
| 12 library http_parser.scan; |
| 13 |
| 14 import 'package:string_scanner/string_scanner.dart'; |
| 15 |
| 16 /// An HTTP token. |
| 17 final token = new RegExp(r'[^()<>@,;:"\\/[\]?={} \t\x00-\x1F\x7F]+'); |
| 18 |
| 19 /// Linear whitespace. |
| 20 final _lws = new RegExp(r"(?:\r\n)?[ \t]+"); |
| 21 |
| 22 /// A quoted string. |
| 23 final _quotedString = new RegExp(r'"(?:[^"\x00-\x1F\x7F]|\\.)*"'); |
| 24 |
| 25 /// A quoted pair. |
| 26 final _quotedPair = new RegExp(r'\\(.)'); |
| 27 |
| 28 /// A character that is *not* a valid HTTP token. |
| 29 final nonToken = new RegExp(r'[()<>@,;:"\\/\[\]?={} \t\x00-\x1F\x7F]'); |
| 30 |
| 31 /// A regular expression matching any number of [_lws] productions in a row. |
| 32 final whitespace = new RegExp("(?:${_lws.pattern})*"); |
| 33 |
| 34 /// Parses a list of elements, as in `1#element` in the HTTP spec. |
| 35 /// |
| 36 /// [scanner] is used to parse the elements, and [parseElement] is used to parse |
| 37 /// each one individually. The values returned by [parseElement] are collected |
| 38 /// in a list and returned. |
| 39 /// |
| 40 /// Once this is finished, [scanner] will be at the next non-LWS character in |
| 41 /// the string, or the end of the string. |
| 42 List parseList(StringScanner scanner, parseElement()) { |
| 43 var result = []; |
| 44 |
| 45 // Consume initial empty values. |
| 46 while (scanner.scan(",")) { |
| 47 scanner.scan(whitespace); |
| 48 } |
| 49 |
| 50 result.add(parseElement()); |
| 51 scanner.scan(whitespace); |
| 52 |
| 53 while (scanner.scan(",")) { |
| 54 scanner.scan(whitespace); |
| 55 |
| 56 // Empty elements are allowed, but excluded from the results. |
| 57 if (scanner.matches(",") || scanner.isDone) continue; |
| 58 |
| 59 result.add(parseElement()); |
| 60 scanner.scan(whitespace); |
| 61 } |
| 62 |
| 63 return result; |
| 64 } |
| 65 |
| 66 /// Parses a single quoted string, and returns its contents. |
| 67 /// |
| 68 /// If [name] is passed, it's used to describe the expected value if it's not |
| 69 /// found. |
| 70 String expectQuotedString(StringScanner scanner, {String name}) { |
| 71 if (name == null) name = "quoted string"; |
| 72 scanner.expect(_quotedString, name: name); |
| 73 var string = scanner.lastMatch[0]; |
| 74 return string |
| 75 .substring(1, string.length - 1) |
| 76 .replaceAllMapped(_quotedPair, (match) => match[1]); |
| 77 } |
OLD | NEW |