OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, 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 library matcher.util; |
| 6 |
| 7 import 'core_matchers.dart'; |
| 8 import 'interfaces.dart'; |
| 9 |
| 10 /// A [Map] between whitespace characters and their escape sequences. |
| 11 const _escapeMap = const { |
| 12 '\n': r'\n', |
| 13 '\r': r'\r', |
| 14 '\f': r'\f', |
| 15 '\b': r'\b', |
| 16 '\t': r'\t', |
| 17 '\v': r'\v', |
| 18 '\x7F': r'\x7F', // delete |
| 19 }; |
| 20 |
| 21 /// A [RegExp] that matches whitespace characters that should be escaped. |
| 22 final _escapeRegExp = new RegExp( |
| 23 "[\\x00-\\x07\\x0E-\\x1F${_escapeMap.keys.map(_getHexLiteral).join()}]"); |
| 24 |
| 25 /// Useful utility for nesting match states. |
| 26 void addStateInfo(Map matchState, Map values) { |
| 27 var innerState = new Map.from(matchState); |
| 28 matchState.clear(); |
| 29 matchState['state'] = innerState; |
| 30 matchState.addAll(values); |
| 31 } |
| 32 |
| 33 /// Takes an argument and returns an equivalent [Matcher]. |
| 34 /// |
| 35 /// If the argument is already a matcher this does nothing, |
| 36 /// else if the argument is a function, it generates a predicate |
| 37 /// function matcher, else it generates an equals matcher. |
| 38 Matcher wrapMatcher(x) { |
| 39 if (x is Matcher) { |
| 40 return x; |
| 41 } else if (x is Function) { |
| 42 return predicate(x); |
| 43 } else { |
| 44 return equals(x); |
| 45 } |
| 46 } |
| 47 |
| 48 /// Returns [str] with all whitespace characters represented as their escape |
| 49 /// sequences. |
| 50 /// |
| 51 /// Backslash characters are escaped as `\\` |
| 52 String escape(String str) { |
| 53 str = str.replaceAll('\\', r'\\'); |
| 54 return str.replaceAllMapped(_escapeRegExp, (match) { |
| 55 var mapped = _escapeMap[match[0]]; |
| 56 if (mapped != null) return mapped; |
| 57 return _getHexLiteral(match[0]); |
| 58 }); |
| 59 } |
| 60 |
| 61 /// Given single-character string, return the hex-escaped equivalent. |
| 62 String _getHexLiteral(String input) { |
| 63 int rune = input.runes.single; |
| 64 return r'\x' + rune.toRadixString(16).toUpperCase().padLeft(2, '0'); |
| 65 } |
OLD | NEW |