Type_chk.cc 278 KB
Newer Older
Elemer Lelik's avatar
Elemer Lelik committed
1
/******************************************************************************
Adam Knapp's avatar
Adam Knapp committed
2
 * Copyright (c) 2000-2021 Ericsson Telecom AB
Elemer Lelik's avatar
Elemer Lelik committed
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v2.0
Elemer Lelik's avatar
Elemer Lelik committed
5
 * which accompanies this distribution, and is available at
6
 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
Elemer Lelik's avatar
Elemer Lelik committed
7
8
 *
 * Contributors:
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 *   Baji, Laszlo
 *   Balasko, Jeno
 *   Baranyi, Botond
 *   Beres, Szabolcs
 *   Bibo, Zoltan
 *   Cserveni, Akos
 *   Delic, Adam
 *   Dimitrov, Peter
 *   Feher, Csaba
 *   Forstner, Matyas
 *   Gecse, Roland
 *   Kovacs, Ferenc
 *   Nagy, Lenard
 *   Raduly, Csaba
 *   Szabados, Kristof
 *   Szabo, Janos Zoltan – initial implementation
 *   Szabo, Bence Janos
 *   Szalai, Gabor
 *   Tatarka, Gabor
 *   Zalanyi, Balazs Andor
Elemer Lelik's avatar
Elemer Lelik committed
29
30
 *
 ******************************************************************************/
Elemer Lelik's avatar
Elemer Lelik committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "../common/dbgnew.hh"
#include "Type.hh"
#include "Typestuff.hh" // FIXME CTs
#include "CompField.hh"
#include "CompType.hh"
#include "TypeCompat.hh"
#include "EnumItem.hh"
#include "SigParam.hh"

#include "Valuestuff.hh"
#include "main.hh"

#include "ttcn3/Ttcnstuff.hh"
#include "ttcn3/TtcnTemplate.hh"
#include "ttcn3/Templatestuff.hh"
#include "ttcn3/Attributes.hh"
#include "ttcn3/ArrayDimensions.hh"
#include "ttcn3/PatternString.hh"

#include "asn1/Tag.hh"
#include "XerAttributes.hh"
52
#include "ttcn3/RawAST.hh"
53
#include "ttcn3/JsonAST.hh"
Elemer Lelik's avatar
Elemer Lelik committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

#include <ctype.h>
#include <stdlib.h> // for qsort
#include <string.h>

extern int rawAST_debug;

namespace Common {

using Ttcn::MultiWithAttrib;
using Ttcn::SingleWithAttrib;
using Ttcn::WithAttribPath;
using Ttcn::Qualifier;
using Ttcn::Qualifiers;

void Type::chk()
{
  if(w_attrib_path) w_attrib_path->chk_global_attrib();
72
73
74
  if (legacy_codec_handling) {
    parse_attributes();
  }
Elemer Lelik's avatar
Elemer Lelik committed
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
  if(!tags_checked) {
    tags_checked = true;
    if(tags) tags->chk();
  }
  if (checked) return;
  switch(typetype) {
  case T_ERROR:
  case T_NULL:
  case T_BOOL:
  case T_INT:
  case T_REAL:
  case T_BSTR:
  case T_HSTR:
  case T_OSTR:
  case T_CSTR:
  case T_USTR:
  case T_UTF8STRING:
  case T_NUMERICSTRING:
  case T_PRINTABLESTRING:
  case T_TELETEXSTRING:
  case T_VIDEOTEXSTRING:
  case T_IA5STRING:
  case T_GRAPHICSTRING:
  case T_VISIBLESTRING:
  case T_GENERALSTRING:
  case T_UNIVERSALSTRING:
  case T_BMPSTRING:
  case T_UTCTIME:
  case T_GENERALIZEDTIME:
  case T_OBJECTDESCRIPTOR:
  case T_OID:
  case T_ROID:
  case T_ANY:
  case T_EXTERNAL:
  case T_EMBEDDED_PDV:
  case T_UNRESTRICTEDSTRING:
  case T_VERDICT:
  case T_DEFAULT:
    break;
  case T_INT_A:
    chk_Int_A();
    break;
  case T_ENUM_A:
    chk_Enum_A();
    break;
  case T_ENUM_T:
    chk_Enum_T();
    break;
  case T_BSTR_A:
    chk_BStr_A();
    break;
  case T_OPENTYPE:
    chk_SeCho_T();
    break;
  case T_ANYTYPE:
    // TODO maybe check for address type and add it automagically, then fall through
BenceJanosSzabo's avatar
BenceJanosSzabo committed
131
132
133
134
    if(!xerattrib) {
      xerattrib = new XerAttributes;
    }
    xerattrib->untagged_ = true;
Elemer Lelik's avatar
Elemer Lelik committed
135
136
137
  case T_SEQ_T:
  case T_SET_T:
  case T_CHOICE_T:
138
    chk_SeCho_T();    
Elemer Lelik's avatar
Elemer Lelik committed
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
    break;
  case T_CHOICE_A:
    chk_Choice_A();
    break;
  case T_SEQ_A:
  case T_SET_A:
    chk_Se_A();
    break;
  case T_SEQOF:
  case T_SETOF:
    chk_SeOf();
    break;
  case T_REFD:
  case T_ADDRESS:
    chk_refd();
    break;
  case T_SELTYPE:
    chk_seltype();
    break;
  case T_REFDSPEC:
  case T_OCFT:
    u.ref.type_refd->chk();
    u.ref.component_internal = u.ref.type_refd->is_component_internal();
    break;
  case T_ARRAY:
    chk_Array();
    break;
166
  case T_PORT: {
Elemer Lelik's avatar
Elemer Lelik committed
167
    u.port->chk();
168
169
170
171
172
173
174
175
    Ttcn::FormalParList* map_params = u.port->get_map_parameters(true);
    if (map_params != NULL) {
      map_params->set_genname(get_genname_own());
    }
    Ttcn::FormalParList* unmap_params = u.port->get_map_parameters(false);
    if (unmap_params != NULL) {
      unmap_params->set_genname(get_genname_own());
    }
Elemer Lelik's avatar
Elemer Lelik committed
176
    if (w_attrib_path) u.port->chk_attributes(w_attrib_path);
177
    break; }
Elemer Lelik's avatar
Elemer Lelik committed
178
179
180
181
182
183
184
185
186
187
188
  case T_SIGNATURE:
    chk_Signature();
    break;
  case T_COMPONENT:
    u.component->chk();
    break;
  case T_FUNCTION:
  case T_ALTSTEP:
  case T_TESTCASE:
    chk_Fat();
    break;
189
190
191
  case T_CLASS:
    u.class_->chk();
    break;
Elemer Lelik's avatar
Elemer Lelik committed
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
  default:
    FATAL_ERROR("Type::chk()");
  } // switch

  if(w_attrib_path) {
    switch (get_type_refd_last()->typetype) {
    case T_SEQ_T:
    case T_SET_T:
    case T_CHOICE_T:
      // These types may have qualified attributes
      break;
    case T_SEQOF: case T_SETOF:
      break;
    default:
      w_attrib_path->chk_no_qualif();
      break;
    }
  }
  checked = true;
  if(tags) tags->set_plicit(this);

  /*
  Check all non-table subtype constraints. Table/relational constraints
  are ignored here.
  TODO: non-relational table constraints shall not be ignored.
  */
  if (check_subtype) check_subtype_constraints();

  /*
   * Checking the constraints can be done only if the entire type
   * (including the nested typedefs) is checked, because the
   * component relation constraint has to 'look' into other
   * components.
   */
  if (!parent_type) chk_table_constraints();
227
  
228
229
230
231
232
233
234
235
  if (legacy_codec_handling) {
    chk_coding_attribs();
  }
  else if (my_scope != NULL) {
    chk_encodings();
    chk_variants();
  }
  
236
237
  chk_oer();
  
238
239
240
241
242
  chk_finished = true;
}

void Type::chk_coding_attribs()
{
243
  if (coding_attribs_checked || (!legacy_codec_handling && !variants_checked)) {
244
245
    return;
  }
246
247
  coding_attribs_checked = true;
  coding_attrib_check_stack.add(this);
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
  if (typetype == T_SEQ_T || typetype == T_SET_T || typetype == T_CHOICE_T) {
    // If this record/set/union type has no attributes but one of its fields does,
    // create an empty attribute structure.
    // TODO: do the same for ASN.1 sequence/set/choice types, when ASN.1 gets XER ?
    // The code was originally for TTCN-only encodings.
    if (!rawattrib && hasVariantAttrs() && hasNeedofRawAttrs()) {
      rawattrib = new RawAST(get_default_raw_fieldlength());
    }
    if (!textattrib && hasVariantAttrs() && hasNeedofTextAttrs()) {
      textattrib = new TextAST;
    }
    if (!xerattrib && hasVariantAttrs() && hasNeedofXerAttrs()) {
      xerattrib = new XerAttributes;
    }
    if (!jsonattrib && hasVariantAttrs() && hasNeedofJsonAttrs()) {
      jsonattrib = new JsonAST;
    }
  }
  
  if (rawattrib != NULL || is_root_basic()) {
Elemer Lelik's avatar
Elemer Lelik committed
268
269
    chk_raw();
  }
270
  if (textattrib != NULL || is_root_basic()) {
Elemer Lelik's avatar
Elemer Lelik committed
271
272
273
    chk_text();
  }
  
274
  if (jsonattrib != NULL || is_root_basic()) {
Elemer Lelik's avatar
Elemer Lelik committed
275
276
277
278
279
280
281
    chk_json();
  }
  
  // We need to call chk_xer() always because it is collecting
  // XER attributes from parent types.
  chk_xer();
  
282
  if (!legacy_codec_handling) {
283
    if (RecursionTracker::is_happening(this)) {
284
      coding_attrib_check_stack.remove(coding_attrib_check_stack.size() - 1);
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
      return;
    }
    
    RecursionTracker tracker(this);
    
    if (is_ref()) {
      get_type_refd()->chk_coding_attribs();
    }
    else {
      switch (typetype) {
      case T_SEQ_T:
      case T_SEQ_A:
      case T_SET_T:
      case T_SET_A:
      case T_CHOICE_T:
      case T_CHOICE_A:
      case T_ANYTYPE:
      case T_OPENTYPE:
        for (size_t i = 0; i < get_nof_comps(); ++i) {
          get_comp_byIndex(i)->get_type()->chk_coding_attribs();
        }
        break;
307

308
309
310
311
312
      case T_ARRAY:
      case T_SEQOF:
      case T_SETOF:
        get_ofType()->chk_coding_attribs();
        break;
313

314
315
316
      default:
        break;
      }
317
318
    }
  }
319
  coding_attrib_check_stack.remove(coding_attrib_check_stack.size() - 1);
Elemer Lelik's avatar
Elemer Lelik committed
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
}

void Type::parse_attributes()
{
  if (raw_parsed) return;

  // The type has no attributes of its own; connect it to the nearest group
  // or the module. This allows global attributes to propagate.
  for (Type *t = this; t && w_attrib_path == 0; t = t->parent_type) {
    switch (t->ownertype) {
    case OT_TYPE_DEF: {
      Ttcn::Def_Type *pwn = static_cast<Ttcn::Def_Type*>(t->owner);
      Ttcn::Group *nearest_group = pwn->get_parent_group();

      w_attrib_path = new WithAttribPath;
      if (nearest_group) { // there is a group
        w_attrib_path->set_parent(nearest_group->get_attrib_path());
      }
      else { // no group, use the module
        Common::Module *mymod = t->my_scope->get_scope_mod();
        // OT_TYPE_DEF is always from a TTCN-3 module
        Ttcn::Module *my_ttcn_module = static_cast<Ttcn::Module *>(mymod);
        w_attrib_path->set_parent(my_ttcn_module->get_attrib_path());
      }
      break; }

    case OT_RECORD_OF:
    case OT_COMP_FIELD:
      continue; // try the enclosing type

    default:
      break;
    }
    break;
  }

  if ((hasVariantAttrs())
357
      && (enable_text() || enable_raw() || enable_xer() || enable_json())) {
Elemer Lelik's avatar
Elemer Lelik committed
358
359
#ifndef NDEBUG
    if (rawAST_debug) {
360
      const char *fn = get_fullname().c_str();
Elemer Lelik's avatar
Elemer Lelik committed
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
      fprintf(stderr, "parse_attributes for %s\n", fn);
    }
#endif
    bool new_raw=false;      // a RawAST  object was allocated here
    bool new_text=false;     // a TextAST object was allocated here
    bool new_xer=false;      // a XerAttribute object was allocated here
    bool new_ber=false;      // a BerAST object was allocated here
    bool new_json = false;   // a JsonAST object was allocated here
    bool raw_found=false;    // a raw  attribute was found by the parser
    bool text_found=false;   // a text attribute was found by the parser
    bool xer_found=false;    // a XER  attribute was found by the parser
    bool ber_found=false;    // a BER attribute was found by the parser
    bool json_found = false; // a JSON attribute was found by the parser
    raw_checked=false;
    text_checked=false;
    json_checked = false;
    xer_checked=false;
    bool override_ref=false;
    // Parse RAW attributes
    switch(typetype) {
    case T_REFD: {
      ReferenceChain refch(this, "While checking attributes");
      if(w_attrib_path)
      {
        // Get all the attributes that apply (from outer scopes too).
        // Outer (generic) first, inner (specific) last.
        const vector<SingleWithAttrib> & real_attribs
          = w_attrib_path->get_real_attrib();

        // see if there's an encode with override
        for(size_t i = real_attribs.size(); i > 0 && !override_ref; i--)
        {
393
          if(real_attribs[i-1]->get_modifier() == Ttcn::MOD_OVERRIDE
Elemer Lelik's avatar
Elemer Lelik committed
394
395
396
397
398
399
            && real_attribs[i-1]->get_attribKeyword()
              != SingleWithAttrib::AT_ENCODE)
            override_ref = true;
        }
      }
      if(!rawattrib && !override_ref){
400
        Type *t=this; 
Elemer Lelik's avatar
Elemer Lelik committed
401
402
        refch.reset();
        while(!t->rawattrib && t->is_ref()) t=t->get_type_refd(&refch);
403
        rawattrib=new RawAST(t->rawattrib,t->get_default_raw_fieldlength());
Elemer Lelik's avatar
Elemer Lelik committed
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
        new_raw=true;
      }
      if(!textattrib && !override_ref){
        Type *t=this;
        refch.reset();
        while(!t->textattrib && t->is_ref()) t=t->get_type_refd(&refch);
        textattrib=new TextAST(t->textattrib);
        new_text=true;
      }
      if (!jsonattrib && !override_ref){
        Type *t = this;
        refch.reset();
        while (!t->jsonattrib && t->is_ref()) {
          t = t->get_type_refd(&refch);
        }
        jsonattrib = new JsonAST(t->jsonattrib);
        new_json = true;
      }
    }
    // no break
    case T_BOOL:
    case T_INT:
    case T_REAL:
    case T_BSTR:
    case T_HSTR:
    case T_OSTR:
    case T_CSTR: // TTCN-3 charstring
    case T_ENUM_T:
      /* The list of types supporting RAW encoding is described in the
       * API guide, section 3.3; this batch of labels plus the next three
       * accurately match the list.
       *
       * For TEXT, it's section 3.4; the list does not include real and
       * bin/hex/octet strings
       */
    case T_USTR: // TTCN-3 universal charstring, this is an addition for XER attributes
    case T_VERDICT: // TTCN-3 verdict, for XER

      if(rawattrib==NULL){
443
        rawattrib= new RawAST(get_default_raw_fieldlength());
Elemer Lelik's avatar
Elemer Lelik committed
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
        new_raw=true;
      }
      if(textattrib==NULL){textattrib= new TextAST; new_text=true;}
      if (xerattrib==NULL) {
        xerattrib = new XerAttributes; new_xer = true;
      }
      if (berattrib==NULL) {
        berattrib = new BerAST;
        new_ber = true;
      }
      
      if (NULL == jsonattrib) {
        jsonattrib = new JsonAST;
        new_json = true;
      }

      if(w_attrib_path)
      {
        vector<SingleWithAttrib> const &real_attribs
          = w_attrib_path->get_real_attrib();
        // These are attributes without qualifiers.

        size_t nof_elements = real_attribs.size();
        for(size_t i = 0; i < nof_elements; i++)
        {
          SingleWithAttrib *temp_single = real_attribs[i];
          if (temp_single->get_attribKeyword() ==
            SingleWithAttrib::AT_VARIANT) { // only "variant" is parsed
            parse_rawAST(rawattrib, textattrib, xerattrib, berattrib, jsonattrib,
              temp_single->get_attribSpec(), get_length_multiplier(),
              my_scope->get_scope_mod(), 
              raw_found, text_found, xer_found, ber_found, json_found);
//            textattrib->print_TextAST();
//            rawattrib->print_RawAST();
//            xerattrib->print(get_fullname().c_str());
          } // if AT_VARIANT
        } // next i
      }

      if(!raw_found && new_raw){ delete rawattrib; rawattrib=NULL;}
      if(!text_found && new_text){ delete textattrib; textattrib=NULL;}
      if(!xer_found && new_xer){ delete xerattrib; xerattrib = NULL; }
      if(!ber_found && new_ber){ delete berattrib; berattrib = NULL; }
      if (!json_found && new_json) {
        delete jsonattrib;
        jsonattrib = NULL;
      }
      break;
    case T_SEQOF:
    case T_SETOF:
    case T_CHOICE_T:
    case T_SEQ_T:
    case T_SET_T:
    case T_ANYTYPE:
Elemer Lelik's avatar
Elemer Lelik committed
498
    case T_ARRAY:
499
      if(rawattrib==NULL) {rawattrib= new RawAST(get_default_raw_fieldlength()); new_raw=true;}
Elemer Lelik's avatar
Elemer Lelik committed
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
      if(textattrib==NULL){textattrib= new TextAST; new_text=true;}
      if(xerattrib==NULL) {xerattrib = new XerAttributes; new_xer = true;}
      if(berattrib==NULL) {berattrib = new BerAST; new_ber = true;}
      if (NULL == jsonattrib) {
        jsonattrib = new JsonAST;
        new_json = true;
      }

      if(w_attrib_path)
      {
        vector<SingleWithAttrib> const &real_attribs
          = w_attrib_path->get_real_attrib();

        //calculate the type's attributes (the qualifierless ones)
        size_t nof_elements = real_attribs.size();
        for(size_t i = 0; i < nof_elements; i++)
        {
          SingleWithAttrib *temp_single = real_attribs[i];
          if(temp_single->get_attribKeyword() == SingleWithAttrib::AT_VARIANT
            && (!temp_single->get_attribQualifiers()
              || temp_single->get_attribQualifiers()->get_nof_qualifiers()
                  == 0)){
            // raw/text/xer/ber/json attributes for the whole record/seq.
            // (own or inherited)
            parse_rawAST(rawattrib, textattrib, xerattrib, berattrib, jsonattrib,
              temp_single->get_attribSpec(), get_length_multiplier(),
              my_scope->get_scope_mod(),
              raw_found, text_found, xer_found, ber_found, json_found);
          }
        }
        //calculate the components attributes
        MultiWithAttrib* self_attribs = w_attrib_path->get_with_attr();
        if(self_attribs)
        {
          MultiWithAttrib* new_self_attribs = new MultiWithAttrib;
          SingleWithAttrib* swa = 0;

          // copy all the "encode" attributes
          for(size_t i = 0; i < self_attribs->get_nof_elements(); i++)
          {
            if(self_attribs->get_element(i)->get_attribKeyword()
              == SingleWithAttrib::AT_ENCODE)
            {
              // Copy the attribute without qualifiers
              const SingleWithAttrib* swaref = self_attribs->get_element(i);
              swa = new SingleWithAttrib(swaref->get_attribKeyword(),
546
                swaref->get_modifier(), 0, swaref->get_attribSpec().clone());
Elemer Lelik's avatar
Elemer Lelik committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
              new_self_attribs->add_element(swa);
            }
          }

          if(new_self_attribs->get_nof_elements() > 0)
          { // One or more "encode"s were copied; create a context for them.
            // This is a member because is has to be owned by this Type
            // (the components only refer to it).
            encode_attrib_path = new WithAttribPath;
            encode_attrib_path->set_with_attr(new_self_attribs);
            encode_attrib_path->set_parent(w_attrib_path->get_parent());
          }
          else delete new_self_attribs;

          // This should be bool, but gcc 4.1.2-sol8 generates incorrect code
          // with -O2 :(
Elemer Lelik's avatar
Elemer Lelik committed
563
564
          const int se_of = (typetype == T_SEQOF || typetype == T_SETOF ||
            typetype == T_ARRAY);
Elemer Lelik's avatar
Elemer Lelik committed
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
          const size_t nof_comps = se_of ? 1 : get_nof_comps();

          // Distribute the attributes with qualifiers to the components.
          // If the type is a sequence-of or set-of, we pretend it to have
          // one component with the name "_0" (a valid TTCN-3 identifier
          // can't begin with an underscore). compiler.y has created
          // the appropriate identifier in the qualifier for a "[-]".
          for(size_t i = 0; i < nof_comps; i++)
          {
            const Identifier& comp_id =
              se_of ? underscore_zero : get_comp_id_byIndex(i);
            MultiWithAttrib* component_attribs = new MultiWithAttrib;

            for(size_t j = 0; j < self_attribs->get_nof_elements(); j++)
            {
              const SingleWithAttrib *temp_single =
                self_attribs->get_element(j);
              Qualifiers* temp_qualifiers =
                temp_single->get_attribQualifiers();
              if( !temp_qualifiers
                || temp_qualifiers->get_nof_qualifiers() == 0) continue;

              Qualifiers* calculated_qualifiers = new Qualifiers;
              bool qualifier_added = false;
              for(size_t k=0; k < temp_qualifiers->get_nof_qualifiers(); )
              {
                const Qualifier* temp_qualifier =
                  temp_qualifiers->get_qualifier(k);
                if(temp_qualifier->get_nof_identifiers() > 0
                  && (*temp_qualifier->get_identifier(0) == comp_id))
                {
                  // Found a qualifier whose first identifier matches
                  //  the component name. Remove the qualifier from the
                  //  enclosing type, chop off its head,
                  //  and add it to the component's qualifiers.
                  calculated_qualifiers->add_qualifier(
                    temp_qualifier->get_qualifier_without_first_id());
                  temp_qualifiers->delete_qualifier(k);
                  qualifier_added = true;
                }
                else k++;
              } // next qualifier

              if(qualifier_added)
              {
                // A copy of temp_single, with new qualifiers
                SingleWithAttrib* temp_single2
                = new SingleWithAttrib(temp_single->get_attribKeyword(),
613
                  temp_single->get_modifier(),
Elemer Lelik's avatar
Elemer Lelik committed
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
                  calculated_qualifiers,
                  temp_single->get_attribSpec().clone());
                temp_single2->set_location(*temp_single);
                component_attribs->add_element(temp_single2);
              }
              else delete calculated_qualifiers;
            } // next attrib

            if (component_attribs->get_nof_elements() > 0) {
              Type* component_type = se_of ?
                get_ofType() : get_comp_byIndex(i)->get_type();

              if(encode_attrib_path)
                // The record's "encode" attributes (only) apply to the fields.
                // Interpose them in the path of the field.
                component_type->set_parent_path(encode_attrib_path);
              else
                component_type->set_parent_path(w_attrib_path->get_parent());

              component_type->set_with_attr(component_attribs);
            }
            else delete component_attribs;
          } // next component index

          // Any remaining attributes with qualifiers are erroneous
          for(size_t i = 0; i < self_attribs->get_nof_elements();)
          {
            Qualifiers *temp_qualifiers = self_attribs->get_element(i)
                ->get_attribQualifiers();
            if(temp_qualifiers && temp_qualifiers->get_nof_qualifiers() != 0)
            {
              size_t nof_qualifiers = temp_qualifiers->get_nof_qualifiers();
              for(size_t j = 0; j < nof_qualifiers; j++)
              {
                const Qualifier *temp_qualifier =
                  temp_qualifiers->get_qualifier(j);
                const Identifier& tmp_id = *temp_qualifier->get_identifier(0);
                // Special case when trying to reference the inner type
                // of a record-of when it wasn't a record-of.
                if (tmp_id == underscore_zero) temp_qualifier->error(
654
655
656
657
                  "Type `%s' cannot be indexed", get_typename().c_str());
                else temp_qualifier->error(
                  "Reference to non-existent field `%s' in type `%s'",
                  tmp_id.get_dispname().c_str(), get_typename().c_str());
Elemer Lelik's avatar
Elemer Lelik committed
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
              }
              self_attribs->delete_element(i);
            }else{
              i++;
            }
          } // next i
        } // end if(self_attribs)
      } // end if(w_attrib_path)
      if (!raw_found && new_raw)  { delete rawattrib;  rawattrib = NULL; }
      if (!text_found && new_text){ delete textattrib; textattrib= NULL; }
      if (!xer_found && new_xer)  { delete xerattrib;  xerattrib = NULL; }
      if (!ber_found && new_ber)  { delete berattrib;  berattrib = NULL; }
      if (!json_found && new_json) {
        delete jsonattrib;
        jsonattrib = NULL;
      }
      break;
    default:
      // nothing to do, ASN1 types or types without defined raw attribute
      break;
    } // switch
    if (rawattrib && !enable_raw()) { delete rawattrib;  rawattrib = NULL;}
    if (textattrib&& !enable_text()){ delete textattrib; textattrib= NULL;}
    if (xerattrib && !enable_xer()) { delete xerattrib;  xerattrib = NULL;}
    if (berattrib && !enable_ber()) { delete berattrib;  berattrib = NULL;}
    if (NULL != jsonattrib && !enable_json()) {
      delete jsonattrib;
      jsonattrib = NULL;
    }
  } // endif( hasVariantAttrs && enable_{raw,text,xer} )

  raw_parsed = true;
}

// Implements "NAME AS ..." transformations.
void change_name(string &name, XerAttributes::NameChange change) {
  switch (change.kw_) {
  case NamespaceSpecification::NO_MANGLING:
    break; // cool, nothing to do!

  case NamespaceSpecification::UPPERCASED:
    // Walking backwards calls size() only once. Loop var must be signed.
    for (int i = name.size()-1; i >= 0; --i) {
701
      name[i] = (char)toupper(name[i]);
Elemer Lelik's avatar
Elemer Lelik committed
702
703
704
705
706
    }
    break;

  case NamespaceSpecification::LOWERCASED:
    for (int i = name.size()-1; i >= 0; --i) {
707
      name[i] = (char)tolower(name[i]);
Elemer Lelik's avatar
Elemer Lelik committed
708
709
710
711
    }
    break;

  case NamespaceSpecification::CAPITALIZED:
712
    name[0] = (char)toupper(name[0]);
Elemer Lelik's avatar
Elemer Lelik committed
713
714
715
    break;

  case NamespaceSpecification::UNCAPITALIZED:
716
    name[0] = (char)tolower(name[0]);
Elemer Lelik's avatar
Elemer Lelik committed
717
718
719
720
721
722
723
724
    break;

  default: // explicitly specified name
    name = change.nn_;
    break;
  } // switch for NAME
}

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
void Type::get_types_w_no_coding_table(vector<Type>& type_list, bool only_own_table)
{
  // this helps avoid infinite recursions in self-referencing types
  if (RecursionTracker::is_happening(this)) {
    return;
  }
  RecursionTracker tracker(this);
  if ((only_own_table && coding_table.size() == 0) ||
      (!only_own_table && get_type_w_coding_table() == NULL)) {
    type_list.add(this);
  }
  switch (get_typetype_ttcn3()) {
  case T_SEQ_T:
  case T_SET_T:
  case T_CHOICE_T:
  case T_ANYTYPE:
  case T_OPENTYPE:
    for (size_t j = 0; j < get_nof_comps(); ++j) {
      get_comp_byIndex(j)->get_type()->get_types_w_no_coding_table(type_list, only_own_table);
    }
    break;
  case T_SEQOF:
  case T_SETOF:
  case T_ARRAY:
    get_ofType()->get_types_w_no_coding_table(type_list, only_own_table);
    break;
  default:
    break;
  }
}

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
void Type::chk_encodings()
{
  if (legacy_codec_handling) {
    FATAL_ERROR("Type::chk_encodings");
  }
  switch (get_type_refd_last()->get_typetype_ttcn3()) {
  case T_NULL:
  case T_BOOL:
  case T_INT:
  case T_REAL:
  case T_ENUM_T:
  case T_BSTR:
  case T_HSTR:
  case T_OSTR:
  case T_CSTR:
  case T_USTR:
  case T_OID:
  case T_CHOICE_T:
  case T_SEQOF:
  case T_SETOF:
  case T_SEQ_T:
  case T_SET_T:
  case T_VERDICT:
  case T_ARRAY:
  case T_ANYTYPE:
    if (!is_asn1()) {
      WithAttribPath* ap = get_attrib_path();
      if (ap != NULL) {
        MultiWithAttrib* mwa = ap->get_with_attr();
        if (mwa != NULL) {
          for (size_t i = 0; i < mwa->get_nof_elements(); ++i) {
            const SingleWithAttrib* swa = mwa->get_element(i);
            if (swa->get_attribKeyword() == SingleWithAttrib::AT_ENCODE) {
789
              Ttcn::attribute_modifier_t mod = swa->get_modifier();
790
791
792
793
794
              Ttcn::Qualifiers* quals = swa->get_attribQualifiers();
              if (quals != NULL && quals->get_nof_qualifiers() != 0) {
                for (size_t j = 0; j < quals->get_nof_qualifiers(); ++j) {
                  Ttcn::Qualifier* qual = const_cast<Ttcn::Qualifier*>(
                    quals->get_qualifier(j));
795
796
797
798
799
800
801
                  Type* t = get_field_type(qual, EXPECTED_CONSTANT);
                  if (t != NULL) {
                    if (t->my_scope != my_scope) {
                      qual->warning("Encode attribute is ignored, because it "
                        "refers to a type from a different type definition");
                    }
                    else {
802
                      t->add_coding(swa->get_attribSpec().get_spec(), mod, false);
803
804
                    }
                  }
805
806
807
                }
              }
              else {
808
                add_coding(swa->get_attribSpec().get_spec(), mod, false);
809
810
811
812
              }
            }
          }
        }
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
        WithAttribPath* global_ap = NULL;
        Ttcn::Def_Type* def = static_cast<Ttcn::Def_Type*>(owner);
        Ttcn::Group* nearest_group = def->get_parent_group();

        if (nearest_group != NULL) { // there is a group
          global_ap = nearest_group->get_attrib_path();
        }
        else { // no group, use the module
          Common::Module* mymod = my_scope->get_scope_mod();
          // OT_TYPE_DEF is always from a TTCN-3 module
          Ttcn::Module* my_ttcn_module = static_cast<Ttcn::Module *>(mymod);
          global_ap = my_ttcn_module->get_attrib_path();
        }
        if (global_ap != NULL) {
          bool has_global_override = false;
          bool modifier_conflict = false;
          Ttcn::attribute_modifier_t first_mod = Ttcn::MOD_NONE;
          const vector<SingleWithAttrib>& real = global_ap->get_real_attrib();
831
832
833
          for (size_t i = 0; i < real.size(); ++i) {
            const SingleWithAttrib* swa = real[i];
            if (swa->get_attribKeyword() == SingleWithAttrib::AT_ENCODE) {
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
              Ttcn::attribute_modifier_t mod = swa->get_modifier();
              if (i == 0) {
                first_mod = mod;
              }
              else if (!modifier_conflict && mod != first_mod) {
                modifier_conflict = true;
                swa->error("All 'encode' attributes of a group or module must "
                  "have the same modifier ('override', '@local' or none)");
              }
              if (mod == Ttcn::MOD_OVERRIDE) {
                has_global_override = true;
              }
              if (has_global_override && modifier_conflict) {
                break;
              }
            }
          }
          // make a list of the type and its field and element types that inherit
          // the global 'encode' attributes
          // overriding global attributes are inherited by types with no coding
          // table (no 'encode' attributes) of their own
          // non-overriding global attributes are inherited by types that have
          // no coding table of their own and cannot use the coding table of any 
          // other type (get_type_w_coding_table() == NULL)
          vector<Type> type_list;
          get_types_w_no_coding_table(type_list, has_global_override);
          if (type_list.size() != 0) {
            for (size_t i = 0; i < real.size(); ++i) {
              const SingleWithAttrib* swa = real[i];
              if (swa->get_attribKeyword() == SingleWithAttrib::AT_ENCODE) {
                for (size_t j = 0; j < type_list.size(); ++j) {
                  type_list[j]->add_coding(swa->get_attribSpec().get_spec(),
                    Ttcn::MOD_NONE, true);
                }
              }
869
            }
870
            type_list.clear();
871
872
873
874
875
876
877
878
879
880
          }
        }
      }
    }
    else {
      switch (ownertype) {
      case OT_TYPE_ASS:
      case OT_RECORD_OF:
      case OT_COMP_FIELD:
      case OT_SELTYPE:
881
      case OT_FIELDSETTING:
882
        // ASN.1 types automatically have BER, PER, XER, OER and JSON encoding
883
884
885
        add_coding(string("BER:2002"), Ttcn::MOD_NONE, true);
        add_coding(string(get_encoding_name(CT_PER)), Ttcn::MOD_NONE, true);
        add_coding(string(get_encoding_name(CT_JSON)), Ttcn::MOD_NONE, true);
886
        add_coding(string(get_encoding_name(CT_OER)), Ttcn::MOD_NONE, true);
887
        if (asn1_xer) {
888
          // XER encoding for ASN.1 types can be forced with a command line option
889
          add_coding(string(get_encoding_name(CT_XER)), Ttcn::MOD_NONE, true);
890
891
892
893
894
895
896
897
898
899
900
901
902
        }
        break;
      default:
        break;
      }      
    }
    break;
  default:
    // the rest of the types can't have 'encode' attributes
    break;
  }
}

903
904
905
906
907
void Type::chk_variants()
{
  if (legacy_codec_handling) {
    FATAL_ERROR("Type::chk_encodings");
  }
908
  variants_checked = true;
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
  if (is_asn1() || ownertype != OT_TYPE_DEF) {
    return;
  }
  // check global (group/module) variant attributes first
  WithAttribPath* global_ap = NULL;
  Ttcn::Def_Type* def = static_cast<Ttcn::Def_Type*>(owner);
  Ttcn::Group* nearest_group = def->get_parent_group();

  if (nearest_group != NULL) { // there is a group
    global_ap = nearest_group->get_attrib_path();
  }
  else { // no group, use the module
    Common::Module* mymod = my_scope->get_scope_mod();
    // OT_TYPE_DEF is always from a TTCN-3 module
    Ttcn::Module* my_ttcn_module = static_cast<Ttcn::Module *>(mymod);
    global_ap = my_ttcn_module->get_attrib_path();
  }
  if (global_ap != NULL) {
927
928
929
930
931
932
    // process all global variants, not just the closest group
    const vector<SingleWithAttrib>& real = global_ap->get_real_attrib();
    for (size_t i = 0; i < real.size(); ++i) {
      const SingleWithAttrib* swa = real[i];
      if (swa->get_attribKeyword() == SingleWithAttrib::AT_VARIANT) {
        chk_this_variant(swa, true);
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
      }
    }
  }
  // check local variant attributes second, so they overwrite global ones if they
  // conflict with each other
  WithAttribPath* ap = get_attrib_path();
  if (ap != NULL) {
    MultiWithAttrib* mwa = ap->get_with_attr();
    if (mwa != NULL) {
      for (size_t i = 0; i < mwa->get_nof_elements(); ++i) {
        const SingleWithAttrib* swa = mwa->get_element(i);
        if (swa->get_attribKeyword() == SingleWithAttrib::AT_VARIANT) {
          Ttcn::Qualifiers* quals = swa->get_attribQualifiers();
          if (quals != NULL && quals->get_nof_qualifiers() != 0) {
            for (size_t j = 0; j < quals->get_nof_qualifiers(); ++j) {
              Ttcn::Qualifier* qual = const_cast<Ttcn::Qualifier*>(
                quals->get_qualifier(j));
              Type* t = get_field_type(qual, EXPECTED_CONSTANT);
              if (t != NULL) {
                if (t->my_scope != my_scope) {
                  qual->warning("Variant attribute is ignored, because it refers "
                    "to a type from a different type definition");
                }
                else {
                  t->chk_this_variant(swa, false);
                }
              }
            }
          }
          else {
            chk_this_variant(swa, false);
          }
        }
      }
    }
  }
  // check the coding attributes set by the variants
  chk_coding_attribs();
}

void Type::chk_this_variant(const Ttcn::SingleWithAttrib* swa, bool global)
{
  // TODO: use something other than get_typename...
  Type* t = get_type_w_coding_table();
  if (t == NULL) {
    if (!global) {
      swa->error("No encoding rules defined for type `%s'",
        get_typename().c_str());
    }
  }
  else {
984
985
986
    const vector<string>* coding_strings = swa->get_attribSpec().get_encodings();
    // gather the built-in codecs referred to by the variant's encoding strings
    vector<MessageEncodingType_t> codings;
987
    bool erroneous = false;
988
    if (coding_strings == NULL) {
989
990
991
992
993
994
995
996
      if (t->coding_table.size() > 1) {
        if (!global) {
          swa->error("The encoding reference is mandatory for variant attributes "
            "of type `%s', which has multiple encodings", get_typename().c_str());
        }
        erroneous = true;
      }
      else if (t->coding_table[0]->built_in) {
997
        codings.add(new MessageEncodingType_t(t->coding_table[0]->built_in_coding));
998
      }
999
1000
1001
1002
1003
1004
      else { // PER or custom encoding
        MessageEncodingType_t coding =
          strcmp(t->coding_table[0]->custom_coding.name, "PER") == 0 ?
          CT_PER : CT_CUSTOM;
        swa->warning("Variant attributes related to %s encoding are ignored",
          get_encoding_name(coding));
1005
1006
1007
      }
    }
    else {
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
      for (size_t i = 0; i < coding_strings->size(); ++i) {
        const string& enc_str = *(*coding_strings)[i];
        MessageEncodingType_t coding = get_enc_type(enc_str);
        if (!has_encoding(coding, &enc_str)) {
          erroneous = true;
          if (!global) {
            if (coding != CT_CUSTOM) {
              swa->error("Type `%s' does not support %s encoding",
                get_typename().c_str(), get_encoding_name(coding));
            }
            else {
              swa->error("Type `%s' does not support custom encoding `%s'",
                get_typename().c_str(), enc_str.c_str());
            }
1022
1023
          }
        }
1024
1025
1026
1027
1028
1029
1030
        else if (coding != CT_PER && coding != CT_CUSTOM) {
          codings.add(new MessageEncodingType_t(coding));
        }
        else { // PER or custom encoding
          swa->warning("Variant attributes related to %s encoding are ignored",
            get_encoding_name(coding));
        }
1031
1032
      }
    }
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
    if (!erroneous && codings.size() != 0) {
      for (size_t i = 0; i < codings.size(); ++i) {
        MessageEncodingType_t coding = *codings[i];
        bool new_ber = false;    // a BerAST object was allocated here
        bool new_raw = false;    // a RawAST object was allocated here
        bool new_text = false;   // a TextAST object was allocated here
        bool new_xer = false;    // a XerAttribute object was allocated here
        bool new_json = false;   // a JsonAST object was allocated here
        bool ber_found = false;  // a BER attribute was found by the parser
        bool raw_found = false;  // a RAW attribute was found by the parser
        bool text_found = false; // a TEXT attribute was found by the parser
        bool xer_found = false;  // a XER attribute was found by the parser
        bool json_found = false; // a JSON attribute was found by the parser
        if (berattrib == NULL) {
          berattrib = new BerAST;
          new_ber = true;
1049
        }
1050
1051
1052
1053
1054
1055
1056
        if (rawattrib == NULL) {
          Type* t_refd = this;
          while (t_refd->rawattrib == NULL && t_refd->is_ref()) {
            t_refd = t_refd->get_type_refd();
          }
          rawattrib = new RawAST(t_refd->rawattrib, get_default_raw_fieldlength());
          new_raw = true;
1057
        }
1058
1059
1060
1061
1062
1063
1064
        if (textattrib == NULL) {
          Type* t_refd = this;
          while (t_refd->textattrib == NULL && t_refd->is_ref()) {
            t_refd = t_refd->get_type_refd();
          }
          textattrib = new TextAST(t_refd->textattrib);
          new_text = true;
1065
        }
1066
1067
1068
        if (xerattrib == NULL) {
          xerattrib = new XerAttributes;
          new_xer = true;
1069
        }
1070
1071
1072
1073
1074
1075
1076
1077
        if (jsonattrib == NULL) {
          Type* t_refd = this;
          while (t_refd->jsonattrib == NULL && t_refd->is_ref()) {
            t_refd = t_refd->get_type_refd();
          }
          jsonattrib = new JsonAST(t_refd->jsonattrib);
          new_json = true;
        }
1078
        bool xer_namespace_before = xerattrib->namespace_.uri != 0;
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
        int ret = parse_rawAST(rawattrib, textattrib, xerattrib, berattrib, jsonattrib,
          swa->get_attribSpec(), get_length_multiplier(), my_scope->get_scope_mod(), 
          raw_found, text_found, xer_found, ber_found, json_found, coding);
        bool mismatch = false;
        if (ber_found || raw_found || text_found || xer_found || json_found) {
          switch (coding) {
          case CT_BER:
            mismatch = !ber_found;
            break;
          case CT_RAW:
            mismatch = !raw_found;
            break;
          case CT_TEXT:
            mismatch = !text_found;
            break;
          case CT_XER:
            mismatch = !xer_found;
1096
1097
1098
            if (!xer_namespace_before && xerattrib->namespace_.uri != 0 && global) {
              xerattrib->namespace_.global_variant = true;
            }
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
            break;
          case CT_JSON:
            mismatch = !json_found;
            break;
          default:
            FATAL_ERROR("Type::chk_this_variant");
            break;
          }
        }
        if (mismatch && ret == 0) {
          if (!global || coding_strings != NULL) {
            // don't display this if there were parsing errors in the variant 
            // attribute, or if it didn't have encoding strings
            swa->error("Variant attribute is not related to %s encoding",
              get_encoding_name(coding));
          }
        }
        if (new_ber && !ber_found) {
          delete berattrib;
          berattrib = NULL;
        }
        if (new_raw && !raw_found) {
          delete rawattrib;
          rawattrib = NULL;
        }
        if (new_text && !text_found) {
          delete textattrib;
          textattrib = NULL;
        }
        if (new_xer && !xer_found) {
          delete xerattrib;
          xerattrib = NULL;
        }
        if (new_json && !json_found) {
          delete jsonattrib;
          jsonattrib = NULL;
1135
1136
1137
        }
      }
    }
1138
1139
1140
1141
1142
    if (codings.size() != 0) {
      for (size_t i = 0; i < codings.size(); ++i) {
        delete codings[i];
      }
      codings.clear();
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
    }
  } // if t != NULL
  if (global) {
    // send global variant attributes to field/element types
    switch (typetype) {
    case T_SEQ_T:
    case T_SEQ_A:
    case T_SET_T:
    case T_SET_A:
    case T_CHOICE_T:
    case T_CHOICE_A:
    case T_ANYTYPE:
    case T_OPENTYPE:
      for (size_t i = 0; i < get_nof_comps(); ++i) {
        get_comp_byIndex(i)->get_type()->chk_this_variant(swa, global);
      }
      break;
      
    case T_ARRAY:
    case T_SEQOF:
    case T_SETOF:
      get_ofType()->chk_this_variant(swa, global);
      break;
      
    default:
      break;
    }
  }
}

Elemer Lelik's avatar
Elemer Lelik committed
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
void Type::chk_xer_any_attributes()
{
  Type * const last = get_type_refd_last();
  switch (last->typetype == T_SEQOF ?
    last->u.seof.ofType->get_type_refd_last()->typetype : 0) {
  case T_UTF8STRING: // SEQUENCE OF UTF8String, ASN.1
  case T_USTR:       // record of universal charstring
    break;
    // fall through
  default:
    error("ANY-ATTRIBUTES can only be applied to record of string");
    break;
  } // switch

  switch (parent_type != NULL ? parent_type->typetype : 0) {
  case T_SEQ_A: case T_SET_A:
  case T_SEQ_T: case T_SET_T:
    for (size_t x = 0; x < parent_type->get_nof_comps(); ++x) {
      CompField * cf = parent_type->get_comp_byIndex(x);
      if (cf->get_type() != this) continue;
Elemer Lelik's avatar
Elemer Lelik committed
1193
1194
      if (cf->has_default()) {
        error("The field with ANY-ATTRIBUTES cannot have DEFAULT");
Elemer Lelik's avatar
Elemer Lelik committed
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
      }
    }
    break;
  default:
    error("ANY-ATTRIBUTES can only be applied to a member of "
      "SEQUENCE, SET, record or set");
    break;
  }

  if (xerattrib->untagged_
    || (parent_type && parent_type->xerattrib && parent_type->xerattrib->untagged_)) {
    error("Neither the type with ANY-ATTRIBUTES, nor its enclosing type "
      "may be marked UNTAGGED");
  }
}

void Type::chk_xer_any_element()
{
  Type *const last = get_type_refd_last();
  switch (last->typetype) {
  case T_UTF8STRING: // UTF8String, ASN.1
  case T_USTR:       // universal charstring
    break; // acceptable
  case T_SEQOF: {
    /* A special case for TTCN-3 where applying ANY-ELEMENT to the record-of
     * has the same effect as applying it to the string member.
     * This should no longer be necessary now that we can refer
     * to the embedded type of a record-of with [-], but it has to stay
     * unless the standard deprecates it. */
    Type *oftype = last->u.seof.ofType;
    if (oftype->xerattrib == 0) oftype->xerattrib = new XerAttributes;
    // Transfer the ANY-ATTRIBUTE from the record-of to its member type
    oftype->xerattrib->anyElement_ = xerattrib->anyElement_;
    xerattrib->anyElement_.nElements_ = 0;
    xerattrib->anyElement_.uris_ = 0;
    // Re-check the member type since we fiddled with it
    const char * type_name = "record of";
    Error_Context cntxt(this, "In embedded type of %s", type_name);
    oftype->xer_checked = false;
    oftype->chk_xer();
    break; }
  default:
    error("ANY-ELEMENT can only be applied to UTF8String "
      "or universal charstring type");
    break;
  } // switch

  if (xerattrib->attribute_ || xerattrib->base64_ || xerattrib->untagged_
1243
    || (xerattrib->defaultForEmpty_ != NULL || xerattrib->defaultForEmptyIsRef_)
Elemer Lelik's avatar
Elemer Lelik committed
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
    || xerattrib->whitespace_ != XerAttributes::PRESERVE) {
    error("A type with ANY-ELEMENT may not have any of the following encoding instructions: "
      "ATTRIBUTE, BASE64, DEFAULT-FOR-EMPTY, PI-OR-COMMENT, UNTAGGED or WHITESPACE");
  }
}

void Type::chk_xer_attribute()
{
  if (xerattrib->element_) {
    error("ELEMENT and ATTRIBUTE are incompatible");
  }

  switch (parent_type!=NULL ? parent_type->typetype :-0) {
  case 0: // no parent accepted in case a field of this type is declared
  case T_SEQ_A: case T_SEQ_T:
  case T_SET_A: case T_SET_T:
    break; // acceptable
  default:
    error("A type with ATTRIBUTE must be a member of "
      "SEQUENCE, SET, record or set");
    break;
  }

  if (xerattrib->untagged_
    || (parent_type && parent_type->xerattrib && parent_type->xerattrib->untagged_)) {
    error("Neither the type with ATTRIBUTE, nor its enclosing type "
      "may be marked UNTAGGED");
  }

  if (has_ae(xerattrib)) {
    // TODO: || (xerattrib->defaultForEmpty_ && it is an ASN.1 type)
    // DEFAULT-FOR-EMPTY is allowed only for TTCN-3
    error("A type with ATTRIBUTE shall not also have any of the final "
      "encoding instructions ANY-ELEMENT" /*", DEFAULT-FOR-EMPTY"*/ " or PI-OR-COMMENT");
  }
}

/// CompField cache
struct CFCache {
  /// Pointer to the field
  CompField *cf;
  /// The type of the field
  Type *top;
  /// The ultimate type, top->get_type_refd_last()
  Type *last;
  /// The typetype of last, on which we sort. Its name is meant to be
  /// mnemonic (it belongs to \c last, not \c top)
  Type::typetype_t lastt;
};

/// Comparison function for CFCache based on typetype
int tcomp(const void *l, const void *r)
{
  int retval = ((const CFCache*)l)->lastt - ((const CFCache*)r)->lastt;
  return retval;
}

/** Find the original component name if it was changed by TEXT
 *
 * If there is a TEXT whose \a new_text matches \p text, return
 * the corresponding \a target.
 *
 * If there are no TEXT coding instructions, always returns \p text.
 *
 * @param[in,out] text on input, a name possibly modified by any TEXT encoding
 * instruction; on output, the actual component name
 */
void Type::target_of_text(string & text)
{
  for (size_t t = 0; t < xerattrib->num_text_; ++t) {
    NamespaceSpecification& txt = xerattrib->text_[t];

    if ((unsigned long)txt.prefix == 0
      ||(unsigned long)txt.prefix == NamespaceSpecification::ALL) {
      FATAL_ERROR("Type::target_of_text()");
      continue;
    }

    string target(txt.target);

    switch ((unsigned long)txt.new_text) {
    case NamespaceSpecification::CAPITALIZED: // tARGET -> TARGET
1326
      target[0] = (char)toupper(target[0]);
Elemer Lelik's avatar
Elemer Lelik committed
1327
1328
      break;
    case NamespaceSpecification::UNCAPITALIZED:
1329
      target[0] = (char)tolower(target[0]); // TARGET -> tARGET
Elemer Lelik's avatar
Elemer Lelik committed
1330
1331
1332
      break;
    case NamespaceSpecification::UPPERCASED:
      for (int si = target.size() - 1; si >= 0; --si) {
1333
        target[si] = (char)toupper(target[si]);
Elemer Lelik's avatar
Elemer Lelik committed
1334
1335
1336
1337
      }
      break;
    case NamespaceSpecification::LOWERCASED:
      for (int si = target.size() - 1; si >= 0; --si) {
1338
        target[si] = (char)tolower(target[si]);
Elemer Lelik's avatar
Elemer Lelik committed
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
      }
      break;

    case 0: // "text" not possible
      FATAL_ERROR("Type::target_of_text() Text with no target and DFE");
      break;

    default: // it's a string, "text 'field' as 'string'"
      target = txt.uri;
      break;
    } // switch new_text

    if (target == text) {
      text = txt.target; // we want the value before the change
      break;
    }
  } // next text
}

// The suffix of the name of the variable which contains the D-F-E value.
static const string dfe_suffix("_dfe");

/** Construct a Value to represent defaultForEmpty
 *
 * @param last pointer to a Type which is the end of the reference chain,
 * usually this->get_type_refd_last()
 * @param dfe_str string containing the value from defaultForEmpty
1366
1367
 * @param ref Reference containing the reference in defaultForEmpty
 * @param is_ref_dfe true if reference is used instead of text in defaultForempty
Elemer Lelik's avatar
Elemer Lelik committed
1368
1369
 * @return a newly allocated Common::Value
 */
1370
Value *Type::new_value_for_dfe(Type *last, const char *dfe_str, Common::Reference* ref, bool is_ref_dfe)
Elemer Lelik's avatar
Elemer Lelik committed
1371
{
1372
1373
1374
1375
  string defaultstring;
  if (is_ref_dfe) {
    Value* v = new Value(Value::V_REFD, ref->clone());
    v->set_my_scope(get_my_scope()->get_scope_mod());
1376
1377
1378
1379
1380
    Type * t = v->get_expr_governor_last();
    if (t == NULL) {
      delete v;
      return 0;
    }
BenceJanosSzabo's avatar
BenceJanosSzabo committed
1381
    bool same_mod = false;
1382
    if (last->get_my_scope()->get_scope_mod() == t->get_my_scope()->get_scope_mod()) {
BenceJanosSzabo's avatar
BenceJanosSzabo committed
1383
1384
1385
      same_mod = true;
    }
    if (!is_compatible_tt_tt(last->typetype, t->typetype, last->is_asn1(), t->is_asn1(), same_mod)) {
1386
      v->get_reference()->error("Incompatible types were given to defaultForEmpty variant: `%s' instead of `%s'.",
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
        v->get_expr_governor_last()->get_typename().c_str(), last->get_typename().c_str());
      delete v;
      return 0;
    }
    if (!v->is_unfoldable()) {
      switch(v->get_value_refd_last()->get_valuetype()) {
        case Value::V_CSTR:
          defaultstring = v->get_val_str().c_str();
          break;
        case Value::V_USTR:
        case Value::V_ISO2022STR:
          defaultstring = v->get_val_ustr().get_stringRepr_for_pattern();
          break;
        case Value::V_INT:
          defaultstring = Int2string(v->get_val_Int()->get_val());
          break;
        case Value::V_REAL:
          defaultstring = Real2string(v->get_val_Real());
          break;
        case Value::V_BOOL:
          if (v->get_val_bool()) {
            defaultstring = "true";
          } else {
            defaultstring = "false";
          }
          break;
        case Value::V_ENUM: {
          Value* v2 = v->get_value_refd_last();
          defaultstring = v2->get_val_id()->get_ttcnname().c_str();
          break; }
        //case Value::V_CHOICE: //In the switch below the choice is handled but
                                //it is not possible to write DFE for unions???
        default:
          break;
      }
      dfe_str = defaultstring.c_str();
    } else if (v->get_reference()->get_refd_assignment()->get_asstype() ==  Assignment::A_MODULEPAR) {
      return v;
    } else {
       v->get_reference()->error("Only strings, constants and module parameters are allowed for a defaultForEmpty value.\n");
       delete v;
       return 0;
    }
    delete v;
  }
  if (!is_ref_dfe) {
    defaultstring = dfe_str;
  }
Elemer Lelik's avatar
Elemer Lelik committed
1435
1436
1437
1438
  switch (last->typetype) {
  case T_CSTR:
  case T_USTR:
  case T_UTF8STRING:
1439
1440
      return new Value(Common::Value::V_CSTR,
        new string(defaultstring));
Elemer Lelik's avatar
Elemer Lelik committed
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

  case T_INT:
  case T_INT_A:
    return new Value(Common::Value::V_INT,
      new int_val_t(dfe_str, *this));

  case T_REAL: {
    const Real& rval = string2Real(dfe_str, *this);
    return new Value(Value::V_REAL, rval);
  }

  case T_BOOL: {
    if (!strcmp(dfe_str, "true")
      ||!strcmp(dfe_str, "1")) {
      return new Value(Value::V_BOOL, true);
    }
    else if (!strcmp(dfe_str, "false")
      ||     !strcmp(dfe_str, "0")) {
      return new Value(Value::V_BOOL, false);
    }
    else error("Invalid boolean default value");
    break;
  }

  case T_ENUM_A: case T_ENUM_T: {
    // If there is a TEXT, the DFE value corresponds to TextToBeUsed.
    // Fetch the "real" name of the field (Target).

    target_of_text(defaultstring);

    Identifier *val_id = new Identifier(Common::Identifier::ID_TTCN, // FIXME when ASN1 is supported
      defaultstring);

    if (!last->has_ei_withName(*val_id)) {
      error("No enumeration item item '%s'", defaultstring.c_str());
#ifndef NDEBUG
      for (size_t ee=0; ee < last->u.enums.eis->get_nof_eis(); ++ee) {
        note("Maybe %s", last->u.enums.eis->get_ei_byIndex(ee)->get_name().get_name().c_str());
      }
#endif
    }

    return new Value(Common::Value::V_ENUM, val_id);
  }
BenceJanosSzabo's avatar
BenceJanosSzabo committed
1485
  case T_CHOICE_A: case T_CHOICE_T: case T_ANYTYPE: {
Elemer Lelik's avatar
Elemer Lelik committed
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
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
    // Try to guess which alternative the given DFE text belongs to.
    // Sort the fields based on typetype, so BOOL, INT, REAL, ENUM
    // are tried before the various string types
    // (any string looks 'right' for a string value).
    size_t num_comps = last->get_nof_comps();
    CFCache *sorted = new CFCache[num_comps];
    for (size_t c = 0; c < num_comps; c++) {
      CompField *cf = last->get_comp_byIndex(c);
      Type *cft = cf->get_type();
      Type *cftlast = cft->get_type_refd_last();
      sorted[c].cf = cf;
      sorted[c].top  = cft;
      sorted[c].last = cftlast;
      sorted[c].lastt = cftlast->typetype;
    }
    qsort(sorted, num_comps, sizeof(CFCache), tcomp);

    Value * retval = 0;
    size_t c;
    for (c = 0; c < num_comps && retval == 0; c++) {
      CFCache &current = sorted[c];
      // We can't just call new_value_for_dfe(), because some alternatives
      // would generate errors even if a later type could accept the value.
      switch (current.lastt) {
      case T_BOOL:
        if (!strcmp(dfe_str, "true")
          ||!strcmp(dfe_str, "1")) {
          retval = new Value(Value::V_BOOL, true);
        }
        else if (!strcmp(dfe_str, "false")
          ||     !strcmp(dfe_str, "0")) {
          retval = new Value(Value::V_BOOL, false);
        }
        break;

      case T_INT: case T_INT_A: {
        const char *start = dfe_str, *end;
        while (isspace((const unsigned char)*start)) ++start;
        if (*start == '+') ++start;
        int ndigits = BN_dec2bn(NULL, start); // includes any '-' sign
        end = start + ndigits;
        // Pretend that all trailing whitespace characters were digits
        while (isspace(*end)) ++ndigits, ++end;

        // Check that all the string was used up in the conversion,
        // otherwise "3.1415" and "1e6" would appear as integers.
        if (defaultstring.size() == (size_t)ndigits + (start - dfe_str )) {
          retval = current.top->new_value_for_dfe(current.last, start);
        }
        break; }

      case T_REAL: {
        float f;
        char tail[2];
        int num_converted = sscanf(dfe_str, "%f %1s", &f, tail);
        // If tail was converted (num_converted>1) that's an error
        if (num_converted == 1) { // sscanf was happy
          retval = current.top->new_value_for_dfe(current.last, dfe_str);
        }
        break; }

      case T_ENUM_A: case T_ENUM_T: {
        current.top->target_of_text(defaultstring);
        Identifier alt(Identifier::ID_TTCN, defaultstring);
        if (current.last->has_ei_withName(alt)) {
          retval = current.top->new_value_for_dfe(current.last, dfe_str);
        }
        break; }

      case T_CSTR:
      case T_USTR:
      case T_UTF8STRING: {
        retval = current.top->new_value_for_dfe(current.last, dfe_str);
        break; }

      default:
        break;
      } // switch
    } // next c

    if (retval != 0) {
      c--;
      retval->set_genname(sorted[c].top->genname, dfe_suffix);
      retval->set_my_scope(sorted[c].top->my_scope);
      retval->set_my_governor(sorted[c].top);
      Value *choice_retval = new Value(Value::V_CHOICE,
        new Identifier(sorted[c].cf->get_name()), retval);
      retval = choice_retval;
    }

    delete [] sorted;
    return retval; }

  /* Useless without a properly constructed Value(V_SEQ)
  case T_SEQ_A: case T_SEQ_T: {
    NamedValues *nvs = new NamedValues;
    //NamedValue  *nv  = new NamedValue(new Identifier, new Value);
    nvs->add_nv(nv);
    xerattrib->defaultValue_ = new Value(Value::V_SEQ, nvs);
    break; }
   */

  default: // complain later
    break;
  } // switch
  return 0;
}

void Type::chk_xer_dfe()
{
  Type * const last = get_type_refd_last();

  if (/* TODO xerattrib->attribute_ is error for ASN.1 only */
    xerattrib->untagged_ || has_ae(xerattrib)) {
    error("A type with DEFAULT-FOR-EMPTY shall not have any of the final "
      "encoding instructions ANY-ELEMENT, ATTRIBUTE, UNTAGGED."); // 23.2.8
  }

  if (is_charenc() == Yes) {
1605
    xerattrib->defaultValue_ = new_value_for_dfe(last, xerattrib->defaultForEmpty_, xerattrib->defaultForEmptyRef_, xerattrib->defaultForEmptyIsRef_);
Elemer Lelik's avatar
Elemer Lelik committed
1606
1607
1608
1609
1610
1611
1612
    if (xerattrib->defaultValue_ != 0) {
      xerattrib->defaultValue_->set_genname(this->genname, dfe_suffix);
      xerattrib->defaultValue_->set_my_scope(this->my_scope);
      xerattrib->defaultValue_->set_my_governor(last);
    }
    else {
      error("DEFAULT-FOR-EMPTY not supported for character-encodable type %s",
1613
        get_typename().c_str());
Elemer Lelik's avatar
Elemer Lelik committed
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
    }
  }
  else if (last->typetype == T_SEQ_A || last->typetype == T_SEQ_T) {
    // If DEFAULT-FOR-EMPTY applies to a record (SEQUENCE), then only one
    // component can produce element content, and it should be the last,
    // because all the others should have ATTRIBUTE or ANY-ATTRIBUTE,
    // and those are moved to the front. 23.2.2 b)
    // FIXME only b) appears to have this restriction, not c)d)e)
    const size_t num_cf = last->get_nof_comps();
    if (num_cf > 0) {
      CompField *cf = last->get_comp_byIndex(num_cf-1); // last field
      Type *cft = cf->get_type(); // cft: CompField type
      cft = cft->get_type_refd_last();
      //typetype_t cftt = cft->get_typetype();

1629
      xerattrib->defaultValue_ = new_value_for_dfe(cft, xerattrib->defaultForEmpty_, xerattrib->defaultForEmptyRef_, xerattrib->defaultForEmptyIsRef_);
Elemer Lelik's avatar
Elemer Lelik committed
1630
1631
1632
1633
1634
1635
1636
      if (xerattrib->defaultValue_ != 0) {
        xerattrib->defaultValue_->set_genname(last->genname, string("_dfe"));
        xerattrib->defaultValue_->set_my_scope(cft->my_scope);
        xerattrib->defaultValue_->set_my_governor(cft);
      }
      else {
        error("DEFAULT-FOR-EMPTY not supported for fields of type %s",
1637
          cft->get_typename().c_str());
Elemer Lelik's avatar
Elemer Lelik committed
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
      }
    } // endif comps >0
  } // if SEQ/SET
  else {
    error("DEFAULT-FOR-EMPTY not applicable to type");
  }
}

void Type::chk_xer_embed_values(int num_attributes)
{
  Type * const last = get_type_refd_last();

Elemer Lelik's avatar
Elemer Lelik committed
1650
  enum complaint_type { ALL_GOOD, HAVE_DEFAULT, UNTAGGED_EMBEDVAL,
Elemer Lelik's avatar
Elemer Lelik committed
1651
    NOT_SEQUENCE, EMPTY_SEQUENCE, FIRST_NOT_SEQOF, SEQOF_NOT_STRING,
1652
    SEQOF_BAD_LENGTH, UNTAGGED_OTHER, ATTRIBUTE_EMBEDVAL } ;
Elemer Lelik's avatar
Elemer Lelik committed
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
  complaint_type complaint = ALL_GOOD;
  size_t expected_length = (size_t)-1;
  Type *cf0t = 0; // type of first component
  CompField *cf = 0;
  switch (last->typetype) {
  case T_SEQ_A: case T_SEQ_T: { // 25.2.1, the type must be a sequence
    const size_t num_cf = last->get_nof_comps();
    if (num_cf == 0) {
      complaint = EMPTY_SEQUENCE; // must have a "first component"
      break;
    }
    CompField *cf0 = last->get_comp_byIndex(0);
    cf0t = cf0->get_type()->get_type_refd_last();
Elemer Lelik's avatar
Elemer Lelik committed
1666
1667
1668
    if (cf0->has_default()) {
      complaint = HAVE_DEFAULT;
      break; // 25.2.1 first component cannot have default
Elemer Lelik's avatar
Elemer Lelik committed
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
    }

    switch (cf0t->get_typetype()) { // check the first component
    case T_SEQOF: {
      Type *cfot = cf0t->get_ofType(); // embedded type
      switch (cfot->get_type_refd_last()->get_typetype()) {
      case T_UTF8STRING:
      case T_USTR: { // hooray, a SEQUENCE OF some string
        if ( (cf0t->xerattrib && cf0t->xerattrib->untagged_)
          || (cfot->xerattrib && cfot->xerattrib->untagged_)) {
          complaint = UNTAGGED_EMBEDVAL; // 25.2.2
          break;
        }
1682
1683
1684
1685
1686
1687
        // Either the type of the field or the last_refd type of the field
        if ((cf0->get_type()->xerattrib && cf0->get_type()->xerattrib->attribute_)
          || (cf0t->xerattrib && cf0t->xerattrib->attribute_)) {
          complaint = ATTRIBUTE_EMBEDVAL;
          break;
        }
Elemer Lelik's avatar
Elemer Lelik committed
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740

        // Check length restriction on the record of. If there is one,
        // it better be the correct number.
        // FIXME: if there is also a USE-NIL, it cannot have a length restriction; only check at runtime
        const SubType *sub =  cf0t->sub_type;
        const Int len = sub ? sub->get_length_restriction() :-1;
        // get_length_restriction() itself may return -1
        expected_length = num_cf -num_attributes -xerattrib->useOrder_;
        if (len > 0 && (size_t)len != expected_length) {
          // The +1 from 25.2.6 b) is compensated because
          // the EMBED-VALUES member itself is ignored.
          complaint = SEQOF_BAD_LENGTH;
          break;
        }
        break; } //acceptable

      default: // 25.2.1
        complaint = SEQOF_NOT_STRING;
        break;
      } // switch
      break; }

    default: // 25.2.1
      complaint = FIRST_NOT_SEQOF;
      break;
    } // switch(type of first component)

    for (size_t c = 1; c < num_cf; ++c) { // check the other components
      cf = last->get_comp_byIndex(c);
      Type *cft = cf->get_type()->get_type_refd_last();
      if (cft->xerattrib && cft->xerattrib->untagged_ && (cft->is_charenc() == Yes)){
        complaint = UNTAGGED_OTHER;
        break;
      }
    }
    break; } // case T_SEQ*

  default:
    complaint = NOT_SEQUENCE;
    break;
  } // switch typetype

  // TODO 25.2.4, 25.2.5
  if (complaint == ALL_GOOD) embed_values_possible = true;
  else if (xerattrib->embedValues_) {
    switch (complaint) {
    case ALL_GOOD: // Not possible; present in the switch so GCC checks
      // that all enum values are handled (make sure there's no default).
      break;
    case NOT_SEQUENCE:
    case EMPTY_SEQUENCE:
    case FIRST_NOT_SEQOF:
    case SEQOF_NOT_STRING:
Elemer Lelik's avatar
Elemer Lelik committed
1741
    case HAVE_DEFAULT:
Elemer Lelik's avatar
Elemer Lelik committed
1742
1743
      error("A type with EMBED-VALUES must be a sequence type. "
        "The first component of the sequence shall be SEQUENCE OF UTF8String "
Elemer Lelik's avatar
Elemer Lelik committed
1744
        "and shall not be marked DEFAULT");
Elemer Lelik's avatar
Elemer Lelik committed
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
      break;
    case SEQOF_BAD_LENGTH:
      cf0t->error("Wrong length of SEQUENCE-OF for EMBED-VALUES, should be %lu",
        (unsigned long)expected_length);
      break;
    case UNTAGGED_EMBEDVAL:
      error("Neither the SEQUENCE-OF supporting EMBED-VALUES,"
        "nor its component shall have UNTAGGED."); // 25.2.2
      break;
    case UNTAGGED_OTHER:
      cf->error("There shall be no UNTAGGED on any character-encodable "
        "component of a type with DEFAULT-FOR-EMPTY"); // 25.2.3
      break;
1758
1759
1760
    case ATTRIBUTE_EMBEDVAL:
      error("The SEQUENCE-OF supporting EMBED-VALUES must not have ATTRIBUTE.");
      break;
Elemer Lelik's avatar
Elemer Lelik committed
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
    } // switch(complaint)
  } // if complaint and embedValues
}
/** Wraps a C string but compares by contents, not by pointer */
class stringval {
  const char * str;
public:
  explicit stringval(const char *s = 0) : str(s) {}
  // no destructor
  bool operator<(const stringval& right) const {
    if (       str > (const char*)NamespaceSpecification::ALL
      && right.str > (const char*)NamespaceSpecification::ALL)
    {
      return strcmp(str, right.str) < 0;
    }
    else return str < right.str;
  }
  bool operator==(const stringval& right) const {
    if (       str > (const char*)NamespaceSpecification::ALL
      && right.str > (const char*)NamespaceSpecification::ALL)
    {
      return strcmp(str, right.str) == 0;
    }
    else return str == right.str;
  }
  //bool operator!() const { return str==0; }
  const char *c_str() const { return str; }
};


void Type::chk_xer_text()
{
  if (xerattrib->num_text_ == 0
    ||xerattrib->text_ == 0 ) FATAL_ERROR("Type::chk_xer_text()");
  Type * const last = get_type_refd_last();
  static const stringval empty; // NULL pointer

  // Check the type and quit early if wrong
  switch (last->typetype) {
  case T_BOOL:
    break;
  case T_ENUM_A: // not yet
    error("No XER yet for ASN.1 enumerations");
    return;
  case T_ENUM_T:
    break;
  case T_BSTR_A: // ASN.1 bit string with named bits, not yet
    error("No XER yet for ASN.1 bit strings");
    return;
  case T_INT_A: // ASN.1 integer with named numbers, not yet
    error("No XER yet for ASN.1 named numbers");
    return;
  default:
    error("TEXT not allowed for type %s", get_typename().c_str());
    return;
  }

  // Build a map to eliminate duplicates (new assignment to the same
  // enum item/field overwrites previous text).
  // Keys are the identifiers, values are the texts.
  typedef map<stringval, char> text_map_t;
  text_map_t text_map;

  for (size_t t = 0; t < xerattrib->num_text_; ++t) {
    NamespaceSpecification & txt = xerattrib->text_[t];
    switch ((unsigned long)txt.target) {
    case 0: { // just "TEXT".
      // target=0 and new_text!=0 would have to come from "TEXT AS ..."
      // but that's not allowed by syntax, hence FATAL_ERROR.
      if (txt.new_text) FATAL_ERROR("Type::chk_xer_text");
      if (!text_map.has_key(empty)) {
        text_map.add(empty, txt.new_text);
      }
      if (last->typetype != T_BOOL) {
        error("Lone 'TEXT' only allowed for boolean"); // only in TTCN-3 !
      }
      break; }

    case NamespaceSpecification::ALL: {// TEXT ALL AS ...
      switch (txt.keyword) {
      case NamespaceSpecification::NO_MANGLING:
        // Not possible due to syntax; there is no TTCN source from which
        // the bison parser would create such a NamespaceSpecification.
        FATAL_ERROR("Type::chk_xer_text");
        break;
      case NamespaceSpecification::CAPITALIZED:
      case NamespaceSpecification::UNCAPITALIZED:
      case NamespaceSpecification::LOWERCASED:
      case NamespaceSpecification::UPPERCASED:
        break; // OK

      default: // TEXT ALL AS "some string" is not allowed
        error("text all as 'string' is not allowed");
        continue;
      } // switch(keyword)

      // Expand the "all"
      switch (last->typetype) {
      case T_BOOL:
        text_map.add(stringval(mcopystr("true")), txt.new_text);
        text_map.add(stringval(mcopystr("false")), txt.new_text);
        break;

      //case T_ENUM_A:
      case T_ENUM_T: {
        size_t n_eis = last->u.enums.eis->get_nof_eis();
        for (size_t i = 0; i < n_eis; ++i) {
          EnumItem *ei = last->u.enums.eis->get_ei_byIndex(i);
          const stringval enum_name(mcopystr(ei->get_name().get_ttcnname().c_str()));
          if (text_map.has_key(enum_name)) {
            // Duplicate enum name, flagged elsewhere as error.
            // Don't bother with: text_map[enum_name] = txt.new_text;
            Free(const_cast<char*>(enum_name.c_str()));
          }
          else text_map.add(enum_name, txt.new_text);
        }
        break; }

      default:
        FATAL_ERROR("Type::chk_xer_text");
        break;
      } // switch (typetype)
      break;
    }

    default: {// a string: TEXT 'member' AS ...
      if (txt.keyword == NamespaceSpecification::NO_MANGLING) {
        // Attribute syntax does not allow this combination
        FATAL_ERROR("Type::chk_xer_text");
      }
      // HR39956: empty string is disregarded
      if (txt.keyword>NamespaceSpecification::LOWERCASED && !strcmp(txt.new_text,""))
      {
        txt.new_text = (char*)Realloc(txt.new_text, sizeof(" "));
        strcpy(txt.new_text," ");
      }
      stringval ttarget(txt.target);
      if (text_map.has_key(ttarget)) {
        // Override the earlier TEXT instruction
        free_name_or_kw(text_map[ttarget]);
        text_map[ttarget] = txt.new_text;
        free_name_or_kw(txt.target);
      }
      else text_map.add(ttarget, txt.new_text);
      break; }
    } // switch(target)
  } // next text

  xerattrib->text_ = (NamespaceSpecification*)Realloc(xerattrib->text_,
    text_map.size()