Debian Codegraph @

gcc/cobol/parse_ante.h

raw
1 /*
2 * Copyright (c) 2021-2025 Symas Corporation
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of the Symas Corporation nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include <cassert>
32 #include <cstring>
33 #include <cstdio>
34
35 #include <algorithm>
36 #include <list>
37 #include <map>
38 #include <numeric>
39 #include <stack>
40 #include <string>
41
42 #define MAXLENGTH_FORMATTED_DATE 10
43 #define MAXLENGTH_FORMATTED_TIME 19
44 #define MAXLENGTH_CALENDAR_DATE 21
45 #define MAXLENGTH_FORMATTED_DATETIME 30
46
47 #pragma GCC diagnostic push
48 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
49
50 extern YYLTYPE yylloc;
51
52 extern int yylineno, yyleng, yychar;
53 extern char *yytext;
54
55 bool need_nume_set( bool tf = true );
56
57 bool max_errors_exceeded( int nerr );
58
59 extern cbl_label_t *next_sentence;
60 void next_sentence_label(cbl_label_t* label) {
61 parser_label_label(label);
62 next_sentence = NULL;
63 // release codegen label structure, so it can be reused.
64 assert(label->structs.goto_trees || mode_syntax_only());
65 free(label->structs.goto_trees);
66 label->structs.goto_trees = NULL;
67 }
68
69 void apply_declaratives();
70 const char * keyword_str( int token );
71 void labels_dump();
72
73 unsigned int cbl_dialects;
74 size_t cbl_gcobol_features;
75
76 static enum cbl_division_t current_division;
77 static size_t nparse_error = 0;
78
79 size_t parse_error_inc() {
80 mode_syntax_only(current_division);
81 return ++nparse_error;
82 }
83 size_t parse_error_count() { return nparse_error; }
84 void input_file_status_notify();
85
86 #define YYLLOC_DEFAULT(Current, Rhs, N) \
87 do { \
88 if (N) \
89 { \
90 (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
91 (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
92 (Current).last_line = YYRHSLOC (Rhs, N).last_line; \
93 (Current).last_column = YYRHSLOC (Rhs, N).last_column; \
94 location_dump("parse.c", N, \
95 "rhs N ", YYRHSLOC (Rhs, N)); \
96 } \
97 else \
98 { \
99 (Current).first_line = \
100 (Current).last_line = YYRHSLOC (Rhs, 0).last_line; \
101 (Current).first_column = \
102 (Current).last_column = YYRHSLOC (Rhs, 0).last_column; \
103 } \
104 location_dump("parse.c", __LINE__, "current", (Current)); \
105 input_file_status_notify(); \
106 location_set(Current); \
107 } while (0)
108
109 int yylex(void);
110 extern int yydebug;
111
112 #include <cstdarg>
113
114 const char *
115 consistent_encoding_check( const YYLTYPE& loc, const char input[] ) {
116 cbl_field_t faux = {};
117 faux.type = FldAlphanumeric;
118 faux.data.capacity = capacity_cast(strlen(input));
119 faux.data.initial = input;
120
121 auto s = faux.internalize();
122 if( !s ) {
123 error_msg(loc, "inconsistent string literal encoding for '%s'", input);
124 } else {
125 if( s != input ) return s;
126 }
127 return NULL;
128 }
129
130 const char * original_picture();
131 char * original_number( char input[] = NULL );
132
133 static const relop_t invalid_relop = static_cast<relop_t>(-1);
134
135 static cbl_refer_t null_reference;
136 static cbl_field_t *literally_one, *literally_zero;
137
138 cbl_field_t *
139 literal_of( size_t value ) {
140 switch(value) {
141 case 0: return literally_zero;
142 case 1: return literally_one;
143 }
144 cbl_err("logic error: %s: " HOST_SIZE_T_PRINT_UNSIGNED " not supported",
145 __func__, (fmt_size_t)value);
146 return NULL;
147 }
148
149 enum data_section_t { // values reflect mandatory order
150 not_data_datasect_e,
151 file_datasect_e,
152 working_storage_datasect_e,
153 local_storage_datasect_e,
154 linkage_datasect_e,
155 } current_data_section;
156
157 static bool current_data_section_set( const YYLTYPE& loc, enum data_section_t );
158
159 enum data_clause_t {
160 picture_clause_e = 0x0001,
161 usage_clause_e = 0x0002,
162 value_clause_e = 0x0004,
163 occurs_clause_e = 0x0008,
164 global_clause_e = 0x0010,
165 external_clause_e = 0x0020,
166 justified_clause_e = 0x0040,
167 redefines_clause_e = 0x0080,
168 blank_zero_clause_e = 0x0100,
169 synched_clause_e = 0x0200,
170 sign_clause_e = 0x0400,
171 based_clause_e = 0x0800,
172 same_clause_e = 0x1000,
173 volatile_clause_e = 0x2000,
174 type_clause_e = 0x4000,
175 typedef_clause_e = 0x8000,
176 };
177
178 static inline bool
179 has_clause( int data_clauses, data_clause_t clause ) {
180 return clause == (data_clauses & clause);
181 }
182
183
184 static bool
185 is_cobol_charset( const char name[] ) {
186 auto eoname = name + strlen(name);
187 auto ok = std::all_of( name, eoname,
188 []( char ch ) {
189 switch(ch) {
190 case '-':
191 case '_':
192 return true;
193 case '$': // maybe one day (IBM allows)
194 return false;
195 break;
196 }
197 return 0 != ISALNUM(ch);
198 } );
199 return ok;
200 }
201
202 bool
203 in_procedure_division(void) {
204 return current_division == procedure_div_e;
205 }
206
207 static inline bool
208 in_file_section(void) { return current_data_section == file_datasect_e; }
209
210 static cbl_refer_t *
211 intrinsic_inconsistent_parameter( size_t n, cbl_refer_t *args );
212
213 static int
214 intrinsic_token_of( const char name[] );
215
216 static inline bool
217 namcpy(const YYLTYPE& loc, cbl_name_t tgt, const char *src ) {
218 // snprintf(3): writes at most size bytes (including the terminating NUL byte)
219 auto len = snprintf(tgt, sizeof(cbl_name_t), "%s", src);
220 if( ! (0 < len && len < int(sizeof(cbl_name_t))) ) {
221 error_msg(loc, "name truncated to '%s' (max %zu characters)",
222 tgt, sizeof(cbl_name_t)-1);
223 return false;
224 }
225 return true;
226 }
227
228 cbl_field_t *
229 new_alphanumeric( size_t capacity = MAXIMUM_ALPHA_LENGTH,
230 const cbl_name_t name = nullptr );
231
232 static inline cbl_field_t *
233 new_alphanumeric( const cbl_name_t name ) {
234 return new_alphanumeric(MAXIMUM_ALPHA_LENGTH, name);
235 }
236
237 static inline cbl_refer_t *
238 new_reference( enum cbl_field_type_t type, const char *initial ) {
239 return new cbl_refer_t( new_temporary(type, initial) );
240 }
241 static inline cbl_refer_t *
242 new_reference( cbl_field_t *field ) {
243 return new cbl_refer_t(field);
244 }
245 static inline cbl_refer_t *
246 new_reference_like( const cbl_field_t& skel ) {
247 return new cbl_refer_t( new_temporary_like(skel) );
248 }
249
250 static void reject_refmod( YYLTYPE loc, const cbl_refer_t& );
251 static bool require_pointer( YYLTYPE loc, const cbl_refer_t& );
252 static bool require_integer( YYLTYPE loc, const cbl_refer_t& );
253
254 struct cbl_field_t * constant_of( size_t isym );
255
256 static const struct cbl_occurs_t nonarray = cbl_occurs_t();
257
258 using std::list;
259
260 static inline bool isquote( char ch ) {
261 return ch == '\'' || ch == '"';
262 }
263
264 static inline char * dequote( char input[] ) {
265 char *pend = input + strlen(input) - 1;
266 assert(isquote(*input));
267 assert(isquote(*pend));
268 assert(*input == *pend);
269 *input = *pend = '\0';
270 return ++input;
271 }
272
273 static const char *
274 name_of( cbl_field_t *field ) {
275 assert(field);
276 return field->name[0] == '_' && field->data.initial?
277 field->data.initial : field->name;
278 }
279
280 static const char *
281 nice_name_of( cbl_field_t *field ) {
282 auto name = name_of(field);
283 return name[0] == '_'? "" : name;
284 }
285
286 struct evaluate_elem_t {
287 size_t nother;
288 struct cbl_label_t label;
289 struct cbl_field_t *result;
290 struct case_t {
291 private:
292 relop_t oper;
293 public:
294 cbl_field_t *subject, *object, *cond;
295 explicit case_t( cbl_field_t * subject )
296 : oper(eq_op)
297 , subject(subject)
298 , object(NULL)
299 , cond( keep_temporary(FldConditional) )
300 {}
301
302 cbl_field_t * object_set( cbl_field_t *obj, relop_t op ) {
303 oper = op;
304 return object = obj;
305 }
306
307 inline relop_t op() const { return oper; }
308
309 void dump() const {
310 dbgmsg( " cond is '%s'\n\t"
311 "subject is '%s'\n\t"
312 " oper is %s \n\t"
313 " object is '%s'",
314 cond? xstrdup(field_str(cond)) : "none",
315 subject? xstrdup(field_str(subject)) : "none",
316 relop_str(oper),
317 object? xstrdup(field_str(object)) : "none");
318 }
319 static void Dump( const case_t& c ) { c.dump(); }
320 };
321 list<case_t> cases;
322 typedef list<case_t>::iterator case_iter;
323 case_iter pcase;
324
325 void dump() const {
326 dbgmsg( "nother=" HOST_SIZE_T_PRINT_UNSIGNED " label '%s', "
327 HOST_SIZE_T_PRINT_UNSIGNED " cases",
328 (fmt_size_t)nother, label.name, (fmt_size_t)cases.size() );
329 std::for_each( cases.begin(), cases.end(), case_t::Dump );
330 }
331
332 explicit evaluate_elem_t( const char skel[] )
333 : nother(0)
334 , label{LblEvaluate}
335 , result( keep_temporary(FldConditional) )
336 , pcase( cases.end() )
337 {
338 label.line = yylineno;
339 if( -1 == snprintf(label.name, sizeof(label.name),
340 "%.*s_%d", (int)sizeof(label.name)-6, skel, yylineno) ) {
341 yyerror("could not create unique label %<%s_%d%> because it is too long",
342 skel, yylineno);
343 }
344 }
345
346 size_t ncolumn() const { return cases.size(); }
347 size_t nready() const {
348 size_t n=0;
349 for( const auto& c : cases ) {
350 if( c.object == NULL ) break;
351 n++;
352 }
353 return n;
354 }
355 };
356
357 /*
358 * The file_X_args variables hold the arguments to parser_file_X. The
359 * X_body nonterminal collects the arguments, but we defer calling
360 * parser_file_X until either:
361 * 1. end of statement, implying sequentiality, or
362 * 2. ON ERROR, implying random access
363 * In the 2nd case, the call to parser_file_X is made at the top of
364 * the io_error nonterminal, before any statements are parsed. The
365 * effect is to delay the call only until we've parsed ON ERROR.
366 * Because there are no intervening statements, there's no need for a
367 * stack of arguments. One global does the trick.
368 */
369 static class file_delete_args_t {
370 cbl_file_t *file;
371 public:
372 file_delete_args_t() : file(nullptr) {}
373 void init( cbl_file_t *file ) {
374 this->file = file;
375 }
376 bool ready() const { return file != nullptr; }
377 void call_parser_file_delete( bool sequentially ) {
378 parser_file_delete(file, sequentially);
379 file = nullptr;
380 }
381 } file_delete_args;
382
383 cbl_round_t current_rounded_mode();
384
385 static struct file_read_args_t {
386 cbl_file_t *file;
387 cbl_refer_t record, *read_into;
388 int where;
389 enum { where_unknown = 0 };
390
391 file_read_args_t() : file(NULL), read_into(NULL), where(where_unknown) {}
392
393 void
394 init( struct cbl_file_t *file,
395 const cbl_refer_t& record,
396 cbl_refer_t *read_into,
397 int where ) {
398 this->file = file;
399 this->record = record;
400 this->read_into = read_into;
401 this->where = where;
402 }
403
404 bool ready() const { return file != NULL; }
405 void default_march( bool sequential ) {
406 if( where == where_unknown ) {
407 where = sequential? -1 : 1;
408 }
409 }
410
411 void
412 call_parser_file_read( int w = where_unknown) {
413 if( w != where_unknown ) where = w;
414 if( where == where_unknown) {
415 switch( file->access ) {
416 case file_inaccessible_e:
417 case file_access_seq_e:
418 where = -1;
419 break;
420 case file_access_rnd_e:
421 where = 1;
422 break;
423 case file_access_dyn_e:
424 where = 1;
425 break;
426 }
427 }
428 parser_file_read(file, record, where);
429 if( read_into ) {
430 parser_move( *read_into, record, current_rounded_mode() );
431 }
432 *this = file_read_args_t();
433 }
434 } file_read_args;
435
436 static class file_return_args_t {
437 cbl_file_t *file;
438 public:
439 file_return_args_t() : file(NULL) {}
440 void init( cbl_file_t *file ) {
441 this->file = file;
442 }
443 bool ready() const { return file != NULL; }
444 void call_parser_return_start(const cbl_refer_t& into = cbl_refer_t() ) {
445 parser_return_start(file, into);
446 file = NULL;
447 }
448 } file_return_args;
449
450 static class file_rewrite_args_t {
451 cbl_file_t *file;
452 cbl_field_t *record;
453 public:
454 file_rewrite_args_t() : file(nullptr), record(nullptr) {}
455 void init( cbl_file_t *file, cbl_field_t *record ) {
456 this->file = file;
457 this->record = record;
458 }
459 bool ready() const { return file != nullptr; }
460 void call_parser_file_rewrite( bool sequentially ) {
461 sequentially = sequentially || file->access == file_access_seq_e;
462 if( file->access == file_access_rnd_e ) sequentially = false;
463 parser_file_rewrite(file, record, sequentially);
464 file = nullptr;
465 record = nullptr;
466 }
467 } file_rewrite_args;
468
469 static class file_start_args_t {
470 cbl_file_t *file;
471 public:
472 file_start_args_t() : file(NULL) {}
473 cbl_file_t * init( YYLTYPE loc, cbl_file_t *file ) {
474 this->file = file;
475 if( is_sequential(file) ) {
476 error_msg(loc, "START invalid with sequential file %s", file->name);
477 }
478 return file;
479 }
480 bool ready() const { return file != NULL; }
481 void call_parser_file_start() {
482 // not needed: parser_file_start(file, sequentially);
483 file = NULL;
484 }
485 } file_start_args;
486
487 static class file_write_args_t {
488 cbl_file_t *file;
489 cbl_field_t *data_source;
490 bool after;
491 cbl_refer_t *advance;
492 public:
493 file_write_args_t()
494 : file(nullptr)
495 , data_source(nullptr)
496 , after(false)
497 , advance(nullptr)
498 {}
499 cbl_file_t * init( cbl_file_t *file,
500 cbl_field_t *data_source,
501 bool after,
502 const cbl_refer_t *advance ) {
503 this->file = file;
504 this->data_source = data_source;
505 this->after = after;
506 this->advance = new cbl_refer_t(*advance);
507 return this->file;
508 }
509 bool ready() const { return file != nullptr; }
510 void call_parser_file_write( bool sequentially ) {
511 sequentially = sequentially || file->access == file_access_seq_e;
512 parser_file_write(file, data_source, after, *advance, sequentially);
513 *this = file_write_args_t();
514 }
515 } file_write_args;
516
517 /*
518 * Fields
519 */
520 struct group_attr_t {
521 cbl_field_type_t default_usage; // for COMP-5 etc.
522 int encoding; // for ASCII, National, etc.
523 cbl_field_t *field;
524
525 group_attr_t( cbl_field_t *field,
526 cbl_field_type_t default_usage,
527 int encoding )
528 : default_usage(default_usage)
529 , encoding(encoding)
530 , field(field)
531 {}
532 };
533
534 struct refer_list_t;
535
536 struct arith_t {
537 cbl_arith_format_t format;
538 list<cbl_num_result_t> tgts;
539 list<cbl_refer_t> A, B;
540 cbl_refer_t remainder;
541 cbl_label_t *on_error, *not_error;
542
543 explicit arith_t( cbl_arith_format_t format )
544 : format(format), on_error(NULL), not_error(NULL)
545 {}
546 arith_t( cbl_arith_format_t format, refer_list_t * refers );
547
548 bool corresponding() const { return format == corresponding_e; }
549
550 void another_pair( size_t src, size_t tgt ) {
551 assert(src > 0 && tgt > 0);
552
553 cbl_refer_t a(A.front());
554 a.field = cbl_field_of(symbol_at(src));
555 A.push_back( a );
556
557 cbl_num_result_t res = tgts.front();
558 res.refer.field = cbl_field_of(symbol_at(tgt));
559 tgts.push_back( res );
560
561 dbgmsg("%s:%d: SRC: %3" GCC_PRISZ "u %s",
562 __func__, __LINE__, (fmt_size_t)src, a.str());
563 dbgmsg("%s:%d: to %3" GCC_PRISZ "u %s",
564 __func__, __LINE__, (fmt_size_t)tgt, res.refer.str());
565 }
566 void operator()( const corresponding_fields_t::const_reference elem ) {
567 another_pair( elem.first, elem.second );
568 }
569
570 const char * format_str() const {
571 switch(format) {
572 case not_expected_e: return "not_expected_e";
573 case no_giving_e: return "no_giving_e";
574 case giving_e: return "giving_e";
575 case corresponding_e: return "corresponding_e";
576 }
577 return "???";
578 }
579 };
580
581 static cbl_refer_t * ast_op( cbl_refer_t *lhs, char op, cbl_refer_t *rhs );
582
583 static void ast_add( arith_t *arith );
584 static bool ast_subtract( arith_t *arith );
585 static bool ast_multiply( arith_t *arith );
586 static bool ast_divide( arith_t *arith );
587
588 static cbl_field_type_t intrinsic_return_type( int token );
589
590 template <typename T>
591 static T* use_any( list<T>& src, T *tgt) {
592 if( src.empty() ) return NULL;
593
594 std::copy(src.begin(), src.end(), tgt);
595 src.clear();
596
597 return tgt;
598 }
599 template <typename T>
600 static T* use_any( list<T>& src, std::vector<T>& tgt) {
601 if( src.empty() ) return NULL;
602
603 std::copy(src.begin(), src.end(), tgt.begin());
604 src.clear();
605
606 return tgt.data();
607 }
608
609 class evaluate_t;
610 /*
611 * Evaluate
612 */
613 class eval_subject_t {
614 friend evaluate_t;
615 struct { cbl_label_t *done, *yeah, *when; } labels;
616 cbl_field_t *result;
617 relop_t abbr_relop;
618 typedef std::list<cbl_refer_t> column_list_t;
619 column_list_t columns;
620 column_list_t::iterator pcol;
621
622 static cbl_label_t * label( const char skel[] );
623
624 void new_object_labels();
625 public:
626 eval_subject_t();
627 void append( const cbl_refer_t& field ) {
628 columns.push_back(field);
629 pcol = columns.begin();
630 }
631 cbl_label_t *yeah() { return labels.yeah; }
632 cbl_label_t *when() { return labels.when; }
633 cbl_label_t *done() { return labels.done; }
634
635 cbl_field_t *subject() const {
636 if( pcol == columns.end() ) return nullptr;
637 return pcol->field;
638 }
639 size_t subject_count() const { return columns.size(); }
640 size_t object_count() { return std::distance(columns.begin(), pcol); }
641
642 void object_relop( relop_t op ) { abbr_relop = op; }
643 relop_t object_relop() const { return abbr_relop; }
644
645 void rewind() { pcol = columns.begin(); }
646
647 bool compatible( const cbl_field_t *object ) const;
648
649 // compare sets result
650 cbl_field_t * compare( int token );
651 cbl_field_t * compare( relop_t op,
652 const cbl_refer_t& object, bool deciding = false);
653 cbl_field_t * compare( const cbl_refer_t& object,
654 const cbl_refer_t& object2 = nullptr);
655
656 void write_when_label() {
657 parser_label_label(labels.when);
658 labels.when = label("when");
659 }
660 void write_yeah_label() {
661 parser_label_label(labels.yeah);
662 labels.yeah = label("yeah");
663 }
664
665 // decide() calls codegen with the result and increments the subject column.
666 // On FALSE, skip past <statements> and fall into next WHEN.
667 bool decided( cbl_field_t *result ) {
668 this->result = result;
669 parser_if( result );
670 parser_else();
671 parser_label_goto( labels.when );
672 parser_fi();
673 pcol++;
674 return true;
675 }
676 bool decide( int token ) {
677 if( pcol == columns.end() ) return false;
678 if( compare( token ) ) {
679 parser_if( result );
680 parser_else();
681 parser_label_goto( labels.when );
682 parser_fi();
683 }
684 pcol++;
685 return true;
686 }
687 bool decide( const cbl_refer_t& object, bool invert ) {
688 if( pcol == columns.end() ) return false;
689 if( compare( object ) ) {
690 if( invert ) {
691 parser_logop( result, NULL, not_op, result );
692 }
693 parser_if( result );
694 parser_else();
695 parser_label_goto( labels.when );
696 parser_fi();
697 }
698 pcol++;
699 return true;
700 }
701 bool decide( relop_t op, const cbl_refer_t& object, bool invert ) {
702 if( pcol == columns.end() ) return false;
703 dbgmsg("%s() if not %s goto %s", __func__, result->name, when()->name);
704
705 if( compare(op, object, true) ) {
706 if( invert ) {
707 parser_logop( result, NULL, not_op, result );
708 }
709 parser_if( result );
710 parser_else();
711 parser_label_goto( labels.when );
712 parser_fi();
713 }
714 pcol++;
715 return true;
716 }
717 bool decide( const cbl_refer_t& object, const cbl_refer_t& object2, bool invert ) {
718 if( pcol == columns.end() ) return false;
719 if( compare(object, object2) ) {
720 if( invert ) {
721 parser_logop( result, NULL, not_op, result );
722 }
723 parser_if( result );
724 parser_else();
725 parser_label_goto( labels.when );
726 parser_fi();
727 }
728 pcol++;
729 return true;
730 }
731 };
732
733 class evaluate_t : private std::stack<eval_subject_t> {
734 public:
735 size_t depth() const { return size(); }
736
737 void alloc() {
738 push(eval_subject_t());
739 }
740 void free() { assert(!empty()); pop(); }
741
742 eval_subject_t& current() {
743 assert(!empty());
744 if( yydebug ) {
745 auto& ev( top() );
746 dbgmsg("eval_subject: res: %s, When %s, Yeah %s, Done %s",
747 ev.result->name,
748 ev.when()->name, ev.yeah()->name, ev.done()->name);
749 }
750 return top();
751 }
752
753 } eval_stack;
754
755
756
757 static void dump_inspect( const cbl_inspect_t& i );
758 void dump_inspect_match( const cbl_inspect_match_t& M );
759
760 struct perform_t {
761 struct cbl_perform_tgt_t tgt;
762 bool before;
763 list<cbl_perform_vary_t> varys;
764 list<cbl_declarative_t> dcls;
765
766 struct ec_labels_t {
767 cbl_label_t
768 *init, // Format 3, code that installs handlers
769 *fini, // Format 3, code that reverts handlers
770 *top, // Format 3, above imperative-statement-1
771 *from, // Format 3, imperative-statement-1
772 *finally,
773 *other, *common;
774 ec_labels_t()
775 : init(NULL), fini(NULL),
776 top(NULL), from(NULL), finally(NULL),
777 other(NULL), common(NULL)
778 {}
779 void generate() {
780 init = new_label( LblLoop, "init" );
781 fini = new_label( LblLoop, "fini" );
782 top = new_label( LblLoop, "top" );
783 from = new_label( LblLoop, "from" );
784 other = new_label( LblLoop, "other" );
785 common = new_label( LblLoop, "common" );
786 finally = new_label( LblLoop, "finally" );
787 }
788 static cbl_label_t *
789 new_label( cbl_label_type_t type, const cbl_name_t role );
790 } ec_labels;
791
792 struct {
793 cbl_label_t *start, *end;
794 cbl_field_t *unsatisfied, *size;
795 cbl_refer_t table;
796 } search;
797
798 explicit perform_t( cbl_label_t *from, cbl_label_t *to = NULL )
799 : tgt( from, to ), before(true)
800 , search()
801 {}
802 ~perform_t() { varys.clear(); }
803 cbl_field_t * until() {
804 assert(!varys.empty());
805 cbl_field_t *f = varys.front().until;
806 assert(f->type == FldConditional);
807 return f;
808 }
809 };
810
811 static list<perform_t> performs;
812
813 static inline perform_t *
814 perform_alloc() {
815 performs.push_back(perform_t(NULL));
816 return &performs.back();
817 }
818
819 static inline void
820 perform_free(void) {
821 assert(performs.size() > 0);
822 performs.pop_back();
823 }
824
825 static inline perform_t *
826 perform_current(void) {
827 assert(performs.size() > 0);
828 return &performs.back();
829 }
830
831 static inline perform_t *
832 perform_tgt_set( cbl_label_t *from, cbl_label_t *to = NULL ) {
833 struct perform_t *perf = perform_current();
834 perf->tgt = cbl_perform_tgt_t(from, to);
835 return perf;
836 }
837
838 #define PERFORM_EXCEPT 1
839 static void
840 perform_ec_setup() {
841 struct perform_t *perf = perform_current();
842 perf->ec_labels.generate();
843 perf->tgt.from( perf->ec_labels.from );
844
845 #if PERFORM_EXCEPT
846 parser_label_goto(perf->ec_labels.init);
847 parser_label_label(perf->ec_labels.top);
848 #endif
849 parser_perform_start(&perf->tgt);
850 }
851
852 static void
853 perform_ec_cleanup() {
854 struct perform_t *perf = perform_current();
855 #if PERFORM_EXCEPT
856 parser_label_goto(perf->ec_labels.fini);
857 parser_label_label(perf->ec_labels.init);
858 /* ... empty init block ... */
859 parser_label_goto(perf->ec_labels.top);
860 parser_label_label(perf->ec_labels.fini);
861 #endif
862 }
863
864 static list<cbl_label_t*> searches;
865
866 static inline cbl_label_t *
867 search_alloc( cbl_label_t *name ) {
868 searches.push_back(name);
869 return searches.back();
870 }
871
872 static inline void
873 search_free(void) {
874 assert(searches.size() > 0);
875 searches.pop_back();
876 }
877
878 static inline cbl_label_t *
879 search_current(void) {
880 assert(searches.size() > 0);
881 return searches.back();
882 }
883
884 static list<cbl_num_result_t> rhs;
885 typedef list<cbl_num_result_t>::iterator rhs_iter;
886
887 struct tgt_list_t {
888 list<cbl_num_result_t> targets;
889 };
890
891 static struct cbl_label_t *
892 label_add( const YYLTYPE& loc, enum cbl_label_type_t type, const char name[] );
893 static struct cbl_label_t *
894 label_add( enum cbl_label_type_t type, const char name[], int line );
895
896 static struct cbl_label_t *
897 paragraph_reference( const char name[], size_t section );
898
899 static inline void
900 list_add( list<cbl_num_result_t>& list, const cbl_refer_t& refer, int round ) {
901 struct cbl_num_result_t arg = { static_cast<cbl_round_t>(round), refer };
902 list.push_back(arg);
903 }
904
905 static list<cbl_domain_t> domains;
906 typedef list<cbl_domain_t>::iterator domain_iter;
907
908 /*
909 * The name queue is a queue of lists of data-item names recognized by the
910 * lexer, but not returned to the parser. These lists are "teed up" by the
911 * lexer until no more qualifiers are found. At that point, the last name is
912 * returned as a NAME or NAME88 token. NAME88 is returned only if a correctly,
913 * uniquely specified Level 88 data item is found in the symbol table (because
914 * else we can't know).
915 *
916 * When the parser gets a NAME or NAME88 token, it retrieves the pending list
917 * of qualifiers, if any, from the name queue. It adds the returned name to
918 * the list and calls symbol_find() to search the name map. For correctly
919 * specified names, the lexer has already done that work, which is now
920 * unfortunately repeated. For incorrect names, the parser emits a most useful
921 * diagnostic.
922 */
923 static name_queue_t name_queue;
924
925 void
926 tee_up_empty() {
927 name_queue.allocate();
928 }
929 void
930 tee_up_name( const YYLTYPE& loc, const char name[] ) {
931 name_queue.push(loc, name);
932 }
933 cbl_namelist_t
934 teed_up_names() {
935 return name_queue_t::namelist_of( name_queue.peek() );
936 }
937
938 #define cdf_tokens cdf_current_tokens()
939
940 int
941 redefined_token( const cbl_name_t name ) {
942 return cdf_tokens.redefined_as(name);
943 }
944
945 struct file_list_t {
946 list<cbl_file_t*> files;
947 file_list_t() {}
948 explicit file_list_t( cbl_file_t* file ) {
949 files.push_back(file);
950 }
951 file_list_t( file_list_t& that ) : files(that.files.size()) {
952 std::copy( that.files.begin(), that.files.end(), files.begin() );
953 }
954
955 static size_t symbol_index( cbl_file_t* file ) {
956 return ::symbol_index( symbol_elem_of(file) );
957 }
958 };
959
960 struct field_list_t {
961 list<cbl_field_t*> fields;
962 field_list_t() {}
963 explicit field_list_t( cbl_field_t *field ) {
964 fields.push_back(field);
965 }
966 std::vector<const cbl_field_t*>
967 as_vector() const {
968 std::vector<const cbl_field_t*> output( fields.begin(), fields.end() );
969 return output;
970 }
971 };
972
973 cbl_field_t **
974 use_list( field_list_t *src, cbl_field_t *tgt[] ) {
975 assert(src);
976 std::copy(src->fields.begin(), src->fields.end(), tgt);
977 src->fields.clear();
978 delete src;
979
980 return tgt;
981 }
982
983 cbl_file_t **
984 use_list( list<cbl_file_t*>& src, bool clear = true ) {
985 if( src.empty() ) return NULL;
986 auto tgt = new cbl_file_t*[ src.size() ];
987 std::copy(src.begin(), src.end(), tgt);
988
989 if( clear )
990 src.clear();
991
992 return tgt;
993 }
994
995 struct refer_list_t {
996 list<cbl_refer_t> refers;
997 explicit refer_list_t( cbl_refer_t *refer ) {
998 if( refer ) {
999 refers.push_back(*refer);
1000 delete refer;
1001 }
1002 }
1003 refer_list_t * push_back( cbl_refer_t *refer ) {
1004 refers.push_back(*refer);
1005 delete refer;
1006 return this;
1007 }
1008 inline list<cbl_refer_t>& items() { return refers; }
1009 inline list<cbl_refer_t>::iterator begin() { return refers.begin(); }
1010 inline list<cbl_refer_t>::iterator end() { return refers.end(); }
1011 inline size_t size() const { return refers.size(); }
1012
1013 cbl_refer_t *
1014 use_list( cbl_refer_t tgt[] ) {
1015 std::copy(refers.begin(), refers.end(), tgt);
1016 refers.clear();
1017 return tgt;
1018 }
1019 std::vector<cbl_refer_t>
1020 vectorize() {
1021 std::vector<cbl_refer_t> tgt(refers.size());
1022 std::copy(refers.begin(), refers.end(), tgt.begin());
1023 refers.clear();
1024 return tgt;
1025 }
1026 };
1027
1028 struct refer_marked_list_t : public refer_list_t {
1029 cbl_refer_t *marker;
1030
1031 refer_marked_list_t() : refer_list_t(NULL), marker(NULL) {}
1032 refer_marked_list_t( cbl_refer_t *marker, const refer_list_t *refers )
1033 : refer_list_t(*refers), marker(marker) {}
1034 refer_marked_list_t( cbl_refer_t *marker, cbl_refer_t *input )
1035 : refer_list_t(input)
1036 , marker(marker) {}
1037
1038 refer_marked_list_t * push_back( refer_list_t *refers ) {
1039 push_back(refers);
1040 return this;
1041 }
1042 refer_marked_list_t * push_on( cbl_refer_t *marker, cbl_refer_t *input ) {
1043 refers.push_back(*input);
1044 this->marker = marker;
1045 return this;
1046 }
1047 };
1048
1049 struct refer_collection_t {
1050 list<refer_marked_list_t> lists;
1051
1052 explicit refer_collection_t( const refer_marked_list_t& marked_list )
1053 {
1054 lists.push_back( marked_list );
1055 }
1056 refer_collection_t * push_back( const refer_marked_list_t& marked_list )
1057 {
1058 lists.push_back( marked_list );
1059 return this;
1060 }
1061
1062 const cbl_refer_t* last_delimiter() const {
1063 return lists.back().marker;
1064 }
1065 cbl_refer_t* last_delimiter( cbl_refer_t* marker) {
1066 return lists.back().marker = marker;
1067 }
1068
1069 size_t total_size() const {
1070 size_t n = 0;
1071 for( auto p=lists.begin(); p != lists.end(); p++ ) {
1072 n += p->refers.size();
1073 }
1074 return n;
1075 }
1076 };
1077
1078 void ast_inspect( YYLTYPE loc, cbl_refer_t& input, bool backward,
1079 cbl_inspect_opers_t& inspects );
1080
1081 template <typename E>
1082 struct elem_list_t {
1083 list<E*> elems;
1084 explicit elem_list_t( E *elem ) {
1085 elems.push_back(elem);
1086 }
1087 void clear() {
1088 for( auto p = elems.begin(); p != elems.add(); p++ ) {
1089 delete *p;
1090 }
1091 elems.clear();
1092 }
1093 };
1094
1095 typedef elem_list_t<cbl_label_t> label_list_t;
1096
1097 template <typename L, typename E>
1098 E use_list( L *src, E tgt ) {
1099 assert(src);
1100 std::copy(src->elems.begin(), src->elems.end(), tgt);
1101 src->elems.clear();
1102 delete src;
1103
1104 return tgt;
1105 }
1106
1107 struct unstring_tgt_t {
1108 cbl_refer_t *tgt, *delimiter, *count;
1109 explicit unstring_tgt_t( cbl_refer_t *tgt,
1110 cbl_refer_t *delimiter = NULL,
1111 cbl_refer_t *count = NULL )
1112 : tgt(tgt), delimiter(delimiter), count(count)
1113 {}
1114
1115 static cbl_refer_t tgt_of( const unstring_tgt_t& that ) {
1116 return maybe_empty(that.tgt);
1117 }
1118 static cbl_refer_t delimiter_of( const unstring_tgt_t& that ) {
1119 return maybe_empty(that.delimiter);
1120 }
1121 static cbl_refer_t count_of( const unstring_tgt_t& that ) {
1122 return maybe_empty(that.count);
1123 }
1124 private:
1125 static cbl_refer_t maybe_empty( cbl_refer_t *p ) {
1126 return p? *p : cbl_refer_t();
1127 }
1128 };
1129
1130 struct unstring_tgt_list_t {
1131 list<unstring_tgt_t> unstring_tgts;
1132
1133 explicit unstring_tgt_list_t( unstring_tgt_t *unstring_tgt ) {
1134 unstring_tgts.push_back(*unstring_tgt);
1135 delete unstring_tgt;
1136 }
1137 unstring_tgt_list_t * push_back( unstring_tgt_t *unstring_tgt ) {
1138 unstring_tgts.push_back(*unstring_tgt);
1139 delete unstring_tgt;
1140 return this;
1141 }
1142
1143 size_t size() const { return unstring_tgts.size(); }
1144
1145 typedef cbl_refer_t xform_t( const unstring_tgt_t& that );
1146 void use_list( std::vector<cbl_refer_t>& output, xform_t func ) {
1147 std::transform( unstring_tgts.begin(),
1148 unstring_tgts.end(),
1149 output.begin(), func );
1150 }
1151 };
1152
1153 struct unstring_into_t : public unstring_tgt_list_t {
1154 cbl_refer_t pointer, tally;
1155 explicit unstring_into_t( unstring_tgt_list_t *tgt_list,
1156 cbl_refer_t *pointer = NULL,
1157 cbl_refer_t *tally = NULL )
1158 : unstring_tgt_list_t(*tgt_list)
1159 , pointer( pointer? *pointer : cbl_refer_t() )
1160 , tally( tally? *tally : cbl_refer_t() )
1161 {
1162 delete tgt_list;
1163 if( pointer ) delete pointer;
1164 if( tally ) delete tally;
1165 }
1166 };
1167
1168 struct ffi_args_t {
1169 list<cbl_ffi_arg_t> elems;
1170
1171 explicit ffi_args_t( cbl_ffi_arg_t *arg ) {
1172 this->push_back(arg);
1173 }
1174
1175 ffi_args_t( size_t narg, cbl_ffi_arg_t *args ) {
1176 std::copy(args, args+narg, std::back_inserter(elems));
1177 }
1178
1179 // set explicitly, or assume
1180 ffi_args_t * push_back( cbl_ffi_arg_t *arg ) {
1181 if( arg->crv == by_default_e ) {
1182 arg->crv = elems.empty()? by_reference_e : elems.back().crv;
1183 }
1184 elems.push_back(*arg);
1185 delete arg;
1186 return this;
1187 }
1188
1189 // infer reference/content/value from previous
1190 ffi_args_t * push_back( cbl_refer_t* refer,
1191 cbl_ffi_arg_attr_t attr = none_of_e ) {
1192 cbl_ffi_crv_t crv = elems.empty()? by_reference_e : elems.back().crv;
1193 cbl_ffi_arg_t arg( crv, refer, attr );
1194 elems.push_back(arg);
1195 return this;
1196 }
1197 void dump() const {
1198 int i=0;
1199 for( const auto& arg : elems ) {
1200 dbgmsg( "%8d) %-10s %-16s %s", i++,
1201 cbl_ffi_crv_str(arg.crv),
1202 3 + cbl_field_type_str(arg.refer.field->type),
1203 arg.refer.field->pretty_name() );
1204 }
1205 }
1206
1207 const char *
1208 parameter_types() const {
1209 auto output = new char[ 1 + elems.size() ];
1210 auto p = std::transform( elems.begin(), elems.end(), output,
1211 []( auto arg ) {
1212 return function_descr_t::parameter_type(*arg.field());
1213 } );
1214 assert(output < p);
1215 p[-1] = '\0';
1216 return output;
1217 }
1218 };
1219
1220 struct relop_abbr_t {
1221 relop_t relop;
1222 cbl_refer_t *rhs;
1223 };
1224
1225 typedef struct elem_list_t<relop_abbr_t> relop_abbr__list_t;
1226
1227 #pragma GCC diagnostic push
1228 #pragma GCC diagnostic ignored "-Wreorder"
1229
1230 struct sort_key_t : public field_list_t {
1231 bool ascending;
1232 sort_key_t( bool ascending, field_list_t key )
1233 : ascending(ascending), field_list_t(key)
1234 {}
1235 };
1236
1237 #pragma GCC diagnostic pop
1238
1239 struct sort_keys_t {
1240 list<sort_key_t> key_list;
1241 };
1242
1243 struct file_sort_io_t {
1244 file_list_t file_list;
1245 cbl_perform_tgt_t tgt;
1246
1247 explicit file_sort_io_t( file_list_t& files ) : file_list(files) {}
1248 explicit file_sort_io_t( cbl_perform_tgt_t& tgt ) : tgt(tgt.from(), tgt.to()) {}
1249 size_t nfile() const { return file_list.files.size(); }
1250 };
1251
1252
1253 struct merge_t {
1254 cbl_file_t *master;
1255 list<cbl_file_t*> updates;
1256 // collation missing
1257 enum output_type_t { output_unknown_e,
1258 output_proc_e,
1259 output_file_e } type;
1260 cbl_perform_tgt_t tgt;
1261 list<cbl_file_t*> outputs;
1262
1263 explicit merge_t( cbl_file_t *input ) : master(input), type(output_unknown_e) {}
1264 };
1265
1266 static list<merge_t> merges;
1267
1268 static inline merge_t&
1269 merge_alloc( cbl_file_t *file ) {
1270 merges.push_back(merge_t(file));
1271 return merges.back();
1272 }
1273
1274 static inline void
1275 merge_free(void) {
1276 assert(merges.size() > 0);
1277 merges.pop_back();
1278 }
1279
1280 static inline merge_t&
1281 merge_current(void) {
1282 assert(merges.size() > 0);
1283 return merges.back();
1284 }
1285
1286 static list<cbl_refer_t> lhs;
1287
1288 struct vargs_t {
1289 std::list<cbl_refer_t> args;
1290 vargs_t() {}
1291 explicit vargs_t( struct cbl_refer_t *p ) { args.push_back(*p); delete p; }
1292 void push_back( cbl_refer_t *p ) { args.push_back(*p); delete p; }
1293 };
1294
1295 static const char intermediate[] = ":intermediate";
1296
1297 #include <set>
1298
1299 std::set<const char *> pristine_values;
1300
1301 // key is a name after DEBUGGING/ERROR/EXCEPTION
1302 // value is the list of sections invoked
1303 std::map<std::string, std::list<std::string>>
1304 debugging_clients, error_clients, exception_clients;
1305
1306 class prog_descr_t {
1307 std::set<std::string> call_targets, subprograms;
1308 public:
1309 std::set<function_descr_t> function_repository;
1310 size_t program_index;
1311 cbl_label_t *declaratives_eval, *paragraph, *section;
1312 const char *collating_sequence;
1313 struct locale_t {
1314 cbl_name_t name; const char *os_name;
1315 locale_t() : name(""), os_name(nullptr) {}
1316 locale_t(const cbl_name_t name, const char *os_name)
1317 : name(""), os_name(os_name) {
1318 if( name ) {
1319 bool ok = namcpy(YYLTYPE(), this->name, name);
1320 gcc_assert(ok);
1321 }
1322 }
1323 } locale;
1324 cbl_options_t options;
1325
1326 explicit prog_descr_t( size_t isymbol )
1327 : program_index(isymbol)
1328 , declaratives_eval(NULL)
1329 , paragraph(NULL)
1330 , section(NULL)
1331 , collating_sequence(NULL)
1332 {}
1333
1334 std::set<std::string> external_targets() {
1335 std::set<std::string> externals;
1336 std::set_difference( call_targets.begin(), call_targets.end(),
1337 subprograms.begin(), subprograms.end(),
1338 std::inserter(externals, externals.begin()) );
1339 return externals;
1340 }
1341 };
1342
1343 static char *
1344 uniq_label_impl( const char stem[], int line ) {
1345 char *name = xasprintf("%s_%d_%d", stem, yylineno, line);
1346 return name;
1347 }
1348 #define uniq_label(S) uniq_label_impl( (S), __LINE__ )
1349
1350 /*
1351 * One of these days, paragraph and section will have to move into
1352 * prog_descr_t, because the current section and paragraph depend on the
1353 * current program, which may be nested and "pop back" into existence at END
1354 * PROGRAM.
1355 */
1356 struct error_labels_t {
1357 cbl_label_t *on_error, *not_error, *compute_error;
1358 error_labels_t() : on_error(NULL), not_error(NULL), compute_error(NULL) {}
1359 void clear() { on_error = not_error = compute_error = NULL; }
1360 error_labels_t& generate() {
1361 on_error = label_add(LblArith, uniq_label("arith"), yylineno);
1362 not_error = label_add(LblArith, uniq_label("arith"), yylineno);
1363 compute_error = label_add(LblCompute, uniq_label("compute"), yylineno);
1364 return *this;
1365 }
1366 };
1367
1368 struct cbl_typedef_less {
1369 bool operator()( const cbl_field_t *a, const cbl_field_t *b ) const {
1370 auto result = strcasecmp(a->name, b->name);
1371 if( result < 0 ) return true;
1372 if( result > 0 ) return false;
1373
1374 // Names that match are different if they're in different programs
1375 // and neither is external.
1376 auto lhs = field_index(a);
1377 auto rhs = field_index(b);
1378 if( lhs != rhs ) {
1379 if( !a->has_attr(external_e) && !b->has_attr(external_e) ) {
1380 return lhs < rhs;
1381 }
1382 }
1383 return false;
1384 }
1385 };
1386
1387 static bool
1388 is_conditional( const cbl_field_t *field ) {
1389 return FldConditional == field->type;
1390 }
1391 static bool
1392 is_conditional( const cbl_refer_t *refer ) {
1393 return is_conditional(refer->field);
1394 }
1395
1396 typedef std::set< const cbl_field_t*, cbl_typedef_less > unique_typedefs_t;
1397
1398 static cbl_label_t * implicit_paragraph();
1399 static cbl_label_t * implicit_section();
1400
1401 /*
1402 * Incomplete because not needed at this time: we do not attempt to
1403 * set used/lain for labels used by these functions:
1404 * parser_lsearch_start( cbl_label_t *name,
1405 * parser_lsearch_conditional(cbl_label_t * name)
1406 * parser_lsearch_when( cbl_label_t *name, cbl_field_t *conditional )
1407 * parser_lsearch_end( cbl_label_t *name )
1408 * parser_bsearch_start( cbl_label_t* name,
1409 * parser_bsearch_conditional( cbl_label_t* name )
1410 * parser_bsearch_when(cbl_label_t* name,
1411 * parser_bsearch_end( cbl_label_t* name )
1412 * parser_string_overflow( cbl_label_t *name )
1413 * parser_string_overflow_end( cbl_label_t *name )
1414 * parser_call_exception( cbl_label_t *name )
1415 * parser_call_exception_end( cbl_label_t *name )
1416 * parser_entry_activate( size_t iprog, const cbl_label_t *declarative )
1417 */
1418
1419 class program_stack_t : protected std::stack<prog_descr_t> {
1420 struct pending_t {
1421 bool initial;
1422 pending_t() : initial(false) {}
1423 } pending;
1424 public:
1425 bool pending_initial() { return pending.initial = true; }
1426
1427 void push( prog_descr_t descr ) {
1428 std::stack<prog_descr_t>& me(*this);
1429 me.push(descr);
1430 }
1431 inline void pop() {
1432 std::stack<prog_descr_t>& me(*this);
1433 me.pop();
1434 }
1435 inline prog_descr_t& top() {
1436 std::stack<prog_descr_t>& me(*this);
1437 return me.top();
1438 }
1439 inline const prog_descr_t& top() const {
1440 const std::stack<prog_descr_t>& me(*this);
1441 return me.top();
1442 }
1443 inline size_t size() const {
1444 const std::stack<prog_descr_t>& me(*this);
1445 return me.size();
1446 }
1447 inline bool empty() const {
1448 const std::stack<prog_descr_t>& me(*this);
1449 return me.empty();
1450 }
1451
1452 void apply_pending() {
1453 if( pending.initial ) {
1454 auto e = symbol_at(top().program_index);
1455 auto prog(cbl_label_of(e));
1456 prog->initial = pending.initial;
1457 }
1458 }
1459
1460 // cppcheck-suppress-begin useStlAlgorithm
1461 cbl_label_t *first_declarative() {
1462 auto eval = top().declaratives_eval;
1463 if( eval ) return eval;
1464 // scan stack container for declaratives
1465 for( const auto& prog : c ) {
1466 if( prog.declaratives_eval ) {
1467 eval = prog.declaratives_eval;
1468 break;
1469 }
1470 }
1471 return eval;
1472 }
1473 // cppcheck-suppress-end useStlAlgorithm
1474 };
1475
1476 struct rel_part_t {
1477 cbl_refer_t *operand; // lhs
1478 bool has_relop, invert;
1479 relop_t relop;
1480
1481 rel_part_t()
1482 : operand(nullptr),
1483 has_relop(false),
1484 invert(false),
1485 relop(relop_t(-1))
1486 {}
1487 rel_part_t( cbl_refer_t *operand, relop_t relop, bool invert )
1488 : operand(operand),
1489 has_relop(relop != -1),
1490 invert(invert),
1491 relop(relop)
1492 {}
1493 rel_part_t& relop_set( relop_t op ) {
1494 has_relop = true;
1495 relop = op;
1496 return *this;
1497 }
1498
1499 bool is_value() const { return operand && is_elementary(operand->field->type); }
1500 };
1501
1502 /*
1503 * Evaluation of OR is deferred in case it's followed by AND. As each
1504 * logical operand is encountered, it's first assigned to the
1505 * "andable" member. As ANDs are encountered, they're ANDed to
1506 * andable. When OR is first encountered, we've reached the end of a
1507 * string of ANDs (possibly empty): we move andable to orable, and
1508 * assign the rhs to andable (because it could be followed by AND).
1509 * Successive ORs produce (orable = orable OR andable), followed by
1510 * assigning the rhs to andable.
1511 *
1512 * At the end of the AND/OR evaluation, there is always an andable
1513 * value, because that's where we began. If there is a orable, that
1514 * indicates that the final OR remains unevaluated. In the resolve()
1515 * method, we OR the two, and return that orable. If there's no
1516 * orable, we simply return the andable.
1517 */
1518 class log_expr_t {
1519 cbl_field_t *orable, *andable;
1520 public:
1521 explicit log_expr_t( cbl_field_t *init ) : orable(NULL), andable(init) {
1522 if( ! is_conditional(init) ) {
1523 dbgmsg("%s:%d: logic error: %s is not a truth value",
1524 __func__, __LINE__, name_of(init));
1525 }
1526 }
1527
1528 cbl_field_t * and_term() {
1529 return andable;
1530 }
1531 log_expr_t * and_term( cbl_field_t *rhs ) {
1532 if( ! is_conditional(rhs) ) {
1533 dbgmsg("%s:%d: logic error: %s is not a truth value",
1534 __func__, __LINE__, name_of(rhs));
1535 } else {
1536 parser_logop( andable, andable, and_op, rhs );
1537 }
1538 return this;
1539 }
1540 log_expr_t * or_term( cbl_field_t *rhs ) {
1541 if( ! is_conditional(rhs) ) {
1542 dbgmsg("%s:%d: logic error: %s is not a truth value",
1543 __func__, __LINE__, name_of(rhs));
1544 return this;
1545 }
1546 if( ! orable ) {
1547 orable = andable;
1548 } else {
1549 parser_logop( orable, orable, or_op, andable );
1550 }
1551 andable = rhs;
1552 return this;
1553 }
1554 cbl_field_t * resolve() {
1555 assert(andable);
1556 if( orable ) {
1557 parser_logop( andable, orable, or_op, andable );
1558 orable = NULL;
1559 }
1560 assert(!orable);
1561 return andable; // leave in (initial) ANDable state
1562 }
1563 bool unresolved() const {
1564 return orable != NULL;
1565 }
1566 };
1567
1568 static void ast_enter_section( cbl_label_t * );
1569 static void ast_enter_paragraph( cbl_label_t * );
1570
1571 static class current_t {
1572 friend cbl_options_t current_options();
1573 cbl_options_t options_paragraph;
1574 program_stack_t programs;
1575 unique_typedefs_t typedefs;
1576 std::set<function_descr_t> udfs;
1577 int first_statement;
1578 bool in_declaratives;
1579 // from command line or early TURN
1580 std::list<exception_turn_t> exception_turns;
1581
1582 error_labels_t error_labels;
1583
1584 static void declarative_execute( cbl_label_t *eval ) {
1585 assert(eval);
1586 auto iprog = symbol_elem_of(eval)->program;
1587 if( iprog == current_program_index() ) {
1588 parser_perform(eval);
1589 } else {
1590 parser_entry_activate( iprog, eval );
1591 auto name = cbl_label_of(symbol_at(iprog))->name;
1592 cbl_unimplemented("Global declarative %s for %s",
1593 eval->name, name);
1594 parser_call( new_literal(strlen(name), name, quoted_e),
1595 cbl_refer_t(), 0, NULL, NULL, NULL, false );
1596 }
1597 }
1598
1599 rel_part_t antecedent_cache;
1600
1601 public:
1602 current_t()
1603 : first_statement(0)
1604 , in_declaratives(false)
1605 {}
1606
1607 bool option( cbl_options_t::arith_t option ) {
1608 if( programs.size() == 1 ) {
1609 options_paragraph.arith = option;
1610 return true;
1611 }
1612 return false;
1613 }
1614 bool option_binary( cbl_options_t::float_endidanism_t option ) {
1615 if( programs.size() == 1 ) {
1616 options_paragraph.binary_endidanism = option;
1617 return true;
1618 }
1619 return false;
1620 }
1621 bool option_decimal( cbl_options_t::float_endidanism_t option ) {
1622 if( programs.size() == 1 ) {
1623 options_paragraph.decimal_endidanism = option;
1624 return true;
1625 }
1626 return false;
1627 }
1628 bool option( cbl_options_t::float_encoding_t option ) {
1629 if( programs.size() == 1 ) {
1630 options_paragraph.float_encoding = option;
1631 return true;
1632 }
1633 return false;
1634 }
1635 bool default_round( cbl_round_t option ) {
1636 if( programs.size() == 1 ) {
1637 options_paragraph.default_round = option;
1638 return true;
1639 }
1640 return false;
1641 }
1642 bool intermediate_round( cbl_round_t option ) {
1643 if( programs.size() == 1 ) {
1644 options_paragraph.intermediate_round = option;
1645 return true;
1646 }
1647 return false;
1648 }
1649
1650 template <typename T>
1651 bool initial_option( cbl_section_type_t section, T value ) {
1652 if( programs.size() == 1 ) {
1653 switch( section ) {
1654 case file_sect_e:
1655 case linkage_sect_e:
1656 break;
1657 case working_sect_e:
1658 options_paragraph.initial_value.working = value;
1659 return true;
1660 break;
1661 case local_sect_e:
1662 options_paragraph.initial_value.local = value;
1663 return true;
1664 break;
1665 }
1666 }
1667 return false;
1668 }
1669
1670 bool initial_value( cbl_section_type_t section, size_t isym ) {
1671 return initial_option( section, isym );
1672 }
1673
1674 cbl_enabled_exceptions_t enabled_exception_cache;
1675
1676 typedef std::list<cbl_declarative_t> declaratives_list_t;
1677 class declaratives_t : protected declaratives_list_t {
1678 struct file_exception_t {
1679 ec_type_t type; uint32_t file;
1680 file_exception_t() : type(ec_none_e), file(0) {}
1681 file_exception_t(ec_type_t type, uint32_t file)
1682 : type(type), file(file)
1683 {}
1684 bool operator<( const file_exception_t& that ) const {
1685 if( type == that.type ) return file < that.file;
1686 return type < that.type;
1687 }
1688 };
1689 std::set<file_exception_t> file_exceptions;
1690 public:
1691 declaratives_t() {}
1692 // current compiled data for enabled ECs and Declaratives, used by library.
1693 struct runtime_t {
1694 tree ena, dcl;
1695 runtime_t() : ena(nullptr), dcl(nullptr) {}
1696 } runtime;
1697
1698 bool empty() const {
1699 return declaratives_list_t::empty();
1700 }
1701 inline const declaratives_list_t& as_list() const { return *this; }
1702
1703 bool add( const_reference declarative ) {
1704 auto d = std::find_if( begin(), end(),
1705 [sect = declarative.section]( const_reference decl ) {
1706 return decl.section == sect;
1707 } );
1708 if( d != end() ) {
1709 auto label = cbl_label_of(symbol_at(d->section));
1710 yyerror("USE already defined for %s", label->name);
1711 return false;
1712 }
1713 for( auto f = declarative.files;
1714 f && f < declarative.files + declarative.nfile; f++ ) {
1715 file_exception_t ex( declarative.type, *f );
1716 auto result = file_exceptions.insert(ex);
1717 if( ! result.second ) {
1718 yyerror("%s defined twice for %s",
1719 ec_type_str(declarative.type),
1720 cbl_file_of(symbol_at(*f))->name);
1721 return false;
1722 }
1723 }
1724 declaratives_list_t::push_back(declarative);
1725 return true;
1726 }
1727
1728 // cppcheck-suppress-begin useStlAlgorithm
1729 uint32_t status() const {
1730 uint32_t status_word = 0;
1731 for( auto dcl : *this ) {
1732 status_word |= (EC_ALL_E & dcl.type );
1733 }
1734 return status_word;
1735 }
1736 // cppcheck-suppress-end useStlAlgorithm
1737
1738 bool has_format_1() const {
1739 return std::any_of( begin(), end(),
1740 []( const cbl_declarative_t& dcl ) {
1741 return dcl.is_format_1();
1742 } );
1743 }
1744
1745 std::vector<uint64_t>
1746 encode() const {
1747 std::vector<uint64_t> encoded;
1748 auto p = std::back_inserter(encoded);
1749 for( const auto& dcl : *this ) {
1750 *p++ = dcl.section;
1751 *p++ = dcl.global;
1752 *p++ = dcl.type;
1753 *p++ = dcl.nfile;
1754 p = std::copy(dcl.files, std::end(dcl.files), p);
1755 *p++ = dcl.mode;
1756 }
1757 return encoded;
1758 }
1759
1760 } declaratives;
1761
1762 void exception_add( ec_type_t ec, bool enabled = true) {
1763 exception_turns.push_back(exception_turn_t(ec, enabled));
1764 }
1765 std::list<exception_turn_t>& pending_exceptions() {
1766 return exception_turns;
1767 }
1768
1769 bool typedef_add( const cbl_field_t *field ) {
1770 auto result = typedefs.insert(field);
1771 return result.second;
1772 }
1773 const cbl_field_t * has_typedef( const cbl_field_t *field ) {
1774 auto found = typedefs.find(field);
1775 return found == typedefs.end()? NULL : *found;
1776 }
1777
1778 void udf_add( size_t isym ) {
1779 auto udf = function_descr_t::init(isym);
1780 auto p = udfs.insert(udf);
1781 assert(p.second);
1782 }
1783 const function_descr_t * udf_in( const char name[] ) {
1784 auto udf = function_descr_t::init(name);
1785 auto p = udfs.find(udf);
1786 const function_descr_t *output = NULL;
1787 if( p != udfs.end() ) output = &*p;
1788 return output;
1789 }
1790 void udf_update( const ffi_args_t *ffi_args );
1791 bool udf_args_valid( const cbl_label_t *func,
1792 const std::list<cbl_refer_t>& args,
1793 std::vector<function_descr_arg_t>& params /*out*/ );
1794
1795 void udf_dump() const {
1796 if( yydebug ) {
1797 int i=0;
1798 for( auto udf : udfs ) {
1799 dbgmsg("%4d %-30s %-30s", i++, keyword_str(udf.token), udf.name);
1800 }
1801 }
1802 }
1803
1804 void repository_add_all();
1805 bool repository_add( const char name[] );
1806 int repository_in( const char name[] );
1807
1808 bool repository_add( size_t isym ) {
1809 auto udf = function_descr_t::init(isym);
1810 auto p = udfs.find(udf); // previously defined functions in "udfs"
1811 assert(p != udfs.end()); // If it's a symbol, it must be in udfs.
1812 auto result = programs.top().function_repository.insert(*p);
1813 if( yydebug ) {
1814 for( auto descr : programs.top().function_repository ) {
1815 dbgmsg("%s:%d: %-20s %-20s %-20s", __func__, __LINE__,
1816 keyword_str(descr.token), descr.name, descr.cname);
1817 }
1818 }
1819 return result.second;
1820 }
1821
1822 size_t declarative_section() const {
1823 return symbol_index(symbol_elem_of(programs.top().section));
1824 }
1825 const char * declarative_section_name() const {
1826 return in_declaratives? programs.top().section->name : NULL;
1827 }
1828
1829 std::list<std::string>& debugging_declaratives(bool all) const {
1830 const char *para = programs.top().paragraph->name;
1831 auto client = debugging_clients.find(all? ":all:" : para);
1832 if( client == debugging_clients.end() ) {
1833 static std::list<std::string> empty;
1834 return empty;
1835 }
1836 return client->second;
1837 }
1838
1839 bool
1840 collating_sequence( const cbl_name_t name ) {
1841 assert(name);
1842 assert(!programs.empty());
1843 prog_descr_t& program = programs.top();
1844 if( program.collating_sequence ) return false; // already defined
1845 program.collating_sequence = name;
1846 return true;
1847 }
1848 const char *
1849 collating_sequence() const {
1850 assert(!programs.empty());
1851 return programs.top().collating_sequence;
1852 }
1853
1854 cbl_round_t rounded_mode() const { return programs.top().options.default_round; }
1855 cbl_round_t rounded_mode( cbl_round_t mode ) {
1856 return programs.top().options.default_round = mode;
1857 }
1858
1859 const char *
1860 locale() {
1861 return programs.empty()? NULL : programs.top().locale.os_name;
1862 }
1863 const char *
1864 locale( const cbl_name_t name ) {
1865 if( programs.empty() ) return NULL;
1866 const prog_descr_t::locale_t& locale = programs.top().locale;
1867 return 0 == strcmp(name, locale.name)? locale.name : NULL;
1868 }
1869 const prog_descr_t::locale_t&
1870 locale( const cbl_name_t name, const char os_name[] ) {
1871 if( programs.empty() ) {
1872 static prog_descr_t::locale_t empty;
1873 return empty;
1874 }
1875 return programs.top().locale = prog_descr_t::locale_t(name, os_name);
1876 }
1877
1878 bool new_program ( const YYLTYPE& loc, cbl_label_type_t type,
1879 const char name[], const char os_name[],
1880 bool common, bool initial )
1881 {
1882 size_t parent = programs.empty()? 0 : programs.top().program_index;
1883 cbl_label_t label = {};
1884 label.type = type;
1885 label.parent = parent;
1886 label.line = yylineno;
1887 label.common = common;
1888 label.initial = initial;
1889 label.os_name = os_name;
1890 if( !namcpy(loc, label.name, name) ) { gcc_unreachable(); }
1891
1892 const cbl_label_t *L;
1893 if( (L = symbol_program_add(parent, &label)) == NULL ) return false;
1894 programs.push( prog_descr_t(symbol_index(symbol_elem_of(L))) );
1895 programs.apply_pending();
1896
1897 bool fOK = symbol_at(programs.top().program_index) + 1 == symbols_end();
1898 assert(fOK);
1899
1900 if( (L = symbol_program_local(name)) != NULL ) {
1901 error_msg(loc, "program '%s' already defined on line %d",
1902 L->name, L->line);
1903 return false;
1904 }
1905
1906 options_paragraph = cbl_options_t();
1907 first_statement = 0;
1908
1909 return fOK;
1910 }
1911
1912 void program_needs_initial() { programs.pending_initial(); }
1913
1914 size_t program_index(void) const {
1915 assert(!programs.empty());
1916 return programs.top().program_index;
1917 }
1918 const cbl_label_t * program(void) {
1919 return programs.empty()?
1920 NULL : cbl_label_of(symbol_at(programs.top().program_index));
1921 }
1922 cbl_label_t * section(void) {
1923 return programs.empty()? NULL : programs.top().section;
1924 }
1925 cbl_label_t * paragraph(void) {
1926 return programs.empty()? NULL : programs.top().paragraph;
1927 }
1928
1929 bool is_first_statement( const YYLTYPE& loc ) {
1930 if( ! in_declaratives && first_statement == 0 ) {
1931 auto eval = programs.top().declaratives_eval;
1932 if( eval ) {
1933 size_t ilabel = symbol_index(symbol_elem_of(eval));
1934 if( ! symbol_label_section_exists(ilabel) ) {
1935 if( ! dialect_ibm() ) {
1936 error_msg(loc,
1937 "Per ISO a program with DECLARATIVES must begin with a SECTION, "
1938 "requires %<-dialect ibm%>");
1939 }
1940 }
1941 }
1942 first_statement = loc.first_line;
1943 return true;
1944 }
1945 return false;
1946 }
1947
1948 /*
1949 * At the end of each program, ensure there are no uses of an ambiguous
1950 * procedure (SECTION or PARAGRAPH) name. At the end of a top-level program,
1951 * adjust any CALL targets to use the mangled name of the internal (contained
1952 * or COMMON ) program. We ensure there are no duplicate program names, per
1953 * ISO, in new_program.
1954 */
1955 std::set<std::string> end_program() {
1956 cbl_enabled_exceptions_t& enabled_exceptions( cdf_enabled_exceptions() );
1957 if( enabled_exceptions.size() ) {
1958 declaratives_evaluate();
1959 }
1960
1961 assert(!programs.empty());
1962
1963 const procref_t *ref = ambiguous_reference(program_index());
1964 std::set<std::string> externals = programs.top().external_targets();
1965
1966 /*
1967 * For each called local program, replace the original undecorated
1968 * target with the mangled name.
1969 *
1970 * At END-PROGRAM for the top-level program, we know all
1971 * subprograms, and whether or not they are COMMON. PROGRAM may be
1972 * the caller, or a subprogram could call COMMON sibling.
1973 */
1974
1975 static std::unordered_set<size_t> callers_we_have_seen;
1976 if( programs.size() == 1 ) {
1977 if( yydebug ) parser_call_targets_dump();
1978 for( size_t caller : symbol_program_programs() ) {
1979 // We are running through the entire growing list of called programs
1980 // at the point of each END PROGRAM. This confuses the name changing
1981 // routines, so we use a std::set to avoid doing callers more than
1982 // once.
1983 if( callers_we_have_seen.find(caller) != callers_we_have_seen.end() )
1984 {
1985 continue;
1986 }
1987 const char *caller_name = cbl_label_of(symbol_at(caller))->name;
1988 for( auto callable : symbol_program_callables(caller) ) {
1989 auto called = cbl_label_of(symbol_at(callable));
1990 auto mangled_name =
1991 called->mangled_name? called->mangled_name : called->name;
1992
1993 size_t n =
1994 parser_call_target_update(caller,
1995 called->name,
1996 mangled_name);
1997 // Zero is not an error
1998 dbgmsg("updated " HOST_SIZE_T_PRINT_UNSIGNED
1999 " calls from #%-3" GCC_PRISZ "u (%s) s/%s/%s/",
2000 (fmt_size_t)n, (fmt_size_t)caller, caller_name,
2001 called->name, mangled_name);
2002 }
2003 callers_we_have_seen.insert(caller);
2004 }
2005 if( yydebug ) parser_call_targets_dump();
2006 }
2007
2008 parser_leave_paragraph( programs.top().paragraph );
2009 parser_leave_section( programs.top().section );
2010 programs.pop();
2011
2012 debugging_clients.clear();
2013 error_clients.clear();
2014 exception_clients.clear();
2015
2016 if( ref ) {
2017 yywarn("could not resolve paragraph (or section) '%s' at line %d",
2018 ref->paragraph(), ref->line_number());
2019 // add string to indicate ambiguity error
2020 externals.insert(":ambiguous:");
2021 }
2022 return externals;
2023 }
2024
2025 size_t program_level() const { return programs.size(); }
2026
2027 size_t program_section() const {
2028 if( programs.empty() || programs.top().section == NULL ) return 0;
2029 auto section = programs.top().section;
2030 return symbol_index(symbol_elem_of(section));
2031 }
2032
2033 cbl_label_t * doing_declaratives( bool begin ) {
2034 if( begin ) {
2035 in_declaratives = true;
2036 return NULL;
2037 }
2038 assert( !begin );
2039 in_declaratives = false;
2040 if( declaratives.empty() ) return NULL;
2041 assert(!declaratives.empty());
2042
2043 declaratives.runtime.dcl = parser_compile_dcls(declaratives.encode());
2044
2045 // Create section to evaluate declaratives. Given them unique names so
2046 // that we can figure out what is going on in a trace or looking at the
2047 // assembly language.
2048 static int eval_count = 1;
2049 char eval[32], lave[32];
2050
2051 sprintf(eval, "_DECLARATIVES_EVAL%d", eval_count);
2052 sprintf(lave, "_DECLARATIVES_LAVE%d", eval_count++);
2053
2054 struct cbl_label_t*& eval_label = programs.top().declaratives_eval;
2055 eval_label = label_add(LblSection, eval, yylineno);
2056 struct cbl_label_t * lave_label = label_add(LblSection, lave, yylineno);
2057
2058 ast_enter_section(eval_label);
2059
2060 declarative_runtime_match(declaratives.as_list(), lave_label);
2061
2062 parser_label_label(lave_label);
2063
2064 return lave_label;
2065 }
2066
2067 cbl_label_t * new_section( cbl_label_t * section ) {
2068 std::swap( programs.top().section, section );
2069 return section;
2070 }
2071
2072 ec_type_t ec_type_of( file_status_t status ) {
2073 static std::vector<ec_type_t> ec_by_status {
2074 /* 0 */ ec_none_e, // ec_io_warning_e if low byte is nonzero
2075 /* 1 */ ec_io_at_end_e,
2076 /* 2 */ ec_io_invalid_key_e,
2077 /* 3 */ ec_io_permanent_error_e,
2078 /* 4 */ ec_io_logic_error_e,
2079 /* 5 */ ec_io_record_operation_e,
2080 /* 6 */ ec_io_file_sharing_e,
2081 /* 7 */ ec_io_record_content_e,
2082 /* 8 */ ec_io_imp_e, // unused, not defined by ISO
2083 /* 9 */ ec_io_imp_e,
2084 };
2085 int status10 = static_cast<unsigned int>(status) / 10;
2086 gcc_assert(ec_by_status.size() == 10);
2087 gcc_assert(0 <= status10 && status10 < 10 && status10 != 8);
2088 return ec_by_status[status10];
2089 }
2090
2091 /*
2092 * END DECLARATIVES causes:
2093 * 1. Create section _DECLARATIVES_EVAL
2094 * and exit label _DECLARATIVES_LAVE
2095 * 2. declarative_runtime_match generates runtime evaluation "ladder".
2096 * 3. After a declarative is executed, control branches to the exit label.
2097 *
2098 * After each verb, we call declaratives_evaluate,
2099 * which PERFORMs _DECLARATIVES_EVAL.
2100 *
2101 * If the matched declarative is defined by a superior program as
2102 * GLOBAL, it cannot be PERFORMed. Instead, it is CALLed with an
2103 * alternative entry point (TODO).
2104 */
2105 void
2106 declaratives_evaluate( cbl_file_t *file ) {
2107 gcc_assert(file);
2108 parser_file_stash(file);
2109
2110 cbl_label_t *eval = programs.first_declarative();
2111 if( eval ) {
2112 auto iprog = symbol_elem_of(eval)->program;
2113 if( iprog == current_program_index() ) {
2114 parser_perform(eval);
2115 } else {
2116 parser_entry_activate( iprog, eval );
2117 auto name = cbl_label_of(symbol_at(iprog))->name;
2118 parser_call( new_literal(strlen(name), name, quoted_e),
2119 cbl_refer_t(), 0, NULL, NULL, NULL, false );
2120 }
2121 }
2122 }
2123
2124 void
2125 declaratives_evaluate( std::list<cbl_file_t*>& files ) {
2126 for( auto& file : files ) {
2127 declaratives_evaluate(file);
2128 }
2129 }
2130
2131 /*
2132 * To indicate to the runtime-match function that we want to evaluate
2133 * only the exception condition, unrelated to a file, we set the
2134 * file register to 0 and the handled-exception register to the
2135 * handled exception condition.
2136 *
2137 * declaratives_execute performs the "declarative ladder" produced
2138 * by declaratives_runtime_match. That section CALLs the
2139 * runtime-match procedure __gg__match_exception, passing it the
2140 * values of those two registers. When that function sees there's
2141 * no file involved, it interprets the "handled" parameter as
2142 * ec_type_t, and returns the matching declarative symbol-table
2143 * index, per usual.
2144 */
2145 void
2146 declaratives_evaluate() {
2147 cbl_label_t *eval = programs.first_declarative();
2148 if( eval ) declarative_execute(eval);
2149 }
2150
2151 cbl_label_t * new_paragraph( cbl_label_t *para ) {
2152 auto& prog( programs.top() );
2153 auto old(prog.paragraph);
2154 prog.paragraph = para;
2155 return old;
2156 }
2157
2158 void antecedent_dump() const {
2159 if( ! yydebug ) return;
2160 if( ! antecedent_cache.operand ) {
2161 yywarn( "Antecedent: none" );
2162 } else {
2163 yywarn( "Antecedent: %c %s %s %c",
2164 antecedent_cache.invert? '!':' ',
2165 name_of(antecedent_cache.operand->field),
2166 relop_str(antecedent_cache.relop),
2167 antecedent_cache.has_relop? 'T' : 'F' );
2168 }
2169 }
2170 void antecedent( const rel_part_t& ante ) { antecedent_cache = ante; antecedent_dump(); }
2171 void antecedent_reset() { antecedent_cache = rel_part_t(); antecedent_dump(); }
2172 rel_part_t& antecedent() { return antecedent_cache; }
2173 rel_part_t& antecedent( relop_t op ) {
2174 antecedent_cache.relop_set(op);
2175 antecedent_dump();
2176 return antecedent_cache;
2177 }
2178 rel_part_t& antecedent_invert( bool invert=true ) {
2179 antecedent_cache.invert = invert;
2180 antecedent_dump();
2181 return antecedent_cache;
2182 }
2183
2184 void compute_begin() { error_labels.generate(); }
2185 bool in_compute() { return error_labels.on_error != NULL; }
2186 void compute_end() { error_labels.clear(); }
2187 cbl_label_t * compute_on_error() { return error_labels.on_error; }
2188 cbl_label_t * compute_not_error() { return error_labels.not_error; }
2189 cbl_label_t * compute_label() { return error_labels.compute_error; }
2190 } current;
2191
2192 void current_enabled_ecs( tree ena ) {
2193 current.declaratives.runtime.ena = ena;
2194 }
2195
2196 #define PROGRAM current.program_index()
2197
2198 static void
2199 add_debugging_declarative( const cbl_label_t * label ) {
2200 // cppcheck-suppress [unreadVariable] obviously not true
2201 const char *section = current.declarative_section_name();
2202 if( section ) {
2203 debugging_clients[label->name].push_back(section);
2204 }
2205 }
2206
2207 cbl_options_t current_options() {
2208 return current.options_paragraph;
2209 }
2210
2211 size_t current_program_index() {
2212 return current.program()? current.program_index() : 0;
2213 }
2214
2215 cbl_label_t * current_section() {
2216 return current.section();
2217 }
2218 cbl_label_t * current_paragraph() {
2219 return current.paragraph();
2220 }
2221
2222 const char *
2223 current_declarative_section_name() {
2224 return current.declarative_section_name();
2225 }
2226
2227 void
2228 add_cobol_exception( ec_type_t type, bool enabled ) {
2229 current.exception_add( type, enabled );
2230 }
2231
2232 static cbl_round_t rounded_of( int token );
2233
2234 cbl_round_t
2235 current_rounded_mode() {
2236 return current.rounded_mode();
2237 }
2238
2239 #if needed
2240 static cbl_round_t
2241 current_rounded_mode( cbl_round_t rounded) {
2242 return current.rounded_mode(rounded);
2243 }
2244 #endif
2245 static cbl_round_t current_rounded_mode( int token );
2246
2247 size_t program_level() { return current.program_level(); }
2248
2249 static size_t constant_index( int token );
2250
2251 static relop_t relop_of(int);
2252 static relop_t relop_invert(relop_t op);
2253
2254 static enum classify_t classify_of( int token );
2255
2256 static void subscript_dimension_error( YYLTYPE loc, size_t, const cbl_refer_t *name );
2257
2258 /*
2259 * Utility functions
2260 */
2261
2262 char *
2263 normalize_picture( char picture[] );
2264
2265 static inline cbl_field_t *
2266 new_tempnumeric(const cbl_name_t name = nullptr) {
2267 return new_temporary(FldNumericBin5, name);
2268 }
2269
2270 static inline cbl_field_t *
2271 new_tempnumeric_float(const cbl_name_t name = nullptr) {
2272 return new_temporary(FldFloat, name);
2273 }
2274
2275 uint32_t
2276 type_capacity( enum cbl_field_type_t type, uint32_t digits );
2277
2278 bool
2279 valid_picture( enum cbl_field_type_t type, const char picture[] );
2280
2281 bool
2282 move_corresponding( cbl_refer_t& tgt, cbl_refer_t& src );
2283
2284 static bool
2285 literal_subscripts_valid( YYLTYPE loc, const cbl_refer_t& name );
2286 static bool
2287 literal_refmod_valid( YYLTYPE loc, const cbl_refer_t& r );
2288
2289 static bool
2290 is_integer_literal( const cbl_field_t *field ) {
2291 if( field->type == FldLiteralN ) {
2292 const char *initial = field->data.initial;
2293
2294 switch( *initial ) {
2295 case '-': case '+': ++initial;
2296 }
2297
2298 const char *eos = initial + strlen(initial);
2299 auto p = std::find_if_not( initial, eos, fisdigit );
2300 if( p == eos ) return true;
2301
2302 if( *p++ == symbol_decimal_point() ) {
2303 switch( *p++ ) {
2304 case 'E': case 'e':
2305 switch( *p++ ) {
2306 case '+': case '-':
2307 return std::all_of(p, eos, []( char ch ) { return ch == '0'; } );
2308 break;
2309 }
2310 }
2311 }
2312 }
2313 return false;
2314 }
2315
2316 static inline bool
2317 is_string_literal( const cbl_field_t *field ) {
2318 return is_literal(field) && is_quoted(field);
2319 }
2320
2321 static inline bool
2322 needs_picture( cbl_field_type_t type ) {
2323 switch(type) {
2324 case FldDisplay:
2325 case FldInvalid:
2326 gcc_unreachable();
2327 return false; // not a valid question
2328
2329 case FldAlphaEdited:
2330 case FldAlphanumeric:
2331 case FldNumericBinary:
2332 case FldNumericDisplay:
2333 case FldNumericEdited:
2334 case FldPacked:
2335 return true;
2336
2337 case FldFloat:
2338 case FldNumericBin5:
2339 return false;
2340
2341 case FldBlob:
2342 case FldClass:
2343 case FldConditional:
2344 case FldForward:
2345 case FldGroup:
2346 case FldIndex:
2347 case FldLiteralA:
2348 case FldLiteralN:
2349 case FldPointer:
2350 case FldSwitch:
2351 return false;
2352 }
2353
2354 dbgmsg("%s:%d: unknown cbl_field_type_t %u", __func__, __LINE__, type);
2355 gcc_unreachable();
2356 return false;
2357 }
2358
2359 static bool
2360 is_callable( const cbl_field_t *field ) {
2361 switch ( field->type ) {
2362 case FldInvalid:
2363 case FldNumericEdited:
2364 case FldAlphaEdited:
2365 case FldClass:
2366 case FldConditional:
2367 case FldForward:
2368 case FldSwitch:
2369 case FldDisplay:
2370 case FldBlob:
2371 case FldNumericDisplay:
2372 case FldNumericBinary:
2373 case FldFloat:
2374 case FldPacked:
2375 case FldNumericBin5:
2376 case FldLiteralN:
2377 case FldIndex:
2378 return false;
2379 case FldGroup:
2380 case FldLiteralA:
2381 case FldAlphanumeric:
2382 case FldPointer:
2383 return true;
2384 }
2385 cbl_internal_error( "%s:%d: invalid %<symbol_type_t%> %d",
2386 __func__, __LINE__, field->type );
2387 return false;
2388 }
2389
2390 /*
2391 * intrinsic calls
2392 */
2393 struct cbl_fieldloc_t {
2394 YYLTYPE loc;
2395 cbl_field_t *field;
2396
2397 cbl_fieldloc_t() : loc{ 1,1, 1,1 }, field(NULL) {}
2398 cbl_fieldloc_t( const YYLTYPE& loc, cbl_field_t *field )
2399 : loc(loc), field(field)
2400 {}
2401 };
2402
2403 static size_t
2404 intrinsic_invalid_parameter( int token, const std::vector<cbl_refer_t>& args );
2405
2406 static const char *
2407 intrinsic_cname( int token );
2408
2409 static bool
2410 intrinsic_call_0( cbl_field_t *output, int token ) {
2411 const char *name = intrinsic_cname(token);
2412 if( !name ) return false;
2413 parser_intrinsic_call_0( output, name );
2414 return true;
2415 }
2416
2417 static bool
2418 intrinsic_call_1( cbl_field_t *output, int token,
2419 cbl_refer_t *r1, const YYLTYPE& loc ) {
2420 std::vector<cbl_refer_t> args { *r1 };
2421 if( 0 == intrinsic_invalid_parameter(token, args) ) {
2422 error_msg(loc, "invalid parameter '%s'", r1->field->name);
2423 return false;
2424 }
2425
2426 const char *func = intrinsic_cname(token);
2427 if( !func ) return false;
2428 parser_intrinsic_call_1( output, func, *r1 );
2429 return true;
2430 }
2431
2432 static bool
2433 intrinsic_call_2( cbl_field_t *tgt, int token, const cbl_refer_t *r1, cbl_refer_t *r2 ) {
2434 std::vector<cbl_refer_t> args { *r1, r2? *r2 : cbl_refer_t() };
2435 size_t n = intrinsic_invalid_parameter(token, args);
2436 if( n < args.size() ) {
2437 error_msg(args[n].loc, "invalid parameter '%s'", args[n].field->name);
2438 return false;
2439 }
2440 const char *fund = intrinsic_cname(token);
2441 if( !fund ) return false;
2442 parser_intrinsic_call_2( tgt, fund, args[0], args[1] );
2443 return true;
2444 }
2445
2446 static bool
2447 intrinsic_call_3( cbl_field_t *tgt, int token,
2448 cbl_refer_t *r1, cbl_refer_t *r2, cbl_refer_t *r3 ) {
2449 std::vector<cbl_refer_t> args { *r1, *r2, *r3 };
2450 size_t n = intrinsic_invalid_parameter(token, args);
2451 if( n < args.size() ) {
2452 error_msg(args[n].loc, "invalid parameter '%s'", args[n].field->name);
2453 return false;
2454 }
2455 const char *func = intrinsic_cname(token);
2456 if( !func ) return false;
2457 parser_intrinsic_call_3( tgt, func, *r1, *r2, *r3 );
2458 return true;
2459 }
2460
2461 static bool
2462 intrinsic_call_4( cbl_field_t *tgt, int token,
2463 cbl_refer_t *r1, cbl_refer_t *r2,
2464 cbl_refer_t *r3, cbl_refer_t *r4 ) {
2465 std::vector<cbl_refer_t> args { *r1, *r2, *r3, *r4 };
2466 size_t n = intrinsic_invalid_parameter(token, args);
2467 if( n < args.size() ) {
2468 error_msg(args[n].loc, "invalid parameter '%s'", args[n].field->name);
2469 return false;
2470 }
2471 const char *func = intrinsic_cname(token);
2472 if( !func ) return false;
2473 parser_intrinsic_call_4( tgt, func, *r1, *r2, *r3, *r4 );
2474 return true;
2475 }
2476
2477 /*
2478 * Local functions
2479 */
2480
2481 static inline cbl_field_t *
2482 new_literal( const char initial[] ) {
2483 return new_literal( strlen(initial), initial );
2484 }
2485
2486 cbl_refer_t *
2487 negate( cbl_refer_t * refer, bool neg = true ) {
2488 if( ! neg ) return refer;
2489 assert( is_numeric(refer->field) );
2490 auto output = new_reference(new_tempnumeric());
2491 parser_subtract( *output, literally_zero, *refer, current_rounded_mode() );
2492 return output;
2493 }
2494
2495 cbl_field_t *
2496 conditional_set( cbl_field_t *tgt, bool tf ) {
2497 static cbl_field_t *one = new_literal("1");
2498
2499 enum relop_t op = tf? eq_op : ne_op;
2500 parser_relop( tgt, one, op, one );
2501 return tgt;
2502 }
2503
2504 static inline cbl_field_t *
2505 table_primary_index( cbl_field_t *table ) {
2506 assert(table);
2507 return 0 == table->occurs.indexes.nfield?
2508 NULL : cbl_field_of(symbol_at(table->occurs.indexes.fields[0]));
2509 }
2510
2511 static inline const cbl_refer_t // return copy, not element reference
2512 invalid_key( const cbl_refer_t& ref ) {
2513 assert(ref.field);
2514 auto p = std::find_if( ref.subscripts.begin(), ref.subscripts.end(),
2515 [parent = ref.field->parent]( const auto &sub ) {
2516 return sub.field->parent == parent;
2517 } );
2518 return p != ref.subscripts.end() ? *p : nullptr;
2519 }
2520
2521 static inline symbol_elem_t *
2522 symbol_find( const std::list<const char *>& names ) {
2523 auto found = symbol_find(PROGRAM, names);
2524 if( found.first && !found.second ) {
2525 auto field = cbl_field_of(found.first);
2526 yyerror( "%s is not unique, first defined on line %d",
2527 field->name, field->line );
2528 return NULL;
2529 }
2530 return found.first;
2531 }
2532
2533 static inline cbl_field_t *
2534 field_find( const std::list<const char *>& names ) {
2535 if( names.size() == 1 ) {
2536 auto value = cdf_value(names.front());
2537 if( value ) {
2538 cbl_field_t * field;
2539 if( value->is_numeric() ) {
2540 field = new_tempnumeric();
2541 parser_set_numeric(field, value->as_number());
2542 } else {
2543 field = new_literal(value->string);
2544 }
2545 return field;
2546 }
2547 }
2548 symbol_elem_t *e = symbol_find(names);
2549 return e? cbl_field_of(e) : NULL;
2550 }
2551
2552 static inline symbol_elem_t *
2553 symbol_find( const YYLTYPE& loc, const char *name ) {
2554 cbl_namelist_t names;
2555 if( ! name_queue.empty() ) {
2556 auto names = name_queue.pop_as_names();
2557 }
2558 names.push_front(name);
2559 auto found = symbol_find( PROGRAM, names );
2560 if( found.first && !found.second ) {
2561 auto field = cbl_field_of(found.first);
2562 error_msg(loc, "'%s' is not unique, first defined on line %d",
2563 field->name, field->line);
2564 return NULL;
2565 }
2566 return found.first;
2567 }
2568
2569 static inline cbl_field_t *
2570 register_find( const char *name ) {
2571 return cbl_field_of(symbol_register(name));
2572 }
2573
2574 static bool
2575 valid_redefine( const YYLTYPE& loc,
2576 const cbl_field_t *field, const cbl_field_t *orig ) {
2577 // Must have same level.
2578 if( field->level != orig->level ) {
2579 error_msg(loc, "cannot redefine %s %s as %s %s "
2580 "because they have different levels",
2581 orig->level_str(), orig->name,
2582 field->level_str(), field->name);
2583 return false;
2584 }
2585
2586 // no higher level intervenes
2587 /*
2588 * No entry having a level-number numerically lower than the
2589 * level-number of data-name-2 may occur between the data
2590 * description entries of data-name-2 and the subject of the entry.
2591 */
2592 struct { symbol_elem_t *field, *orig; } sym = {
2593 symbol_at(field_index(field)),
2594 symbol_at(field_index(orig)) };
2595
2596 auto e = std::find_if( sym.orig + 1, sym.field,
2597 [lowest = field->level]( auto& elem ) {
2598 if( elem.type != SymField ) return false;
2599 auto f = cbl_field_of(&elem);
2600 return 0 < f->level && f->level < lowest;
2601 } );
2602 if( e != sym.field ) {
2603 auto wrong = cbl_field_of(e);
2604 error_msg(loc, "%s %s on line %d lies between %s and %s",
2605 wrong->level_str(), wrong->name, wrong->line,
2606 orig->name, field->name);
2607 return false;
2608 }
2609
2610 // cannot redefine a table
2611 if( orig->occurs.ntimes() ) {
2612 error_msg(loc, "cannot redefine table %s %s",
2613 orig->level_str(), orig->name);
2614 return false;
2615 }
2616
2617 // redefined field cannot be ODO
2618 if( orig->occurs.depending_on ) {
2619 error_msg(loc, "redefined data item %s %s has OCCURS DEPENDING ON",
2620 orig->level_str(), orig->name);
2621 return false;
2622 }
2623 // redefiner cannot have ODO
2624 if( field->occurs.depending_on ) {
2625 error_msg(loc, "data item %s %s cannot use REDEFINES and OCCURS DEPENDING ON",
2626 field->level_str(), field->name);
2627 return false;
2628 }
2629
2630 if( is_variable_length(orig) ) {
2631 error_msg(loc, "redefined data item %s %s has OCCURS DEPENDING ON",
2632 orig->level_str(), orig->name);
2633 return false;
2634 }
2635 // We don't know about the redefining group until it's completely defined.
2636
2637 /*
2638 * 8) The storage area required for the subject of the entry
2639 * shall not be larger than the storage area required for the
2640 * data item referenced by data-name-2, unless the data item
2641 * referenced by data- name-2 has been specified with level
2642 * number 1 and without the EXTERNAL clause.
2643 */
2644 if( field->type != FldGroup && orig->type != FldGroup ) {
2645 if( orig->size() < field->size() ) {
2646 if( orig->level > 1 || orig->has_attr(external_e) ) {
2647 dbgmsg( "size error orig: %s", field_str(orig) );
2648 dbgmsg( "size error redef: %s", field_str(field) );
2649 error_msg(loc, "%s (%s size %u) larger than REDEFINES %s (%s size %u)",
2650 field->name,
2651 3 + cbl_field_type_str(field->type), field->size(),
2652 orig->name,
2653 3 + cbl_field_type_str(orig->type), orig->size() );
2654 }
2655 }
2656 }
2657
2658 /*
2659 * 4) No entry having a level-number numerically lower than the
2660 * level-number of data-name-2 may occur between the data
2661 * description entries of data-name-2 and the subject of the entry.
2662 */
2663 bool same_group = std::none_of( symbol_at(field_index(orig)),
2664 symbol_at(field_index(field)),
2665 [level = field->level]( const auto& elem ) {
2666 if( elem.type == SymField ) {
2667 auto f = cbl_field_of(&elem);
2668 return 0 < f->level && f->level < level;
2669 }
2670 return false;
2671 } );
2672 if( ! same_group ) {
2673 error_msg(loc, "cannot redefine %s %s as %s %s "
2674 "because they belong to different groups",
2675 orig->level_str(), orig->name,
2676 field->level_str(), field->name);
2677 return false;
2678 }
2679
2680 return true;
2681 }
2682
2683 static void
2684 field_value_all(struct cbl_field_t * field ) {
2685 // Expand initial by repeating its contents until it is of length capacity:
2686 assert(field->data.initial != NULL);
2687 size_t initial_length = strlen(field->data.initial);
2688 char *new_initial = static_cast<char*>(xmalloc(field->data.capacity + 1));
2689 size_t i = 0;
2690 while(i < field->data.capacity) {
2691 new_initial[i] = field->data.initial[i%initial_length];
2692 i += 1;
2693 }
2694 new_initial[field->data.capacity] = '\0';
2695 free(const_cast<char *>(field->data.initial));
2696 field->data.initial = new_initial;
2697 }
2698
2699 static cbl_field_t *
2700 parent_has_value( cbl_field_t *field ) {
2701 while( (field = parent_of(field)) != NULL ) {
2702 if( field->data.initial ) break;
2703 }
2704 return field;
2705 }
2706
2707 static uint32_t
2708 group_attr( const cbl_field_t * field ) {
2709 if( field->parent == 0 ) return 0;
2710
2711 const symbol_elem_t *e = symbol_at(field->parent);
2712 if( SymField != e->type ) return 0;
2713
2714 const cbl_field_t *p = cbl_field_of(e);
2715 if( p->type != FldGroup ) return 0;
2716
2717 return p->attr;
2718 }
2719
2720 static struct cbl_field_t *
2721 field_add( const YYLTYPE& loc, cbl_field_t *field ) {
2722 switch(current_data_section) {
2723 case not_data_datasect_e:
2724 case file_datasect_e:
2725 case working_storage_datasect_e:
2726 break;
2727 case local_storage_datasect_e:
2728 field->attr |= local_e;
2729 break;
2730 case linkage_datasect_e:
2731 field->attr |= linkage_e;
2732 break;
2733 }
2734
2735 // Use isym 0 to indicate the location of the field under construction.
2736 symbol_field_location(0, loc);
2737
2738 struct symbol_elem_t *e = symbol_field_add(PROGRAM, field);
2739 if( !e ) return NULL;
2740 symbol_field_location(symbol_index(e), loc);
2741 field = cbl_field_of(e);
2742 assert(field->type != FldDisplay);
2743
2744 if( field->parent == 0 ) {
2745 switch(field->level) {
2746 case 0: case 1: case 77: case 78:
2747 break;
2748 default:
2749 error_msg(loc, "%s %s is not part of an 01 record",
2750 field->level_str(), field->name );
2751 return NULL;
2752 break;
2753 }
2754 }
2755 return field;
2756 }
2757
2758 static const char *
2759 field_attr_str( const cbl_field_t *field ) {
2760 static const std::vector<cbl_field_attr_t> attrs {
2761 figconst_1_e, figconst_2_e, figconst_4_e, rjust_e, ljust_e,
2762 zeros_e, signable_e, constant_e, function_e, quoted_e, filler_e,
2763 intermediate_e, embiggened_e, all_alpha_e, all_x_e,
2764 all_ax_e, prog_ptr_e, scaled_e, refmod_e, based_e, any_length_e,
2765 global_e, external_e, blank_zero_e, linkage_e, local_e, leading_e,
2766 separate_e, envar_e, dnu_1_e, bool_encoded_e, hex_encoded_e,
2767 depends_on_e, initialized_e, has_value_e, ieeedec_e, big_endian_e,
2768 same_as_e, record_key_e, typedef_e, strongdef_e,
2769 };
2770 return field->attr_str(attrs);
2771 }
2772
2773 static bool
2774 uniform_picture( const char *picture, char model ) {
2775 const char *eopicture( picture + strlen(picture) );
2776 model = TOLOWER(model);
2777 return std::all_of(picture, eopicture,
2778 [model]( char ch ) {
2779 return model == TOLOWER(ch);
2780 } );
2781 }
2782
2783 static enum cbl_field_attr_t
2784 uniform_picture( const char *picture ) {
2785 static char ch[] = { 'A', 'X' };
2786 for( auto p = ch; p < ch + sizeof(ch); p++ ) {
2787 if( uniform_picture(picture, *p) ) {
2788 switch(*p) {
2789 case 'A': return all_alpha_e;
2790 case 'X': return all_x_e;
2791 }
2792 }
2793 }
2794 return none_e;
2795 }
2796
2797 static bool
2798 field_type_update( cbl_field_t *field, cbl_field_type_t type,
2799 YYLTYPE loc,
2800 bool is_usage = false)
2801 {
2802 // preserve NumericEdited if already established
2803 if( !is_usage && field->has_attr(blank_zero_e) ) {
2804 if( type == FldNumericDisplay && field->type == FldNumericEdited ) {
2805 return true;
2806 }
2807 }
2808
2809 // disallow USAGE if inherited from parent (all members must be of same type)
2810 if( is_usage && field->usage != type ) {
2811 switch( field->usage ) {
2812 case FldInvalid:
2813 case FldDisplay:
2814 break; // ok
2815 default:
2816 error_msg(loc, "cannot set %s to USAGE %s "
2817 "because the group is restricted to USAGE %s",
2818 field->name, cbl_field_type_str(type),
2819 cbl_field_type_str(field->usage));
2820 return false;
2821 }
2822 }
2823
2824 if( ! symbol_field_type_update(field, type, is_usage) ) {
2825 error_msg(loc, "cannot set USAGE of %s to %s (from %s)", field->name,
2826 cbl_field_type_str(type) + 3, cbl_field_type_str(field->type) + 3);
2827 return false;
2828 }
2829
2830 dbgmsg( "%s:%d: %s became %s based on %s", __func__, __LINE__, field->name,
2831 cbl_field_type_str(field->type), cbl_field_type_str(type) );
2832
2833 return true;
2834 }
2835
2836 static bool
2837 field_capacity_error( const YYLTYPE& loc, const cbl_field_t *field ) {
2838 uint32_t parent_capacity = 0;
2839 if( field->parent ) {
2840 auto e = symbol_at(field->parent);
2841 if( e->type == SymField ) parent_capacity = cbl_field_of(e)->data.capacity;
2842 }
2843 /*
2844 * Field may become a table whose capacity was inherited from a parent with
2845 * data. If so, the field's capacity will be overwritten by its
2846 * PICTURE-defined size.
2847 */
2848 if( parent_capacity < field->data.capacity && !symbol_redefines(field) ) {
2849 dbgmsg( "%s: %s", __func__, field_str(field) );
2850 error_msg(loc, "%s has USAGE incompatible with PICTURE",
2851 field->name );
2852 return true;
2853 }
2854 return false;
2855 }
2856 #define ERROR_IF_CAPACITY(L, F) \
2857 do { if( field_capacity_error(L, F) ) YYERROR; } while(0)
2858
2859 static const char *
2860 blank_pad_initial( const char initial[], size_t capacity, size_t new_size ) {
2861 assert(capacity < new_size);
2862 assert(initial != NULL);
2863
2864 if( normal_value_e != cbl_figconst_of(initial) ) return initial;
2865
2866 auto p = reinterpret_cast<char *>( xmalloc(2 + new_size) );
2867 memset(p, 0x20, new_size);
2868 memcpy(p, initial, capacity);
2869 p[new_size] = '\0'; // for debugging
2870 p[++new_size] = '\0'; // for debugging
2871 return p;
2872 }
2873
2874 static bool
2875 value_encoding_check( const YYLTYPE& loc, cbl_field_t *field ) {
2876 if( ! field->internalize() ) {
2877 error_msg(loc, "inconsistent string literal encoding for '%s'",
2878 field->data.initial);
2879 return false;
2880 }
2881 return true;
2882 }
2883
2884
2885 #pragma GCC diagnostic push
2886 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
2887
2888 static struct cbl_field_t *
2889 field_alloc( const YYLTYPE& loc, cbl_field_type_t type, size_t parent, const char name[] ) {
2890 cbl_field_t *f, field = {};
2891 field.type = type;
2892 field.usage = FldInvalid;
2893 field.parent = parent;
2894 field.line = yylineno;
2895
2896 if( !namcpy(loc, field.name, name) ) return NULL;
2897 f = field_add(loc, &field);
2898 assert(f);
2899 return f;
2900 }
2901
2902 static const cbl_file_t protofile;
2903
2904 // Add a file to the symbol table with its record area field.
2905 // The default organization is sequential.
2906 #pragma GCC diagnostic push
2907 #pragma GCC diagnostic ignored "-Wformat-truncation"
2908 static cbl_file_t *
2909 file_add( YYLTYPE loc, cbl_file_t *file ) {
2910 gcc_assert(file);
2911 enum { level = 1 };
2912 struct cbl_field_t area = { 0, FldAlphanumeric, FldInvalid, 0, 0,0, level, {}, yylineno },
2913 *field = field_add(loc, &area);
2914 file->default_record = field_index(field);
2915
2916 // install file, and set record area's name
2917 auto e = symbol_file_add(PROGRAM, file);
2918 if( !e ) {
2919 error_msg(loc, "%s was defined previously on line %d", file->name, file->line);
2920 return NULL;
2921 }
2922 file = cbl_file_of(e);
2923 snprintf(field->name, sizeof(field->name),
2924 "%s" HOST_SIZE_T_PRINT_UNSIGNED "_%s",
2925 record_area_name_stem, (fmt_size_t)symbol_index(e), file->name);
2926 if( file->attr & external_e ) {
2927 snprintf(field->name, sizeof(field->name),
2928 "%s%s", record_area_name_stem, file->name);
2929 }
2930 field->file = field->parent = symbol_index(e);
2931
2932 return file;
2933 }
2934 #pragma GCC diagnostic pop
2935 #pragma GCC diagnostic pop
2936
2937
2938 static cbl_alphabet_t *
2939 alphabet_add( const YYLTYPE& loc, cbl_encoding_t encoding ) {
2940 cbl_alphabet_t alphabet(loc, encoding);
2941 symbol_elem_t *e = symbol_alphabet_add(PROGRAM, &alphabet);
2942 assert(e);
2943 return cbl_alphabet_of(e);
2944 }
2945
2946 // The current field always exists in the symbol table, even if it's incomplete.
2947 static cbl_field_t *
2948 current_field(cbl_field_t * field = NULL) {
2949 static cbl_field_t *local;
2950 if( field ) local = field;
2951 gcc_assert(field_index(local));
2952 return local;
2953 }
2954
2955 static void
2956 set_real_from_capacity( const YYLTYPE& loc,
2957 cbl_field_t *field,
2958 REAL_VALUE_TYPE *r ) {
2959 if( field == current_field() ) {
2960 error_msg(loc, "cannot define %s via self-reference", field->name);
2961 return;
2962 }
2963 field->data.set_real_from_capacity(r);
2964 }
2965
2966 static struct cbl_special_name_t *
2967 special_of( const char F[], int L, const char name[] ) {
2968 struct symbol_elem_t *e = symbol_special(PROGRAM, name);
2969 if( !e ) {
2970 dbgmsg("%s:%d: no special symbol '%s' found", F, L, name);
2971 return NULL;
2972 }
2973 return cbl_special_name_of(e);
2974 }
2975 #define special_of( F ) special_of(__func__, __LINE__, (F))
2976
2977 static const special_name_t *
2978 cmd_or_env_special_of( std::string name ) {
2979 static const std::map< std::string, special_name_t > fujitsus
2980 { // Fujitsu calls these "function names", not device names
2981 { "ARGUMENT-NUMBER", ARG_NUM_e },
2982 { "ARGUMENT-VALUE", ARG_VALUE_e } ,
2983 { "ENVIRONMENT-NAME", ENV_NAME_e },
2984 { "ENVIRONMENT-VALUE", ENV_VALUE_e },
2985 };
2986
2987 std::transform(name.begin(), name.end(), name.begin(), ::toupper);
2988 auto p = fujitsus.find(name.c_str());
2989 return p != fujitsus.end()? &p->second : nullptr;
2990 }
2991
2992 static inline void
2993 parser_add2( const cbl_num_result_t& to,
2994 const cbl_refer_t& from ) {
2995 parser_add(to.refer, to.refer, from, to.rounded);
2996 }
2997
2998 static inline void
2999 parser_subtract2( const cbl_num_result_t& to,
3000 const cbl_refer_t& from ) {
3001 parser_subtract(to.refer, to.refer, from, to.rounded);
3002 }
3003
3004 static bool
3005 parser_move_carefully( const char */*F*/, int /*L*/,
3006 tgt_list_t *tgt_list,
3007 const cbl_refer_t& src,
3008 bool is_index )
3009 {
3010 for( const auto& num_result : tgt_list->targets ) {
3011 const cbl_refer_t& tgt = num_result.refer;
3012
3013 if( is_index ) {
3014 if( tgt.field->type != FldIndex && src.field->type != FldIndex) {
3015 error_msg(src.loc, "invalid SET %s (%s) TO %s (%s): not a field index",
3016 tgt.field->name, cbl_field_type_str(tgt.field->type),
3017 src.field->name, cbl_field_type_str(src.field->type));
3018 delete tgt_list;
3019 return false;
3020 }
3021 } else {
3022 if( ! valid_move( tgt.field, src.field ) ) {
3023 if( src.field->type == FldPointer &&
3024 tgt.field->type == FldPointer ) {
3025 if( dialect_mf() || dialect_gnu() ) return true;
3026 dialect_error(src.loc, "MOVE POINTER", "mf");
3027 }
3028 if( ! is_index ) {
3029 char ach[16];
3030 char stype[32];
3031 char dtype[32];
3032 strcpy(stype, cbl_field_type_str(src.field->type));
3033 strcpy(dtype, cbl_field_type_str(tgt.field->type));
3034
3035 if( src.field->attr & all_alpha_e )
3036 {
3037 strcpy(stype, "FldAlphabetic");
3038 }
3039 if( tgt.field->attr & all_alpha_e )
3040 {
3041 strcpy(dtype, "FldAlphabetic");
3042 }
3043 if( !(src.field->attr & scaled_e) && src.field->data.rdigits )
3044 {
3045 sprintf(ach, ".%d", src.field->data.rdigits);
3046 strcat(stype, ach);
3047 }
3048 if( !(tgt.field->attr & scaled_e) && tgt.field->data.rdigits )
3049 {
3050 sprintf(ach, ".%d", tgt.field->data.rdigits);
3051 strcat(dtype, ach);
3052 }
3053 error_msg(src.loc, "cannot MOVE '%s' (%s) to '%s' (%s)",
3054 name_of(src.field), stype,
3055 name_of(tgt.field), dtype);
3056 delete tgt_list;
3057 return false;
3058 }
3059 }
3060 }
3061 }
3062 size_t ntgt = tgt_list->targets.size();
3063 std::vector <cbl_refer_t> tgts(ntgt);
3064 std::transform( tgt_list->targets.begin(), tgt_list->targets.end(), tgts.begin(),
3065 []( const cbl_num_result_t& res ) { return res.refer; } );
3066 parser_move(ntgt, tgts.data(), src);
3067 delete tgt_list;
3068 return true;
3069 }
3070 #define parser_move2(P, S) \
3071 parser_move_carefully(__func__, __LINE__, (P), (S), false)
3072 #define parser_index(P, S) \
3073 parser_move_carefully(__func__, __LINE__, (P), (S), true)
3074
3075 static void
3076 ast_set_pointers( const list<cbl_num_result_t>& tgts, cbl_refer_t src ) {
3077 assert(!tgts.empty());
3078 assert(src.field || src.prog_func);
3079 size_t nptr = tgts.size();
3080 std::vector <cbl_refer_t> ptrs(nptr);
3081
3082 std::transform( tgts.begin(), tgts.end(), ptrs.begin(), cbl_num_result_t::refer_of );
3083 parser_set_pointers(nptr, ptrs.data(), src);
3084 }
3085
3086 void
3087 stringify( refer_collection_t *inputs,
3088 const cbl_refer_t& into, const cbl_refer_t& pointer,
3089 cbl_label_t *on_error = NULL,
3090 cbl_label_t *not_error = NULL);
3091
3092 void unstringify( const cbl_refer_t& src, refer_list_t *delimited,
3093 unstring_into_t * into,
3094 cbl_label_t *on_error = NULL,
3095 cbl_label_t *not_error = NULL );
3096
3097 static cbl_label_t *
3098 implicit_paragraph()
3099 {
3100 cbl_name_t name;
3101 sprintf(name, "_implicit_paragraph_" HOST_SIZE_T_PRINT_UNSIGNED,
3102 (fmt_size_t)symbol_index());
3103 // Programs have to start with an implicit paragraph
3104 return label_add(LblParagraph, name, yylineno);
3105 }
3106 static cbl_label_t *
3107 implicit_section()
3108 {
3109 cbl_name_t name;
3110 sprintf(name, "_implicit_section_" HOST_SIZE_T_PRINT_UNSIGNED,
3111 (fmt_size_t)symbol_index());
3112 // Programs have to start with an implicit section
3113 return label_add(LblSection, name, yylineno);
3114 }
3115
3116 static void
3117 // cppcheck-suppress constParameterPointer
3118 ast_enter_exit_section( cbl_label_t * section ) {
3119 auto implicit = section? implicit_paragraph() : NULL;
3120
3121 struct { cbl_label_t *para, *sect;
3122 inline bool exists() const { return sect != NULL && para != NULL; }
3123 } prior = {
3124 current.new_paragraph(implicit),
3125 current.new_section(section)
3126 };
3127 if( false && yydebug ) {
3128 fprintf(stderr, "( %d ) %s:%d: leaving section %s paragraph %s\n",
3129 yylineno, __func__, __LINE__,
3130 prior.sect? prior.sect->name : "''",
3131 prior.para? prior.para->name : "''");
3132 }
3133 if( prior.exists() ) {
3134 parser_leave_paragraph(prior.para);
3135 parser_leave_section(prior.sect);
3136 }
3137 if( section ) {
3138 parser_enter_section(section);
3139 parser_enter_paragraph(implicit);
3140 }
3141 }
3142
3143 static inline void
3144 ast_enter_section( cbl_label_t * section ) {
3145 assert(section);
3146 section->lain = yylineno;
3147 ast_enter_exit_section( section );
3148 }
3149
3150 static inline void
3151 ast_exit_section() {
3152 ast_enter_exit_section( NULL );
3153 }
3154
3155 static void
3156 ast_enter_paragraph( cbl_label_t * para ) {
3157 para->lain = yylineno;
3158 cbl_label_t *prior = current.new_paragraph(para);
3159 if( prior ) {
3160 parser_leave_paragraph(prior);
3161 }
3162 parser_enter_paragraph(para);
3163 }
3164
3165 static bool
3166 data_division_ready() {
3167 // Install and use any alphabets.
3168 if( nparse_error == 0 ) { // error might have stemmed from the alphabet itself
3169 const char *name = current.collating_sequence();
3170
3171 if( ! symbols_alphabet_set(PROGRAM, name) ) {
3172 error_msg(yylloc, "no alphabet '%s' defined", name);
3173 return false;
3174 }
3175 }
3176
3177 // Tell codegen about symbols.
3178 static size_t nsymbol = 0;
3179 if( (nsymbol = symbols_update(nsymbol, nparse_error == 0)) > 0 ) {
3180 if( ! literally_one ) {
3181 literally_one = new_literal("1");
3182 literally_zero = new_literal("0");
3183 }
3184 }
3185
3186 if( nsymbol == 0 || nparse_error > 0 ) {
3187 dbgmsg( HOST_SIZE_T_PRINT_DEC " errors in DATA DIVISION, compilation ceases",
3188 (fmt_size_t)nparse_error );
3189 return false;
3190 }
3191
3192 return true;
3193 }
3194
3195 static
3196 bool
3197 anybody_redefines( const cbl_field_t *tree )
3198 {
3199 bool retval = false;
3200 while(tree)
3201 {
3202 if( symbol_redefines(tree) )
3203 {
3204 retval = true;
3205 break;
3206 }
3207 // cppcheck-suppress [unreadVariable] obviously not true
3208 tree = parent_of(tree);
3209 }
3210 return retval;
3211 }
3212
3213 static bool
3214 procedure_division_ready( YYLTYPE loc, cbl_field_t *returning, ffi_args_t *ffi_args ) {
3215 auto prog = cbl_label_of(symbols_begin(current.program_index()));
3216
3217 if( prog->type == LblFunction ) {
3218 if( ! returning ) {
3219 error_msg(loc, "FUNCTION %s requires RETURNING", prog->name);
3220 return false;
3221 } else {
3222 prog->returning = field_index(returning);
3223 }
3224 current.udf_update(ffi_args);
3225 }
3226
3227 if( returning ) {
3228 if( ! (returning->level == 1 || returning->level == 77) ) {
3229 error_msg(loc, "RETURNING %s must be level 01 or 77", returning->name);
3230 }
3231 if( symbol_redefines(returning) ) {
3232 error_msg(loc, "RETURNING %s cannot REDFINE anything", returning->name);
3233 }
3234 }
3235 if( ffi_args ) {
3236 size_t i=0;
3237 for( const auto& arg : ffi_args->elems ) {
3238 auto field = arg.refer.field;
3239 i++;
3240 if( returning == field ) {
3241 error_msg(loc, "RETURNING %s duplicates USING parameter %zu",
3242 returning->name, i);
3243 }
3244 if( ! (field->level == 1 || field->level == 77) ) {
3245 error_msg(loc, "USING %s must be level 01 or 77",
3246 field->name);
3247 }
3248 if( symbol_redefines(field) ) {
3249 error_msg(loc, "USING %s cannot REDEFINE anything",
3250 field->name );
3251 }
3252 }
3253 }
3254
3255 // Apply ECs from the command line
3256 std::list<exception_turn_t>& exception_turns = current.pending_exceptions();
3257 for( const auto& exception_turn : exception_turns) {
3258 apply_cdf_turn(exception_turn);
3259 }
3260 exception_turns.clear();
3261
3262 // Start the Procedure Division.
3263 size_t narg = ffi_args? ffi_args->elems.size() : 0;
3264 std::vector <cbl_ffi_arg_t> args(narg);
3265 cbl_ffi_arg_t*pargs = NULL;
3266 if( narg > 0 ) {
3267 std::copy(ffi_args->elems.begin(), ffi_args->elems.end(), args.begin());
3268 pargs = args.data();
3269 }
3270
3271 // Create program initialization section. We build it on an island,
3272 // that gets executed only if the program is IS INITIAL, or when the
3273 // program is the subject of a CANCEL statement.
3274
3275 static const char init[] = "_INITIALIZE_PROGRAM";
3276 static const char tini[] = "_INITIALIZE_DONE";
3277
3278 struct cbl_label_t * init_label = label_add(LblSection, init, yylineno);
3279 struct cbl_label_t * tini_label = label_add(LblSection, tini, yylineno);
3280
3281 // parser_division(procedure_div_e) needs initial_section:
3282 prog->initial_section = symbol_index(symbol_elem_of(init_label));
3283
3284 if( current.program_index() > 1 ) {
3285 ast_exit_section();
3286 }
3287 parser_division( procedure_div_e, returning, narg, pargs );
3288
3289 std::for_each( symbols_begin(current.program_index()), symbols_end(),
3290 []( auto& elem ) {
3291 if( elem.type == SymField ) {
3292 auto f = cbl_field_of(&elem);
3293 if( f->has_attr(local_e) ) {
3294 parser_local_add(f);
3295 }
3296 }
3297 } );
3298
3299 // At this point we count up the number of variables that will need to be
3300 // initialized in _INITIALIZE_PROGRAM:
3301 int count_of_variables = 0;
3302 for( symbol_elem_t *e =
3303 symbols_begin(1 + current.program_index());
3304 e < symbols_end(); e++ ) {
3305 if( is_program(*e) ) break;
3306 if( e->type != SymField ) continue;
3307 cbl_field_t *f = cbl_field_of(e);
3308 if( !f->var_decl_node )
3309 {
3310 // This can happen when there was an error parsing the data division
3311 continue;
3312 }
3313 if( f->type == FldForward ) continue;
3314 if( f->type == FldLiteralA ) continue;
3315 if( anybody_redefines(f) ) continue;
3316 if( f->has_attr(linkage_e) ) continue;
3317 if( f->has_attr(local_e) ) continue;
3318 if( f->is_typedef() ) {
3319 auto isym = end_of_group( symbol_index(e) );
3320 e = symbol_at(--isym);
3321 continue;
3322 }
3323 count_of_variables += 1;
3324 }
3325 // Allocate space for the static table of variables
3326 parser_init_list_size(count_of_variables);
3327
3328 // Do a second pass:
3329 // Initialize the static table with the variables:
3330 for( symbol_elem_t *e =
3331 symbols_begin(1 + current.program_index());
3332 e < symbols_end(); e++ ) {
3333 if( is_program(*e) ) break;
3334 if( e->type != SymField ) continue;
3335 cbl_field_t *f = cbl_field_of(e);
3336 if( !f->var_decl_node )
3337 {
3338 // This can happen when there was an error parsing the data division
3339 continue;
3340 }
3341 if( f->type == FldForward ) continue;
3342 if( f->type == FldLiteralA ) continue;
3343 if( anybody_redefines(f) ) continue;
3344 if( f->has_attr(linkage_e) ) continue;
3345 if( f->has_attr(local_e) ) continue;
3346 if( f->is_typedef() ) {
3347 auto isym = end_of_group( symbol_index(e) );
3348 e = symbol_at(--isym);
3349 continue;
3350 }
3351 parser_init_list_element(f);
3352 }
3353
3354 // This is where we jump over the island
3355 parser_label_goto(tini_label);
3356
3357 // And here we create the initialization section:
3358 ast_enter_section(init_label); // _INITIALIZE_PROGRAM section.
3359
3360 parser_init_list();
3361
3362 // Lay down an implicit section to end the init_label
3363 ast_enter_section(implicit_section());
3364
3365 // This is the end of the island
3366 parser_label_label(tini_label);
3367
3368 if( current.program()->initial ) {
3369 // We perform the section we just layed down when IS INITIAL
3370 parser_perform(init_label);
3371 }
3372 return true;
3373 }
3374
3375 static size_t file_section_fd;
3376 static size_t current_sort_file;
3377
3378 static bool
3379 file_section_fd_set( file_entry_type_t type, char name[], const YYLTYPE& loc ) {
3380 static std::set<size_t> has_fd;
3381
3382 // File must have been uniquely created by SELECT.
3383 // FD names are also unique within a program.
3384 auto e = symbol_file(PROGRAM, name);
3385 if( !e ) {
3386 error_msg(loc, "file name not found");
3387 return false;
3388 }
3389
3390 file_section_fd = symbol_index(e);
3391 auto result = has_fd.insert(file_section_fd);
3392 if( !result.second ) {
3393 auto f = cbl_file_of(e);
3394 const char *type_str = "???";
3395 switch(type) {
3396 case fd_e: type_str = "FD"; break;
3397 case sd_e: type_str = "SD"; break;
3398 }
3399 error_msg(loc, "%s %s previously defined on line %d",
3400 type_str, f->name, f->line);
3401 return false;
3402 }
3403
3404 auto& file(*cbl_file_of(e));
3405 file.entry_type = type;
3406
3407 if( file.org == file_disorganized_e ) {
3408 file.org = file_sequential_e;
3409 }
3410
3411 return file_section_fd > 0;
3412 }
3413
3414 /*
3415 * While in the File Section, set the parent of each 01 to be the FD
3416 * default_record, and its file member to the file's symbol index.
3417 */
3418 static bool
3419 file_section_parent_set( cbl_field_t *field ) {
3420 if( symbol_at(file_section_fd)->type == SymFile ) {
3421 auto file = cbl_file_of(symbol_at(file_section_fd));
3422 auto record_area = cbl_field_of(symbol_at(file->default_record));
3423
3424 record_area->data.capacity = std::max(record_area->data.capacity,
3425 field->data.capacity);
3426
3427 field->file = file_section_fd;
3428 const auto redefined = symbol_redefines(record_area);
3429 field->parent = redefined? record_area->parent : file->default_record;
3430 }
3431 return file_section_fd > 0;
3432 }
3433
3434 void ast_call(const YYLTYPE& loc, cbl_refer_t name,
3435 const cbl_refer_t& returning,
3436 size_t narg, cbl_ffi_arg_t args[],
3437 cbl_label_t *except,
3438 cbl_label_t *not_except,
3439 bool is_function );
3440
3441 cbl_field_t *
3442 ast_file_status_between( file_status_t lower, file_status_t upper );
3443
3444 void internal_ebcdic_lock();
3445 void internal_ebcdic_unlock();
3446
3447 void
3448 ast_end_program(const char name[] ) {
3449 std::for_each( symbols_begin(), symbols_end(),
3450 []( const auto& elem ) {
3451 if( elem.type == SymLabel ) {
3452 auto& L( *cbl_label_of(&elem) );
3453 if( L.used ) {
3454 if( ! L.lain ) {
3455 YYLTYPE loc { L.line, 1, L.line, 1 };
3456 error_msg(loc, "line %d: %s "
3457 "is used on line %d and never defined",
3458 L.line, L.name, L.used );
3459 }
3460 dbgmsg("label: %.20s: %d/%d/%d",
3461 L.name, L.line, L.lain, L.used);
3462 }
3463 }
3464 } );
3465 if( current_program_index() == 0 ) {
3466 parser_program_hierarchy( cbl_prog_hier_t() );
3467 } else {
3468 ast_exit_section();
3469 }
3470 parser_end_program(name);
3471 internal_ebcdic_unlock();
3472 }
3473
3474 static bool
3475 goodnight_gracie() {
3476 const cbl_label_t *prog = current.program();
3477 assert(prog);
3478
3479 std::set<std::string> externals = current.end_program();
3480
3481 if( !externals.empty() ) {
3482 for( const auto& name : externals ) {
3483 yywarn("%s calls external symbol '%s'",
3484 prog->name, name.c_str());
3485 }
3486 return false;
3487 }
3488
3489 // pointer still valid because name is in symbol table
3490 ast_end_program(prog->name);
3491 return true;
3492 }
3493
3494 // false after USE statement, to enter Declarative with EC intact.
3495 static bool statement_cleanup = true;
3496 static YYLTYPE current_location;
3497
3498 static void statement_epilog( int token );
3499
3500 const char * keyword_str( int token );
3501
3502 const YYLTYPE& cobol_location() { return current_location; }
3503
3504 static inline void
3505 location_set( const YYLTYPE& loc ) {
3506 current_location = loc;
3507 gcc_location_set(loc);
3508 }
3509
3510 static void statement_begin( const YYLTYPE& loc, int token );
3511
3512 static void ast_first_statement( const YYLTYPE& loc ) {
3513 if( current.is_first_statement( loc ) ) {
3514 parser_first_statement(loc.first_line);
3515 }
3516 }
3517
3518 #pragma GCC diagnostic push