message-format-wg
message-format-wg copied to clipboard
Simpler description of the matching algorithm
I think we can have a simpler exposition of the matching algorithm. Here is my take
Implementing the algorithm for matching requires two capabilities of functions. I think of these in terms of objects, but of course it can be done in a non-OO language.
Given a bound selector BS consisting of a value, a function, and a set of options, we need two operations.
-
BS.matches(Locale locale, String matchKey)
- Returns FAILURE or SUCCESS
- “*” as a matchKey is always success
- Example: suppose BV is {1 :number maximumFractionDigits=0}, and the locale is ‘en’
- If the matchKey is either 1 or one, there is a match. If it is any other plural value or numeric value, it fails.
- If the locale is ‘fr’, then there is a match if the matchKey is 0, 1, or one.
-
BS.compare(Locale locale, String matchKey1, matchKey2)
- Only to be called if both matchKey1 and matchKey2 have passed the ‘matches’ test.
- Returns WORSE if matchKey1 is worse than matchKey2, similarly for SAME, and BETTER.
- Must be a total order.
- Example:
- For the BV above, “*” is worse than “one” is worse than “1”
Here is how the matching can be performed. Each variant has a list of keys plus a message.
- Let bestVariant be empty
- For each variant V
- For each bound selector X[i]
- If X.matches(locale, V.key[i]) == FAILURE, continue to the next variant
- // Now we know that all of the keys match
- If bestVariant is empty, let bestVariant be V, continue to the next variant
- Let possibleBetter = false
- For each bound selector X[i]
- Let comparison = X.compare(locale, V.key[i], bestVariant.key[i])
- If comparison == WORSE, continue to the next variant
- If comparison == BETTER, let possibleBetter = true
- If possibleBetter == true, then let bestVariant be V
- For each bound selector X[i]
- Return bestVariant
Note: there are various further optimizations that can be done without changing the result. For example, it is possible to combine the two calls on matches and compare (but at the expense of complicating the algorithm a bit).