| 1 |
#charset "us-ascii" |
| 2 |
|
| 3 |
/* |
| 4 |
* Tokenizer - customizable tokenizer class for use with the intrinsic |
| 5 |
* class 'grammar-production' parser. |
| 6 |
* |
| 7 |
* This tokenizer implementation is parameterized with a set of rules |
| 8 |
* (see below); a basic set of rules is provided, but users can |
| 9 |
* customize the tokenizer quite extensively simply by subclassing the |
| 10 |
* Tokenizer class and overriding the 'rules_' property with a new set |
| 11 |
* of rules declarations. |
| 12 |
*/ |
| 13 |
|
| 14 |
#include "tads.h" |
| 15 |
#include "t3.h" |
| 16 |
#include "dict.h" |
| 17 |
#include "tok.h" |
| 18 |
#include "vector.h" |
| 19 |
|
| 20 |
/* ------------------------------------------------------------------------ */ |
| 21 |
/* |
| 22 |
* Tokenizer exceptions |
| 23 |
*/ |
| 24 |
|
| 25 |
/* |
| 26 |
* base class for all tokenizer errors (to allow blanket 'catch') |
| 27 |
*/ |
| 28 |
class TokenizerError: Exception |
| 29 |
displayException() { "Tokenizer exception"; } |
| 30 |
; |
| 31 |
|
| 32 |
/* |
| 33 |
* no match for token |
| 34 |
*/ |
| 35 |
class TokErrorNoMatch: TokenizerError |
| 36 |
construct(str) |
| 37 |
{ |
| 38 |
/* remember the full remaining text */ |
| 39 |
remainingStr_ = str; |
| 40 |
|
| 41 |
/* |
| 42 |
* for convenience, separately remember the single character |
| 43 |
* that we don't recognize - this is simply the first character |
| 44 |
* of the rest of the line |
| 45 |
*/ |
| 46 |
curChar_ = str.substr(1, 1); |
| 47 |
} |
| 48 |
|
| 49 |
displayException() |
| 50 |
{ "Tokenizer error: unexpected character '<<curChar_>>'"; } |
| 51 |
|
| 52 |
/* |
| 53 |
* The remainder of the string. This is the part that couldn't be |
| 54 |
* matched; we were successful in matching up to this point. |
| 55 |
*/ |
| 56 |
remainingStr_ = nil |
| 57 |
|
| 58 |
/* current character (first character of remainingStr_) */ |
| 59 |
curChar_ = nil |
| 60 |
; |
| 61 |
|
| 62 |
/* ------------------------------------------------------------------------ */ |
| 63 |
/* |
| 64 |
* Basic token types |
| 65 |
*/ |
| 66 |
|
| 67 |
/* word */ |
| 68 |
enum token tokWord; |
| 69 |
|
| 70 |
/* quoted string */ |
| 71 |
enum token tokString; |
| 72 |
|
| 73 |
/* punctuation */ |
| 74 |
enum token tokPunct; |
| 75 |
|
| 76 |
/* integer number */ |
| 77 |
enum token tokInt; |
| 78 |
|
| 79 |
|
| 80 |
/* ------------------------------------------------------------------------ */ |
| 81 |
/* |
| 82 |
* Tokenizer base class |
| 83 |
*/ |
| 84 |
class Tokenizer: object |
| 85 |
/* |
| 86 |
* Tokenizing rules. The subclass can override this to specify a |
| 87 |
* list that defines different tokenization rules. Each entry in the |
| 88 |
* master rules_ list is one rule. Each rule is a list consisting of |
| 89 |
* the name of the rule; the pattern to match for the rule; the token |
| 90 |
* type (an 'enum token') to use when the rule is matched; the value |
| 91 |
* computation rule; and the value test rule. |
| 92 |
* |
| 93 |
* The name of a rule is just an arbitrary string to identify the |
| 94 |
* rule. This can be used to insert new rules in order relative to |
| 95 |
* known existing rules, or to delete known existing rules. |
| 96 |
* |
| 97 |
* If the value computation rule is nil, we'll just use the matching |
| 98 |
* text as the token value. If the value rule is a string, we'll use |
| 99 |
* the string as a replacement pattern (with rexReplace). If it's a |
| 100 |
* property ID, we'll invoke the property of self with the following |
| 101 |
* arguments: |
| 102 |
* |
| 103 |
* txt, typ, toks |
| 104 |
* |
| 105 |
* 'txt' is the matched text; 'typ' is the token type from the rule; |
| 106 |
* and 'toks' is a vector to which the new token or tokens are to be |
| 107 |
* added. The routine is responsible for adding the appropriate |
| 108 |
* values to the result list. Note that the routine can add more |
| 109 |
* than one token to the results if desired. |
| 110 |
* |
| 111 |
* If the value test rule is non-nil, it must be either a method or a |
| 112 |
* function; we'll call the method or function to test to see if the |
| 113 |
* matched value is valid. We'll call the method (on self) with the |
| 114 |
* matching text as the argument; if the method returns true, the |
| 115 |
* rule matches, otherwise the rule fails, and we'll continue looking |
| 116 |
* for another rule as though we hadn't matched the rule's regular |
| 117 |
* expression in the first place. This can be used for rules that |
| 118 |
* require more than a simple regular expression match; for example, |
| 119 |
* the value test can be used to look up the match in a dictionary, |
| 120 |
* so that the rule only matches tokens that are defined in the |
| 121 |
* dictionary. |
| 122 |
*/ |
| 123 |
rules_ = static |
| 124 |
[ |
| 125 |
/* skip whitespace */ |
| 126 |
['whitespace', R'<Space>+', nil, &tokCvtSkip, nil], |
| 127 |
|
| 128 |
/* certain punctuation marks */ |
| 129 |
['punctuation', R'[.,;:?!]', tokPunct, nil, nil], |
| 130 |
|
| 131 |
/* |
| 132 |
* Words - note that we convert everything to lower-case. A |
| 133 |
* word must start with an alphabetic character, but can contain |
| 134 |
* alphabetics, digits, hyphens, and apostrophes after that. |
| 135 |
*/ |
| 136 |
['word', R'<Alpha>(<AlphaNum>|[-\'])*', tokWord, &tokCvtLower, nil], |
| 137 |
|
| 138 |
/* strings */ |
| 139 |
['string single-quote', R'\'(.*)\'', tokString, nil, nil], |
| 140 |
['string double-quote', R'"(.*)"', tokString, nil, nil], |
| 141 |
|
| 142 |
/* integer numbers */ |
| 143 |
['integer', R'[0-9]+', tokInt, nil, nil] |
| 144 |
] |
| 145 |
|
| 146 |
/* |
| 147 |
* Insert a new rule before or after the existing rule with the name |
| 148 |
* 'curName'. If 'curName' is nil, or rule is found with the given |
| 149 |
* name, we'll insert the new rule at the end of the list. 'rule' |
| 150 |
* must be a list with the standard elements for a tokenizer rule. |
| 151 |
* 'after' is nil to insert the new rule before the given existing |
| 152 |
* rule, true to insert after it. |
| 153 |
*/ |
| 154 |
insertRule(rule, curName, after) |
| 155 |
{ |
| 156 |
local idx; |
| 157 |
|
| 158 |
/* |
| 159 |
* if the name of an existing rule was supplied, find the |
| 160 |
* existing rule with the given name |
| 161 |
*/ |
| 162 |
idx = nil; |
| 163 |
if (curName != nil) |
| 164 |
idx = rules_.indexWhich({x: tokRuleName(x) == curName}); |
| 165 |
|
| 166 |
/* if we didn't find curName, insert at the end of the list */ |
| 167 |
if (idx == nil) |
| 168 |
idx = rules_.length(); |
| 169 |
|
| 170 |
/* if we're inserting after the given element, adjust the index */ |
| 171 |
if (after) |
| 172 |
++idx; |
| 173 |
|
| 174 |
/* insert the new rule */ |
| 175 |
insertRuleAt(rule, idx); |
| 176 |
} |
| 177 |
|
| 178 |
/* |
| 179 |
* Insert a rule at the given index in our rules list. 'rule' must |
| 180 |
* be a list with the standard elements for a tokenizer rule. 'idx' |
| 181 |
* is the index of the new rule; we'll insert before the existing |
| 182 |
* element at this index; so if 'idx' is 1, we'll insert before the |
| 183 |
* first existing rule. |
| 184 |
*/ |
| 185 |
insertRuleAt(rule, idx) |
| 186 |
{ |
| 187 |
/* insert the rule */ |
| 188 |
rules_ = rules_.insertAt(idx, rule); |
| 189 |
} |
| 190 |
|
| 191 |
/* |
| 192 |
* Delete a rule by name. This finds the rule with the given name |
| 193 |
* and removes it from the list. |
| 194 |
*/ |
| 195 |
deleteRule(name) |
| 196 |
{ |
| 197 |
local idx; |
| 198 |
|
| 199 |
/* find the rule with the given name */ |
| 200 |
idx = rules_.indexWhich({x: tokRuleName(x) == name}); |
| 201 |
|
| 202 |
/* if we found the named element, remove it from the list */ |
| 203 |
if (idx != nil) |
| 204 |
deleteRuleAt(idx); |
| 205 |
} |
| 206 |
|
| 207 |
/* delete the rule at the given index */ |
| 208 |
deleteRuleAt(idx) |
| 209 |
{ |
| 210 |
/* delete the rule */ |
| 211 |
rules_ = rules_.removeElementAt(idx); |
| 212 |
} |
| 213 |
|
| 214 |
/* convert a string to lower-case (for value computation rules) */ |
| 215 |
tokCvtLower(txt, typ, toks) |
| 216 |
{ |
| 217 |
/* add the lower-cased version of the string to the result list */ |
| 218 |
toks.append([txt.toLower(), typ, txt]); |
| 219 |
} |
| 220 |
|
| 221 |
/* |
| 222 |
* processing routine to skip a match - this is used for whitespace |
| 223 |
* and other text that does not result in any tokens in the result |
| 224 |
* list |
| 225 |
*/ |
| 226 |
tokCvtSkip(txt, typ, toks) |
| 227 |
{ |
| 228 |
/* simply skip the text without generating any new tokens */ |
| 229 |
} |
| 230 |
|
| 231 |
/* |
| 232 |
* Tokenize a string. If we find text that we can't match to any of |
| 233 |
* the rules, we'll throw an exception (TokErrorNoMatch). If we |
| 234 |
* succeed in tokenizing the entire string, we'll return a list with |
| 235 |
* one element per token. Each element of the main list is a |
| 236 |
* sublist with the following elements describing a token: |
| 237 |
* |
| 238 |
* - The first element gives the token's value. |
| 239 |
* |
| 240 |
* - The second element the token type (given as a token type enum |
| 241 |
* value). |
| 242 |
* |
| 243 |
* - The third element the original token strings, before any |
| 244 |
* conversions or evaluations were performed. For example, this |
| 245 |
* maintains the original case of strings that are lower-cased for |
| 246 |
* the corresponding token values. |
| 247 |
*/ |
| 248 |
tokenize(str) |
| 249 |
{ |
| 250 |
local toks = new Vector(32); |
| 251 |
local startIdx = 1; |
| 252 |
local len = str.length(); |
| 253 |
|
| 254 |
/* keep going until we run out of string */ |
| 255 |
mainLoop: |
| 256 |
while (startIdx <= len) |
| 257 |
{ |
| 258 |
/* run through the rules in sequence until we match one */ |
| 259 |
ruleLoop: |
| 260 |
for (local i = 1, local cnt = rules_.length() ; i <= cnt ; ++i) |
| 261 |
{ |
| 262 |
local cur; |
| 263 |
local match; |
| 264 |
local val; |
| 265 |
|
| 266 |
/* get the current rule */ |
| 267 |
cur = rules_[i]; |
| 268 |
|
| 269 |
/* check for a match to the rule's pattern */ |
| 270 |
match = rexMatch(tokRulePat(cur), str, startIdx); |
| 271 |
if (match != nil && match > 0) |
| 272 |
{ |
| 273 |
local test; |
| 274 |
local txt; |
| 275 |
local typ; |
| 276 |
|
| 277 |
/* get the matching text */ |
| 278 |
txt = str.substr(startIdx, match); |
| 279 |
|
| 280 |
/* |
| 281 |
* if there's a value test, invoke it to determine |
| 282 |
* if the token really matches |
| 283 |
*/ |
| 284 |
if ((test = tokRuleTest(cur)) != nil) |
| 285 |
{ |
| 286 |
local accept; |
| 287 |
|
| 288 |
/* check what kind of test function we have */ |
| 289 |
switch (dataType(test)) |
| 290 |
{ |
| 291 |
case TypeFuncPtr: |
| 292 |
case TypeObject: |
| 293 |
/* it's a function or anonymous function */ |
| 294 |
accept = (test)(txt); |
| 295 |
break; |
| 296 |
|
| 297 |
case TypeProp: |
| 298 |
/* it's a method */ |
| 299 |
accept = self.(test)(txt); |
| 300 |
break; |
| 301 |
|
| 302 |
default: |
| 303 |
/* consider anything else to be accepted */ |
| 304 |
accept = true; |
| 305 |
break; |
| 306 |
} |
| 307 |
|
| 308 |
/* |
| 309 |
* if the value test failed, it means that the |
| 310 |
* token doesn't match this rule after all - |
| 311 |
* ignore the regex match and keep searching for |
| 312 |
* another rule |
| 313 |
*/ |
| 314 |
if (!accept) |
| 315 |
continue ruleLoop; |
| 316 |
} |
| 317 |
|
| 318 |
/* get the type of the token from the rule */ |
| 319 |
typ = tokRuleType(cur); |
| 320 |
|
| 321 |
/* get this value processing rule */ |
| 322 |
val = tokRuleVal(cur); |
| 323 |
|
| 324 |
/* determine what value to use */ |
| 325 |
switch(dataTypeXlat(val)) |
| 326 |
{ |
| 327 |
case TypeNil: |
| 328 |
/* use the matching text verbatim */ |
| 329 |
toks.append([txt, typ, txt]); |
| 330 |
break; |
| 331 |
|
| 332 |
case TypeProp: |
| 333 |
/* |
| 334 |
* invoke the property - it's responsible for |
| 335 |
* adding the token or tokens to the results |
| 336 |
* lists |
| 337 |
*/ |
| 338 |
self.(val)(txt, typ, toks); |
| 339 |
break; |
| 340 |
|
| 341 |
case TypeSString: |
| 342 |
/* it's a regular expression replacement */ |
| 343 |
toks.append( |
| 344 |
[rexReplace(tokRulePat(cur), |
| 345 |
txt, val, ReplaceOnce), |
| 346 |
typ, txt]); |
| 347 |
break; |
| 348 |
|
| 349 |
case TypeFuncPtr: |
| 350 |
/* invoke the function */ |
| 351 |
(val)(txt, typ, toks); |
| 352 |
break; |
| 353 |
|
| 354 |
default: |
| 355 |
/* |
| 356 |
* use any other value exactly as given in |
| 357 |
* the rule |
| 358 |
*/ |
| 359 |
toks.append([val, typ, txt]); |
| 360 |
break; |
| 361 |
} |
| 362 |
|
| 363 |
/* |
| 364 |
* continue the search at the next character after |
| 365 |
* the end of this token |
| 366 |
*/ |
| 367 |
startIdx += match; |
| 368 |
|
| 369 |
/* start over with the rest of the string */ |
| 370 |
continue mainLoop; |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
/* |
| 375 |
* We failed to find a match for this part of the string. |
| 376 |
* Throw an exception and let the caller figure out what to |
| 377 |
* do. The exception parameter gives the rest of the |
| 378 |
* string, so the caller can display a suitable error |
| 379 |
* message if desired. |
| 380 |
*/ |
| 381 |
throw new TokErrorNoMatch(str.substr(startIdx)); |
| 382 |
} |
| 383 |
|
| 384 |
/* we're done with the string - return out value and type lists */ |
| 385 |
return toks.toList(); |
| 386 |
} |
| 387 |
; |
| 388 |
|
| 389 |
/* ------------------------------------------------------------------------ */ |
| 390 |
/* |
| 391 |
* Test Section |
| 392 |
*/ |
| 393 |
|
| 394 |
#ifdef TOK_TEST |
| 395 |
|
| 396 |
main(args) |
| 397 |
{ |
| 398 |
"Enter text to tokenize. Type Q or QUIT when done. "; |
| 399 |
for (;;) |
| 400 |
{ |
| 401 |
local str, toks; |
| 402 |
|
| 403 |
/* read a string */ |
| 404 |
"\b>"; |
| 405 |
str = inputLine(); |
| 406 |
|
| 407 |
/* catch tokenization errors */ |
| 408 |
try |
| 409 |
{ |
| 410 |
/* tokenize the string */ |
| 411 |
toks = Tokenizer.tokenize(str); |
| 412 |
|
| 413 |
/* if the first token is 'quit', we're done */ |
| 414 |
if (toks.length() > 0 |
| 415 |
&& getTokType(toks[1]) == tokWord |
| 416 |
&& (getTokVal(toks[1])== 'quit' || getTokVal(toks[1]) == 'q')) |
| 417 |
{ |
| 418 |
/* they want to stop - exit the command loop */ |
| 419 |
break; |
| 420 |
} |
| 421 |
|
| 422 |
/* display the tokens */ |
| 423 |
for (local i = 1, local cnt = toks.length() ; i <= cnt ; ++i) |
| 424 |
"(<<getTokVal(toks[i])>>) "; |
| 425 |
} |
| 426 |
catch (TokErrorNoMatch err) |
| 427 |
{ |
| 428 |
"Unrecognized punctuation: <<err.remainingStr_.substr(1, 1)>>"; |
| 429 |
} |
| 430 |
} |
| 431 |
} |
| 432 |
|
| 433 |
#endif /* TOK_TEST */ |
| 434 |
|