aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/icu/i18n/messageformat2_serializer.cpp
blob: b55c55ab7ced9b2e6a6c5010be3d16f5944a93b0 (plain) (blame)
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
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#if !UCONFIG_NO_MF2

#include "unicode/messageformat2_data_model.h"
#include "messageformat2_macros.h"
#include "messageformat2_serializer.h"
#include "uvector.h" // U_ASSERT

U_NAMESPACE_BEGIN

namespace message2 {

// Generates a string representation of a data model
// ------------------------------------------------

using namespace data_model;

// Private helper methods

void Serializer::whitespace() {
    result += SPACE;
}

void Serializer::emit(UChar32 c) {
    result += c;
}

void Serializer::emit(const UnicodeString& s) {
    result += s;
}

template <int32_t N>
void Serializer::emit(const UChar32 (&token)[N]) {
    // Don't emit the terminator
    for (int32_t i = 0; i < N - 1; i++) {
        emit(token[i]);
    }
}

void Serializer::emit(const Literal& l) {
    if (l.isQuoted()) {
      emit(PIPE);
      const UnicodeString& contents = l.unquoted();
      for (int32_t i = 0; ((int32_t) i) < contents.length(); i++) {
        // Re-escape any PIPE or BACKSLASH characters
        switch(contents[i]) {
        case BACKSLASH:
        case PIPE: {
          emit(BACKSLASH);
          break;
        }
        default: {
          break;
        }
        }
        emit(contents[i]);
      }
      emit(PIPE);
    } else {
      emit(l.unquoted());
    }
}

void Serializer::emit(const Key& k) {
    if (k.isWildcard()) {
        emit(ASTERISK);
        return;
    }
    emit(k.asLiteral());
}

void Serializer::emit(const SelectorKeys& k) {
  const Key* ks = k.getKeysInternal();
  int32_t len = k.len;
  // It would be an error for `keys` to be empty;
  // that would mean this is the single `pattern`
  // variant, and in that case, this method shouldn't be called
  U_ASSERT(len > 0);
  for (int32_t i = 0; i < len; i++) {
    if (i != 0) {
      whitespace();
    }
    emit(ks[i]);
  }
}

void Serializer::emit(const Operand& rand) {
    U_ASSERT(!rand.isNull());

    if (rand.isVariable()) {
        emit(DOLLAR);
        emit(rand.asVariable());
    } else {
        // Literal: quoted or unquoted
        emit(rand.asLiteral());
    }
}

void Serializer::emit(const OptionMap& options) {
    // Errors should have been checked before this point
    UErrorCode localStatus = U_ZERO_ERROR;
    U_ASSERT(!options.bogus);
    for (int32_t i = 0; i < options.size(); i++) {
        const Option& opt = options.getOption(i, localStatus);
        // No need to check error code, since we already checked
        // that !bogus
        whitespace();
        emit(opt.getName());
        emit(EQUALS);
        emit(opt.getValue());
    }
}

void Serializer::emitAttributes(const OptionMap& attributes) {
    // Errors should have been checked before this point
    UErrorCode localStatus = U_ZERO_ERROR;
    U_ASSERT(!attributes.bogus);
    for (int32_t i = 0; i < attributes.size(); i++) {
        const Option& attr = attributes.getOption(i, localStatus);
        // No need to check error code, since we already checked
        // that !bogus
        whitespace();
        emit(AT);
        emit(attr.getName());
        const Operand& v = attr.getValue();
        if (!v.isNull()) {
            emit(EQUALS);
            emit(v);
        }
    }
}

void Serializer::emit(const Reserved& reserved) {
    // Re-escape '\' / '{' / '|' / '}'
    for (int32_t i = 0; i < reserved.numParts(); i++) {
        const Literal& l = reserved.getPart(i);
        if (l.isQuoted()) {
            emit(l);
        } else {
            const UnicodeString& s = l.unquoted();
            for (int32_t j = 0; ((int32_t) j) < s.length(); j++) {
                switch(s[j]) {
                case LEFT_CURLY_BRACE:
                case PIPE:
                case RIGHT_CURLY_BRACE:
                case BACKSLASH: {
                    emit(BACKSLASH);
                    break;
                }
                default:
                    break;
                }
                emit(s[j]);
            }
        }
    }
}

 void Serializer::emit(const Expression& expr) {
    emit(LEFT_CURLY_BRACE);

    if (!expr.isReserved() && !expr.isFunctionCall()) {
        // Literal or variable, no annotation
        emit(expr.getOperand());
    } else {
        // Function call or reserved
        if (!expr.isStandaloneAnnotation()) {
          // Must be a function call that has an operand
          emit(expr.getOperand());
          whitespace();
        }
        UErrorCode localStatus = U_ZERO_ERROR;
        const Operator* rator = expr.getOperator(localStatus);
        U_ASSERT(U_SUCCESS(localStatus));
        if (rator->isReserved()) {
          const Reserved& reserved = rator->asReserved();
          emit(reserved);
        } else {
            emit(COLON);
            emit(rator->getFunctionName());
            // No whitespace after function name, in case it has
            // no options. (when there are options, emit(OptionMap) will
            // emit the leading whitespace)
            emit(rator->getOptionsInternal());
        }
    }
    emitAttributes(expr.getAttributesInternal());
    emit(RIGHT_CURLY_BRACE);
}

void Serializer::emit(const PatternPart& part) {
    if (part.isText()) {
        // Raw text
        const UnicodeString& text = part.asText();
        // Re-escape '{'/'}'/'\'
        for (int32_t i = 0; ((int32_t) i) < text.length(); i++) {
          switch(text[i]) {
          case BACKSLASH:
          case LEFT_CURLY_BRACE:
          case RIGHT_CURLY_BRACE: {
            emit(BACKSLASH);
            break;
          }
          default:
            break;
          }
          emit(text[i]);
        }
        return;
    }
    // Markup
    if (part.isMarkup()) {
        const Markup& markup = part.asMarkup();
        emit(LEFT_CURLY_BRACE);
        if (markup.isClose()) {
            emit(SLASH);
            } else {
            emit(NUMBER_SIGN);
        }
        emit(markup.getName());
        emit(markup.getOptionsInternal());
        emitAttributes(markup.getAttributesInternal());
        if (markup.isStandalone()) {
            emit(SLASH);
        }
        emit(RIGHT_CURLY_BRACE);
        return;
    }
    // Expression
    emit(part.contents());
}

void Serializer::emit(const Pattern& pat) {
    int32_t len = pat.numParts();
    // Always quote pattern, which should match the normalized input
    // if the parser is constructing it correctly
    emit(LEFT_CURLY_BRACE);
    emit(LEFT_CURLY_BRACE);
    for (int32_t i = 0; i < len; i++) {
        // No whitespace is needed here -- see the `pattern` nonterminal in the grammar
        emit(pat.getPart(i));
    }
    emit(RIGHT_CURLY_BRACE);
    emit(RIGHT_CURLY_BRACE);
}

void Serializer::serializeDeclarations() {
    const Binding* bindings = dataModel.getLocalVariablesInternal();
    U_ASSERT(bindings != nullptr);

    for (int32_t i = 0; i < dataModel.bindingsLen; i++) {
        const Binding& b = bindings[i];
        if (b.isLocal()) {
            // No whitespace needed here -- see `message` in the grammar
            emit(ID_LOCAL);
            whitespace();
            emit(DOLLAR);
            emit(b.getVariable());
            // No whitespace needed here -- see `local-declaration` in the grammar
            emit(EQUALS);
            // No whitespace needed here -- see `local-declaration` in the grammar
        } else {
            // Input declaration
            emit(ID_INPUT);
            // No whitespace needed here -- see `input-declaration` in the grammar
        }
        emit(b.getValue());
    }
}

void Serializer::serializeUnsupported() {
    const UnsupportedStatement* statements = dataModel.getUnsupportedStatementsInternal();
    U_ASSERT(statements != nullptr);

    for (int32_t i = 0; i < dataModel.unsupportedStatementsLen; i++) {
        const UnsupportedStatement& s = statements[i];
        emit(s.getKeyword());
        UErrorCode localErrorCode = U_ZERO_ERROR;
        const Reserved* r = s.getBody(localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            whitespace();
            emit(*r);
        }
        const Expression* e = s.getExpressionsInternal();
        for (int32_t j = 0; j < s.expressionsLen; j++) {
            emit(e[j]);
        }
    }
}

void Serializer::serializeSelectors() {
    U_ASSERT(!dataModel.hasPattern());
    const Expression* selectors = dataModel.getSelectorsInternal();

    emit(ID_MATCH);
    for (int32_t i = 0; i < dataModel.numSelectors(); i++) {
        // No whitespace needed here -- see `selectors` in the grammar
        emit(selectors[i]);
    }
}

void Serializer::serializeVariants() {
    U_ASSERT(!dataModel.hasPattern());
    const Variant* variants = dataModel.getVariantsInternal();
    for (int32_t i = 0; i < dataModel.numVariants(); i++) {
        const Variant& v = variants[i];
        emit(v.getKeys());
        // No whitespace needed here -- see `variant` in the grammar
        emit(v.getPattern());
    }
}


// Main (public) serializer method
void Serializer::serialize() {
    serializeDeclarations();
    serializeUnsupported();
    // Pattern message
    if (dataModel.hasPattern()) {
      emit(dataModel.getPattern());
    } else {
      // Selectors message
      serializeSelectors();
      serializeVariants();
    }
}

} // namespace message2
U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_MF2 */

#endif /* #if !UCONFIG_NO_FORMATTING */