Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 1376 lines (1275 sloc) 39.781 kb
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
// vim: set ts=2 sw=2 tw=0 :
/**
* Template for a rule understood by the parser
*
* Rules convert parts of the parse stream in to a {@link Value}.
*/
internal abstract class GTeonoma.Rule : Object {
internal string name {
get;
protected set;
}
internal uint precedence {
get;
protected set;
}
/**
* Parse a particular value from the parse stream.
*/
internal abstract Result parse (Parser p, out Value ret_value, uint depth);
/**
* Pretty-print the parsed value.
*/
internal abstract bool print (Printer p, Value @value);
}

/**
* The kinds of actions used by {@link ObjectRule}.
*/
internal enum GTeonoma.Token {
/**
* A boolean property controls the presence or absence of a keyword.
*/
BOOL,
/**
* Stops the parser from back-tracking (i.e., commits it to the current path).
*/
COMMIT,
/**
* A {@link Gee.List} property containing other objects.
*
* Although the generics in Vala allow passing of structs, this is not
* possible with the parser; they must be a list of objects extending
* {@link Object}.
*/
LIST,
/**
* A property containing an object, number or string.
*/
PROPERTY,
/**
* Some literal text to be parsed.
*/
SYMBOL
}

internal enum GTeonoma.NextPrecedence {
RESET,
SAME,
HIGHER;
internal uint get (uint current_precedence) {
switch (this) {
case NextPrecedence.RESET:
return 0;

case NextPrecedence.SAME:
return current_precedence;

case NextPrecedence.HIGHER:
return current_precedence + 1;

default:
assert_not_reached ();
}
}
}

/**
* A unit of parsing to be done for an object.
*/
internal struct GTeonoma.chunk {
internal chunk.bool(string property, string word) {
token = Token.BOOL;
this.property = property;
this.word = word;
}
internal chunk.commit () {
token = Token.COMMIT;
}
internal chunk.list (string property, string word, Type type, bool optional, NextPrecedence next) {
token = Token.LIST;
this.optional = optional;
this.next = next;
this.property = property;
this.word = word;
this.type = type;
}
internal chunk.prop (string property, bool optional, NextPrecedence next) {
token = Token.PROPERTY;
this.optional = optional;
this.next = next;
this.property = property;
}
internal chunk.symbol (string word) {
token = Token.SYMBOL;
this.word = word;
}
/**
* The kind of parse action needed.
*/
Token token;
/**
* The name of the property to be manipulated, if any.
*/
string? property;
/**
* The symbol to be parsed, if any.
*/
string? word;
/**
* Whether this action can be skipped.
*/
bool optional;
/**
* The next precedence level for parsing this chunk.
*/
NextPrecedence next;
/**
* The type relevant to this action.
*/
Type type;
# if DEBUG
/**
* Format this chunk back into something approximating the string that created it.
*/
internal string to_string () {
switch (token) {
case Token.BOOL :
return @"%b{$(property)}{$(word)}";

case Token.COMMIT :
return "%%!";

case Token.LIST:
return @"%$(optional ? 'l' : 'L'){$(property)::$(type.name())}{$(word)}";

case Token.PROPERTY:
return @"%$(optional ? 'p' : 'P'){$(property)}";

case Token.SYMBOL:
return word;
}
assert_not_reached ();
}
# endif
}

/**
* Internal state machine for parsing the strings to {@link GTeonoma.Rules.register}
*/
internal enum GTeonoma.ObjectParseState {
COMMAND,
PARSE_BOOL,
PARSE_LIST,
PROPERTY_BOOL,
PROPERTY_LIST,
PROPERTY_PROPERTY,
START_BOOL,
START_LIST,
START_PARSE_BOOL,
START_PARSE_LIST,
START_PROPERTY,
TEXT
}

internal class GTeonoma.OrderedRule {
internal Rule rule;
internal int order;
internal OrderedRule (Rule rule, int order) {
this.rule = rule;
this.order = order;
}
internal static int compare (OrderedRule a, OrderedRule b) {
if (a.rule.precedence > b.rule.precedence) {
return 1;
}
if (a.rule.precedence < b.rule.precedence) {
return -1;
}
return a.order - b.order;
}
}

/**
* A collection of parse rules
*
* This is where the parser and pretty printer will look up rules for the
* corresponding types.
*/
public class GTeonoma.Rules : Object {
private Gee.HashMap<Type, Gee.TreeSet<OrderedRule> > rules;

public Rules () {
rules = new Gee.HashMap<Type, Gee.TreeSet<OrderedRule> > ();
}

/**
* Retrieve the correct rule for a particular type
*/
internal new Gee.List<Rule> get (Type type, uint precedence = 0) {
var list = new Gee.ArrayList<Rule> ();
if (rules.has_key (type)) {
foreach (var o_rule in rules[type]) {
if (o_rule.rule.precedence >= precedence) {
list.add (o_rule.rule);
}
}
}
if (list.size == 0) {
list.add (new FailRule (type));
}
return list;
}

NextPrecedence get_next_precedence (char modifier, string prop_name, Type type, Type prop_type, ref bool left_recursion, bool optional) throws RegisterError {
if (!type.is_a (prop_type)) {
if (modifier != '\0') {
throw new RegisterError.BAD_FORMAT (@"Property $(prop_name) requests a change in precedence from current rule, but it is not of the same type.");
}
left_recursion &= !optional;
return NextPrecedence.RESET;
}
switch (modifier) {
case '\0':
/* We could recurse infinitely, and the grammar hasn't told
* use what to do. Assume we are to raise precedence. */
if (left_recursion) {
left_recursion &= !optional;
return NextPrecedence.HIGHER;
} else {
/* We are going in to some other rule family. */
return NextPrecedence.SAME;
}

case '+':
left_recursion &= !optional;
return NextPrecedence.HIGHER;

case '-':
if (left_recursion) {
throw new RegisterError.LEFT_RECURSION (@"Property $(prop_name) requests lower precedence than current rule, but this will cause left-deep recursion.");
} else {
return NextPrecedence.RESET;
}

default:
throw new RegisterError.BAD_FORMAT (@"Unknown modifier $(modifier) on $(prop_name).");
}
}

/**
* Add a new rule to parse an object, flags, or enum.
*
* When adding a flags or enum, the nicks of the various values will be
* parsed from the input stream. For flags, the flags can appear in any order
* and multiple times in the input stream.
*
* For an object, a format string describing how to parse and display the
* object is needed. Any characters in the format string are taken literally.
* Whitespace is considered, but the amount and type of white space is
* ignored.<<BR>> ''%%'' is used to indicate a percent sign.<<BR>> ''%n''
* causes a new line to be emitted, but no white space is required when
* parsing.<<BR>> ''%''(space) emits no space, but allows white space while
* parsing.<<BR>> ''%_'' emits space only if the last character was not white
* space.<<BR>> ''%-'' does not require space, but emits it when
* printing.<<BR>> ''%I'' and ''%i'' increase and decrease the indentation of
* subsequent lines, respectively.<<BR>> ''%p{''//name//''}'' parses a
* property //name//; using ''p'' versus ''P'' causes the parsing to be
* optional versus mandatory.<<BR>> ''%b{''//name//''}{''//text//''}'' causes
* a boolean property //name// to be set to true if //text// can be parsed
* from the input stream.<<BR>> ''%l{''//name//''}{''//text//''}'' cause a
* list of items, separated by //text// to be parsed an placed into a
* property //name// of type {@link Gee.List}. Using ''l'' versus ''L''
* controls whether the list may be empty or must be non-empty. A type
* argument must be provided after the format string for the contents of the
* list; this type must extend {@link GLib.Object}.<<BR>> ''%!'' causes the
* parser to commit to this course of parsing; the parser will not back-track
* after committing.
*
* For properties and lists, the property name may be preceded by ''+'' or
* ''-'', which influence how recursion occurs. If a property has the same
* type as the object being parsed, the parser could recurse infinitely; this
* is left-deep recursion. By default, if left-deep recursion is detected in
* the grammar, the parser will only parse rules which are of higher
* precedence will be followed. Any property which would not cause left-deep
* recursion will be parsed at the same precedence level. However, this is
* can be explicitly controlled using the modifiers. By prefixing with ''+'',
* the property will always only parse higher-precedence rules. By prefixing
* with ''-'', the property will parse lower-precedence rules; though it
* cannot be left-deep recursion.
*
* This is admittedly confusing, but consider it in the following way for
* simple algebraic rules: addition and subtraction should have precedence 0;
* multiplication and division should have precedence 1; literals, variables,
* and parenthesis should have precedence 2. The left expression of addition,
* subtraction, multiplication, and division rules should be marked with
* ''+'', though this will be inferred if unspecified. The expression in the
* brackets rule should be marked with ''-''.
*
* @param name the pretty name for this type when errors are printed
*
* @param precedence the precedence of the rule, 0 being the lowest
* precedence. Given an algebraic expression, it is useful to have the same
* type for all the operations even though the multiplication should have
* higher precedence than the addition. Rather than having the object
* hierarchy support this, this argument can be used to control nesting. By
* increasing this value for the different expressions, a hierarchy can be
* made.
*
* @param format the format string if the type is an object; null otherwise.
*/
public void register<T> (string? name = null, uint precedence = 0, string? format = null, Type[]? types = null) throws RegisterError {
var type = typeof (T);

if (type.is_enum ()) {
if (format != null) {
throw new RegisterError.UNNECESSARY_FORMAT (@"Enumeration $(type.name()) does not require a format string.");
}
this[type] = new EnumRule (name, type);
return;
}
if (type.is_flags ()) {
if (format != null) {
throw new RegisterError.UNNECESSARY_FORMAT (@"Flags $(type.name()) does not require a format string.");
}
this[type] = new FlagsRule (name, type);
}

if (!type.is_a (typeof (Object))) {
throw new RegisterError.BAD_TYPE (@"Type $(type.name()) is not a flag, enum, or subclass of Object.");
}
if (format == null || format.length == 0) {
throw new RegisterError.BAD_FORMAT (@"Format string missing for $(type.name()).\n");
}

var index = 0;
var obj_class = (ObjectClass) type.class_ref ();
assert (obj_class != null);
chunk[] chunks = {};
var buffer = new StringBuilder ();
var state = ObjectParseState.TEXT;
char modifier = '\0';
string? prop_name = null;
var optional = false;
var left_recursion = true;
var first = false;
unichar c;
for (int i = 0; format.get_next_char (ref i, out c); ) {
switch (state) {
case ObjectParseState.TEXT :
switch (c) {
case '%' :
state = ObjectParseState.COMMAND;
break;

default :
left_recursion &= c.isspace ();
buffer.append_unichar (c);
break;
}
break;

case ObjectParseState.COMMAND :
if (c == ' ' || c == 'i' || c == 'I' || c == '%' || c == 'n' || c == '_' || c == '-') {
buffer.append_c ('%');
buffer.append_unichar (c);
state = ObjectParseState.TEXT;
continue;
}
if (buffer.len > 0) {
chunks += chunk.symbol (buffer.str);
buffer.truncate ();
}
optional = c.islower ();
switch (c) {
case '!':
chunks += chunk.commit ();
state = ObjectParseState.TEXT;
break;

case 'b':
state = ObjectParseState.START_BOOL;
break;

case 'l':
case 'L':
state = ObjectParseState.START_LIST;
break;

case 'p':
case 'P':
state = ObjectParseState.START_PROPERTY;
break;

default:
throw new RegisterError.BAD_FORMAT (@"Unrecognized command $(c) in format string for $(type.name()).\n");
}
break;

case ObjectParseState.START_BOOL:
case ObjectParseState.START_LIST:
case ObjectParseState.START_PROPERTY:
case ObjectParseState.START_PARSE_BOOL:
case ObjectParseState.START_PARSE_LIST:
if (c != '{') {
throw new RegisterError.BAD_FORMAT (@"Expected { in format string for $(type.name()).\n");
}
first = true;
modifier = '\0';
switch (state) {
case ObjectParseState.START_BOOL:
state = ObjectParseState.PROPERTY_BOOL;
break;

case ObjectParseState.START_LIST:
state = ObjectParseState.PROPERTY_LIST;
break;

case ObjectParseState.START_PROPERTY:
state = ObjectParseState.PROPERTY_PROPERTY;
break;

case ObjectParseState.START_PARSE_BOOL:
state = ObjectParseState.PARSE_BOOL;
break;

case ObjectParseState.START_PARSE_LIST:
state = ObjectParseState.PARSE_LIST;
break;
}
break;

case ObjectParseState.PROPERTY_BOOL:
case ObjectParseState.PROPERTY_LIST:
case ObjectParseState.PROPERTY_PROPERTY:
if (c == '}') {
prop_name = buffer.str;
var prop = obj_class.find_property (prop_name);
if (prop == null) {
throw new RegisterError.MISSING_PROPERTY (@"Property $(prop_name) is not found in $(type.name()).\n");
}
buffer.truncate ();
switch (state) {
case ObjectParseState.PROPERTY_BOOL:
state = ObjectParseState.START_PARSE_BOOL;
break;

case ObjectParseState.PROPERTY_LIST:
state = ObjectParseState.START_PARSE_LIST;
break;

case ObjectParseState.PROPERTY_PROPERTY:
chunks += chunk.prop (prop_name, optional, get_next_precedence (modifier, prop_name, type, prop.value_type, ref left_recursion, optional));
prop_name = null;
state = ObjectParseState.TEXT;
break;
}
} else if (first && (c == '+' || c == '-')) {
modifier = (char) c;
} else if (Parser.is_identifier (c, first)) {
buffer.append_unichar (c);
first = false;
} else {
if (obj_class.find_property (prop_name) == null) {
throw new RegisterError.BAD_FORMAT (@"Unexpected $(c) in format string for $(type.name()).\n");
}
}
break;

case ObjectParseState.PARSE_BOOL:
case ObjectParseState.PARSE_LIST:
if (c == '}') {
var keyword = buffer.str;
buffer.truncate ();
switch (state) {
case ObjectParseState.PARSE_BOOL:
if (obj_class.find_property (prop_name) == null) {
throw new RegisterError.MISSING_PROPERTY (@"Property $(prop_name) is not found in $(type.name()).\n");
}
chunks += chunk.bool(prop_name, keyword);
break;

case ObjectParseState.PARSE_LIST:
if (obj_class.find_property (prop_name) == null) {
throw new RegisterError.MISSING_PROPERTY (@"Property $(prop_name) is not found in $(type.name()).\n");
}
if (types == null || index >= types.length) {
throw new RegisterError.MISSING_TYPES (@"Missing generic type information for list $(prop_name) in $(type.name()).\n");
}
chunks += chunk.list (prop_name, keyword, types[index++], optional, get_next_precedence (modifier, prop_name, type, types[index], ref left_recursion, optional));
break;
}
state = ObjectParseState.TEXT;
} else {
buffer.append_unichar (c);
}
break;
}
}
if (state != ObjectParseState.TEXT) {
throw new RegisterError.BAD_FORMAT (@"Unexpected end of format string for $(type.name()).\n");
}
if (buffer.len > 0) {
chunks += chunk.symbol (buffer.str);
buffer.truncate ();
}
if (chunks.length == 0) {
throw new RegisterError.BAD_FORMAT (@"Empty format string for $(type.name()).\n");
}
var rule = new ObjectRule (name, type, precedence, chunks);
this[type] = rule;
}

/**
* Register the double type.
*/
public void register_double () throws RegisterError {
this[typeof (double)] = new FloatRule ();
}

public void register_enum<T> (string? name = null, owned NameTransformer? transformer = null) throws RegisterError {
var type = typeof (T);

if (!type.is_enum ()) {
throw new RegisterError.UNNECESSARY_FORMAT (@"Type $(type.name()) is not an enumeration.");
}
this[type] = new EnumRule (name?? type.name (), type, (owned) transformer);
}

/**
* Add support for C string literals using {@link StringLiteral}.
*/
public void register_string_literal (bool has_quotes = true) {
register_custom<StringLiteral> ("string", () => new StringLiteralParser (has_quotes), (literal) => has_quotes ? @"\"$(literal.str.escape(" "))\"" : literal.str.escape (""));
}

/**
* Add support for C/Vala-ish identifers using {@link Identifier}.
*
* @param allow_unicode controls of Unicode characters are allowed in an identifier (similar to Java).
* @param allow_at permits an ''\@'' character to preceed an identifier like Vala and C#.
*/
public void register_identifier (bool allow_unicode = false, bool allow_at = false) {
register_custom<Identifier> ("identifier", () => new IdentifierParser (allow_unicode, allow_at), (identifier) => identifier.name);
}

/**
* Register a new signed integer type.
* @param size in bits (8, 32, or 64)
*/
public void register_int (int size, Type type) throws RegisterError requires (type.is_fundamental ()) {
switch (size) {
case 8 :
this[type] = new Int8Rule (type);
break;

case 32 :
this[type] = new Int32Rule (type);
break;

case 64 :
this[type] = new Int64Rule (type);
break;

default :
throw new RegisterError.BAD_TYPE ("Unsupported size.");
}
}

/**
* Register a new unsigned integer type.
* @param size in bits (8, 32, or 64)
*/
public void register_uint (int size, Type type) throws RegisterError requires (type.is_fundamental ()) {
switch (size) {
case 8:
this[type] = new UInt8Rule (type);
break;

case 32:
this[type] = new UInt32Rule (type);
break;

case 64:
this[type] = new UInt64Rule (type);
break;

default:
throw new RegisterError.BAD_TYPE ("Unsupported size.");
}
}

/**
* Register a new custom rule.
*
* To parse a truly unsual object, for instance a string literal or a regular
* expression literal, extend {@link CustomParser} and then add the rule using
* this method.
*
* @param name a friendly name to be printed during compilation
*
* @param parser_factory a delegate that creates new instances of the parser.
* Everytime an object must be parsed, this method will be called.
*
* @param stringifier a delegate that will convert a previously parsed object
* to a string representation
*/
public void register_custom<T> (string name, owned CustomParser.CustomParserFactory<T> parser_factory, owned CustomParser.StringifyObject<T> stringifier) {
this[typeof (T)] = new CustomRule<T> (name, (owned) parser_factory, (owned) stringifier);
}

/**
* Register a rule for a specified type and all of its ancestral types.
*/
internal new void set (Type type, Rule rule) {
var interfaces = type.interfaces ();
if (interfaces != null) {
foreach (var interface_type in interfaces) {
set_type (interface_type, rule);
}
}
for (; type != Type.INVALID; type = type.parent ()) {
set_type (type, rule);
}
}

private void set_type (Type type, Rule rule) {
Gee.TreeSet<OrderedRule> list;
if (rules.has_key (type)) {
list = rules[type];
} else {
list = new Gee.TreeSet<OrderedRule> (OrderedRule.compare);
rules[type] = list;
}
list.add (new OrderedRule (rule, list.size));
}
}

/**
* Errors raised while adding new types to {@link Rules}
*/
public errordomain GTeonoma.RegisterError {
/**
* Format string supplied when not required.
*/
UNNECESSARY_FORMAT,
/**
* Error in format string.
*/
BAD_FORMAT,
/**
* Unsupported type.
*/
BAD_TYPE,
/**
* Missing supplementary type information.
*/
MISSING_TYPES,
/**
* Left deep-recursion detected.
*
* Parsing expression grammars cannot handle non-syntax directed left-deep
* recursion (i.e., ''S = S x'' is invalid, but ''S = "[" S x "]"'' is
* valid).
*/
LEFT_RECURSION,
/**
* Non-existent property in target class.
*/
MISSING_PROPERTY
}
/**
* A rule that causes failure
*
* This rule is automatically invoked for invalid types.
*/
internal class GTeonoma.FailRule : Rule {
string error;
public FailRule (Type type) {
name = "failure";
error = @"Internal error: No rule for type `$(type.name())'.";
}

internal override Result parse (Parser p, out Value @value, uint depth) {
@value = Value (typeof (Object));
p.push_error (error);
return Result.ABORT;
}

internal override bool print (Printer p, Value @value) {
p.append ("\n");
p.append (error);
p.append ("\n");
return false;
}
}

/**
* A rule to parse data into and out of the properties of an object.
*/
internal class GTeonoma.ObjectRule : Rule {
private Type type;
private ObjectClass obj_type;
private chunk[] chunks;

internal ObjectRule (string name, Type type, uint precedence, chunk[] chunks) {
this.name = name;
this.type = type;
this.obj_type = (ObjectClass) type.class_ref ();
this.chunks = chunks;
this.precedence = precedence;
}

internal override Result parse (Parser p, out Value ret_value, uint depth) {
ret_value = Value (type);
var obj = Object.new (type);
if (obj is SourceInfo) {
((SourceInfo) obj).source = p.get_location ();
}
bool committed = false;
for (var index = 0; index < chunks.length; index++) {
switch (chunks[index].token) {
case Token.BOOL:
if (p.check_string (chunks[index].word)) {
var prop_value = Value (typeof (bool));
prop_value.set_boolean (true);
obj.set_property (chunks[index].property, prop_value);
}
break;

case Token.COMMIT:
committed = true;
continue;

case Token.PROPERTY:
Value prop_value;
p.mark_set ();
var prop = obj_type.find_property (chunks[index].property);
assert (prop != null);
p.start_property (name, chunks[index].property, depth);
var result = p.parse_type (prop.value_type, out prop_value, chunks[index].next[precedence], depth + 1);
p.end_property (name, chunks[index].property, depth);
if (result == Result.OK) {
obj.set_property (chunks[index].property, prop_value);
p.mark_clear ();
} else if (chunks[index].optional && (result == Result.FAIL || result == Result.EOI)) {
/* Ignore. */
p.mark_rewind ();
} else {
p.push_error (@"Expected $(p.names_for(prop.value_type)) missing in $(name).");
p.mark_clear ();
return result;
}
break;

case Token.LIST:
bool end_of_input = false;
var list = new Gee.ArrayList<Object> ();
Value child_value;
Result result;
p.mark_set ();
p.start_property (name, chunks[index].property, depth);
while ((result = p.parse_type (chunks[index].type, out child_value, chunks[index].next[precedence], depth + 1)) == Result.OK) {
list.add (child_value.get_object ());
p.mark_reset ();
if (!p.check_string (chunks[index].word, null, out end_of_input)) {
break;
}
}
p.end_property (name, chunks[index].property, depth);
if (result == Result.ABORT) {
p.mark_clear ();
return result;
} else if (!chunks[index].optional && list.size == 0) {
p.push_error (@"Expected $(p.names_for(chunks[index].type)) missing in $(name).");
p.mark_clear ();
return (end_of_input || result == Result.EOI) ? Result.EOI : (committed ? Result.ABORT : Result.FAIL);
} else {
p.push_error (@"Expected one of $(p.names_for(chunks[index].type)) in $(name).");
p.mark_rewind ();
Value list_value = Value (typeof (Gee.List));
list_value.set_object (list);
obj.set_property (chunks[index].property, list_value);
}
break;

case Token.SYMBOL:
bool end_of_input;
if (!p.check_string (chunks[index].word, name, out end_of_input)) {
return end_of_input ? Result.EOI : (committed ? Result.ABORT : Result.FAIL);
}
break;
}
}
ret_value.set_object (obj);
return Result.OK;
}
Value get_prop (string prop_name, Object obj) {
Value @value = Value (obj_type.find_property (prop_name).value_type);
obj.get_property (prop_name, ref @value);
return @value;
}

internal override bool print (Printer p, Value @value) requires (@value.type ().is_object ()) {
Object obj = @value.get_object ();
if (!obj.get_type ().is_a (type)) {
return false;
}
for (var index = 0; index < chunks.length; index++) {
switch (chunks[index].token) {
case Token.BOOL:
if (get_prop (chunks[index].property, obj).get_boolean ()) {
p.append (chunks[index].word);
}
break;

case Token.COMMIT:
break;

case Token.PROPERTY:
/*
* Make our type more specific in the case of alternate rules. Otherwise, we might pick the wrong branch.
*/
var prop_value = get_prop (chunks[index].property, obj);
if (prop_value.type ().is_object ()) {
if (prop_value.get_object () == null) {
if (!chunks[index].optional) {
return false;
}
} else {
var new_value = Value (prop_value.get_object ().get_type ());
new_value.set_object (prop_value.get_object ());
p.print (new_value);
}
} else {
p.print (prop_value);
}
break;

case Token.LIST:
var list = get_prop (chunks[index].property, obj).get_object () as Gee.List<Object>;
if (list == null) {
return false;
}
var first = true;
foreach (var child in list) {
if (first) {
first = false;
} else {
p.append (chunks[index].word);
}
var child_value = Value (child.get_type ());
child_value.set_object (child);
p.print (child_value);
}
break;

case Token.SYMBOL:
p.append (chunks[index].word);
break;
}
}
return true;
}
}

public delegate string? NameTransformer (string input);

/**
* Rule to parse an enum.
*/
internal class GTeonoma.EnumRule : Rule {
EnumClass enum_class;
Type type;
NameTransformer name_transformer;
public EnumRule (string? name, Type type, owned NameTransformer? name_transformer = null) {
this.name = name?? type.name ();
this.type = type;
this.enum_class = (EnumClass) type.class_ref ();
this.name_transformer = name_transformer;
}

internal override Result parse (Parser p, out Value @value, uint depth) {
@value = Value (type);
bool end_of_input;
var word = p.get_word (out end_of_input);
if (name_transformer != null) {
var original_word = word;
word = name_transformer (word);
if (word == null) {
p.push_error (@"Unexpected symbol `$original_word'.");
return end_of_input ? Result.EOI : Result.FAIL;
}
}
var enum_value = enum_class.get_value_by_nick (word);
if (enum_value == null) {
p.push_error (@"Unexpected symbol `$word'.");
return end_of_input ? Result.EOI : Result.FAIL;
} else {
@value.set_enum (enum_value.value);
return Result.OK;
}
}

internal override bool print (Printer p, Value @value) requires (@value.type () == type) {
var enum_value = enum_class.get_value (@value.get_enum ());
assert (enum_value != null);
p.append (enum_value.value_nick);
return true;
}
}

/**
* Rule to parse a flags (a.k.a. enum with Flags attribute)
*/
internal class GTeonoma.FlagsRule : Rule {
private Type type;
private FlagsClass flags_class;
public FlagsRule (string? name, Type type) {
this.name = name?? type.name ();
this.type = type;
this.flags_class = (FlagsClass) type.class_ref ();
}

internal override Result parse (Parser p, out Value @value, uint depth) {
@value = Value (type);
while (true) {
p.mark_set ();
p.consume_whitespace ();
var word = p.get_word (null);
if (word.length == 0) {
p.mark_rewind ();
break;
}
unowned FlagsValue? flag = flags_class.get_value_by_nick (word);
if (flag == null) {
p.mark_rewind ();
break;
}
@value.set_flags (@value.get_flags () & flag.value);
p.mark_clear ();
}
return Result.OK;
}

internal override bool print (Printer p, Value @value) requires (@value.type () == type) {
var first = true;
foreach (unowned FlagsValue flag in flags_class.values) {
if ((flag.value & @value.get_flags ()) == flag.value) {
if (first) {
first = false;
} else {
p.append ("%_");
}
p.append (flag.value_nick);
}
}
return true;
}
}

/**
* Rule to parse an integer
*
* Because of oddness in {@link Value} overrides are needed to complete the right action.
*/
internal abstract class GTeonoma.IntegerRule : Rule {
Type type;
public IntegerRule (Type type) requires (type.is_fundamental ()) {
this.name = "integer constant";
this.type = type;
}

internal override Result parse (Parser p, out Value @value, uint depth) {
@value = Value (type);
unichar c;
uint64 accumulator = 0;
var negate = false;
switch ((c = p[true])) {
case '0' :
switch (p[false]) {
case 'x' :
case 'X' :
p.get (true);
while ((c = p[false]).isxdigit ()) {
accumulator = accumulator * 16 + p[true].xdigit_value ();
}
break;

case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6':
case '7':
accumulator = p[true].digit_value ();
while ((c = p[false]).isdigit ()) {
if (c >= '8') {
p.push_error ("Non-octal digit in octal number.");
return Result.ABORT;
}
accumulator = accumulator * 8 + p[true].digit_value ();
}
break;
}
break;

case '-':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (c == '-') {
negate = true;
} else {
accumulator = c.digit_value ();
}
while (p[false].isdigit ()) {
accumulator = accumulator * 10 + p[true].digit_value ();
}
break;

case '\0':
return Result.EOI;

default:
return Result.FAIL;
}

var long_var = false;
var unsigned_var = false;
switch (p[false]) {
case 'l':
case 'L':
long_var = true;
p.get (true);
break;

case 'u':
case 'U':
unsigned_var = true;
p.get (true);
break;
}
//TODO longs and unsigned don't make sense, do they?
return set_value (accumulator, negate, ref @value) ? Result.OK : Result.FAIL;
}
protected abstract bool set_value (uint64 number, bool negate, ref Value @value);
}

internal class GTeonoma.Int8Rule : IntegerRule {
public Int8Rule (Type type) {
base (type);
}
internal override bool print (Printer p, Value @value) {
p.append (@value.get_char ().to_string ());
return true;
}
protected override bool set_value (uint64 number, bool negate, ref Value @value) {
if (number > int8.MAX) {
return false;
}
@value.set_char (negate ? -((char) number) : (char) number);
return true;
}
}
internal class GTeonoma.Int32Rule : IntegerRule {
public Int32Rule (Type type) {
base (type);
}
internal override bool print (Printer p, Value @value) {
p.append (@value.get_int ().to_string ());
return true;
}
protected override bool set_value (uint64 number, bool negate, ref Value @value) {
if (number > int32.MAX) {
return false;
}
@value.set_int (negate ? -((int32) number) : (int32) number);
return true;
}
}
internal class GTeonoma.Int64Rule : IntegerRule {
public Int64Rule (Type type) {
base (type);
}
internal override bool print (Printer p, Value @value) {
p.append (@value.get_int64 ().to_string ());
return true;
}
protected override bool set_value (uint64 number, bool negate, ref Value @value) {
if (number > int64.MAX) {
return false;
}
@value.set_int64 (negate ? -((int64) number) : (int64) number);
return true;
}
}
internal class GTeonoma.UInt8Rule : IntegerRule {
public UInt8Rule (Type type) {
base (type);
}
internal override bool print (Printer p, Value @value) {
p.append (@value.get_uchar ().to_string ());
return true;
}
protected override bool set_value (uint64 number, bool negate, ref Value @value) {
if (number > uint8.MAX || negate) {
return false;
}
@value.set_uchar ((uint8) number);
return true;
}
}
internal class GTeonoma.UInt32Rule : IntegerRule {
public UInt32Rule (Type type) {
base (type);
}
internal override bool print (Printer p, Value @value) {
p.append (@value.get_uint ().to_string ());
return true;
}
protected override bool set_value (uint64 number, bool negate, ref Value @value) {
if (number > uint32.MAX || negate) {
return false;
}
@value.set_uint ((uint32) number);
return true;
}
}
internal class GTeonoma.UInt64Rule : IntegerRule {
public UInt64Rule (Type type) {
base (type);
}
internal override bool print (Printer p, Value @value) {
p.append (@value.get_uint64 ().to_string ());
return true;
}
protected override bool set_value (uint64 number, bool negate, ref Value @value) {
if (negate) {
return false;
}
@value.set_uint64 (number);
return true;
}
}

/**
* Rule to parse a double.
*/
internal class GTeonoma.FloatRule : Rule {
public FloatRule () {
this.name = "floating point constant";
}

internal override Result parse (Parser p, out Value @value, uint depth) {
@value = Value (typeof (double));
bool not_an_int = false;
var accumulator = new StringBuilder ();
if (p[false] == '-') {
accumulator.append_unichar (p[true]);
}
while (p[false].isdigit ()) {
accumulator.append_unichar (p[true]);
}
if (p[false] == '.') {
accumulator.append_unichar (p[true]);
not_an_int = true;
while (p[false].isdigit ()) {
accumulator.append_unichar (p[true]);
}
}
var exponent = p[false];
if (exponent == 'e' || exponent == 'E') {
not_an_int = true;
accumulator.append_unichar (p[true]);
if (p[false] == '-') {
accumulator.append_unichar (p[true]);
}
while (p[false].isdigit ()) {
accumulator.append_unichar (p[true]);
}
}
double result = 0;
if (not_an_int && double.try_parse (accumulator.str, out result)) {
@value.set_double (result);
return Result.OK;
} else {
return p[false] == '\0' ? Result.EOI : Result.FAIL;
}
}
internal override bool print (Printer p, Value @value) requires (@value.type () == typeof (double)) {
p.append (@value.get_double ().to_string ());
return true;
}
}

internal class GTeonoma.CustomRule<T> : Rule {
private Type type;
private CustomParser.CustomParserFactory<T> constructor;
private CustomParser.StringifyObject<T> stringifier;

internal CustomRule (string? name, owned CustomParser.CustomParserFactory<T> constructor, owned CustomParser.StringifyObject<T> stringifier) {
type = typeof (T);
assert (type.is_a (typeof (Object)));
this.name = name?? type.name ();
this.constructor = (owned) constructor;
this.stringifier = (owned) stringifier;
}

internal override Result parse (Parser p, out Value @value, uint depth) {
@value = Value (type);
CustomParser<T> state = constructor ();
var seen_accepting = false;
long last_buffer_len = 0;
var end_of_input = false;
var buffer = new StringBuilder ();

var source_location = p.get_location ();
p.mark_set ();

var finished = false;
while (!finished) {
var c = p[true];
if (c == '\0') {
end_of_input = true;
p.push_error (@"Unexpected end of input in $name.");
p.mark_rewind ();
finished = true;
break;
}
buffer.append_unichar (c);
var statetype = state.next_state (c);
switch (statetype) {
case CustomParser.StateType.ACCEPTING :
case CustomParser.StateType.FINAL :
seen_accepting = true;
last_buffer_len = buffer.len;
if (statetype == CustomParser.StateType.FINAL) {
finished = true;
p.mark_clear ();
} else {
p.mark_reset ();
}
break;

case CustomParser.StateType.INTERMEDIATE :
break;

case CustomParser.StateType.INVALID:
p.push_error (@"Unexpected $(c.to_string()) in $name.");
p.mark_rewind ();
finished = true;
break;
}
}
if (seen_accepting) {
buffer.truncate (last_buffer_len);
var obj = (Object) state.build_object (buffer.str);
if (obj is SourceInfo) {
((SourceInfo) obj).source = source_location;
}
@value.set_object (obj);
return Result.OK;
} else {
return end_of_input ? Result.EOI : Result.FAIL;
}
}

internal override bool print (Printer p, Value @value) requires (@value.type () == type) {
Object obj = @value.get_object ();
if (!obj.get_type ().is_a (type)) {
return false;
}
p.append (stringifier ((T) obj));
return true;
}
}

/**
* Rule to parse an unusual object
*
* Unusual objects include string literals and regular expressions. This is
* needed when parsing an object where spacing is important and/or each element
* in the grammar does/should not correspond to an object in the syntax tree.
*/
public abstract class GTeonoma.CustomParser<T> : Object {
/**
* Update the current state given the next character of input.
*
* The parser will feed characters to the custom parser one at a time by
* calling this method. After this class has seen a character, it must return
* what it thinks of that character. From a theoretical perspective, this
* class is assumed to be a DFA and is send character one at a time. The type
* of the state the DFA is in is returned, not the DFA state itself. The
* parser then makes a decision about whether to continue with this DFA or
* return.
*
* The parser will mark the last time a state was {@link StateType.ACCEPTING}
* and will continue until it is in state {@link StateType.INVALID}. Once a
* character is rejected, it will rewind to the last accepting state and
* present this input to {@link build_object}. If no accepting state is ever
* reached, parsing will fail.
*
* Obviously, the underlying algorithm need not be a DFA.
*
* @return the type of the new state of the DFA.
*/
public abstract StateType next_state (unichar input);

/**
* The type of state the parser is currently in.
*/
public enum StateType {
/**
* The current input has been accepted.
*
* This signals that the input seen so far is valid and a resulting object
* can be constructed. If the current input is not invalid, but it is not yet
* possible to build the object, this method should return false.
*/
ACCEPTING,
/**
* The current input is insufficient to determine if it is valid or invalid.
*
* It is not a valid state, but it is not invalid and needs more input to settle.
*/
INTERMEDIATE,
/**
* The current input is accepted and no future input will be accepted.
*
* Effectively, this is {@link ACCEPTING} followed by {@link INVALID} for
* any subsequent input.
*/
FINAL,
/**
* The current input is invalid.
*
* When the current parsing state is an error state, the parser rewinds to
* the last accepting state it has seen and then calls {@link build_object}.
* If no accepting state has been found, the parsing fails.
*/
INVALID
}

/**
* Construct the output object given the validated input.
*/
public abstract T build_object (string str);

/**
* Pretty print a custom-parsed object.
*/
public delegate string StringifyObject<T> (T obj);

/**
* Create a new custom parser to parse an object.
*/
public delegate CustomParser<T> CustomParserFactory<T> ();
}
Something went wrong with that request. Please try again.