~jdpipe/ascend/trunk-old

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
%{
/*	ASCEND modelling environment
	Copyright (C) 1990, 1993, 1994 Thomas Guthrie Epperly
	Copyright (C) 2006, 2010 Carnegie Mellon University

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2, or (at your option)
	any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*//** @file
	ASCEND lexer

	This module is the input file for Flex (Lexical Analyzer
	Generator). Its goal is to convert a stream of characters into a
	stream of tokens.  It has been defined to be consistent with the
	routines required by the common compiler-compiler yacc.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "../general/platform.h"
#include "../general/ascMalloc.h"
#include "../general/config.h"
#include "../compiler/compiler.h"

/* everything between here and the next comment is only here... */
#include "../compiler/fractions.h"
#include "../compiler/dimen.h"
#include "../compiler/functype.h"
#include "../compiler/func.h"
#include "../compiler/expr_types.h"
#include "../compiler/stattypes.h"
#include "../compiler/fractions.h"
#include "../compiler/proc.h"
/* ...because ascParse.h has a nasty union we can't digest without them. */
#include "../compiler/ascParse.h"

/* these below we actually need */
#include "../general/list.h"
#include "../compiler/module.h"
#include "../compiler/scanner.h"
#include "../compiler/symtab.h"
#include "../compiler/parser.h"

#define YY_BREAK
/*  Defining yybreak as above means that all of our matches must end
 *  in break or return because the normal flex supplied yybreak will
 *  be preempted by our empty one.
 *  In cases where matches contain a conditional return, make sure a
 *  break follows in the failure case.
 */

#define ENDTOK 0
/*  Return value when we reach the end of the input.
 *  This to must be 0 or negative according to yacc
 */

#define MAX_REQUIRE_DEPTH 10
/*  The maximum number of REQUIREd file nesting we will accept.
 *  See RequireStack below.
 */

#define WORKBUF_INIT_SIZE 4095
/*  We need a temporary buffer to copy yytext into before returning
 *  to the scanner (see g_workbuf below).
 *  WORKBUF_INIT_SIZE is the initial size of g_workbuf
 */

static unsigned long yy_line = 1;
/*  The current line number;
 *  every match of newline (\n) needs to ++ this variable.
 */

static unsigned long start_line = 0;
/*  The ine number where an open-comment, open-brace, or
 *  open-double-quote occurs.  We use this to help in error reporting.
 */

static int CommentNestLevel = 0;
/*  Nesting level of (* comments *)
 */

static int BracesNestLevel = 0;
/*  Nesting level of {braced} expressions
 */

static int MatchedBackslash = 0;
/*  If this variable is positive, we matched a backslash \ in a DoubleQuote
 *  or BracedText state, and we should call ProcessBackslashes() to
 *  process them.
 */

static int RequireIndex = 0;
/*  The current nesting level of REQUIREd files
 */

static YY_BUFFER_STATE RequireStack[MAX_REQUIRE_DEPTH];
/* The Flex buffers used for the REQUIREd files
 */

static char *g_workbuf = NULL;
/*  We need a place to keep doubly-quoted-text and braced-text for passing
 *  it back to the parser.  yytext will not work since the parser may ask
 *  the scanner to read another token, at which point the value in yytext
 *  gets lost.
 *
 *  The initial size of g_workbuf is WORKBUF_INIT_SIZE, and g_workbuf
 *  doubles when it needs more space.
 *
 *  A call to CopyIntoWorkBuffer(yytext,yyleng) will copy yyleng characters
 *  of yytext into the working buffer.
 *
 *  Note that having a single work buffer will not work if we ever create
 *  yacc productions that scan multiple chunks of doubly-quoted-text and/or
 *  braced-text before acting on them.
 */


/*  Forward declaration of functions
 *  provided at the end of this file.
 */
static int Asc_ScannerPopBuffer(void);
static char *CopyIntoWorkBuffer(CONST char *, unsigned long);
static int Process_Backslashes(void);
static void ErrMsg_BracesEOF(void);
static void ErrMsg_CommentEOF(void);
static void ErrMsg_DoubleQuoteEOF(void);
static void ErrMsg_LongID(void);
static void ErrMsg_LongSymbol(void);
static void ErrMsg_SymbolEOF(void);
static void ErrMsg_SymbolEOL(void);
static void ErrMsg_UnexpectedChar(void);

%}

%x Comment
%x Symbol
%x BracedText
%x DoubleQuote

blank        [\f\r\t\v ]
digit        [0-9]
letter       [a-zA-Z]

exp          ([eE][-+]?{digit}+)
real         (((({digit}+"."{digit}*)|("."{digit}+)){exp}?)|({digit}+{exp}))
integer      {digit}+
IDChar       {letter}({integer}|{letter}|_)*

%%

<INITIAL>"<="			{ return LEQ_TOK; }
<INITIAL>">="			{ return GEQ_TOK; }
<INITIAL>"<>"			{ return NEQ_TOK; }
<INITIAL>".."			{ return DOTDOT_TOK; }
<INITIAL>"::"			{ return DBLCOLON_TOK;}
<INITIAL>":="			{ return ASSIGN_TOK; }
<INITIAL>":=="			{ return CASSIGN_TOK; }
<INITIAL>"=="			{ return BEQ_TOK ; }
<INITIAL>"!="			{ return BNE_TOK ; }

<INITIAL>"="			{ return '=' ;}
<INITIAL>">"			{ return '>' ;}
<INITIAL>"<"			{ return '<' ;}
<INITIAL>","			{ return ',' ;}
<INITIAL>"."			{ return '.' ;}
<INITIAL>";"			{ return ';' ;}
<INITIAL>":"			{ return ':' ;}
<INITIAL>"["			{ return '[' ;}
<INITIAL>"]"			{ return ']' ;}
<INITIAL>"("			{ return '(' ;}
<INITIAL>")"			{ return ')' ;}
<INITIAL>"+"			{ return '+' ;}
<INITIAL>"-"			{ return '-' ;}
<INITIAL>"*"			{ return '*' ;}
<INITIAL>"/"			{ return '/' ;}
<INITIAL>"^"			{ return '^' ;}
<INITIAL>"|"			{ return '|' ;}

		/****  Reserved Keywords  ****/

<INITIAL>"ADD"			{ return ADD_TOK			; }
<INITIAL>"ALIASES"		{ return ALIASES_TOK		; }
<INITIAL>"AND"			{ return AND_TOK			; }
<INITIAL>"ANY"			{ return ANY_TOK			; }
<INITIAL>"ARE_ALIKE"    { return AREALIKE_TOK		; }
<INITIAL>"ARE_THE_SAME" { return ARETHESAME_TOK   ; }
<INITIAL>"ARRAY"		{ return ARRAY_TOK		; }
<INITIAL>"ATOM"			{ return ATOM_TOK			; }
<INITIAL>"BREAK"		{ return BREAK_TOK		; }
<INITIAL>"CALL"			{ return CALL_TOK			; }
<INITIAL>"CARD"			{ return CARD_TOK			; }
<INITIAL>"CASE"			{ return CASE_TOK			; }
<INITIAL>"CHECK"		{ return CHECK_TOK		; }
<INITIAL>"CHOICE"		{ return CHOICE_TOK	  	; }
<INITIAL>"CONDITIONAL"		{ return CONDITIONAL_TOK		; }
<INITIAL>"CONSTANT"		{ return CONSTANT_TOK		; }
<INITIAL>"CONTINUE"		{ return CONTINUE_TOK		; }
<INITIAL>"CREATE"		{ return CREATE_TOK		; }
<INITIAL>"DATA"			{ return DATA_TOK			; }
<INITIAL>"DECREASING"		{ return DECREASING_TOK		; }
<INITIAL>"DEFAULT"		{ return DEFAULT_TOK		; }
<INITIAL>"DEFINITION"		{ return DEFINITION_TOK		; }
<INITIAL>"DER" { return DER_TOK ; }
<INITIAL>"DIMENSION"		{ return DIMENSION_TOK		; }
<INITIAL>"DIMENSIONLESS"	{ return DIMENSIONLESS_TOK	; }
<INITIAL>"DO"			{ return DO_TOK			; }
<INITIAL>"ELSE"			{ return ELSE_TOK			; }
<INITIAL>"END"			{ return END_TOK			; }
<INITIAL>"EXPECT"		{ return EXPECT_TOK		; }
<INITIAL>"EXTERNAL"		{ return EXTERNAL_TOK		; }
<INITIAL>"FALSE"		{ return FALSE_TOK		; }
<INITIAL>"FALL_THROUGH" { return FALLTHRU_TOK		; }
<INITIAL>"FIX"		    { return FIX_TOK	        ; }
<INITIAL>"FREE"		    { return FREE_TOK	        ; }
<INITIAL>"FOR"			{ return FOR_TOK			; }
<INITIAL>"FROM"			{ return FROM_TOK			; }
<INITIAL>"GLOBAL"		{ return GLOBAL_TOK		; }
<INITIAL>"ASSERT"       { return ASSERT_TOK			; }
<INITIAL>"IF"			{ return IF_TOK			; }
<INITIAL>"'ignore'"		{ return IGNORE_TOK 	;}
<INITIAL>"INDEPENDENT" { return INDEPENDENT_TOK ;}
<INITIAL>"IMPORT"		{ return IMPORT_TOK		; }
<INITIAL>"IN"			{ return IN_TOK			; }
<INITIAL>"INCREASING"		{ return INCREASING_TOK		; }
<INITIAL>"INPUT"		{ return INPUT_TOK		; }
<INITIAL>"INTERSECTION"		{ return INTERSECTION_TOK		; }
<INITIAL>"IS_A"			{ return ISA_TOK			; }
<INITIAL>"IS_REFINED_TO"	{ return ISREFINEDTO_TOK		; }
<INITIAL>"LINK"   		{ return LINK_TOK		; } 
<INITIAL>"MAXIMIZE"		{ return MAXIMIZE_TOK		; }
<INITIAL>"MAX_INTEGER"		{ return MAXINTEGER_TOK		; }
<INITIAL>"MAX_REAL"		{ return MAXREAL_TOK		; }
<INITIAL>"METHOD"		{ return METHOD_TOK		; }
<INITIAL>"METHODS"		{ return METHODS_TOK		; }
<INITIAL>"MINIMIZE"		{ return MINIMIZE_TOK		; }
<INITIAL>"MODEL"		{ return MODEL_TOK		; }
<INITIAL>"NOT"			{ return NOT_TOK			; }
<INITIAL>"NOTES"		{ return NOTES_TOK		; }
<INITIAL>"OF"			{ return OF_TOK			; }
<INITIAL>"OPTION"		{ return OPTION_TOK			; }
<INITIAL>"OR"			{ return OR_TOK			; }
<INITIAL>"OTHERWISE"		{ return OTHERWISE_TOK		; }
<INITIAL>"OUTPUT"		{ return OUTPUT_TOK		; }
<INITIAL>"PROD"			{ return PROD_TOK			; }
<INITIAL>"PROVIDE"		{ return PROVIDE_TOK		; }
<INITIAL>"REFINES"		{ return REFINES_TOK		; }
<INITIAL>"REPLACE"		{ return REPLACE_TOK		; }
<INITIAL>"REQUIRE"		{ return REQUIRE_TOK		; }
<INITIAL>"RETURN"		{ return RETURN_TOK		; }
<INITIAL>"RUN"			{ return RUN_TOK			; }
<INITIAL>"SATISFIED"		{ return SATISFIED_TOK		; }
<INITIAL>"SELECT"		{ return SELECT_TOK		; }
<INITIAL>"SUCH_THAT"		{ return SUCHTHAT_TOK		; }
<INITIAL>"SUM"			{ return SUM_TOK			; }
<INITIAL>"SIZE"			{ return SIZE_TOK			; }
<INITIAL>"SOLVE"		{ return SOLVE_TOK		; }
<INITIAL>"SOLVER"		{ return SOLVER_TOK		; }
<INITIAL>"SWITCH"		{ return SWITCH_TOK		; }
<INITIAL>"STOP"			{ return STOP_TOK			; }
<INITIAL>"THEN"			{ return THEN_TOK			; }
<INITIAL>"TRUE"			{ return TRUE_TOK			; }
<INITIAL>"UNION"		{ return UNION_TOK		; }
<INITIAL>"UNITS"		{ return UNITS_TOK		; }
<INITIAL>"UNIVERSAL"		{ return UNIVERSAL_TOK		; }
<INITIAL>"UNLINK"   		{ return UNLINK_TOK		; } 
<INITIAL>"USE"			{ return USE_TOK			; }
<INITIAL>"VALUE"		{ return VALUE_TOK		; }
<INITIAL>"WHEN"			{ return WHEN_TOK			; }
<INITIAL>"WHERE"		{ return WHERE_TOK		; }
<INITIAL>"WHILE"		{ return WHILE_TOK		; }
<INITIAL>"WILL_BE"		{ return WILLBE_TOK		; }
<INITIAL>"WILL_BE_THE_SAME"	{ return WILLBETHESAME_TOK	; }
<INITIAL>"WILL_NOT_BE_THE_SAME"	{ return WILLNOTBETHESAME_TOK	; }
<INITIAL>"WITH"			{ return WITH_TOK			; }
<INITIAL>"WITH_VALUE"		{ return WITH_VALUE_T		; }

	/*
	 *  Code to handle (* Comments *)
	 *
	 *  "(*" puts us into the Comment state.  Comments nest, so in the
	 *  Comment state we need to look for "(*" that increases the nesting
	 *  level and "*)" that will lower it.
	 *  Flex is faster if we match as much as possible, so we repeat
	 *  patterns with and without the "\n" (although it is more difficult
	 *  for the maintainer to understand) to avoid the overhead of a
	 *  separate "\n" rule.
	 *  Do NOT try to match \(\*+ since that causes "(****)" to parse
	 *  incorrectly.
	 */

<INITIAL>\(\*			{
				  /*  Match "(" followed by "*" puts us into
				   *  the COMMENT state.  Don't use \*+ since
				   *  that will parse "(***)" incorrectly.
				   *  Initialize the nesting level.
				   *  Store the current line for ErrMsg use.
				   */
				  BEGIN (Comment);
				  CommentNestLevel = 1;
				  start_line = yy_line;
				  break;
				}
<Comment>\(\*[^*(\n]*		{
				  /*  Match "(" followed "*" followed by
				   *  anything that's not "(" nor "*".
				   *  Increase the commment nesting level.
				   */
				  CommentNestLevel++;
				  break;
				}
<Comment>\(\*[^*(\n]*\n		{
				  /*  Match "(" followed by "*" followed by
				   *  anything that's not "(" nor "*".
				   *  Increase the commment nesting level.
				   */
				  yy_line++;
				  CommentNestLevel++;
				  break;
				}
<Comment>[^*(\n]*\*+\)		{
				  /*  Match anything not "*" or "(" followed
				   *  by one or more "*"s followed by ")".
				   *  This decreases the comment nesting level
				   *  and kicks us out if we're back to zero.
				   */
				  CommentNestLevel--;
				  if (CommentNestLevel == 0) {
				    BEGIN (INITIAL);
				  }
				  break;
				}
<Comment>[^*(\n]*		{
				  /*  Eat anything that's not a "*" nor a "("
				   */
				  break;
				}
<Comment>[^*(\n]*\n		{
				  /*  Eat anything that's not a "*" nor a "("
				   *  that is followed by a newline.
				   *  This rule also matches empty line.
				   */
				  yy_line++;
				  break;
				}
<Comment>\(+[^*(\n]*		{
				  /*  Eat "("s not followed by "*"
				   */
				  break;
				}
<Comment>\(+[^*(\n]*\n		{
				  /*  Eat "("s not followed by "*" plus a "\n"
				   */
				  yy_line++;
				  break;
				}
<Comment>\*+[^*()\n]*		{
				  /*  Eat "*"s not followed by ")"
				   */
				  break;
				}
<Comment>\*+[^*()\n]*\n		{
				  /*  Eat "*" not followed by ")" plus a "\n"
				   */
				  yy_line++;
				  break;
				}
<Comment><<EOF>>		{
				  /*  An EOF in a Comment means bad nesting.
				   *  Print an error and pop back a level
				   *  or return ENDTOK if no more input.
				   */
				  ErrMsg_CommentEOF();
				  CommentNestLevel = 0;
				  if ( Asc_ScannerPopBuffer() == 1 ) {
				    return ENDTOK;
				  }
				  break;
				}


	/*
	 *  Code to handle 'Symbols'
	 *
	 *  Symbols are simple: they are 'singely quoted strings' that
	 *  exist on a single line.  Look for anything that is not
	 *  a quote or a newline to get the text of the symbol.
	 */

<INITIAL>\'			{
				  /*  A single quote (') in the INITIAL state
				   *  puts us into the Symbol state.
				   */
				  BEGIN (Symbol);
				  break;
				}
<Symbol>[^'\n]*\'		{
				  /*  Anything that is not a (') nor a newline
				   *  followed by a (') is the symbol's text.
				   *  Return to the INITIAL state, store the
				   *  symbol in the symbol table and return
				   *  SYMBOL_TOK to the parser.
				   */
				  BEGIN (INITIAL);
				  /*  strip off the final (')
				   */
				  yytext[--yyleng] = '\0';
				  if (yyleng > YY_MAXLEN) {
				    ErrMsg_LongSymbol();
				    break;
				  }
				  zz_lval.sym_ptr = AddSymbolL(yytext,yyleng);
				  return SYMBOL_TOK;
				}
<Symbol>[^'\n]*\n		{
				  /*  If we find a newline before a ('), the
				   *  symbol is unterminated.  Print an error
				   *  message and return to the INITIAL state.
				   */
				  ErrMsg_SymbolEOL();
				  yy_line++;
				  BEGIN(INITIAL);
				  break;
				}
<Symbol><<EOF>>			{
				  /*  If we find an EOF before a ('), the
				   *  symbol is unterminated.  Print an error
				   *  message and pop to the previously
				   *  REQUIREd file or return ENDTOK if the
				   *  pop fails due to no more input.
				   */
				  ErrMsg_SymbolEOF();
				  if ( Asc_ScannerPopBuffer() == 1 ) {
				    return ENDTOK;
				  }
				  break;
				}


	/*
	 *  Code to handle "Text in Double Quotes"
	 *
	 *  The DoubleQuote state begins with a double quote and ends
	 *  with a double quote; double quotes can be included by
	 *  escaping them with a backslash (e.g. \").  There is no
	 *  nesting level to worry about.
	 *  Flex is faster if we match as much as possible, so we repeat
	 *  patterns with and without the "\n" (although it is more difficult
	 *  for the maintainer to understand) to avoid the overhead of a
	 *  separate "\n" rule.
	 *  We want to keep the text, so we need to call yymore().
	 */

<INITIAL>\"			{
				  /*  A double quote puts us into the
				   *  DoubleQuote state.  Save the line
				   *  number for error reporting.
				   */
				  BEGIN (DoubleQuote);
				  start_line = yy_line;
				  break;
				}
<DoubleQuote>[^\\"\n]*\\.	{
				  /*  A backslash \ in the DoubleQuote
				   *  state protects any character.
				   */
				  MatchedBackslash++;
				  yymore();
				  break;
				}
<DoubleQuote>[^\\"\n]*\\\n	{
				  /*  A backslash \ in the DoubleQuote
				   *  state protects a newline.
				   */
				  MatchedBackslash++;
				  yy_line++;
				  yymore();
				  break;
				}
<DoubleQuote>[^\\"\n]*\"	{
				  /*  A double quote in the DoubleQuote state
				   *  (that is not protected by backslash)
				   *  will put us back in the INITIAL state.
				   *  Process the string and return DQUOTE_TOK
				   *  to the parser.
				   */
				  BEGIN (INITIAL);
				  /*  Remove the final double quote
				   */
				  yytext[--yyleng] = '\0';
				  /*  Do backslash substitutions on the string
				   *  before returing it to the scanner.
				   */
				  if ( MatchedBackslash != 0 ) {
				    Process_Backslashes();
				    MatchedBackslash = 0;
				  }
				  zz_lval.dquote_ptr =
				      CopyIntoWorkBuffer(yytext,yyleng);
				  return DQUOTE_TOK;
				}
<DoubleQuote>[^\\"\n]*		{
				  /*  Match anything that is not backslash nor
				   *  doublequote and add it to the text.
				   */
				  yymore();
				  break;
				}
<DoubleQuote>[^\\"\n]*\n	{
				  /*  Match anything that is not backslash nor
				   *  doublequote and add it to the text.
				   *  This also matches an empty line.
				   */
				  yy_line++;
				  yymore();
				  break;
				}
<DoubleQuote><<EOF>>		{
				  /*  End of File in a DoubleQuote state
				   *  means no matching double quote.
				   *  Print an error and pop next buffer
				   *  off the RequireStack or return ENDTOK
				   *  if there is no more input.
				   */
				  ErrMsg_DoubleQuoteEOF();
				  MatchedBackslash = 0;
				  if ( Asc_ScannerPopBuffer() == 1 ) {
				    return ENDTOK;
				  }
				  break;
				}


	/*
	 *  Code to handle { Text in Braces }
	 *
	 *  "{" puts us into the BracedText state.	Braces nest, so
	 *  in the BracedText state we need to look for "{" that increases
	 *  the nesting level and "}" that will lower it.
	 *  Flex is faster if we match as much as possible, so we repeat
	 *  patterns with and without the "\n" (although it is more difficult
	 *  for the maintainer to understand) to avoid the overhead of a
	 *  separate "\n" rule.
	 *  We want to keep the text we scan, so we have to call yymore().
	 */

<INITIAL>\{{blank}*\n		{ /*  A "{" puts us into the BracedText state.
				   *  If from the opening "{" to the first
				   *  newline is all whitespace, then ignore
				   *  it.
				   *  Initialize the nesting level.
				   *  Save the current line number for
				   *  error message reporting.
				   */
				  BEGIN (BracedText);
				  BracesNestLevel = 1;
				  start_line = yy_line;
				  yy_line++;
				  break;
				}
<INITIAL>\{			{
				  /*  A "{" puts us into the BracedText state.
				   *  Initialize the nesting level.
				   *  Save the current line number for
				   *  error message reporting.
				   */
				  BEGIN (BracedText);
				  BracesNestLevel = 1;
				  start_line = yy_line;
				  break;
				}
<BracedText>[^\\{}\n]*\\.	{
				  /*  A backslash \ in the BracedText state
				   *  protects any character and does not
				   *  affect the Nesting Level.
				   */
				  MatchedBackslash++;
				  yymore();
				  break;
				}
<BracedText>[^\\{}\n]*\\\n	{
				  /*  A backslash \ in the BracedText state
				   *  protects a newline.
				   */
				  MatchedBackslash++;
				  yy_line++;
				  yymore();
				  break;
				}
<BracedText>\{[^\\{}\n]*	{
				  /*  A "{" in the braces state gets added to
				   *  the text and increase the nesting level.
				   */
				  BracesNestLevel++;
				  yymore();
				  break;
				}
<BracedText>\{[^\\{}\n]*\n	{
				  /*  A "{" in the braces state gets added to
				   *  the text and increase the nesting level.
				   */
				  yy_line++;
				  BracesNestLevel++;
				  yymore();
				  break;
				}
<BracedText>[^\\{}\n]*\}	{
				  /*  A "}" will reduce the nesting level.
				   *  If the nesting level is zero, go back to
				   *  the INITIAL level, save the text as a
				   *  Symbol, do the backslash substitution,
				   *  and return BRACEDTEXT_TOK to the
				   *  parse; otherwise, add the "}" to the
				   *  text and keep scanning.
				   */
				  BracesNestLevel--;
				  if (BracesNestLevel == 0) {
				    BEGIN (INITIAL);
				    /*	Remove the final "}"
				     */
				    yytext[--yyleng] = '\0';
				    /*	Do backslash substitutions on the text
				     *	before returing it to the scanner.
				     */
				    if ( MatchedBackslash != 0 ) {
				      Process_Backslashes();
				      MatchedBackslash = 0;
				    }
				    zz_lval.braced_ptr =
				        CopyIntoWorkBuffer(yytext,yyleng);
				    return BRACEDTEXT_TOK;
				  }
				  yymore();
				  break;
				}
<BracedText>[^\\{}\n]*		{
				  /*  Match anything that is not "{" nor "}"
				   *  nor "\\"(backslash) and add it to text.
				   */
				  yymore();
				  break;
				}
<BracedText>[^\\{}\n]*\n		{
				  /*  Match anything that is not "{" nor "}"
				   *  nor "\\"(backslash) followed by a "\n"
				   *  and add it to text.
				   *  This also matches an empty line.
				   */
				  yy_line++;
				  yymore();
				  break;
				}
<BracedText><<EOF>>		{
				  /*  End of File in braces means bad nesting.
				   *  Print an error message and pop to the
				   *  previously REQUIREd file or return
				   *  ENDTOK if no more input.
				   */
				  ErrMsg_BracesEOF();
				  BracesNestLevel = 0;
				  MatchedBackslash = 0;
				  if ( Asc_ScannerPopBuffer() == 1 ) {
				    return ENDTOK;
				  }
				  break;
				}


	/*
	 *  Code to handle Miscellaneous types.
	 *
	 */

<INITIAL>{integer}		{
				  /*  An integer.  Defn near top of file.
				   */
				  zz_lval.int_value = atol(yytext);
				  return INTEGER_TOK;
				}

<INITIAL>{integer}/".."		{
				  /*  An integer as the first number in a
				   *  range (need to avoid parsing "1..2"
				   *  as the real numbers 1.0 and 0.2).
				   */
				  zz_lval.int_value = atol(yytext);
				  return INTEGER_TOK;
				}

<INITIAL>{real}			{
				  /*  A real number.  Defn near top of file.
				   */
				  zz_lval.real_value = atof(yytext);
				  return REAL_TOK;
				}

<INITIAL>{IDChar}+		{
				  /*  An identifier.  Defn near top of file.
				   */
				  if (yyleng >YY_MAXLEN) {
				    ErrMsg_LongID();
				    break;
				  }
				  zz_lval.id_ptr = AddSymbolL(yytext,yyleng);
				  return IDENTIFIER_TOK;
				}

<INITIAL>{blank}*		{
				  /*  Ignore whitespace.  */
				  break;
				}
<INITIAL>{blank}*\n		{
				  /*  Ignore whitespace.  */
				  yy_line++;
				  break;
				}


<INITIAL>.			{
				  /*  Unknown character.  Print error
				   *  message and keep going.
				   */
				  ErrMsg_UnexpectedChar();
				  break;
				}

<INITIAL><<EOF>>		{
				  /*  Print an error message if we
				   *  reached EOF in the middle of a
				   *  type definition.	Pop to the
				   *  previously REQUIREd file or return
				   *  ENDTOK if no more input.
				   */
				  Asc_ErrMsgTypeDefnEOF();
				  if ( Asc_ScannerPopBuffer() == 1 ) {
				    return ENDTOK;
				  }
				  break;
				}

%%
/*
 *  int yywrap(void);
 *
 *  This returns 1 if the scanner should stop parsing, or
 *  0 if the scanner should continue.  Flex requires this
 *  function unless %option noyywrap is defined.
 */
int
yywrap(void)
{
  return 1;
}


/*
 *  See the header file scanner.h for a description of this function.
 */
unsigned long
LineNum(void)
{
  return yy_line;
}


/*
 *  See the header file scanner.h for a description of this function.
 */
void
Asc_ScannerAssignFile(FILE *f, unsigned long linenum)
{
  yyin = f;
  yy_line = linenum;
  if ( RequireIndex == 0 ) {
    yyrestart(f);
  }
}

/*
 *  See the header file scanner.h for a description of this function.
 */
void
Asc_ScannerAssignString(void *yybs, unsigned long linenum, int first)
{
  /* yyin = f; */
  yy_line = linenum;
  yy_switch_to_buffer((YY_BUFFER_STATE)yybs);
  if (first) {
    BEGIN(INITIAL);
  }
  if ( RequireIndex == 0 ) {
    yyrestart((FILE *)NULL); /* ? ? ? should be reading from a string buffer... */
  }
}


/*
 *  See the header file scanner.h for a description of this function.
 */
int
Asc_ScannerPushBuffer(CONST char *filename)
{
  int status;        /* status returned from Asc_RequireModule */
  
  if ( RequireIndex >= MAX_REQUIRE_DEPTH ) {
    FPRINTF(ASCERR,
	    "Error:\tREQUIRE nested too deeply (%d levels) on line %s:%lu.\n"
	    "\tFile \"%s\" not read.\n",
	    RequireIndex,
	    Asc_ModuleBestName(Asc_CurrentModule()),
	    yy_line,
	    filename);
    return 1;
  }

  /*  The current Flex buffer is not on the RequireStack yet, so add it
   *  before calling Asc_OpenModule.  We need to increment RequireIndex
   *  before calling Asc_OpenModule due to the check in
   *  Asc_ScannerAssignFile.
   */
  RequireStack[RequireIndex++] = YY_CURRENT_BUFFER;

  Asc_RequireModule( filename, &status );
  if( status == 5 ) {
    /* already required */
    RequireIndex--;
    /*CONSOLE_DEBUG("REQUIREd module \"%s\" already PROVIDEd", filename);*/
    return 1;
  }
  if( status == 4 ) {
    /* recursive require */
    RequireIndex--;
    ERROR_REPORTER_HERE(ASC_USER_WARNING
		,"Recursive REQUIRE for module \"%s\" (ignored)",filename
	);
    return 1;
  }
  if ( status != 0 ) {
    /*  The open failed.  Decrement RequireIndex and print an error.
     */
    RequireIndex--;
    error_reporter(ASC_USER_ERROR
		,Asc_ModuleBestName(Asc_CurrentModule()),yy_line,NULL
		,"REQUIRE cannot open module \"%s\""
	    ,filename
	);
    return 2;
  }

  /*  Asc_OpenModule was successful, so print a message, switch to the
   *  new buffer in the INITIAL state.
   * SHOULD never reach here with a string buffer as they cannot be
   * REQUIREd.
   */
  /*Asc_FPrintf(stderr,"REQUIREing file \"%s\"\n", filename);*/
  yy_switch_to_buffer(yy_create_buffer(yyin,YY_BUF_SIZE));
  BEGIN (INITIAL);
  return 0;
}


/*
 *  int Asc_ScannerPopBuffer()
 *
 *  When we reach an End Of File (EOF) in the scanner, we call this
 *  function to pop us to the file which REQUIREd the file we just
 *  reached the end of and return 0.  If there are no more files on the
 *  RequireStack, return 1.
 */
static int
Asc_ScannerPopBuffer(void)
{
  Asc_CloseCurrentModule(); /* the current module may be NULL. */
  if ( RequireIndex == 0 ) {
    return 1;
  }

  yy_delete_buffer(YY_CURRENT_BUFFER);
  yy_switch_to_buffer( RequireStack[--RequireIndex] );
  BEGIN(INITIAL);
  return 0;
}

void Asc_ScannerReleaseStringBuffer(void *yybs)
{
  yy_delete_buffer((YY_BUFFER_STATE)yybs);
  yy_switch_to_buffer( RequireStack[--RequireIndex] );
  BEGIN(INITIAL);
}

void *Asc_ScannerCreateStringBuffer(CONST char *string, int len)
{
  /* we hope to god yy_scan_bytes does not change current buffer */
  YY_BUFFER_STATE yybs;
  /* push current, don't care its name or type. */
  RequireStack[RequireIndex++] = YY_CURRENT_BUFFER;
  yybs = yy_scan_bytes(string, len);
  assert(yybs);
  return (void *)yybs;
}

/*
 *  g_workbuf = CopyIntoWorkBuffer(str, len)
 *  char *g_workbuf;
 *  CONST char *str;
 *  unsigned long len;
 *
 *  Copy the string `str' having length `len' into the Scanner's Working
 *  Buffer g_workbuf and return g_workbuf if successful or NULL if
 *  unsuccessful (due to lack of memory).
 *  If g_workbuf is too short to hold `str', it is repeatably doubled until
 *  either it is big enough or memory is exhausted.
 *  We actually copy len+1 characters of `str' into g_workbuf so that the
 *  final \0 gets copied also.
 *  Global Effects: Modifies the contents of g_workbuf
 *                  Possibly changes the address of g_workbuf (on realloc)
 */
static char *
CopyIntoWorkBuffer(CONST char *str, unsigned long len)
{
  static size_t g_workbuf_len = WORKBUF_INIT_SIZE;  /* length of g_workbuf */

  assert(str[len]=='\0'); /* is this true for all yacc? */
  len++;  /* add one to make sure we have a final '\0' */
  if (( len >= g_workbuf_len ) || ( g_workbuf == NULL )) {
    while( len >= g_workbuf_len ) {
      g_workbuf_len *= 2;
    }
    if (g_workbuf == NULL ) {
      g_workbuf = ASC_NEW_ARRAY(char, g_workbuf_len );
    } else {
      g_workbuf = (char*)ascrealloc( (void*)g_workbuf, g_workbuf_len );
    }
    if ( g_workbuf == NULL ) {
      return NULL;
    }
  }
  return strncpy(g_workbuf, str, len); /* does not add a NULL char */
}


extern void
Asc_DestroyScannerWorkBuffer(void)
{
  if (g_workbuf != NULL) {
    ascfree(g_workbuf);
  }
  g_workbuf = NULL;
}

void Asc_DestroyScannerInputBuffer(void)
{
  if (YY_CURRENT_BUFFER != NULL) {
    yy_delete_buffer(YY_CURRENT_BUFFER);
  }
#ifdef ASC_HAVE_LEXDESTROY
  zz_lex_destroy();
#endif
}

/*
 *  int Process_Backslashes(void)
 *
 *  Covert any backslash \ escapes into the correct character.
 *  Operates on and modifies in place the value of yytext; yyleng
 *  is adjusted accordingly.  Returns the number of backslash
 *  substitutions made.  The following are supported:
 *      \a   (alert)
 *      \b   (backspace)
 *      \f   (formfeed)
 *      \n   (newline)
 *      \r   (carriage return)
 *      \t   (horizontal tab)
 *      \v   (vertical tab)
 *      \xhh (hexadecimal hh)              ***** NOT IMPLEMENTED *****
 *      \ooo (octal ooo where o == [0-7])  ***** NOT IMPLEMENTED *****
 *      \\n  (backslash before newline removes the backslash and newline)
 *      \.   (any other char produces that char)
 */
static int
Process_Backslashes(void)
{
  int old_index;
  int new_index;
  int substitution_count = 0;

  for (old_index=0, new_index=0; old_index<yyleng; old_index++) {
    if (yytext[old_index] != '\\') {
      yytext[new_index++] = yytext[old_index];
    } else {
      if (++old_index < yyleng) {
        switch(yytext[old_index]) {
        case 'a':
          yytext[new_index++] = '\a';
          substitution_count++;
          break;
        case 'b':
          yytext[new_index++] = '\b';
          substitution_count++;
          break;
        case 'f':
          yytext[new_index++] = '\f';
          substitution_count++;
          break;
        case 'n':
          yytext[new_index++] = '\n';
          substitution_count++;
          break;
        case 'r':
          yytext[new_index++] = '\r';
          substitution_count++;
          break;
        case 't':
          yytext[new_index++] = '\t';
          substitution_count++;
          break;
        case 'v':
          yytext[new_index++] = '\v';
          substitution_count++;
          break;
        case 'x':
          /* need to add processing for
	   * hexadecimal numbers \xhh here
           */
          yytext[new_index++] = yytext[old_index];
          substitution_count++;
          break;
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
          /* need to add processing for
	   * octal numbers \ooo here
           */
          yytext[new_index++] = yytext[old_index];
          substitution_count++;
          break;
        case '\n':
	  /*  Backslash at the end of the line removes
	   *  the slash and the newline from the result,
	   *  so no futher processing is needed.
	   */
	  substitution_count++;
	  break;
        default:
          yytext[new_index++] = yytext[old_index];
          substitution_count++;
          break;
        }
      }
    }
  }
  yytext[new_index] = '\0';
  yyleng = new_index;
  return substitution_count;
}


/*
 *  void ErrMsg_*(void)
 *
 *  The following all print error messages to the file handle ASCERR.
 *  The type of error is indicated by the function's name and the
 *  arguments to fprintf.
 */
static void
ErrMsg_BracesEOF(void){
	error_reporter(ASC_USER_ERROR, Asc_ModuleBestName(Asc_CurrentModule()), start_line, NULL
		,"End of file reached within a unit, data table or explanation. No closing brace "
		"found for open brace."
	);
}


static void
ErrMsg_CommentEOF(void)
{
  FPRINTF(ASCERR,
          "Error:\tEnd of file reached within a comment.\n"
	  "\tNo close-comment found for comment starting on line %s:%lu\n",
	  Asc_ModuleBestName(Asc_CurrentModule()), start_line);
}


static void
ErrMsg_LongID(void)
{
  FPRINTF(ASCERR,
	  "Error:\tIdentifier too long on line %s:%lu.\n"
	  "\tIdentifier \"%s\" exceeds the maximum identifier size of %d\n",
	  Asc_ModuleBestName(Asc_CurrentModule()),
	  yy_line,
	  yytext,
	  YY_MAXLEN);
}


static void
ErrMsg_LongSymbol(void)
{
  FPRINTF(ASCERR,
	  "Error:\tSymbol too long on line %s:%lu.\n"
	  "\tSymbol %s exceeds the maximum symbol size of %d\n",
	  Asc_ModuleBestName(Asc_CurrentModule()),
	  yy_line,
	  yytext,
	  YY_MAXLEN);
}


static void
ErrMsg_DoubleQuoteEOF(void)
{
  FPRINTF(ASCERR,
          "Error:\tEnd of file reached with a double quoted string.\n"
	  "\tNo close quote found for the open quote on line %s:%lu\n",
	  Asc_ModuleBestName(Asc_CurrentModule()), start_line);
}


static void
ErrMsg_SymbolEOF(void)
{
  FPRINTF(ASCERR,
          "Error:\tEnd of file reached within a symbol.\n"
	  "\tNo close quote found for symbol on line %s:%lu\n",
	  Asc_ModuleBestName(Asc_CurrentModule()), yy_line);
}


static void
ErrMsg_SymbolEOL(void)
{
  FPRINTF(ASCERR,
          "Error:\tEnd of line reached within a symbol.\n"
	  "\tNo close quote found for symbol on line %s:%lu\n",
	  Asc_ModuleBestName(Asc_CurrentModule()), yy_line);
}

#define ERRCOUNT_UNEXPCHAR 5
static void ErrMsg_UnexpectedChar(){
	static int errcount=0;
	if(errcount<ERRCOUNT_UNEXPCHAR){
		error_reporter(ASC_USER_ERROR
			,Asc_ModuleBestName(Asc_CurrentModule()), yy_line, NULL
			,"Unexpected character '%s' in input (ASCII %d). If you pasted"
			" text from another source (a word-processor, web page, etc) be"
			" careful that you haven't pasted strange quotes, hyphens, etc."
			, yytext, yytext[0]
		);
		errcount++;
		if(errcount==ERRCOUNT_UNEXPCHAR){
			ERROR_REPORTER_HERE(ASC_PROG_NOTE
				,"Further reports of this error will be supressed\n"
			);
		}
	}
}