-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb-adv-c2.tex
2765 lines (1783 loc) · 58.3 KB
/
b-adv-c2.tex
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
%%{{{ Lex and YACC
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Lexical and Syntactical Analysis with Lex and YACC}
The capability
\begin{itemize}
\item to compose valid sentences in a given language, as well as
\item to verify that a given string represents a valid sentence
in a given language
\end{itemize}
builds upon two lower level capabilities:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Lexical and Syntactical Analysis with Lex and YACC}
\begin{enumerate}
\item classification: the capability of decomposing a stream
of characters into a stream of lexical entities (words,
punctuation, delimiters) (lexical analysis), and
\item verification: the capability to recognize the
syntactical correctness of a sentence, starting from a
stream of lexical entities (syntactical analysis).
\end{enumerate}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Lexical and Syntactical Analysis}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Given, for instance, the mathematical expression:
$$ sin (a+\sqrt(0.4)) $$
\vspace{20pt}
\begin{enumerate}
\item the first capability means translating the stream of characters
that corresponds to the above expression, i.e.,
\vspace{20pt}
({\tt 's'}, {\tt 'i'}, {\tt 'n'}, {\tt ' '},{\tt '('}, {\tt 'a'}, ...)
\vspace{20pt}
into a stream of tokens, or syntactical atoms:
\vspace{20pt}
({\tt "sin"}, {\tt '('}, {\tt "a"}, {\tt '+'}, {\tt "sqrt"}, ...)
\item the second capability is the one
that allows us to verify the syntactical correctness of the sentence,
given a certain ``grammar,'' i.e., in this case, the grammar of
well-formed mathematical formulae.
\end{enumerate}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Lexical and Syntactical Analysis}
The above mentioned capabilities are experienced by the human being
as inherent and natural abilities, of which one has not even full
awareness.
\vspace{20pt}
When one has to set up, e.g., an interpreter of a computer language,
or any other software module that needs to recognize a given
structure in its input stream, then it is useful to set up
a hierarchical structure at the base of which there are tools
for lexical and syntactical analysis.
\vspace{20pt}
These tools are software systems that ease the development of
lexical and syntactical analyzers. In UNIX, for instance,
two standard utilities are available: Lex and YACC
(or their GNU equivalents: flex and bison!)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Lexical and Syntactical Analysis}
Lex and YACC allow to speed up considerably the development
of parsers, translators, compilers, interpreter, conversion tools.
\vspace{20pt}
They have been especially designed for combined use and for
hosting user-defined C routines where needed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX: a lexical analyzer generator}
LEX may be defined as a ``tokenizator'': given a stream of
chars, LEX performs a classification of groups of contiguous
characters. These groups are called tokens, i.e., words and
symbols that are \emph{atomic\/} from the viewpoint of
syntactical analysis.
\vspace{20pt}
For instance, LEX can translate string
$ sin (a+sqrt(0.4)) $
in a set of couples ``(token, token \#)'', e.g., as follows:
\begin{itemize}
\item ``sin'', {\tt FUNCTION}
\item ``('', {\tt '('}
\item and so forth.
\end{itemize}
\vspace{20pt}
The token \# identifies the class the token belongs to.
\end{frame}
\begin{frame}[fragile]{LEX}
LEX can be used
\begin{itemize}
\item either as a stand-alone tool, so to perform simple
translations or compute statistics on the lexycal atoms,
\item or in conjunction with a parser generator (e.g., YACC).
\end{itemize}
\vspace{20pt}
$$ \mbox{input}
\stackrel{\mbox{\tiny LEX}}{\Rightarrow}
\mbox{tokens / errors}
\stackrel{\mbox{\tiny YACC}}{\Rightarrow}
\mbox{valid / invalid sentences}
\stackrel{\mbox{\tiny User code}}{\Rightarrow}
\mbox{user-defined actions}
$$
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX}
LEX writes a deterministic FSA from a list of \textbf{regular expressions}
(regex). Regardless the number of rules supplied by the user, and regardless
their complexity, the LEX FSA breaks the input stream into tokens
in a time that is proportional to the length of the input stream.
\vspace{20pt}
The number of rules and their complexity only influence
\emph{the size\/} of the output source code.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Structure of a LEX program}
The general structure of a LEX program is as follows:
\vspace{20pt}
\begin{quote}
[ {\em Definitions\/} ]
\pcpc
[ {\em Rules\/} ]
[ \pcpc
{\em User functions\/} ]
\end{quote}
\vspace{20pt}
{\em Definitions\/} and {\em User functions\/} can be missing.
\vspace{20pt}
Hence, the minimum size LEX program is the following one:
\vspace{20pt}
\begin{center}\pcpc\end{center}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX}
LEX performs its classification via a list of
{\bf regular expressions} ({\em regex\/}) that the user needs
to supply via a standard language.
\vspace{20pt}
Regex's describe \emph{patterns of characters\/} to be
located in the text. LEX reads these regex's and produces a
FSM that recognizes those patterns.
\vspace{20pt}
FSM's are indeed the simplest conceptual tool
with which to recognize words expressed by regex's.
%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
%%%%%%%%%%%%%%%%%%%%%%%%%%%
LEX uses the same regex recognizer used by most of those UNIX tools
that do pattern matching:
{\tt vi}, {\tt sed}, {\tt awk}, {\tt find}, {\tt grep},
for instance, adopt the same set of agreement based on the same set of
``metacharacters'':
\vspace{20pt}
\verb! " \ [ ] ^ - ? . * + | { } $ / ( ) % < >!
\vspace{20pt}
(Python, Perl, Java, and others, adopt slightly different sets.)
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
\begin{description}
\item{\tt "}
the quotation mark operator is the simplest metacharacter:
all the characters of a string betweeb quotation marks are
interpreted as plain (non-meta) characters.
\item{\tt [ \ldots ]}
Squared parentheses (pair []) specify classes of characters.
For instance,
{\tt [xyz]} means:
``{\em a single {\tt x}, {\tt y} or {\tt z} char}''
The hyphen sign between any two chars $a$ and $b$ means that all the
chars between ord($a$) and ord($b$) are specified.
For instance,
{\tt [A-Z]} means
``{\em any uppercase letter\/}'', while
{\tt [A-Za-z]} means: ``{\em any letter\/}''.
Furthermore, \verb"[\40-\176]" for instance selects
a range of characters, that is, the one between
$octal(40)$ and $octal(176)$.
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{description}
\item{\tt [\verb"^" \ldots ]}
Character ``{\tt \verb"^"}'' , within the squared parentheses, means
``complementary set''.
For instance, {\tt [\verb"^"0-9]} means
``{\em any char but the digits\/}''.
\item{\tt \verb"\"}
(Backslash) is the same as in the C language function
printf.
\item{\tt .}
(Dot) means ``{\em any character but
{\tt '\verb"\n"'}}''.
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{description}
\item{\tt ?} The question mark goes after optional strings of
characters.
For instance, {\tt ab?c} means:
``{\em either {\tt 'ac'} or {\tt 'abc'}}''.
\item{\tt *} Postfix operator ``star'' means \emph{ZERO\/} or more
instances of a given class.
As an example, {\tt [\verb"^"a-zA-Z]*} means ``{\em zero or more
instances of non-alphabetic chars\/}''.
\item{\tt +} Postfix operator ``plus'' means \emph{ONE\/} or more
instances of a given class.
For instance,
{\tt [xyz]+} means ``{\em any non-empty string, of any size,
consisting of any of the characters
{\tt 'x'}, {\tt 'y'} and {\tt 'z'}}'', such as e.g.
{\tt xyyyyyyzz}.
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{description}
\item{Operators {\tt ()} and {\tt \verb"|"}}. Parentheses group
a set of characters into one object. For instance,
in {\tt (xyz)+}, operator {\tt +} is applied to
string {\tt xyz}. Within a group, the OR between entities
is specified via metacharacter {\tt \verb"|"}.
For instance,
\vspace{20pt}
\begin{center}{\tt (ab\verb"|"cd+)?(ef)*}
\end{center}
\vspace{20pt}
\noindent
means ``{\em zero or more instances of string {\tt "ef"}, possibly
preceded either by string {\tt ab} or by {\tt cd+} ({\tt c} followed
by one or more instances of {\tt d}})''.
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{description}
\item{\tt \verb"^":} This char, if not within square parentheses, means
``at begin-of-file or right after a newline.''
\item{\tt \verb"$":} This means ``at the end of a line''
or ``at end-of-file'', i.e., if the following char is either
\verb"'\n'" or {\tt EOF}.
For instance, \verb"(riga|row)$" means ``string {\tt riga}
or string {\tt row} followed either by \verb"\n" or by {\tt EOF}.
\item{\tt /}: Infix operator slash checks whether an entity is
followed by another one. For instance,
{\tt a/b} means
``character {\tt a}, only when followed by character {\tt b}''.
Note that {\tt ab/\verb"\n"} is equivalent to {\tt ab\verb"$"}.
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{Metacharacters in LEX}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{description}
\item{\tt \{\}:} Curly brackets have two meanings:
\begin{itemize}
\item When grouping two comma-separated numbers, as in
{\tt (xyz)\{1,5\}}, they represent a {\em multiple instance}.
The above example means
``{\em from one to five instances of
string {\tt xyz}}''.
\item When grouping letters, they represent the value of a
regex alias (see further on).
\end{itemize}
\item{\tt \%} Character {\tt \%} is {\em not\/} a metacharacter but has a special
meaning.
\end{description}
\end{frame}
\begin{frame}[fragile]{LEX Definitions}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A LEX source file may include up to three sections; the first
one is the one including the LEX definitions. Definitions include
a list of regex's:
\begin{verbatim}
letter [a-zA-Z]
letters {letter}+
\end{verbatim}
\vspace{20pt}
These are the rules:
\begin{enumerate}
\item At column 1, an identifier is supplied,
\item then some blank or tab chars,
\item and finally a regex.
\end{enumerate}
\vspace{20pt}
The identifier becomes an alias for its regex.
To dereference an alias one has to put curly brackets around it.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules}
The Rules section is mainly a list of
{\em associations\/} in the form
\[ r\Rightarrow a \]
where $r$ is a regex and $a$ is a list of {\em actions},
i.e., user defined C language statements that are executed
when the corresponding regex is recognized.
\vspace{20pt}
For instance:
\vspace{20pt}
\begin{verbatim}
%%
begin printf("{");
end {
putchar('}');
}
\end{verbatim}
\end{frame}
\begin{frame}[fragile]{LEX Rules : Actions}
Note: when no rule is verified, a default rule is executed:
{\tt ECHO}.
\vspace{10pt}
\noindent
(The FSA written by LEX has a {\tt switch} statement with a {\tt default: ECHO;}.)
\vspace{10pt}
\begin{itemize}
\item This means that, e.g., there is no need to supply rules for
the so called ``literal tokens,'' i.e., single characaters whose
token number is equal to their ASCII code.
\item
To ``sift out'' some portion of the input, one needs to recognize it
and to associate a null action to it.
\end{itemize}
\vspace{10pt}
To remove newline characters:
\begin{verbatim}
%%
\n ;
\end{verbatim}
\end{frame}
\begin{frame}[fragile]{LEX Rules : Actions}
Some ``simple transformations'' can be useful in order
to facilitate the import of a file.
\vspace{20pt}
Some word processors, such as Word, regard paragraphs as a single line and
separate paragraphs with \verb"\n".
\vspace{20pt}
The following LEX script converts every single \verb"\n" into character space.
\begin{verbatim}
%%
\n\n ECHO;
\n putchar(' ');
\end{verbatim}
\end{frame}
\begin{frame}[fragile]{LEX Rules : Variables}
When a regex is recognized, the corresponding string (the token)
is copied in a
{\tt char*} called {\tt yytext}.
This is true also for literal tokens.
\vspace{20pt}
This script is similar to the previous one:
\begin{verbatim}
%%
[^\n]\n[^\n] { putchar(yytext[0]);
putchar(' ');
putchar(yytext[2]);
}
\end{verbatim}
\vspace{20pt}
Action {\tt ECHO} is actually a {\tt \#define}:
\begin{verbatim}
#define ECHO puts(yytext)
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules : Variables}
Variable
{\tt int yyleng} is the number of characters of the string
which verifies the current rule; in other words,
\begin{center}\tt yyleng == strlen(yytext)\end{center}
\vspace{20pt}
For instance:\label{digalpoth}
\begin{verbatim}
%%
[0-9]+ dig += yyleng;
[a-zA-Z]+ alp += yyleng;
(.|\n) oth++;
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules : Variables}
The above program has some bugs:
\vspace{20pt}
\begin{enumerate}
\item Variable {\tt dig} etc.
have not been declared.
\item No output message is provided at the end.
\end{enumerate}
\vspace{20pt}
LEX produces a C program. No checks are done on the
correctness of this program. It may also contain syntax errors
in the actions (actions are simply copied as strings into
the output program.)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules : Functions}
A number of functions are available to the LEX user:
\vspace{20pt}
\begin{center}\tt yymore()\end{center}
Next string is attached to the current value of
{\tt yytext}.
\vspace{20pt}
\begin{verbatim}
%%
\"[^"]* {
if (yytext[yyleng-1] == '\\')
yymore();
else
do_that(yytext);
}
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules : Functions}
\begin{verbatim}
%%
\"[^"]* {
if (yytext[yyleng-1] == '\\')
yymore();
else
do_that(yytext);
}
\end{verbatim}
\verb' '\verb*'"he said \"hi\"."'
\verb' '\verb*'"he said \'
\verb' '\verb' "hi\'
\verb' '\verb' "."'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules : Functions}
\begin{center}\tt yyless()\end{center}
``Sends back'' a given number of characters.
\vspace{20pt}
\begin{verbatim}
%%
=-[a-zA-Z] {
printf("Operator =- is ambiguous: ");
printf("not recognized.\n");
yyless(yyleng-2);
manage_assignment();
}
\end{verbatim}
\vspace{20pt}
(In the early days of C, {\tt a =- b} had the same meaning of
{\tt a -= b}).
\vspace{20pt}
{\tt yyless($x$)} pushes back onto the input $\hbox{\tt yyleng}-x$ characters.
\end{frame}
\begin{frame}[fragile]{LEX Rules : Functions}
\begin{description}\item{\tt int input()} reads the next input character.
(Character {\tt NULL} [that is, {\tt (int)0}] is interpreted
as end-of-file condition)
\item{\tt void output(char c)} writes {\tt c} onto the output stream
\item{\tt void unput(char c)} ``pushes back'' {\tt c} into the input stream.
\end{description}
\vspace{20pt}
The user can choose between a standard version of these functions
or make use of his/her own functions with the same name and
prototype.
\end{frame}
\begin{frame}[fragile]{LEX Rules : Functions}
\begin{center}\tt int yywrap(void)\end{center}\label{yywrap}
\vspace{20pt}
This system (or user-) function is called when an {\tt EOF}
is encountered. The system version of this function returns
{\tt 1}, which means ``end of processing.''
The user can substitute this function with a new version
which, if it returns {\tt 0}, let the execution
continue until a new {\tt EOF} is encountered.
\vspace{20pt}
This way it is possible, e.g., to process more than one
input file during the same run.
\vspace{20pt}
Furthermore, {\tt yywrap()} allows the user to specify
end-of-job functions (for instance, printing of the
output and so forth.)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{frame}
\begin{frame}[fragile]{LEX Rules}
LEX adopts two steps to select which user rule to apply:
\vspace{20pt}
\begin{enumerate}
\item The rule that recognizes the largest string is always preferred.
\item If more than one rule recognize largest strings, it is chosen
the rule the user has specified first in the LEX script.
\end{enumerate}
\end{frame}
%\begin{frame}[fragile]{LEX Rules}
%
%An example follows:
%
%\begin{verbatim}
% %%
% integer printf("1");
% [a-z]+ printf("2");
% (.|\n) ;
%\end{verbatim}
%
%Dato ad esempio l'input {\tt "ABC\underline{integers}XY\underline{integer}ABC"},
%Lex produce la stringa {\tt "21"}.
%
%$\Leftarrow$: (motivazione)
%
%$\Leftarrow$: (scambio della prima rule con la seconda)
%\end{frame}
\begin{frame}[fragile]{LEX Rules}
Within a same rule, LEX returns the largest possible string:
\vspace{20pt}
\begin{verbatim}
%%
\'.*\' { yytext[0] = '[';
yytext[yyleng-2] = ']';
printf("%s",yytext);
}
\end{verbatim}
\vspace{20pt}
produces a program that, once read string
\vspace{20pt}
{\tt 'hi' -said- 'how are you?'}
\vspace{20pt}
writes the following string on the output:
\vspace{20pt}
{\tt [hi' -said- 'how are you?]}
\end{frame}
\begin{frame}[fragile]{LEX Rules}
When LEX selects which rule to execute, it
creates an ordered list of possible candidates. The one
to be executed is the one on top. When the action includes macro
\begin{center}\tt REJECT;\end{center}
the following two actions take place:
\begin{enumerate}
\item the input string is sent back onto the input stream;
\item the rule is removed from the list. The rule that is selected
is therefore the new top one.
\end{enumerate}
\end{frame}
\begin{frame}[fragile]{LEX Rules}
\noindent
{\tt REJECT} is useful, e.g., to count all the
``digrams'' in a given text:
\vspace{20pt}
\begin{verbatim}
%%
[A-Z][a-z] { digram[yytext[0]][yytext[1]]++;
REJECT;
}
(.|\n) ;
\end{verbatim}
\vspace{20pt}
each digram in the text is located by the first rule, because
it returns a string of \emph{two\/} characters while the second
one returns a string of just one character.
\vspace{20pt}
{\tt REJECT} writes back the two characters of the digram onto stdin
and ``fires'' the first rule. The second one is executed.
A character is removed from the input stream.
\end{frame}
\begin{frame}[fragile]{LEX Rules}
\label{digram1}
\begin{verbatim}
%%
[a-z][a-z] { extern int dig[26][26];
dig[yytext[0]-'a'][yytext[1]-'a']++;
REJECT; }
(.|\n) ;
%%
int dig[26][26];
int yywrap() { int i, j;
for (i=0; i<26; i++)
for (j=0; j<26; j++)
if (dig[i][j])
printf("digram [%c%c] = %d\n",
'a'+i,'a'+j, dig[i][j]);
return 1;
}
\end{verbatim}
\end{frame}
\begin{frame}[fragile]{Output stream in LEX}
LEX allows to include in the output C source code
any useful information (header files, declaration of
global variables and so forth.)
\vspace{20pt}
Inclusion can be done in three ``zones'' of the output
source file:
\begin{enumerate}
\item at the beginning of the file, that is, before any of the functions,
\item at the beginning of function {\tt yylex()},
\item at the end of the file.
\end{enumerate}
\end{frame}
\begin{frame}[fragile]{Output stream in LEX}
The three zones in the output source code correspond to the following
zones of the LEX script:
\begin{enumerate}
\item In {\em Definitions},
\item On top of {\em Rules\/}, i.e., right after the first \pcpc{};
\item In {\em User Functions}.
\end{enumerate}
\end{frame}
\begin{frame}[fragile]{Output stream in LEX}
Case {\bf 3} is trivial. For
{\bf 1} and {\bf 2}, we need to distinguish the text to be processed
by LEX from the text that needs to be copied verbatim in the output file.
To do this, one can follow any of these ways:
\begin{itemize}
\item {\tt [ \verb"\"t]+.*} \ (at least a blank space or tab character
at column zero, then the data to be flushed onto the output file.)
\item Anything between \verb"%{" and \verb"%}".
\end{itemize}
\end{frame}
\begin{frame}[fragile]{Practical use of LEX}
\begin{enumerate}
\item {\tt lex {\em source}.l}
\item {\tt gcc lex.yy.c -ll}
\item {\tt a.out < input}
\end{enumerate}
\end{frame}
\begin{frame}[fragile]{Practical use of LEX}
File {\tt lex.yy.c} contains function {\tt yylex()}
i.e., the actual scanner. Compiling
{\tt lex.yy.c} with the system library {\tt libl.a},
a {\tt main()} function is automatically supplied
which calls function {\tt yylex()}.
\vspace{20pt}
The user can substitute this default {\tt main()} with
one of their own design.
\vspace{20pt}
Doing this, one can choose between either
automatically generating an executable or
``piping'' LEX output to other programs---for instance,
syntactical analyzers.
\end{frame}
\begin{frame}[fragile]{LEX: Selection of a scanning context}
Writing a lexical analyser can be made easier when using
more than one scanning context. A scanning context is a
set of scanning rules that apply within a certain context
and do not apply in other contexts.
\vspace{20pt}
Classical example: the presence of string
\verb"/*" may imply the activation of a set of rules that
are completely different from the standard rules. The
same applies for constant strings.
\vspace{20pt}
The context switch can be done in various ways:
\begin{itemize}
\item flag method, \item start conditions,
\item multiple scanners
\end{itemize}
\end{frame}
\begin{frame}[fragile]{Practical use of LEX}
\begin{center}{Selection of a scanning context: flag method}
\end{center}
\vspace{20pt}
\begin{verbatim}
int flag=0; /* starts with a tab! */
%%
"/*" flag=1;
"*/" flag=0;
. |
\n if (flag==0) putchar(*yytext);
\end{verbatim}
\vspace{20pt}
It is the programmer's responsibility to use the method in a coherent way.
\end{frame}
\begin{frame}[fragile]{Practical use of LEX}
\begin{center}{Selection of a scanning context: start conditions/multiple scanners}
\end{center}
\vspace{20pt}
An identifier, called ``start condition,'' is associated
to some rules. The rule becomes part of the lexical context
identified by the start condition. The current start condition
can be changed at any time:
\vspace{20pt}
\begin{verbatim}
any (\n|.)
%start REMARK
%%
"/*" BEGIN REMARK;
"*/" BEGIN 0;
<REMARK>{any} ;
{any} putchar(*yytext);
\end{verbatim}
\vspace{20pt}