-
Notifications
You must be signed in to change notification settings - Fork 1
/
type_checking.tex
1555 lines (1275 loc) · 50.6 KB
/
type_checking.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
\documentclass[8pt,a4paper,compress]{beamer}
\usepackage{/home/siyer/lib/slides}
\title{Type Checking}
\date{}
\begin{document}
\begin{frame}
\vfill
\titlepage
\end{frame}
\section{Introduction}
\begin{frame}[fragile]
\pause
Type checking (aka semantic analysis) is the final step in the analysis phase, and includes the following
\begin{itemize}
\pause
\item Determining the types of all names and expressions.
\pause
\item Insuring that all expressions are properly typed, for example that the operands of an operator have the proper types
\pause
\item A certain amount of storage analysis, for example determining the amount of storage that is required in the current stack frame to store a local variable (one word for \lstinline{int}s, two words for \lstinline{long}s); this information is used to allocate locations (at offsets from the base of the current stack frame) for parameters and local variables
\pause
\item A certain amount of AST tree rewriting, usually to make implicit constructs more explicit
\end{itemize}
\pause
\bigskip
Semantic analysis of \jmm programs involves all of the above
\end{frame}
\section{The \protect\jmm Types}
\begin{frame}[fragile]
\pause
A type in \jmm is either a primitive type or a reference type
\pause
\bigskip
\jmm primitive types
\begin{itemize}
\pause
\item \lstinline{int} - 32 bit two's complement integers
\pause
\item \lstinline{boolean} - taking the value \lstinline{true} or \lstinline{false}
\pause
\item \lstinline{char} - 16 bit Unicode (but many systems deal only with the lower 8 bits)
\end{itemize}
\pause
\bigskip
\jmm reference types
\begin{itemize}
\pause
\item arrays
\pause
\item objects of a type described by a class declaration
\pause
\item built-in objects \lstinline{java.lang.Object} and \lstinline{java.lang.String}
\end{itemize}
\pause
\bigskip
\jmm code may interact with classes from the Java library but it must be able to do so using only these types
\end{frame}
\begin{frame}[fragile]
\pause
How do we represent the types \lstinline{int}, \lstinline{int[]}, \lstinline{Factorial}, \lstinline{String[][]}?
\pause
\bigskip
We want a simple, but extensible representation; we want no more complexity than is necessary for representing all of the types in \jmm and for representing any (Java) types that we may add in exercises
\pause
\bigskip
We want the ability to interact with the existing Java class libraries
\pause
\bigskip
Possible solutions
\begin{enumerate}
\pause
\item Java types are represented by objects of (Java) type \lstinline{java.lang.Class}; since \jmm is a subset of Java, why not use \lstinline{Class} objects to represent its types?
\pause
\item Define an abstract class (or interface) \lstinline{Type}, and concrete sub-classes (or implementations) \lstinline{PrimitiveType}, \lstinline{ReferenceType}, and \lstinline{ArrayType}
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\pause
Our solution is to define our own class \lstinline{Type} for representing types, with a simple interface but also encapsulating the \lstinline{java.lang.Class} object that corresponds to the Java representation for that same type
\pause
\bigskip
Since the parser does not know anything about types, we define two placeholder type representations
\begin{enumerate}
\pause
\item \lstinline{TypeName} - for representing named types recognized by the parser like user-defined classes or imported classes until such time as they may be resolved to their proper \lstinline{Type} representation
\pause
\item \lstinline{ArrayTypeName} - for representing array types recognized by the parser like \lstinline{String[]}, until such time that they may resolved to their proper \lstinline{Type} representation
\end{enumerate}
\pause
\bigskip
During analysis, \lstinline{TypeName}s and \lstinline{ArrayTypeName}s are resolved to the \lstinline{Type}s that they represent
\pause
\bigskip
More specifically
\begin{itemize}
\pause
\item A \lstinline{TypeName} is resolved by looking it up in the current context, our symbol table representation, and the \lstinline{Type} found replaces the \lstinline{TypeName}, and finally, the \lstinline{Type}'s accessibility from the place the \lstinline{TypeName} is encountered is checked
\pause
\item Since an \lstinline{ArrayTypeName} has a base type, the base type is resolved to a \lstinline{Type}, whose \lstinline{Class} representation becomes the base type for representing the array type
\pause
\item A \lstinline{Type} resolves to itself
\end{itemize}
\end{frame}
\section{\protect\jmm Symbol Tables}
\begin{frame}[fragile]
\pause
A symbol table maps names to the things they name, for example, types, formal parameters and local variables; these mappings are established in a declaration and consulted each time a declared name is encountered
\pause
\bigskip
In the \jmm compiler, the symbol table is a tree of \lstinline{Context} objects, which spans the abstract syntax tree, with each \lstinline{Context} corresponding to a region of scope in the \jmm source program
\pause
\bigskip
For example, reconsider the simple \lstinline{Factorial} program. In this version we mark two locations in the program using comments: \lstinline{position 1} and \lstinline{position 2}
\begin{lstlisting}[language=Java,style=focusin]
package pass;
import java.lang.System;
public class Factorial {
public static int factorial(int n) {
// position 1:
if (n <= 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
// position 2:
int x = n;
System.out.println(n + "! = " + factorial(x));
}
static int n = 5;
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The symbol table for the \lstinline{Factorial} program, and its relationship to the AST, is illustrated in figure below
\begin{center}
\visible<2->{\includegraphics[scale=0.29]{{figures/figure04.01}.jpg}}
\end{center}
\end{frame}
\begin{frame}[fragile]
\pause
The symbol table takes the form of a tree that corresponds to the shape of the AST
\pause
\bigskip
A \lstinline{context}, ie, a node in this tree, captures the region of scope corresponding to the AST node that points to it
\pause
\bigskip
For example, in the above figure
\begin{enumerate}
\pause
\item The context pointer from the AST's \lstinline{JCompilationUnit} node points to the \lstinline{JCompilationUnitContext} that is at the root of the symbol table
\pause
\item The context pointer from the AST's \lstinline{JClassDeclaration} points to a \lstinline{ClassContext}
\pause
\item The context pointer from the AST's two \lstinline{JMethodDeclaration}s each point to a \lstinline{MethodContext}
\pause
\item The context pointer from the AST's two \lstinline{JBlock}s each point to a \lstinline{LocalContext}
\end{enumerate}
\pause
\bigskip
From any particular location in the program, looking back towards the root \lstinline{CompilationUnitContext}, the symbol table looks like a stack of contexts
\pause
\bigskip
Each \lstinline{surroundingContext} link back towards the \lstinline{CompilationUnitContext} points to the context representing the surrounding lexical scope
\end{frame}
\begin{frame}[fragile]
\pause
During analysis, when the compiler encounters a variable, it looks up that variable in the symbol table by name, beginning at the \lstinline{LocalContext} most recently created in the symbol table
\pause
\bigskip
Type names are looked up in the \lstinline{CompilationUnitContext}; to facilitate this, each context maintains three pointers to surrounding contexts, as illustrated in the following figure
\begin{center}
\visible<3->{\includegraphics[scale=0.5]{{figures/figure04.02}.jpg}}
\end{center}
\end{frame}
\begin{frame}[fragile]
\pause
A \lstinline{CompilationUnitContext} represents the scope of the entire program and contains a mapping from names to types
\begin{itemize}
\pause
\item The implicitly declared types, \lstinline{java.lang.Object}, and \lstinline{java.lang.String}
\pause
\item Imported types
\pause
\item User-defined types, that is, types introduced in clss declarations
\end{itemize}
\pause
\bigskip
A \lstinline{ClassContext} represents the scope within a class declaration; in the \jmm symbol table, no names are declared here, but if we were to add nested type declarations to \jmm, they might be declared here
\pause
\bigskip
A \lstinline{MethodContext} represents the scope within a method declaration; a method's formal parameters are declared here
\pause
\bigskip
A \lstinline{LocalContext} represents the scope within a block, which includes the block defining the body to a method; local variables are declared here
\end{frame}
\begin{frame}[fragile]
\pause
Each kind of context derives from (extends) the class \lstinline{Context}, which supplies the mapping from names to definitions (\lstinline{IDefns})
\pause
\bigskip
The inheritance tree for contexts is illustrated in the following figure
\begin{center}
\visible<3->{\includegraphics[scale=0.5]{{figures/figure04.03}.jpg}}
\end{center}
\pause
\bigskip
An \lstinline{IDefn} is the interface type for symbol table definitions, which has two implementations
\begin{enumerate}
\pause
\item A \lstinline{TypeNameDefn}, which defines a type name; an \lstinline{IDefn} of this sort encapsulates the \lstinline{Type} that it denotes
\pause
\item A \lstinline{LocalVariableDefn} defines a local variable and encapsulates the name, its \lstinline{Type} and an offset in the current run-time stack frame
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\pause
Class member (field and method in \jmm) names are not declared in a \lstinline{ClassContext}, but in the \lstinline{Type}s that they declare
\pause
\bigskip
We rely on the encapsulated \lstinline{Class} object to store the interface information, and we rely on Java reflection to query a type for information about its members
\pause
\bigskip
For example, \lstinline{Type} supports a method \lstinline{fieldFor()} which, when given a name returns a \lstinline{Field} with the given name that is defined for that type
\begin{lstlisting}[language=Java,style=focusin]
public Field fieldFor(String name) {
Class<?> cls = classRep;
while (cls != null) {
java.lang.reflect.Field[] fields = cls.getDeclaredFields();
for (java.lang.reflect.Field field:fields) {
if (field.getName().equals(name)) {
return new Field(field);
}
}
cls = cls.getSuperclass();
}
return null;
}
\end{lstlisting}
\end{frame}
\section{Pre-analysis of \protect\jmm Programs}
\begin{frame}[fragile]
\pause
The semantic analysis of \jmm programs requires two traversals of the AST because a class name or a member name may be referenced before it is declared in the source program
\pause
\bigskip
The traversals are accomplished by the method \lstinline{preAnalyze()} for the first traversal and the method \lstinline{analyze()} for the second, which invoke themselves at the child nodes for recursively descending the AST
\pause
\bigskip
The \lstinline{preAnalyze()} method must traverse down the AST only far enough for
\begin{itemize}
\pause
\item Declaring imported type names
\pause
\item Declaring user-defined class names
\pause
\item Declaring fields
\pause
\item Declaring methods (including their signatures - the types of their parameters)
\end{itemize}
\pause
\bigskip
Therefore, \lstinline{preAnalyze()}need be defined only in the following types of AST nodes
\begin{itemize}
\pause
\item \lstinline{JCompilationUnit}
\pause
\item \lstinline{JClassDeclaration}
\pause
\item \lstinline{JFieldDeclaration}
\pause
\item \lstinline{JMethodDeclaration}
\pause
\item \lstinline{JConstructorDeclaration}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\pause
For the \lstinline{JCompilationUnit} node at the top of the AST, \lstinline{preAnalyze()} does the following
\begin{enumerate}
\pause
\item It creates a \lstinline{CompilationUnitContext}
\pause
\item It declares the implicit \jmm types, \lstinline{java.lang.String} and \lstinline{java.lang.Object}
\pause
\item It declares any imported types
\pause
\item It declares the types defined by class declaration, ie, creates a \lstinline{Type} for each declared class, whose \lstinline{classRep} refers to a \lstinline{Class} object for an empty class; for example, in the pre-analysis phase of our \lstinline{Factorial} program above, the \lstinline{Type} for \lstinline{Factorial} would have a \lstinline{classRep}, the \lstinline{Class} object for the class
\begin{lstlisting}[language=Java,style=focusin]
class Factorial {}
\end{lstlisting}
\pause
\item Finally, \lstinline{preAnalyze()} invokes itself for each of the type declarations in the compilation unit
\end{enumerate}
\pause
\bigskip
Here is the code for \lstinline{preAnalyze()} in \lstinline{JCompilationUnit}
\begin{lstlisting}[language=Java,style=focusin]
public void preAnalyze() {
context = new CompilationUnitContext();
// Declare the two implicit types java.lang.Object and
// java.lang.String
context.addType(0, Type.OBJECT);
context.addType(0, Type.STRING);
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
Here is the code for \lstinline{preAnalyze()} in \lstinline{JCompilationUnit}
\begin{lstlisting}[language=Java,style=focusin]
// Declare any imported types
for (TypeName imported: imports) {
try {
Class<?> classRep =
Class.forName(imported.toString());
context.addType(imported.line(),
Type.typeFor(classRep));
}
catch (Exception e) {
JAST.compilationUnit.reportSemanticError(
imported.line(),
"Unable to find %s", imported.toString());
}
}
// Declare the locally declared type(s)
CLEmitter.initializeByteClassLoader();
for (JAST typeDeclaration: typeDeclarations) {
((JTypeDecl)
typeDeclaration).declareThisType(context);
}
// Pre-analyze the locally declared type(s). Generate
// (partial) Class instances, reflecting only the member
// interface type information
CLEmitter.initializeByteClassLoader();
for (JAST typeDeclaration: typeDeclarations) {
((JTypeDecl)
typeDeclaration).preAnalyze(context);
}
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
In a class declaration, \lstinline{preAnalyze()} does the following
\begin{enumerate}
\pause
\item It firstly creates a new \lstinline{ClassContext}, whose \lstinline{surroundingContext} points to the \lstinline{CompilationUnitContext}
\pause
\item It resolves the class's super type
\pause
\item It creates a new \lstinline{CLEmitter} instance, which will eventually be converted to the \lstinline{Class} object for representing the declared class
\pause
\item It adds a class header, defining a name and any modifiers, to this \lstinline{CLEmitter} instance
\pause
\item It recursively invokes \lstinline{preAnalyze()} on each of the class's members, which causes field declarations, constructors and method declarations (but with empty bodies) to be added to the \lstinline{CLEmitter} instance
\pause
\item If there is no explicit constructor (having no arguments) in the set of members, it adds the implicit constructor to the \lstinline{CLEmitter} instance; for example, for the \lstinline{Factorial} program above, the following implicit constructor is added
\begin{lstlisting}[language=Java,style=focusin]
public Factorial() {
super();
}
\end{lstlisting}
\pause
\item Finally, the \lstinline{CLEmitter} instance produces a \lstinline{Class} object, and that replaces the \lstinline{classRep} for the \lstinline{Type} of the declared class name in the (parent) \lstinline{ClassContext}
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\pause
Here is the code for \lstinline{preAnalyze()} in \lstinline{JClassDeclaration}
\begin{lstlisting}[language=Java,style=focusin]
public void preAnalyze(Context context) {
// Construct a class context
this.context = new ClassContext(this, context);
// Resolve superclass
superType = superType.resolve(this.context);
// Creating a partial class in memory can result in a
// java.lang.VerifyError if the semantics below are
// violated, so we can't defer these checks to analyze()
thisType.checkAccess(line, superType);
if (superType.isFinal()) {
JAST.compilationUnit.reportSemanticError(line,
"Cannot extend a final type: %s",
superType.toString());
}
// Create the (partial) class
CLEmitter partial = new CLEmitter();
// Add the class header to the partial class
String qualifiedName =
JAST.compilationUnit.packageName() == "" ? name :
JAST.compilationUnit.packageName() + "/" + name;
partial.addClass(mods, qualifiedName, superType.jvmName(),
null, false);
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
\begin{lstlisting}[language=Java,style=focusin]
// Pre-analyze the members and add them to the partial class
for (JMember member: classBlock) {
member.preAnalyze(this.context, partial);
if (member instanceof JConstructorDeclaration &&
((JConstructorDeclaration) member).
params.size() == 0) {
hasExplicitConstructor = true;
}
}
// Add the implicit empty constructor?
if (!hasExplicitConstructor) {
codegenPartialImplicitConstructor(partial);
}
// Get the Class rep for the (partial) class and make it the
// representation for this type
Type id = this.context.lookupType(name);
if (id != null &&
!JAST.compilationUnit.errorHasOccurred()) {
id.setClassRep(partial.toClass());
}
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
In a method declaration, \lstinline{preAnalyze()} does the following
\begin{enumerate}
\pause
\item It resolves the types of the formal parameters
\pause
\item It resolves the return type
\pause
\item It checks proper use of the \lstinline{abstract} modifier
\pause
\item It computes the method descriptor
\pause
\item It generates (partial) code for the method
\end{enumerate}
\pause
\bigskip
Here is the code for \lstinline{preAnalyze()} in \lstinline{JMethodDeclaration}
\begin{lstlisting}[language=Java,style=focusin]
public void preAnalyze(Context context, CLEmitter partial) {
// Resolve types of the formal parameters
for (JFormalParameter param: params) {
param.setType(param.type().resolve(context));
}
// Resolve return type
returnType = returnType.resolve(context);
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
\begin{lstlisting}[language=Java,style=focusin]
// Check proper local use of abstract
if (isAbstract && body != null) {
JAST.compilationUnit.reportSemanticError(line(),
"abstract method cannot have a body");
}
else if (body == null && ! isAbstract) {
JAST.compilationUnit.reportSemanticError(line(),
"Method with null body must be abstract");
}
else if (isAbstract && isPrivate ) {
JAST.compilationUnit.reportSemanticError(line(),
"private method cannot be declared abstract");
}
else if (isAbstract && isStatic ) {
JAST.compilationUnit.reportSemanticError(line(),
"static method cannot be declared abstract");
}
// Compute descriptor
descriptor = "(";
for (JFormalParameter param: params) {
descriptor += param.type().toDescriptor();
}
descriptor += ")" + returnType.toDescriptor();
// Generate the method with an empty body (for now)
partialCodegen(context, partial);
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The code for \lstinline{partialCodegen()} is as follows
\begin{lstlisting}[language=Java,style=focusin]
public void partialCodegen(Context context, CLEmitter partial) {
// Generate a method with an empty body; need a return to
// make the class verifier happy.
partial.addMethod(mods, name, descriptor, null, false);
// Add implicit RETURN
if (returnType == Type.VOID) {
partial.addNoArgInstruction(RETURN);
}
else if (returnType == Type.INT ||
returnType == Type.BOOLEAN ||
returnType == Type.CHAR) {
partial.addNoArgInstruction(ICONST_0);
partial.addNoArgInstruction(IRETURN);
}
else {
// A reference type.
partial.addNoArgInstruction(ACONST_NULL);
partial.addNoArgInstruction(ARETURN);
}
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
Pre-analysis for a \lstinline{JFieldDeclaration} is similar to that for a \lstinline{JMethodDeclaration}, and does the following
\begin{enumerate}
\pause
\item Enforces the rule that fields may not be declared \lstinline{abstract}
\pause
\item Resolves the field's declared type
\pause
\item Generates the JVM code for the field declaration, via the \lstinline{CLEmitter} created for the enclosing class declaration
\end{enumerate}
\pause
\bigskip
The code itself is rather simple
\begin{lstlisting}[language=Java,style=focusin]
public void preAnalyze(Context context, CLEmitter partial) {
// Fields may not be declared abstract.
if (mods.contains("abstract")) {
JAST.compilationUnit.reportSemanticError(line(),
"Field cannot be declared abstract");
}
for (JVariableDeclarator decl: decls) {
// Add field to (partial) class
decl.setType(decl.type().resolve( context));
partial.addField(mods, decl.name(),
decl.type().toDescriptor(), false);
}
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The following figure illustrates how much of the symbol table is constructed for our \lstinline{Factorial} program once pre-analysis is complete
\begin{center}
\visible<2->{\includegraphics[scale=0.5]{{figures/figure04.04}.jpg}}
\end{center}
\end{frame}
\section{Analysis of \protect\jmm Programs}
\begin{frame}[fragile]
\pause
The analysis phase, ie, the \lstinline{analyze()} method, recursively descends throughout the AST all the way to its leaves
\begin{itemize}
\pause
\item Re-writing field and local variable initializations as assignments
\pause
\item Declaring both formal parameters and local variables
\pause
\item Allocating locations in the stack frame for the formal parameters and local variables
\pause
\item Computing the types of expressions and enforcing the language type rules
\pause
\item Reclassifying ambiguous names
\pause
\item Doing a limited amount of tree surgery
\end{itemize}
\pause
\bigskip
At the top of the AST, \lstinline{analyze()} simply recursively descends into each of the type (class) declarations, delegating analysis to one class declaration at a time
\begin{lstlisting}[language=Java,style=focusin]
public JAST analyze(Context context) {
for (JAST typeDeclaration : typeDeclarations) {
typeDeclaration.analyze(this.context);
}
return this;
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
In \lstinline{JFieldDeclaration}, \lstinline{analyze()} rewrites the field initializer as an explicit assignment statement, analyzes that and then stores it in the \lstinline{JFieldDeclaration}'s initializations list
\begin{lstlisting}[language=Java,style=focusin]
public JFieldDeclaration analyze(Context context) {
for (JVariableDeclarator decl : decls) {
// All initializations must be turned into assignment
// statements and analyzed
if (decl.initializer() != null) {
JAssignOp assignOp = new JAssignOp(decl.line(),
new JVariable(decl.line(),
decl.name()), decl.initializer());
assignOp.isStatementExpression = true;
initializations.add(new JStatementExpression(decl.line(),
assignOp).analyze(context));
}
}
return this;
}
\end{lstlisting}
\pause
\bigskip
In \lstinline{JClassDeclaration}, \lstinline{analyze()} separates the assignment statements into two lists: one for the static fields and one for the instance fields
\begin{lstlisting}[language=Java,style=focusin]
// Copy declared fields for purposes of initialization.
for (JMember member : classBlock) {
if (member instanceof JFieldDeclaration) {
JFieldDeclaration fieldDecl = (JFieldDeclaration) member;
if (fieldDecl.mods().contains("static")) {
staticFieldInitializations.add(fieldDecl);
} else {
instanceFieldInitializations.add(fieldDecl);
}
}
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The following figure shows how the static field declaration (\lstinline{static int n = 5;}) in the \lstinline{Factorial} program is rewritten
\begin{center}
\visible<2->{\includegraphics[scale=0.35]{{figures/figure04.05}.jpg}}
\end{center}
\end{frame}
\begin{frame}[fragile]
\pause
Both formal parameters and local variables are declared in the symbol table and allocated locations within a method invocation's run-time stack frame
\pause
\bigskip
For example, consider the following class declaration
\begin{lstlisting}[language=Java,style=focusin]
public class Locals {
public int foo(int t, String u) {
int v = u.length();
{
int w = v + 5, x = w + 7;
v = w + x;
}
{
int y = 3;
int z = v + y;
t = t + y + z;
}
return t + v;
}
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The stack frame allocated for an invocation of \lstinline{foo()} at run time by the JVM is shown below
\begin{center}
\visible<2->{\includegraphics[scale=0.5]{{figures/figure04.06}.jpg}}
\end{center}
\pause
\bigskip
The code for analyzing a \lstinline{JMethodDeclaration} performs four steps
\begin{enumerate}
\pause
\item It creates a new \lstinline{MethodContext}, whose \lstinline{surroundingContext} points back to the previous \lstinline{ClassContext}
\pause
\item The first stack frame offset is 0; but if this is an instance method then offset 0 must be allocated to \lstinline{this}, and the \lstinline{nextOffset} is incremented to 1
\pause
\item The formal parameters are declared as local variables and allocated consecutive offsets in the stack frame
\pause
\item It analyzes the method's body
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\pause
\begin{lstlisting}[language=Java,style=focusin]
public JAST analyze(Context context) {
this.context = new MethodContext(context, returnType);
if (!isStatic) {
// Offset 0 is used to addr "this".
this.context.nextOffset();
}
// Declare the parameters
for (JFormalParameter param : params) {
this.context.addEntry(param.line(), param.name(),
new LocalVariableDefn(param.type(), this.context
.nextOffset(), null));
}
if (body != null) {
body = body.analyze(this.context);
}
return this;
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The code for analyzing a \lstinline{JBlock} performs two steps
\begin{enumerate}
\pause
\item It creates a new \lstinline{LocalContext}, whose \lstinline{surroundingContext} points back to the previous \lstinline{MethodContext} (or \lstinline{LocalContext} in the case of nested blocks); its \lstinline{nextOffset} value is copied from the previous context
\pause
\item It analyzes each of the body's statements; any \lstinline{JVariableDeclaration}s declare their variables in the \lstinline{LocalContext} created in step 1; any nested \lstinline{JBlock} simply invokes this two-step process recursively, creating yet another \lstinline{LocalContext} for the nested block
\end{enumerate}
\pause
\bigskip
\begin{lstlisting}[language=Java,style=focusin]
public JBlock analyze(Context context) {
// { ... } defines a new level of scope.
this.context = new LocalContext(context);
for (int i = 0; i < statements.size(); i++) {
statements.set(i, (JStatement) statements.get(i).analyze(
this.context));
}
return this;
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The stages of the symbol table in analyzing \lstinline{Locals.foo()}
\begin{center}
\visible<2->{\includegraphics[scale=0.3]{{figures/figure04.07}.jpg}}
\end{center}
\end{frame}
\begin{frame}[fragile]
\pause
A local variable declaration is represented in the AST with a \lstinline{JVariableDeclaration}; for example, consider the local variable declaration from \lstinline{Locals}
\begin{lstlisting}[language=Java,style=focusin]
int w = v + 5, x = w + 7;
\end{lstlisting}
\pause
\bigskip
Before the \lstinline{JVariableDeclaration} is analyzed, it appears exactly as it was created by the parser, as is illustrated below
\begin{center}
\visible<3->{\includegraphics[scale=0.4]{{figures/figure04.08}.jpg}}
\end{center}
\end{frame}
\begin{frame}[fragile]
\pause
Analysis of a \lstinline{JVariableDeclaration} involves the following
\begin{enumerate}
\pause
\item \lstinline{LocalVariableDefn}s and their corresponding stack frame offsets are allocated for each of the declared variables
\pause
\item The code checks to make sure that the declared variables do not shadow existing local variables
\pause
\item The variables are declared in the local context
\pause
\item Any initializations are rewritten as explicit assignment statements; those assignments are re-analyzed and stored in an \lstinline{initializations} list
\end{enumerate}
\pause
\bigskip
\begin{lstlisting}[language=Java,style=focusin]
public JStatement analyze(Context context) {
for (JVariableDeclarator decl : decls) {
// Local variables are declared here (fields are
// declaredin preAnalyze())
int offset = ((LocalContext) context).nextOffset();
LocalVariableDefn defn = new LocalVariableDefn(decl
.type().resolve(context), offset);
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
\begin{lstlisting}[language=Java,style=focusin]
// First, check for shadowing
IDefn previousDefn = context.lookup(decl.name());
if (previousDefn != null
&& previousDefn instanceof LocalVariableDefn) {
JAST.compilationUnit.reportSemanticError(decl.line(),
"The name " + decl.name()
+ " overshadows another local variable.");
}
// Then declare it in the local context
context.addEntry(decl.line(), decl.name(), defn);
// All initializations must be turned into assignment
// statements and analyzed
if (decl.initializer() != null) {
defn.initialize();
JAssignOp assignOp = new JAssignOp(decl.line(),
new JVariable(decl.line(), decl.name()), decl
.initializer());
assignOp.isStatementExpression = true;
initializations.add(new JStatementExpression(decl
.line(), assignOp).analyze(context));
}
}
return this;
}
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\pause
The sub-tree for \lstinline{int w = v + 5, x = w + 7;} after analysis is shown below
\begin{center}
\visible<2->{\includegraphics[scale=0.4]{{figures/figure04.09}.jpg}}
\end{center}
\end{frame}
\begin{frame}[fragile]
\pause
Simple variables (local variables or fields) are represented in the AST as \lstinline{JVariable} nodes
\pause
\bigskip
Analysis of simple variables involves looking their names up in the symbol table to find their types
\pause
\bigskip
If a variable is not found in the symbol table, we examine the \lstinline{Type} for the surrounding class (in which the variable appears) to see if it is a field; if it is a field, then the field selection is made explicit by rewriting the tree as a \lstinline{JFieldSelection}
\pause
\bigskip
\begin{lstlisting}[language=Java,style=focusin]
public JExpression analyze(Context context) {
iDefn = context.lookup(name);
if (iDefn == null) {
// Not a local, but is it a field?
Type definingType = context.definingType();
Field field = definingType.fieldFor(name);
if (field == null) {
type = Type.ANY;
JAST.compilationUnit.reportSemanticError(line,
"Cannot find name: " + name);
} else {
// Rewrite a variable denoting a field as an