1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
//! Various basic types for YAML handling
//!
use doc_comment::doc_comment;
use hashlink::LinkedHashMap;
use std::borrow::{Borrow, Cow};
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
use yaml_rust::Yaml as YamlNode;
/// A displayable marker for a YAML node
///
/// While `Marker` can be `Display`'d it doesn't understand what its source
/// means. This struct is the result of asking a Marker to render itself.
///
/// ```
/// # use marked_yaml::*;
/// let filenames = vec!["examples/everything.yaml"];
/// let nodes: Vec<_> = filenames
/// .iter()
/// .enumerate()
/// .map(|(i, name)| parse_yaml(i, std::fs::read_to_string(name).unwrap()).unwrap())
/// .collect();
/// for (n, node) in nodes.iter().enumerate() {
/// let marker = node.span().start().unwrap();
/// let rendered = format!("{}", marker.render(|i| filenames[i]));
/// assert!(rendered.starts_with(filenames[n]));
/// }
/// ```
pub struct RenderedMarker<D> {
source: D,
line: usize,
column: usize,
}
impl<D> Display for RenderedMarker<D>
where
D: Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.source.fmt(f)?;
write!(f, ":{}:{}", self.line, self.column)
}
}
/// A marker for a YAML node
///
/// This indicates where a node started or ended.
///
/// ```
/// use marked_yaml::{parse_yaml, Marker};
/// let node = parse_yaml(100, "{foo: bar}").unwrap();
/// let map = node.as_mapping().unwrap();
/// let bar = map.get("foo").unwrap();
/// // the "bar" string started on line 1, column 7 of source ID 100.
/// assert_eq!(bar.span().start(), Some(&Marker::new(100, 1, 7)));
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Marker {
source: usize,
line: usize,
column: usize,
}
impl Marker {
/// Create a new Marker
///
/// This will typically not be used because markers will come from
/// parsing YAML, however it is provided for completeness and in case
/// you need it for your own tests.
///
/// ```
/// # use marked_yaml::Marker;
/// let marker = Marker::new(0, 1, 2);
/// # assert_eq!(marker.source(), 0);
/// # assert_eq!(marker.line(), 1);
/// # assert_eq!(marker.column(), 2);
/// ```
pub fn new(source: usize, line: usize, column: usize) -> Self {
Self {
source,
line,
column,
}
}
/// The source index given for this marker.
///
/// When parsing YAML, we record where nodes start (and often finish).
/// This is the source index provided when parsing the YAML. Likely this
/// refers to a vector of PathBuf recording where input came from, but that
/// is entirely up to the user of this library crate.
///
/// This is likely most useful to computers, not humans.
///
/// ```
/// # use marked_yaml::Marker;
/// # let marker = Marker::new(0, 1, 2);
/// assert_eq!(marker.source(), 0);
/// ```
pub fn source(&self) -> usize {
self.source
}
/// The line number on which this marker resides, 1-indexed
///
/// When parsing YAML, we record where nodes start (and often finish).
/// This is the line number of where this marker resides. Line numbers
/// start with 1 to make them more useful to humans.
///
/// ```
/// # use marked_yaml::Marker;
/// # let marker = Marker::new(0, 1, 2);
/// assert_eq!(marker.line(), 1);
/// ```
pub fn line(&self) -> usize {
self.line
}
/// The column number at which this marker resides, 1-indexed
///
/// When parsing YAML, we record where nodes start (and often finish).
/// This is the column number of where this marker resides. Column numbers
/// start with 1 to make them more useful to humans.
///
/// ```
/// # use marked_yaml::Marker;
/// # let marker = Marker::new(0, 1, 2);
/// assert_eq!(marker.column(), 2);
/// ```
pub fn column(&self) -> usize {
self.column
}
/// Render this marker
///
/// Markers have a source identifier, typically as passed to `parse_yaml()`
/// but have no way in and of themselves to turn that into a useful name.
/// This function allows you to create a rendered marker which knows how
/// to show the source name.
///
/// ```
/// # use marked_yaml::Marker;
/// # let marker = Marker::new(0, 1, 2);
/// let rendered = marker.render(|_| "name");
/// assert_eq!(format!("{}", rendered), "name:1:2")
/// ```
pub fn render<D, F>(self, renderfn: F) -> RenderedMarker<D>
where
D: Display,
F: FnOnce(usize) -> D,
{
RenderedMarker {
source: renderfn(self.source),
line: self.line,
column: self.column,
}
}
/// Set the source index for this marker
///
/// ```
/// # use marked_yaml::Marker;
/// # let mut marker = Marker::new(0, 0, 0);
/// assert_ne!(marker.source(), 1);
/// marker.set_source(1);
/// assert_eq!(marker.source(), 1);
/// ```
pub fn set_source(&mut self, source: usize) {
self.source = source;
}
/// Set the line number for this marker
///
/// ```
/// # use marked_yaml::Marker;
/// # let mut marker = Marker::new(0, 0, 0);
/// assert_ne!(marker.line(), 1);
/// marker.set_line(1);
/// assert_eq!(marker.line(), 1);
/// ```
pub fn set_line(&mut self, line: usize) {
self.line = line;
}
/// Set the column number for this marker
///
/// ```
/// # use marked_yaml::Marker;
/// # let mut marker = Marker::new(0, 0, 0);
/// assert_ne!(marker.column(), 1);
/// marker.set_column(1);
/// assert_eq!(marker.column(), 1);
/// ```
pub fn set_column(&mut self, column: usize) {
self.column = column;
}
}
impl Display for Marker {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}", self.line, self.column)
}
}
/// The span for a YAML marked node
///
/// ```
/// use marked_yaml::{parse_yaml, Marker, Span};
/// let node = parse_yaml(100, "{foo: bar}").unwrap();
/// let map = node.as_mapping().unwrap();
/// assert_eq!(map.span(), &Span::new_with_marks(Marker::new(100, 1, 1), Marker::new(100, 1, 10)));
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Span {
start: Option<Marker>,
end: Option<Marker>,
}
impl Span {
/// Create a span with no marker information
///
/// Sometimes we simply do not know where information came from (for example
/// if it was created by software) and in that case we can create a blank
/// span.
///
/// ```
/// # use marked_yaml::Span;
/// let blank = Span::new_blank();
/// # assert_eq!(blank.start(), None);
/// # assert_eq!(blank.end(), None);
/// ```
pub fn new_blank() -> Self {
Self {
start: None,
end: None,
}
}
/// Create a span with only start information
///
/// Sometimes when creating a span we know where it started but not where
/// it ends. This might be during parsing, or for some other reason.
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// let span = Span::new_start(Marker::new(0, 1, 2));
/// # assert_eq!(span.start().unwrap(), &Marker::new(0, 1, 2));
/// # assert_eq!(span.end(), None);
/// ```
pub fn new_start(start: Marker) -> Self {
Self {
start: Some(start),
end: None,
}
}
/// Create a span with both start and end markers
///
/// When we know both the start and end of a node, we can create a span
/// which has all that knowledge.
///
/// ```
/// # use marked_yaml::{Marker,Span};
/// let span = Span::new_with_marks(Marker::new(0, 1, 1), Marker::new(10, 2, 1));
/// # assert_eq!(span.start().unwrap(), &Marker::new(0, 1, 1));
/// # assert_eq!(span.end().unwrap(), &Marker::new(10, 2, 1));
/// ```
pub fn new_with_marks(start: Marker, end: Marker) -> Self {
Self {
start: Some(start),
end: Some(end),
}
}
/// The start of the span
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// # let span = Span::new_with_marks(Marker::new(0, 1, 1), Marker::new(10, 2, 1));
/// assert_eq!(span.start(), Some(&Marker::new(0, 1, 1)));
/// ```
pub fn start(&self) -> Option<&Marker> {
self.start.as_ref()
}
/// The end of the span
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// # let span = Span::new_with_marks(Marker::new(0, 1, 1), Marker::new(10, 2, 1));
/// assert_eq!(span.end(), Some(&Marker::new(10, 2, 1)));
/// ```
pub fn end(&self) -> Option<&Marker> {
self.end.as_ref()
}
/// The start of the span, mutably
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// # let mut span = Span::new_with_marks(Marker::new(0, 1, 1), Marker::new(10, 2, 1));
/// span.start_mut().unwrap().set_line(5);
/// assert_eq!(span.start(), Some(&Marker::new(0, 5, 1)));
/// ```
pub fn start_mut(&mut self) -> Option<&mut Marker> {
self.start.as_mut()
}
/// The end of the span, mutably
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// # let mut span = Span::new_with_marks(Marker::new(0, 1, 1), Marker::new(10, 2, 1));
/// span.end_mut().unwrap().set_line(5);
/// assert_eq!(span.end(), Some(&Marker::new(10, 5, 1)));
/// ```
pub fn end_mut(&mut self) -> Option<&mut Marker> {
self.end.as_mut()
}
/// Replace the start of the span
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// # let mut span = Span::new_blank();
/// assert_eq!(span.start(), None);
/// span.set_start(Some(Marker::new(0, 1, 2)));
/// assert_eq!(span.start(), Some(&Marker::new(0, 1, 2)));
/// ```
pub fn set_start(&mut self, start: Option<Marker>) {
self.start = start;
}
/// Replace the end of the span
///
/// ```
/// # use marked_yaml::{Marker, Span};
/// # let mut span = Span::new_blank();
/// assert_eq!(span.end(), None);
/// span.set_end(Some(Marker::new(0, 1, 2)));
/// assert_eq!(span.end(), Some(&Marker::new(0, 1, 2)));
/// ```
pub fn set_end(&mut self, end: Option<Marker>) {
self.end = end;
}
}
/// A marked YAML node
///
/// **NOTE**: Nodes are considered equal even if they don't come from the
/// same place. *i.e. their spans are ignored for equality and hashing*
///
/// ```
/// use marked_yaml::parse_yaml;
/// let node = parse_yaml(100, "{foo: bar}").unwrap();
/// assert!(node.as_mapping().is_some());
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Node {
/// A YAML scalar
///
/// You can test if a node is a scalar, and retrieve it as one if you
/// so wish.
Scalar(MarkedScalarNode),
/// A YAML mapping
///
/// You can test if a node is a mapping, and retrieve it as one if you
/// so wish.
Mapping(MarkedMappingNode),
/// A YAML sequence
///
/// You can test if a node is a sequence, and retrieve it as one if you
/// so wish.
Sequence(MarkedSequenceNode),
}
/// A marked scalar YAML node
///
/// Scalar nodes are treated by this crate as strings, though a few special
/// values are processed into the types which YAML would ascribe. In particular
/// strings of the value `null`, `true`, `false`, etc. are able to present as
/// their special values to make it a bit easier for users of the crate.
///
/// **NOTE**: Nodes are considered equal even if they don't come from the
/// same place. *i.e. their spans are ignored for equality and hashing*
///
/// ```
/// use marked_yaml::{parse_yaml, Marker};
/// let node = parse_yaml(100, "{foo: bar}").unwrap();
/// let map = node.as_mapping().unwrap();
/// let bar = map.get("foo").unwrap();
/// // the "bar" string started on line 1, column 7 of source ID 100.
/// assert_eq!(bar.span().start(), Some(&Marker::new(100, 1, 7)));
/// ```
#[derive(Clone, Debug)]
pub struct MarkedScalarNode {
span: Span,
value: String,
may_coerce: bool,
}
pub(crate) type MappingHash = LinkedHashMap<MarkedScalarNode, Node>;
/// A marked YAML mapping node
///
/// Mapping nodes in YAML are defined as a key/value mapping where the keys are
/// unique and always scalars, whereas values may be YAML nodes of any kind.
///
/// Because *some* users of this crate may need to care about insertion order
/// we use [`hashlink::LinkedHashMap`] for this.
///
/// **NOTE**: Nodes are considered equal even if they don't come from the
/// same place. *i.e. their spans are ignored for equality and hashing*
///
/// ```
/// use marked_yaml::{parse_yaml, Marker, Span};
/// let node = parse_yaml(100, "{foo: bar}").unwrap();
/// let map = node.as_mapping().unwrap();
/// assert_eq!(map.span(), &Span::new_with_marks(Marker::new(100, 1, 1), Marker::new(100, 1, 10)));
/// ```
#[derive(Clone, Debug)]
pub struct MarkedMappingNode {
span: Span,
value: MappingHash,
}
/// A marked YAML sequence node
///
/// Sequence nodes in YAML are simply ordered lists of YAML nodes.
///
/// **NOTE**: Nodes are considered equal even if they don't come from the
/// same place. *i.e. their spans are ignored for equality and hashing*
///
/// ```
/// use marked_yaml::{parse_yaml, Marker, Span};
/// let node = parse_yaml(100, "{foo: [bar]}").unwrap();
/// let map = node.as_mapping().unwrap();
/// let seq = map.get("foo").unwrap();
/// let seq = seq.as_sequence().unwrap();
/// assert_eq!(seq.span(), &Span::new_with_marks(Marker::new(100, 1, 7), Marker::new(100, 1, 11)));
/// ```
#[derive(Clone, Debug)]
pub struct MarkedSequenceNode {
span: Span,
value: Vec<Node>,
}
macro_rules! basic_traits {
($t:path) => {
impl PartialEq for $t {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
#[allow(clippy::partialeq_ne_impl)]
fn ne(&self, other: &Self) -> bool {
self.value != other.value
}
}
impl Eq for $t {}
impl Hash for $t {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
};
}
basic_traits!(MarkedScalarNode);
basic_traits!(MarkedSequenceNode);
basic_traits!(MarkedMappingNode);
impl<T> From<T> for Node
where
T: Into<MarkedScalarNode>,
{
fn from(value: T) -> Node {
Node::Scalar(value.into())
}
}
impl From<MarkedSequenceNode> for Node {
fn from(value: MarkedSequenceNode) -> Node {
Node::Sequence(value)
}
}
impl<T> From<Vec<T>> for Node
where
T: Into<Node>,
{
fn from(value: Vec<T>) -> Node {
Node::Sequence(value.into_iter().collect())
}
}
impl From<MarkedMappingNode> for Node {
fn from(value: MarkedMappingNode) -> Node {
Node::Mapping(value)
}
}
impl From<MappingHash> for Node {
fn from(value: MappingHash) -> Node {
Node::Mapping(value.into())
}
}
macro_rules! node_span {
($t:path) => {
impl $t {
doc_comment!(
concat!(
r#"Retrieve the Span from this node.
```
# use marked_yaml::types::*;
let node = "#,
stringify!($t),
r#"::new_empty(Span::new_blank());
assert_eq!(node.span(), &Span::new_blank());
```"#
),
pub fn span(&self) -> &Span {
&self.span
}
);
doc_comment!(
concat!(
r#"Retrieve the Span from this node mutably.
```
# use marked_yaml::types::*;
let mut node = "#,
stringify!($t),
r#"::new_empty(Span::new_blank());
node.span_mut().set_start(Some(Marker::new(0, 1, 0)));
assert_eq!(node.span().start(), Some(&Marker::new(0, 1, 0)));
```"#
),
pub fn span_mut(&mut self) -> &mut Span {
&mut self.span
}
);
}
};
}
node_span!(MarkedScalarNode);
node_span!(MarkedMappingNode);
node_span!(MarkedSequenceNode);
impl Node {
/// Retrieve the Span from the contained Node
///
/// ```
/// # use marked_yaml::types::*;
/// let node: Node = "foobar".into();
/// let span = node.span();
/// assert_eq!(span.start(), None);
/// ```
pub fn span(&self) -> &Span {
match self {
Node::Scalar(msn) => msn.span(),
Node::Sequence(msn) => msn.span(),
Node::Mapping(mmn) => mmn.span(),
}
}
/// Retrieve the Span from the contained Node, mutably
///
/// ```
/// # use marked_yaml::types::*;
/// let mut node: Node = "foobar".into();
/// let mut span = node.span_mut();
/// assert_eq!(span.start(), None);
/// span.set_start(Some(Marker::new(0, 1, 0)));
/// assert_eq!(span.start(), Some(&Marker::new(0, 1, 0)));
/// ```
pub fn span_mut(&mut self) -> &mut Span {
match self {
Node::Scalar(msn) => msn.span_mut(),
Node::Sequence(msn) => msn.span_mut(),
Node::Mapping(mmn) => mmn.span_mut(),
}
}
/// Retrieve the scalar from this node if there is one
///
/// ```
/// # use marked_yaml::types::*;
/// let node: Node = "foobar".into();
/// let scalar = node.as_scalar();
/// assert!(scalar.is_some());
/// ```
pub fn as_scalar(&self) -> Option<&MarkedScalarNode> {
match self {
Node::Scalar(msn) => Some(msn),
_ => None,
}
}
/// Retrieve the sequence from this node if there is one
///
/// ```
/// # use marked_yaml::types::*;
/// let node: Node = vec!["foobar"].into();
/// let sequence = node.as_sequence();
/// assert!(sequence.is_some());
/// ```
pub fn as_sequence(&self) -> Option<&MarkedSequenceNode> {
match self {
Node::Sequence(msn) => Some(msn),
_ => None,
}
}
/// Retrieve the mapping from this node if there is one
///
/// ```
/// # use marked_yaml::*;
/// let node: Node = parse_yaml(0, "{foobar: baz}").unwrap();
/// let mapping = node.as_mapping();
/// assert!(mapping.is_some());
/// ```
pub fn as_mapping(&self) -> Option<&MarkedMappingNode> {
match self {
Node::Mapping(mmn) => Some(mmn),
_ => None,
}
}
/// Retrieve the scalar from this node if there is one, mutably
///
/// ```
/// # use marked_yaml::types::*;
/// let mut node: Node = "foobar".into();
/// let mut scalar = node.as_scalar_mut();
/// assert!(scalar.is_some());
/// ```
pub fn as_scalar_mut(&mut self) -> Option<&mut MarkedScalarNode> {
match self {
Node::Scalar(msn) => Some(msn),
_ => None,
}
}
/// Retrieve the sequence from this node if there is one, mutably
///
/// ```
/// # use marked_yaml::types::*;
/// let mut node: Node = vec!["foobar"].into();
/// let mut sequence = node.as_sequence_mut();
/// assert!(sequence.is_some());
/// ```
pub fn as_sequence_mut(&mut self) -> Option<&mut MarkedSequenceNode> {
match self {
Node::Sequence(msn) => Some(msn),
_ => None,
}
}
/// Retrieve the mapping from this node if there is one, mutably
///
/// ```
/// # use marked_yaml::*;
/// let mut node: Node = parse_yaml(0, "{foobar: baz}").unwrap();
/// let mut mapping = node.as_mapping_mut();
/// assert!(mapping.is_some());
/// ```
pub fn as_mapping_mut(&mut self) -> Option<&mut MarkedMappingNode> {
match self {
Node::Mapping(mmn) => Some(mmn),
_ => None,
}
}
}
impl MarkedScalarNode {
/// Create a new scalar node with no value
///
/// ```
/// # use marked_yaml::types::*;
/// let node = MarkedScalarNode::new_empty(Span::new_blank());
/// ```
pub fn new_empty(span: Span) -> Self {
Self {
span,
value: String::new(),
may_coerce: true,
}
}
/// Create a new scalar node
///
/// ```
/// # use marked_yaml::types::*;
/// let node = MarkedScalarNode::new(Span::new_blank(), "foobar");
/// ```
pub fn new<'a, S: Into<Cow<'a, str>>>(span: Span, content: S) -> Self {
Self {
span,
value: content.into().into_owned(),
may_coerce: true,
}
}
/// Treat the scalar node as a string
///
/// Since scalars are always stringish, this is always safe.
///
/// ```
/// # use marked_yaml::types::*;
/// let node: MarkedScalarNode = "foobar".into();
/// assert_eq!(node.as_str(), "foobar");
/// ```
pub fn as_str(&self) -> &str {
self.value.as_str()
}
/// Enable or disable permission to coerce values
///
/// The various [`as_bool()`][Self::as_bool()] and other methods
/// which can coerce a string can be forced to always deny
/// coercion.
///
#[cfg_attr(
feature = "serde",
doc = r#"
Note: this also applies for deserializing nodes via serde.
"#
)]
/// ```
/// # use marked_yaml::types::*;
/// let mut node: MarkedScalarNode = "true".into();
/// assert_eq!(node.as_bool(), Some(true));
/// node.set_coerce(false);
/// assert_eq!(node.as_bool(), None);
/// ```
pub fn set_coerce(&mut self, may_coerce: bool) {
self.may_coerce = may_coerce;
}
/// Retrieve whether or not this node is set to be coerceable
///
/// The various [`as_bool()`][Self::as_bool()] and other methods
/// which can coerce a string can be forced to deny coercion.
///
#[cfg_attr(
feature = "serde",
doc = r#"
Note: this also applies for deserializing nodes via serde.
"#
)]
/// ```
/// # use marked_yaml::types::*;
/// let mut node: MarkedScalarNode = "true".into();
/// assert_eq!(node.as_bool(), Some(true));
/// assert_eq!(node.may_coerce(), true);
/// node.set_coerce(false);
/// assert_eq!(node.as_bool(), None);
/// assert_eq!(node.may_coerce(), false);
/// ```
pub fn may_coerce(&self) -> bool {
self.may_coerce
}
/// Treat the scalar node as a boolean
///
/// If the scalar contains any of the following then it is true:
///
/// * `true`
/// * `True`
/// * `TRUE`
///
/// The following are considered false:
///
/// * `false`
/// * `False`
/// * `FALSE`
///
/// Everything else is not a boolean and so will return None
///
/// Note: If you have done [`.set_coerce(false)`](MarkedScalarNode::set_coerce())
/// then no matter the string's value, this will return `None`.
///
/// ```
/// # use marked_yaml::types::*;
/// let node: MarkedScalarNode = "true".into();
/// assert_eq!(node.as_bool(), Some(true));
/// let node: MarkedScalarNode = "FALSE".into();
/// assert_eq!(node.as_bool(), Some(false));
/// let node: MarkedScalarNode = "NO".into(); // YAML boolean, but not for us
/// assert_eq!(node.as_bool(), None);
/// let mut node: MarkedScalarNode = "true".into();
/// node.set_coerce(false);
/// assert_eq!(node.as_bool(), None);
/// ```
pub fn as_bool(&self) -> Option<bool> {
if self.may_coerce {
match self.value.as_str() {
"true" | "True" | "TRUE" => Some(true),
"false" | "False" | "FALSE" => Some(false),
_ => None,
}
} else {
None
}
}
}
impl<'a> From<&'a str> for MarkedScalarNode {
/// Convert from any borrowed string into a node
///
/// ```
/// # use marked_yaml::types::*;
/// let node: MarkedScalarNode = "foobar".into();
/// ```
fn from(value: &'a str) -> Self {
Self::new(Span::new_blank(), value)
}
}
impl From<String> for MarkedScalarNode {
/// Convert from any owned string into a node
///
/// ```
/// # use marked_yaml::types::*;
/// let foobar = "foobar".to_string();
/// let node: MarkedScalarNode = foobar.into();
/// ```
fn from(value: String) -> Self {
Self::new(Span::new_blank(), value)
}
}
impl From<bool> for MarkedScalarNode {
/// Convert from a boolean into a node
///
/// ```
/// # use marked_yaml::types::*;
/// let node = MarkedScalarNode::from(true);
/// ```
fn from(value: bool) -> Self {
if value {
"true".into()
} else {
"false".into()
}
}
}
macro_rules! scalar_from_to_number {
($t:ident, $as:ident) => {
scalar_from_to_number!($t, $as, 0);
};
($t:ident, $as:ident, $zero:expr) => {
impl From<$t> for MarkedScalarNode {
doc_comment!(
concat!(
"Convert from ",
stringify!($t),
r#" into a node
```
# use marked_yaml::types::*;
let value: "#,
stringify!($t),
" = ",
stringify!($zero),
r#";
let node: MarkedScalarNode = value.into();
assert_eq!(&*node, "0");
```"#
),
fn from(value: $t) -> Self {
format!("{}", value).into()
}
);
}
impl MarkedScalarNode {
doc_comment!(
concat!(
"Treat the scalar node as ",
stringify!($t),
r#".
If this scalar node's value can be represented properly as
a number of the right kind then return it. This is essentially
a shortcut for using the `FromStr` trait on the return value of
`.as_str()`.
Note, this honours the setting of [`MarkedScalarNode::set_coerce()`]
```
# use marked_yaml::types::*;
let mut node: MarkedScalarNode = "0".into();
assert_eq!(node.as_"#,
stringify!($t),
r#"(), Some(0"#,
stringify!($t),
r#"));
node.set_coerce(false);
assert_eq!(node.as_"#,
stringify!($t),
r#"(), None);
```"#
),
pub fn $as(&self) -> Option<$t> {
if self.may_coerce {
use std::str::FromStr;
$t::from_str(&self.value).ok()
} else {
None
}
}
);
}
};
}
scalar_from_to_number!(i8, as_i8);
scalar_from_to_number!(i16, as_i16);
scalar_from_to_number!(i32, as_i32);
scalar_from_to_number!(i64, as_i64);
scalar_from_to_number!(i128, as_i128);
scalar_from_to_number!(isize, as_isize);
scalar_from_to_number!(u8, as_u8);
scalar_from_to_number!(u16, as_u16);
scalar_from_to_number!(u32, as_u32);
scalar_from_to_number!(u64, as_u64);
scalar_from_to_number!(u128, as_u128);
scalar_from_to_number!(usize, as_usize);
scalar_from_to_number!(f32, as_f32, 0.0);
scalar_from_to_number!(f64, as_f64, 0.0);
impl Deref for MarkedScalarNode {
type Target = str;
/// Borrow the string value inside this scalar node
///
/// ```
/// # use marked_yaml::types::*;
/// # use std::str::FromStr;
/// let truth: MarkedScalarNode = "true".into();
/// assert!(bool::from_str(&truth).unwrap())
/// ```
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl Borrow<str> for MarkedScalarNode {
fn borrow(&self) -> &str {
&self.value
}
}
impl MarkedSequenceNode {
/// Create a new empty sequence node
///
/// ```
/// # use marked_yaml::types::*;
/// let node = MarkedSequenceNode::new_empty(Span::new_blank());
/// ```
pub fn new_empty(span: Span) -> Self {
Self {
span,
value: Vec::new(),
}
}
/// Create a new sequence node from a vector of nodes
///
/// ```
/// # use marked_yaml::types::*;
/// let node = MarkedSequenceNode::new(Span::new_blank(), Vec::new());
/// ```
pub fn new(span: Span, value: Vec<Node>) -> Self {
Self { span, value }
}
/// Get the node at the given index
///
/// If the index is invalid then None will be returned
///
/// ```
/// # use marked_yaml::types::*;
/// let seq: MarkedSequenceNode = vec!["foobar"].into_iter().collect();
/// assert_eq!(seq.get_node(0)
/// .and_then(Node::as_scalar)
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "foobar");
pub fn get_node(&self, index: usize) -> Option<&Node> {
self.value.get(index)
}
/// Get the scalar at the given index
///
/// If the index is invalid, or the node at that index is not a scalar
/// node, then None will be returned.
///
/// ```
/// # use marked_yaml::types::*;
/// let seq: MarkedSequenceNode = vec!["foobar"].into_iter().collect();
/// assert_eq!(seq.get_scalar(0)
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "foobar");
/// ```
pub fn get_scalar(&self, index: usize) -> Option<&MarkedScalarNode> {
self.get_node(index).and_then(Node::as_scalar)
}
/// Get the sequence at the given index
///
/// If the index is invalid, or the node at that index is not a sequence
/// node, then None will be returned.
///
/// ```
/// # use marked_yaml::types::*;
/// let seq: MarkedSequenceNode = vec![vec!["foobar"]].into_iter().collect();
/// assert_eq!(seq.get_sequence(0)
/// .and_then(|s| s.get_scalar(0))
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "foobar");
/// ```
pub fn get_sequence(&self, index: usize) -> Option<&MarkedSequenceNode> {
self.get_node(index).and_then(Node::as_sequence)
}
/// Get the mapping at the given index
///
/// If the index is invalid, or the node at that index is not a mapping
/// node, then None will be returned.
///
/// ```
/// # use marked_yaml::types::*;
/// # use hashlink::LinkedHashMap;
/// # let map: LinkedHashMap<MarkedScalarNode, Node> = LinkedHashMap::new();
/// let seq: MarkedSequenceNode = vec![map].into_iter().collect();
/// assert!(seq.get_mapping(0).is_some());
/// ```
pub fn get_mapping(&self, index: usize) -> Option<&MarkedMappingNode> {
self.get_node(index).and_then(Node::as_mapping)
}
}
impl Deref for MarkedSequenceNode {
type Target = Vec<Node>;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl DerefMut for MarkedSequenceNode {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
impl<T> FromIterator<T> for MarkedSequenceNode
where
T: Into<Node>,
{
/// Allow collecting things into a sequence node
///
/// ```
/// # use marked_yaml::types::*;
/// let node: MarkedSequenceNode = vec!["hello", "world"].into_iter().collect();
/// ```
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let value: Vec<Node> = iter.into_iter().map(Into::into).collect();
let span = match value.len() {
0 => Span::new_blank(),
1 => *value[0].span(),
_ => Span {
start: value[0].span().start,
end: value[value.len() - 1].span().end,
},
};
Self { span, value }
}
}
impl<T> From<Vec<T>> for MarkedSequenceNode
where
T: Into<Node>,
{
/// Allow converting from vectors of things to sequence nodes
///
/// ```
/// # use marked_yaml::types::*;
/// let node: MarkedSequenceNode = vec!["hello", "world"].into();
/// ```
fn from(value: Vec<T>) -> Self {
let value: Vec<Node> = value.into_iter().map(Into::into).collect();
let span = match value.len() {
0 => Span::new_blank(),
1 => *value[0].span(),
_ => {
let start = value[0].span().start;
let end = value[value.len() - 1].span().end;
Span { start, end }
}
};
Self { span, value }
}
}
impl MarkedMappingNode {
/// Create a new empty mapping node
///
/// ```
/// # use marked_yaml::types::*;
/// let node = MarkedMappingNode::new_empty(Span::new_blank());
/// ```
pub fn new_empty(span: Span) -> Self {
Self {
span,
value: LinkedHashMap::new(),
}
}
/// Create a new mapping node from the given hash table
///
/// ```
/// # use marked_yaml::types::*;
/// # use hashlink::LinkedHashMap;
/// let node = MarkedMappingNode::new(Span::new_blank(), LinkedHashMap::new());
/// ```
pub fn new(span: Span, value: MappingHash) -> Self {
Self { span, value }
}
/// Get the node for the given string key
///
/// If the index is not found then None is returned.
///
/// ```
/// # use marked_yaml::types::*;
/// # use marked_yaml::parse_yaml;
/// let node = parse_yaml(0, "{key: value}").unwrap();
/// let map = node.as_mapping().unwrap();
/// assert_eq!(map.get_node("key")
/// .and_then(Node::as_scalar)
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "value");
/// ```
pub fn get_node(&self, index: &str) -> Option<&Node> {
self.value.get(index)
}
/// Get the scalar for the given string key
///
/// If the key is not found, or the node for that key is not a scalar
/// node, then None will be returned.
///
/// ```
/// # use marked_yaml::types::*;
/// # use marked_yaml::parse_yaml;
/// let node = parse_yaml(0, "{key: value}").unwrap();
/// let map = node.as_mapping().unwrap();
/// assert_eq!(map.get_scalar("key")
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "value");
/// ```
pub fn get_scalar(&self, index: &str) -> Option<&MarkedScalarNode> {
self.get_node(index).and_then(Node::as_scalar)
}
/// Get the sequence at the given index
///
/// If the key is not found, or the node for that key is not a sequence
/// node, then None will be returned.
///
/// ```
/// # use marked_yaml::types::*;
/// # use marked_yaml::parse_yaml;
/// let node = parse_yaml(0, "{key: [value]}").unwrap();
/// let map = node.as_mapping().unwrap();
/// assert_eq!(map.get_sequence("key")
/// .and_then(|s| s.get_scalar(0))
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "value");
/// ```
pub fn get_sequence(&self, index: &str) -> Option<&MarkedSequenceNode> {
self.get_node(index).and_then(Node::as_sequence)
}
/// Get the mapping at the given index
///
/// If the key is not found, or the node for that key is not a mapping
/// node, then None will be returned.
///
/// ```
/// # use marked_yaml::types::*;
/// # use marked_yaml::parse_yaml;
/// let node = parse_yaml(0, "{key: {inner: value}}").unwrap();
/// let map = node.as_mapping().unwrap();
/// assert_eq!(map.get_mapping("key")
/// .and_then(|m| m.get_scalar("inner"))
/// .map(MarkedScalarNode::as_str)
/// .unwrap(),
/// "value");
/// ```
pub fn get_mapping(&self, index: &str) -> Option<&MarkedMappingNode> {
self.get_node(index).and_then(Node::as_mapping)
}
}
impl Deref for MarkedMappingNode {
type Target = MappingHash;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl DerefMut for MarkedMappingNode {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
impl From<MappingHash> for MarkedMappingNode {
fn from(value: MappingHash) -> Self {
Self::new(Span::new_blank(), value)
}
}
impl<T, U> FromIterator<(T, U)> for MarkedMappingNode
where
T: Into<MarkedScalarNode>,
U: Into<Node>,
{
/// Allow collecting into a mapping node
///
/// ```
/// # use marked_yaml::types::*;
/// # use std::collections::HashMap;
/// # let mut hashmap = HashMap::new();
/// hashmap.insert("hello", vec!["world".to_string()]);
/// hashmap.insert("key", vec!["value".to_string()]);
/// let node: MarkedMappingNode = hashmap.into_iter().collect();
/// ```
fn from_iter<I: IntoIterator<Item = (T, U)>>(iter: I) -> Self {
let value: MappingHash = iter
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
let span = match value.len() {
0 => Span::new_blank(),
// Unwrap is safe because there's at least one span here
1 => {
let (k, v) = value.iter().next().unwrap();
Span {
start: k.span().start,
end: v.span().end,
}
}
_ => {
let mut iter = value.iter();
// Unwraps save because there's at least two spans here
let start = iter.next().unwrap().0.span().start;
let end = iter.last().unwrap().1.span().end;
Span { start, end }
}
};
Self { span, value }
}
}
/// Errors which could be encountered while converting from a `yaml_rust::Yaml`
#[derive(Debug, PartialEq, Eq)]
pub enum YamlConversionError {
/// An alias was encountered while converting
Alias,
/// A BadValue was encountered while converting
BadValue,
/// A non-scalar value was encountered when a scalar was expected
NonScalar,
}
impl TryFrom<YamlNode> for MarkedScalarNode {
type Error = YamlConversionError;
fn try_from(value: YamlNode) -> Result<Self, Self::Error> {
match value {
YamlNode::Alias(_) => Err(YamlConversionError::Alias),
YamlNode::Array(_) => Err(YamlConversionError::NonScalar),
YamlNode::BadValue => Err(YamlConversionError::BadValue),
YamlNode::Boolean(b) => Ok(b.into()),
YamlNode::Hash(_) => Err(YamlConversionError::NonScalar),
YamlNode::Integer(i) => Ok(i.into()),
YamlNode::Null => Ok("null".into()),
YamlNode::Real(s) => Ok(s.into()),
YamlNode::String(s) => Ok(s.into()),
}
}
}
impl TryFrom<YamlNode> for Node {
type Error = YamlConversionError;
/// Convert from any `yaml_rust::Yaml` to a Node
///
/// ```
/// # use yaml_rust::YamlLoader;
/// # use marked_yaml::types::*;
/// # use std::convert::TryFrom;
/// let docs = YamlLoader::load_from_str("[1, 2]").unwrap();
/// let yaml = docs.into_iter().next().unwrap();
/// let node = Node::try_from(yaml).unwrap();
/// ```
fn try_from(value: YamlNode) -> Result<Self, Self::Error> {
match value {
YamlNode::Array(arr) => Ok(Node::Sequence(
arr.into_iter()
.map(Node::try_from)
.collect::<Result<MarkedSequenceNode, Self::Error>>()?,
)),
YamlNode::Hash(h) => Ok(Node::Mapping(
h.into_iter()
.map(|(k, v)| Ok((MarkedScalarNode::try_from(k)?, Node::try_from(v)?)))
.collect::<Result<MarkedMappingNode, Self::Error>>()?,
)),
scalar => Ok(Node::Scalar(MarkedScalarNode::try_from(scalar)?)),
}
}
}
impl From<MarkedScalarNode> for YamlNode {
fn from(value: MarkedScalarNode) -> Self {
YamlNode::String(value.value)
}
}
impl From<MarkedSequenceNode> for YamlNode {
fn from(value: MarkedSequenceNode) -> Self {
YamlNode::Array(value.value.into_iter().map(Into::into).collect())
}
}
impl From<MarkedMappingNode> for YamlNode {
fn from(value: MarkedMappingNode) -> Self {
YamlNode::Hash(
value
.value
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
)
}
}
impl From<Node> for YamlNode {
fn from(value: Node) -> Self {
match value {
Node::Scalar(msn) => msn.into(),
Node::Sequence(msn) => msn.into(),
Node::Mapping(mmn) => mmn.into(),
}
}
}
#[cfg(test)]
mod test {
use super::super::*;
use super::*;
#[test]
fn basic_marker_checks() {
let marker = Marker::new(0, 1, 2);
assert_eq!(marker.source(), 0);
assert_eq!(marker.line(), 1);
assert_eq!(marker.column(), 2);
assert_eq!(format!("{}", marker), "1:2");
let rendered = marker.render(|n| {
assert_eq!(n, 0);
"name"
});
assert_eq!(format!("{}", rendered), "name:1:2");
}
#[test]
fn basic_span_checks() {
let span = Span::new_blank();
assert_eq!(span.start(), None);
assert_eq!(span.end(), None);
let mark = Marker::new(0, 1, 2);
let mark2 = Marker::new(3, 4, 5);
let span = Span::new_start(mark);
assert_eq!(span.start(), Some(&mark));
assert_eq!(span.end(), None);
let span = Span::new_with_marks(mark, mark2);
assert_eq!(span.start(), Some(&mark));
assert_eq!(span.end(), Some(&mark2));
}
#[test]
fn basic_explore_load_test() {
let node = parse_yaml(0, include_str!("../examples/everything.yaml")).unwrap();
let map = node.as_mapping().unwrap();
assert_eq!(node.as_scalar(), None);
assert_eq!(node.as_sequence(), None);
assert_eq!(map.get_node("XXX NOT PRESENT XXX"), None);
assert_eq!(map.get_scalar("mapping"), None);
assert_eq!(map.get_sequence("mapping"), None);
assert_eq!(map.get_mapping("simple"), None);
// This actually uses .eq()
assert_ne!(map.get_scalar("boolean1"), map.get_scalar("boolean2"));
// Whereas this uses .ne()
assert!(map.get_scalar("boolean1") != map.get_scalar("boolean2"));
// Now check the spans
assert_eq!(node.span(), map.span());
let seq = map.get_sequence("heterogenous").unwrap();
assert_eq!(seq.span().start(), Some(&Marker::new(0, 24, 3)));
assert_eq!(seq.span(), map.get_node("heterogenous").unwrap().span());
// Helpers for the sequence node
assert_eq!(seq.get_node(0), seq.first());
assert_ne!(seq.get_node(0), None);
assert_ne!(seq.get_scalar(0), None);
assert_ne!(seq.get_mapping(1), None);
assert_ne!(seq.get_sequence(2), None);
}
#[test]
fn basic_scalar_features() {
let scalar1 = MarkedScalarNode::new(Span::new_blank(), "");
let scalar2 = MarkedScalarNode::new_empty(Span::new_blank());
assert_eq!(scalar1, scalar2);
assert_eq!(scalar1.as_str(), "");
assert_eq!(scalar1.as_bool(), None);
assert_eq!(scalar1.as_usize(), None);
let truth: MarkedScalarNode = "true".into();
assert_eq!(truth.as_bool(), Some(true));
let falsehood: MarkedScalarNode = "false".to_string().into();
assert_eq!(falsehood.as_bool(), Some(false));
assert_eq!(truth, true.into());
assert_eq!(falsehood, false.into());
let zero: MarkedScalarNode = "0".into();
assert_eq!(zero.as_usize(), Some(0));
assert_eq!(zero, 0usize.into());
assert_eq!(&*zero, "0");
}
#[test]
fn basic_sequence_features() {
// For features not covered by other tests
let mut seq = MarkedSequenceNode::new_empty(Span::new_blank());
let seq2: MarkedSequenceNode = vec!["foo"].into_iter().collect();
let scalar: MarkedScalarNode = "foo".into();
seq.push(Node::from(scalar));
assert_eq!(seq, seq2);
assert_eq!(seq, vec!["foo"].into());
let seq3: MarkedSequenceNode = vec!["foo", "bar"].into_iter().collect();
seq.push(Node::from("bar"));
assert_eq!(seq, seq3);
assert_eq!(seq, vec!["foo", "bar"].into());
}
#[test]
fn basic_mapping_features() {
// For features not covered by other tests
let mut map = MarkedMappingNode::new_empty(Span::new_blank());
let mut hash = MappingHash::new();
hash.insert("foo".into(), "bar".into());
let map2 = MarkedMappingNode::from(hash);
map.insert("foo".into(), "bar".into());
assert_eq!(map, map2);
assert_eq!(map.get("foo").unwrap().as_scalar().unwrap().as_str(), "bar");
let map3: MarkedMappingNode = vec![("foo", "bar")].into_iter().collect();
assert_eq!(map, map3);
map.insert("baz".into(), "meta".into());
let map4: MarkedMappingNode = vec![("foo", "bar"), ("baz", "meta")].into_iter().collect();
assert_eq!(map, map4);
}
#[test]
fn extra_node_impls() {
let node = Node::from(vec!["foo"]);
assert_ne!(node.as_sequence(), None);
let node = Node::from(MappingHash::new());
assert!(node.as_mapping().unwrap().is_empty());
}
#[test]
fn yaml_conversions() {
use yaml_rust::YamlLoader;
let mut everything =
YamlLoader::load_from_str(include_str!("../examples/everything.yaml")).unwrap();
let everything = everything.pop().unwrap();
let node = Node::try_from(everything.clone()).unwrap();
assert!(node.as_mapping().is_some());
let badscalar = MarkedScalarNode::try_from(everything);
assert_eq!(badscalar, Err(YamlConversionError::NonScalar));
let badscalar = MarkedScalarNode::try_from(YamlNode::BadValue);
assert_eq!(badscalar, Err(YamlConversionError::BadValue));
let badscalar = MarkedScalarNode::try_from(YamlNode::Array(vec![]));
assert_eq!(badscalar, Err(YamlConversionError::NonScalar));
}
fn flatten(node: YamlNode) -> YamlNode {
match node {
YamlNode::Array(arr) => YamlNode::Array(arr.into_iter().map(flatten).collect()),
YamlNode::Boolean(b) => {
YamlNode::String((if b { "true" } else { "false" }).to_string())
}
YamlNode::Hash(h) => YamlNode::Hash(
h.into_iter()
.map(|(k, v)| (flatten(k), flatten(v)))
.collect(),
),
YamlNode::Integer(i) => YamlNode::String(format!("{}", i)),
YamlNode::Null => YamlNode::String("null".to_string()),
YamlNode::Real(r) => YamlNode::String(r),
other => other,
}
}
#[test]
fn back_yaml_conversion() {
use yaml_rust::YamlLoader;
let mut everything =
YamlLoader::load_from_str(include_str!("../examples/everything.yaml")).unwrap();
let everything = everything.pop().unwrap();
let node = Node::try_from(everything.clone()).unwrap();
let other: YamlNode = node.into();
let flat = flatten(everything);
assert_eq!(flat, other);
}
}