/
classes.html
1764 lines (1623 loc) · 103 KB
/
classes.html
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Classes · Crafting Interpreters</title>
<!-- Tell mobile browsers we're optimized for them and they don't need to crop
the viewport. -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="style.css" />
<!-- Oh, God, Source Code Pro is so beautiful it makes me want to cry. -->
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400|Source+Sans+Pro:300,400,600' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" href="image/favicon.png" />
<script src="jquery-3.4.1.min.js"></script>
<script src="script.js"></script>
<!-- Google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42804721-2', 'auto');
ga('send', 'pageview');
</script>
</head>
<body id="top">
<!-- <div class="scrim"></div> -->
<nav class="wide">
<a href="/"><img src="image/logotype-small.png" title="Crafting Interpreters"></a>
<div class="contents">
<!-- If there is a part, it must be a chapter within a part. -->
<h3><a href="#top">Classes<small>12</small></a></h3>
<ul>
<li><a href="#class-declarations"><small>12.1</small> Class Declarations</a></li>
<li><a href="#creating-instances"><small>12.2</small> Creating Instances</a></li>
<li><a href="#properties-on-instances"><small>12.3</small> Properties on Instances</a></li>
<li><a href="#methods-on-classes"><small>12.4</small> Methods on Classes</a></li>
<li><a href="#this"><small>12.5</small> This</a></li>
<li><a href="#constructors-and-initializers"><small>12.6</small> Constructors and Initializers</a></li>
<li class="divider"></li>
<li class="end-part"><a href="#challenges">Challenges</a></li>
<li class="end-part"><a href="#design-note"><small>note</small>Prototypes and Power</a></li>
</ul>
<div class="prev-next">
<a href="resolving-and-binding.html" title="Resolving and Binding" class="left">← Previous</a>
<a href="a-tree-walk-interpreter.html" title="A Tree-Walk Interpreter">↑ Up</a>
<a href="inheritance.html" title="Inheritance" class="right">Next →</a>
</div> </div>
</nav>
<nav class="narrow">
<a href="/"><img src="image/logotype-small.png" title="Crafting Interpreters"></a>
<a href="resolving-and-binding.html" title="Resolving and Binding" class="prev">←</a>
<a href="inheritance.html" title="Inheritance" class="next">→</a>
</nav>
<div class="page">
<div class="nav-wrapper">
<nav class="floating">
<a href="/"><img src="image/logotype-small.png" title="Crafting Interpreters"></a>
<div class="expandable">
<!-- If there is a part, it must be a chapter within a part. -->
<h3><a href="#top">Classes<small>12</small></a></h3>
<ul>
<li><a href="#class-declarations"><small>12.1</small> Class Declarations</a></li>
<li><a href="#creating-instances"><small>12.2</small> Creating Instances</a></li>
<li><a href="#properties-on-instances"><small>12.3</small> Properties on Instances</a></li>
<li><a href="#methods-on-classes"><small>12.4</small> Methods on Classes</a></li>
<li><a href="#this"><small>12.5</small> This</a></li>
<li><a href="#constructors-and-initializers"><small>12.6</small> Constructors and Initializers</a></li>
<li class="divider"></li>
<li class="end-part"><a href="#challenges">Challenges</a></li>
<li class="end-part"><a href="#design-note"><small>note</small>Prototypes and Power</a></li>
</ul>
<div class="prev-next">
<a href="resolving-and-binding.html" title="Resolving and Binding" class="left">← Previous</a>
<a href="a-tree-walk-interpreter.html" title="A Tree-Walk Interpreter">↑ Up</a>
<a href="inheritance.html" title="Inheritance" class="right">Next →</a>
</div> </div>
<a id="expand-nav">≡</a>
</nav>
</div>
<article class="chapter">
<div class="number">12</div>
<h1>Classes</h1>
<div class="sign-up closable">
<h1>This book is a work in progress!</h1>
<span class="dismiss">×</span>
<p>If you see a mistake, find something unclear, or have a suggestion, please <a href="https://github.com/munificent/craftinginterpreters/issues" target="_blank">let me know</a>. To follow its progress, please join the mailing list:</p>
<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup">
<form action="//gameprogrammingpatterns.us7.list-manage.com/subscribe/post?u=0952ca43ed2536d6717766b88&id=6e96334109" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="Your email address" required>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0952ca43ed2536d6717766b88_6e96334109" tabindex="-1" value=""></div>
<input type="submit" value="Sign me up!" name="subscribe" id="mc-embedded-subscribe" class="button">
</form>
</div>
<!--End mc_embed_signup-->
<p class="small">(I post about once a month. Don’t worry, I won’t spam you.)</p>
</div>
<blockquote>
<p>One has no right to love or hate anything if one has not acquired a thorough
knowledge of its nature. Great love springs from great knowledge of the
beloved object, and if you know it but little you will be able to love it only
a little or not at all.</p>
<p><cite>Leonardo da Vinci</cite></p>
</blockquote>
<p>We’re eleven chapters in, and the interpreter sitting on your machine is nearly
a complete scripting language. It could use a couple of built-in data structures
like lists and maps, and it certainly needs a core library for file I/O, user
input etc. But the language itself is sufficient. We’ve got a little procedural
language in the same vein as BASIC, TCL, Scheme (minus macros), and early
versions of Python and Lua.</p>
<p>If this was the 80’s, we’d stop here. But, today, many popular languages support
“object-oriented programming”. Adding that to Lox will give users a familiar set
of tools for writing larger programs. Even if you personally don’t <span
name="hate">like</span> OOP, this chapter and <a href="inheritance.html">the next</a> will help
you understand how others design and build object systems.</p>
<aside name="hate">
<p>If you <em>really</em> hate classes, though, you can skip these two chapters. They are
fairly isolated from the rest of the book. Personally, I find it’s good to learn
more about the things I dislike. Things look simple at a distance, but as I get
closer, details emerge and I gain a more nuanced perspective.</p>
</aside>
<h3><a href="#oop-and-classes" name="oop-and-classes"><small>12 . 0 . 1</small>OOP and classes</a></h3>
<p>There are three broad paths to object-oriented programming: classes,
<a href="http://gameprogrammingpatterns.com/prototype.html">prototypes</a>, and <span name="multimethods"><a href="https://en.wikipedia.org/wiki/Multiple_dispatch">multimethods</a></span>. Classes
came first and are the most popular style. With the rise of JavaScript (and to a
lesser extent <a href="https://www.lua.org/pil/13.4.1.html">Lua</a>), prototypes are more widely known than they used to be.
I’ll talk more about those <a href="#design-note">later</a>. For Lox, we’re taking the, ahem, classic
approach.</p>
<aside name="multimethods">
<p>Multimethods are the approach you’re least likely to be familiar with. I’d love
to talk more about them<span class="em">—</span>I designed <a href="http://magpie-lang.org/">a hobby language</a> around them
once and they are <em>super rad</em><span class="em">—</span>but there are only so many pages I can fit in.
If you’d like to learn more, take a look at <a href="https://en.wikipedia.org/wiki/Common_Lisp_Object_System">CLOS</a> (the object system in
Common Lisp), <a href="https://opendylan.org/">Dylan</a>, <a href="https://julialang.org/">Julia</a>, or <a href="https://docs.perl6.org/language/functions#Multi-dispatch">Perl 6</a>.</p>
</aside>
<p>Since you’ve written about a thousand lines of Java code with me already, I’m
assuming you don’t need a detailed introduction to object orientation. The main
goal is to bundle data with the code that acts on it. Users do that by declaring
a <strong>class</strong> that:</p>
<p><span name="circle"></span></p>
<ol>
<li>
<p>Exposes a <strong>constructor</strong> to create and initialize new <strong>instances</strong> of the
class.</p>
</li>
<li>
<p>Provides a way to store and access <strong>fields</strong> on instances.</p>
</li>
<li>
<p>Defines a set of <strong>methods</strong> shared by all instances of the class that
operate on the instances’ state.</p>
</li>
</ol>
<p>That’s about as minimal as it gets. Most object-oriented languages, all the
way back to Simula, also do inheritance to reuse behavior across <em>classes</em>.
We’ll add that in the <a href="inheritance.html">next chapter</a>. Even kicking that out, we
still have a lot to get through. This is a big chapter and everything doesn’t
quite come together until we have all of the above pieces, so gather your
stamina.</p>
<aside name="circle"><img src="image/classes/circle.png" alt="The relationships between classes, methods, instances, constructors, and fields.">
<p>It’s like the circle of life, <em>sans</em> Sir Elton John.</p>
</aside>
<h2><a href="#class-declarations" name="class-declarations"><small>12 . 1</small>Class Declarations</a></h2>
<p>Like we do, we’re gonna start with syntax. A <code>class</code> statement introduces a new
name, so it lives in the <code>declaration</code> grammar rule:</p>
<div class="codehilite"><pre>
<span class="i">declaration</span> → <span class="i">classDecl</span>
| <span class="i">funDecl</span>
| <span class="i">varDecl</span>
| <span class="i">statement</span> ;
<span class="i">classDecl</span> → <span class="s">"class"</span> <span class="t">IDENTIFIER</span> <span class="s">"{"</span> <span class="i">function</span>* <span class="s">"}"</span> ;
</pre></div>
<p>The new <code>classDecl</code> rule relies on the <code>function</code> rule we defined
<a href="functions.html#function-declarations">earlier</a>. To refresh your memory:</p>
<div class="codehilite"><pre>
<span class="i">function</span> → <span class="t">IDENTIFIER</span> <span class="s">"("</span> <span class="i">parameters</span>? <span class="s">")"</span> <span class="i">block</span> ;
<span class="i">parameters</span> → <span class="t">IDENTIFIER</span> ( <span class="s">","</span> <span class="t">IDENTIFIER</span> )* ;
</pre></div>
<p>In plain English, a class declaration is the <code>class</code> keyword, followed by the
class’s name, then a curly brace body. Inside that body is a list of method
declarations. Unlike function declarations, methods don’t have a leading <span
name="fun"><code>fun</code></span> keyword. Each method is a name, parameter list, and
body. Here’s an example:</p>
<aside name="fun">
<p>Not that I’m trying to say methods aren’t fun or anything.</p>
</aside>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">Breakfast</span> {
<span class="i">cook</span>() {
<span class="k">print</span> <span class="s">"Eggs a-fryin'!"</span>;
}
<span class="i">serve</span>(<span class="i">who</span>) {
<span class="k">print</span> <span class="s">"Enjoy your breakfast, "</span> + <span class="i">who</span> + <span class="s">"."</span>;
}
}
</pre></div>
<p>Like most dynamically-typed languages, fields are not explicitly listed in the
class declaration. Instances are loose bags of data and you can freely add
fields to them as you see fit in the middle of normal imperative code.</p>
<p>Over in our AST generator, the <code>classDecl</code> grammar rule gets its own statement
<span name="class-ast">node</span>:</p>
<div class="codehilite"><pre class="insert-before">
"Block : List<Stmt> statements",
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">
<span class="s">"Class : Token name, List<Stmt.Function> methods"</span>,
</pre><pre class="insert-after">
"Expression : Expr expression",
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>
<aside name="class-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#class-statement">Appendix II</a>.</p>
</aside>
<p>It stores the name and the methods inside the body. Methods are represented by
the existing Stmt.Function class that we use for function declaration AST nodes.
It has all the bits of state that we need for a method: name, parameter list,
and body.</p>
<p>A class can appear anywhere a named declaration is allowed, triggered by the
leading <code>class</code> keyword:</p>
<div class="codehilite"><pre class="insert-before">
try {
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>declaration</em>()</div>
<pre class="insert">
<span class="k">if</span> (<span class="i">match</span>(<span class="i">CLASS</span>)) <span class="k">return</span> <span class="i">classDeclaration</span>();
</pre><pre class="insert-after">
if (match(FUN)) return function("function");
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>declaration</em>()</div>
<p>That calls out to:</p>
<div class="codehilite"><div class="source-file"><em>lox/Parser.java</em><br>
add after <em>declaration</em>()</div>
<pre>
<span class="k">private</span> <span class="t">Stmt</span> <span class="i">classDeclaration</span>() {
<span class="t">Token</span> <span class="i">name</span> = <span class="i">consume</span>(<span class="i">IDENTIFIER</span>, <span class="s">"Expect class name."</span>);
<span class="i">consume</span>(<span class="i">LEFT_BRACE</span>, <span class="s">"Expect '{' before class body."</span>);
<span class="t">List</span><<span class="t">Stmt</span>.<span class="t">Function</span>> <span class="i">methods</span> = <span class="k">new</span> <span class="t">ArrayList</span><>();
<span class="k">while</span> (!<span class="i">check</span>(<span class="i">RIGHT_BRACE</span>) && !<span class="i">isAtEnd</span>()) {
<span class="i">methods</span>.<span class="i">add</span>(<span class="i">function</span>(<span class="s">"method"</span>));
}
<span class="i">consume</span>(<span class="i">RIGHT_BRACE</span>, <span class="s">"Expect '}' after class body."</span>);
<span class="k">return</span> <span class="k">new</span> <span class="t">Stmt</span>.<span class="t">Class</span>(<span class="i">name</span>, <span class="i">methods</span>);
}
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, add after <em>declaration</em>()</div>
<p>There’s more meat to this than most of the other parsing methods, but it roughly
follows the grammar. We’ve already consumed the <code>class</code> keyword, so we look for
the expected class name next, followed by the opening curly brace. Once inside
the body, we keep parsing method declarations until we hit the closing brace.
Each method declaration is parsed by a call to <code>function()</code>, which we defined
back in the <a href="functions.html">chapter where functions were introduced</a>.</p>
<p>Like we do in any open-ended loop in the parser, we also check for hitting the
end of the file. That won’t happen in correct code since a class should have a
closing brace at the end, but it ensures the parser doesn’t get stuck in an
infinite loop if the user has a syntax error and forgets to correctly end the
class body.</p>
<p>We wrap the name and list of methods into a Stmt.Class node and we’re done.
Usually, this would feed into the interpreter, but now we need to plumb it
through the resolver first:</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitBlockStmt</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Void</span> <span class="i">visitClassStmt</span>(<span class="t">Stmt</span>.<span class="t">Class</span> <span class="i">stmt</span>) {
<span class="i">declare</span>(<span class="i">stmt</span>.<span class="i">name</span>);
<span class="i">define</span>(<span class="i">stmt</span>.<span class="i">name</span>);
<span class="k">return</span> <span class="k">null</span>;
}
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitBlockStmt</em>()</div>
<p>We aren’t going to worry about resolving the methods themselves yet, so for now
all we need to do is declare the class name itself. It’s not common to declare a
class as a local variable, but Lox permits it, so we need to handle it
correctly.</p>
<p><em>Now</em> we interpret it:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitBlockStmt</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Void</span> <span class="i">visitClassStmt</span>(<span class="t">Stmt</span>.<span class="t">Class</span> <span class="i">stmt</span>) {
<span class="i">environment</span>.<span class="i">define</span>(<span class="i">stmt</span>.<span class="i">name</span>.<span class="i">lexeme</span>, <span class="k">null</span>);
<span class="t">LoxClass</span> <span class="i">klass</span> = <span class="k">new</span> <span class="t">LoxClass</span>(<span class="i">stmt</span>.<span class="i">name</span>.<span class="i">lexeme</span>);
<span class="i">environment</span>.<span class="i">assign</span>(<span class="i">stmt</span>.<span class="i">name</span>, <span class="i">klass</span>);
<span class="k">return</span> <span class="k">null</span>;
}
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitBlockStmt</em>()</div>
<p>This looks similar to how we execute function declarations. We declare the
class’s name in the current environment. Then we turn the class <em>syntax node</em>
into a LoxClass, the <em>runtime</em> representation of a class. We circle back and
store the class object in the variable we previously declared. That two-stage
variable binding process allows references to the class inside its own methods.</p>
<p>We will refine it throughout the chapter, but the first draft of LoxClass looks
like:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxClass.java</em><br>
create new file</div>
<pre>
<span class="k">package</span> <span class="i">com.craftinginterpreters.lox</span>;
<span class="k">import</span> <span class="i">java.util.List</span>;
<span class="k">import</span> <span class="i">java.util.Map</span>;
<span class="k">class</span> <span class="t">LoxClass</span> {
<span class="k">final</span> <span class="t">String</span> <span class="i">name</span>;
<span class="t">LoxClass</span>(<span class="t">String</span> <span class="i">name</span>) {
<span class="k">this</span>.<span class="i">name</span> = <span class="i">name</span>;
}
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">String</span> <span class="i">toString</span>() {
<span class="k">return</span> <span class="i">name</span>;
}
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, create new file</div>
<p>Literally a wrapper around a name. We don’t even store the methods yet. Not
super useful, but it does have a <code>toString()</code> method so we can write a trivial
script and test that class objects are actually being parsed and executed:</p>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">DevonshireCream</span> {
<span class="i">serveOn</span>() {
<span class="k">return</span> <span class="s">"Scones"</span>;
}
}
<span class="k">print</span> <span class="t">DevonshireCream</span>; <span class="c">// Prints "DevonshireCream".</span>
</pre></div>
<h2><a href="#creating-instances" name="creating-instances"><small>12 . 2</small>Creating Instances</a></h2>
<p>We have classes, but they don’t <em>do</em> anything yet. Lox doesn’t have “static”
methods that you can call right on the class itself, so without actual
instances, classes are useless. Thus instances are the next step.</p>
<p>While some syntax and semantics are fairly standard across OOP languages, the
way you create new instances isn’t. Ruby, following Smalltalk, creates instances
by calling a method on the class object itself, a <span
name="turtles">recursively</span> graceful approach. Some, like C++ and Java
have a <code>new</code> keyword dedicated to birthing a new object. Python has you “call”
the class itself like a function. (JavaScript, ever weird, sort of does both.)</p>
<aside name="turtles">
<p>In Smalltalk, even <em>classes</em> are created by calling methods on an existing
object, usually the desired superclass. It’s sort of a turtles-all-the-way down
thing. It ultimately bottoms out on a few magical classes like Object and
Metaclass that the runtime conjures into being <em>ex nihilo</em>.</p>
</aside>
<p>I took a minimal approach with Lox. We already have class objects, and we
already have function calls, so we’ll use call expressions on class objects to
create new instances. It’s as if a class is a factory function that generates
instances of itself. This feels elegant to me, and also spares us the need to
introduce syntax like <code>new</code>. Therefore, we can skip past the front end straight
into the runtime.</p>
<p>Right now, if you try this:</p>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">Bagel</span> {}
<span class="t">Bagel</span>();
</pre></div>
<p>You get a runtime error. <code>visitCallExpr()</code> checks to see if the called object
implements <code>LoxCallable</code> and reports an error since LoxClass doesn’t. Not <em>yet</em>,
that is:</p>
<div class="codehilite"><pre class="insert-before">
import java.util.Map;
</pre><div class="source-file"><em>lox/LoxClass.java</em><br>
replace 1 line</div>
<pre class="insert">
<span class="k">class</span> <span class="t">LoxClass</span> <span class="k">implements</span> <span class="t">LoxCallable</span> {
</pre><pre class="insert-after">
final String name;
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, replace 1 line</div>
<p>That interface requires two methods:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxClass.java</em><br>
add after <em>toString</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Object</span> <span class="i">call</span>(<span class="t">Interpreter</span> <span class="i">interpreter</span>, <span class="t">List</span><<span class="t">Object</span>> <span class="i">arguments</span>) {
<span class="t">LoxInstance</span> <span class="i">instance</span> = <span class="k">new</span> <span class="t">LoxInstance</span>(<span class="k">this</span>);
<span class="k">return</span> <span class="i">instance</span>;
}
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">int</span> <span class="i">arity</span>() {
<span class="k">return</span> <span class="n">0</span>;
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, add after <em>toString</em>()</div>
<p>The interesting one is <code>call()</code>. When you “call” a class, it instantiates a new
LoxInstance for the called class and returns it. The <code>arity()</code> method is how the
interpreter validates that you passed the right number of arguments to a
callable. For now, we’ll say you can’t pass any. When we get to user-defined
constructors, we’ll revisit this.</p>
<p>That leads us to LoxInstance, the runtime representation of an instance of a Lox
class. Again, our first iteration starts small:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxInstance.java</em><br>
create new file</div>
<pre>
<span class="k">package</span> <span class="i">com.craftinginterpreters.lox</span>;
<span class="k">import</span> <span class="i">java.util.HashMap</span>;
<span class="k">import</span> <span class="i">java.util.Map</span>;
<span class="k">class</span> <span class="t">LoxInstance</span> {
<span class="k">private</span> <span class="t">LoxClass</span> <span class="i">klass</span>;
<span class="t">LoxInstance</span>(<span class="t">LoxClass</span> <span class="i">klass</span>) {
<span class="k">this</span>.<span class="i">klass</span> = <span class="i">klass</span>;
}
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">String</span> <span class="i">toString</span>() {
<span class="k">return</span> <span class="i">klass</span>.<span class="i">name</span> + <span class="s">" instance"</span>;
}
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, create new file</div>
<p>Like LoxClass, it’s pretty bare bones, but we’re only getting started. If you
want to give it a try, here’s a script to run:</p>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">Bagel</span> {}
<span class="k">var</span> <span class="i">bagel</span> = <span class="t">Bagel</span>();
<span class="k">print</span> <span class="i">bagel</span>; <span class="c">// Prints "Bagel instance".</span>
</pre></div>
<p>It doesn’t do much, but it’s starting to do <em>something</em>.</p>
<h2><a href="#properties-on-instances" name="properties-on-instances"><small>12 . 3</small>Properties on Instances</a></h2>
<p>We have instances, so we should make them useful. We’re at a fork in the road.
We could add behavior first<span class="em">—</span>methods<span class="em">—</span>or we could start with state<span class="em">—</span>properties. We’re going to take the latter because, as we’ll see, the two get
entangled in an interesting way and it will be easier to make sense of them if
we get properties working first.</p>
<p>Lox follows JavaScript and Python in how it handles state. Every instance is an
open collection of named values. Methods on the instance’s class can access and
modify properties, but so can <span name="outside">outside</span> code.
Properties are accessed using a <code>.</code> syntax:</p>
<aside name="outside">
<p>Allowing code outside of the class to directly modify an object’s fields goes
against the object-oriented credo that a class <em>encapsulates</em> state. Some
languages take a more principled stance. In Smalltalk, fields are accessed using
simple identifiers<span class="em">—</span>essentially variables that are only in scope inside a
class’s methods. Ruby uses <code>@</code> followed by a name to access a field in an
object. That syntax is only meaningful inside a method and always accesses state
on the current object.</p>
<p>Lox, for better or worse, isn’t quite so pious about its OOP faith.</p>
</aside>
<div class="codehilite"><pre>
<span class="i">someObject</span>.<span class="i">someProperty</span>
</pre></div>
<p>An expression followed by a <code>.</code> and an identifier reads the property with that
name from the object the expression evaluates to. That <code>.</code> is as high precedence
as the parentheses in a function call expression, so we slot it into the grammar
by replacing the existing <code>call</code> rule with:</p>
<div class="codehilite"><pre>
<span class="i">call</span> → <span class="i">primary</span> ( <span class="s">"("</span> <span class="i">arguments</span>? <span class="s">")"</span> | <span class="s">"."</span> <span class="t">IDENTIFIER</span> )* ;
</pre></div>
<p>After a primary expression, we allow a series of any mixture of parenthesized
calls and dotted property accesses. “Property access” is a mouthful, so from
here on out, we’ll call these “get expressions”.</p>
<h3><a href="#get-expressions" name="get-expressions"><small>12 . 3 . 1</small>Get expressions</a></h3>
<p>The <span name="get-ast">syntax tree node</span> is:</p>
<div class="codehilite"><pre class="insert-before">
"Call : Expr callee, Token paren, List<Expr> arguments",
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">
<span class="s">"Get : Expr object, Token name"</span>,
</pre><pre class="insert-after">
"Grouping : Expr expression",
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>
<aside name="get-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#get-expression">Appendix II</a>.</p>
</aside>
<p>Following the grammar, the new parsing code goes in our existing <code>call()</code>
method:</p>
<div class="codehilite"><pre class="insert-before">
while (true) {<span name="while-true"> </span>
if (match(LEFT_PAREN)) {
expr = finishCall(expr);
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>call</em>()</div>
<pre class="insert">
} <span class="k">else</span> <span class="k">if</span> (<span class="i">match</span>(<span class="i">DOT</span>)) {
<span class="t">Token</span> <span class="i">name</span> = <span class="i">consume</span>(<span class="i">IDENTIFIER</span>,
<span class="s">"Expect property name after '.'."</span>);
<span class="i">expr</span> = <span class="k">new</span> <span class="t">Expr</span>.<span class="t">Get</span>(<span class="i">expr</span>, <span class="i">name</span>);
</pre><pre class="insert-after">
} else {
break;
}
}
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>call</em>()</div>
<p>The outer <code>while</code> loop there corresponds to the <code>*</code> in the grammar rule. We zip
along the tokens building up a chain of calls and gets as we find parentheses
and dots, like so:</p><img src="image/classes/zip.png" alt="Parsing a series of '.' and '()' expressions to an AST." />
<p>Instances of the new Expr.Get node feed into the resolver:</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitCallExpr</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Void</span> <span class="i">visitGetExpr</span>(<span class="t">Expr</span>.<span class="t">Get</span> <span class="i">expr</span>) {
<span class="i">resolve</span>(<span class="i">expr</span>.<span class="i">object</span>);
<span class="k">return</span> <span class="k">null</span>;
}
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitCallExpr</em>()</div>
<p>OK, not much to that. Since properties are looked up <span
name="dispatch">dynamically</span>, they don’t get resolved. During resolution,
we only recurse into the expression to the left of the dot. The actual property
access happens in the interpreter:</p>
<aside name="dispatch">
<p>You can literally see that property dispatch in Lox is dynamic since we don’t
process it during the static resolution pass.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitCallExpr</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Object</span> <span class="i">visitGetExpr</span>(<span class="t">Expr</span>.<span class="t">Get</span> <span class="i">expr</span>) {
<span class="t">Object</span> <span class="i">object</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">object</span>);
<span class="k">if</span> (<span class="i">object</span> <span class="k">instanceof</span> <span class="t">LoxInstance</span>) {
<span class="k">return</span> ((<span class="t">LoxInstance</span>) <span class="i">object</span>).<span class="i">get</span>(<span class="i">expr</span>.<span class="i">name</span>);
}
<span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">expr</span>.<span class="i">name</span>,
<span class="s">"Only instances have properties."</span>);
}
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitCallExpr</em>()</div>
<p>First, we evaluate the expression whose property is being accessed. In Lox, only
instances of classes have properties. If the object is some other type like a
number, invoking a getter on it is a runtime error.</p>
<p>If the object is a LoxInstance, then we ask it to look up the property. Looks
like it’s time to give LoxInstance some actual state. A map will do fine:</p>
<div class="codehilite"><pre class="insert-before">
private LoxClass klass;
</pre><div class="source-file"><em>lox/LoxInstance.java</em><br>
in class <em>LoxInstance</em></div>
<pre class="insert">
<span class="k">private</span> <span class="k">final</span> <span class="t">Map</span><<span class="t">String</span>, <span class="t">Object</span>> <span class="i">fields</span> = <span class="k">new</span> <span class="t">HashMap</span><>();
</pre><pre class="insert-after">
LoxInstance(LoxClass klass) {
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, in class <em>LoxInstance</em></div>
<p>Each key in the map is a property name and the corresponding value is the
property’s value. To look up a property on an instance:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxInstance.java</em><br>
add after <em>LoxInstance</em>()</div>
<pre>
<span class="t">Object</span> <span class="i">get</span>(<span class="t">Token</span> <span class="i">name</span>) {
<span class="k">if</span> (<span class="i">fields</span>.<span class="i">containsKey</span>(<span class="i">name</span>.<span class="i">lexeme</span>)) {
<span class="k">return</span> <span class="i">fields</span>.<span class="i">get</span>(<span class="i">name</span>.<span class="i">lexeme</span>);
}
<span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">name</span>,<span name="hidden"> </span>
<span class="s">"Undefined property '"</span> + <span class="i">name</span>.<span class="i">lexeme</span> + <span class="s">"'."</span>);
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, add after <em>LoxInstance</em>()</div>
<aside name="hidden">
<p>Doing a hash table lookup for every field access is fast enough for many
language implementations, but not ideal. High performance VMs for languages like
JavaScript use sophisticated optimizations like “<a href="http://richardartoul.github.io/jekyll/update/2015/04/26/hidden-classes.html">hidden classes</a>” to avoid
that overhead.</p>
<p>Paradoxically, many of the optimizations invented to make dynamic languages fast
rest on the observation that<span class="em">—</span>even in those languages<span class="em">—</span>most code is fairly
static in terms of the types of objects it works with and their fields.</p>
</aside>
<p>An interesting edge case we need to handle is what happens if the instance
doesn’t <em>have</em> a property with the given name. We could silently return some
dummy value like <code>nil</code>, but my experience with languages like JavaScript is that
this behavior masks bugs more often than it does anything useful. Instead, we’ll
make it a runtime error.</p>
<p>So the first thing we do is see if the instance actually has a field with the
given name. Only then does it return it. Otherwise, it raises an error.</p>
<p>Note how I switched from talking about “properties” to “fields”. There is a
subtle difference between the two. Fields are named bits of state stored
directly in an instance. Properties are the named, uh, <em>things</em>, that a get
expression may return. Every field is a property, but as we’ll see <span
name="foreshadowing">later</span>, not every property is a field.</p>
<aside name="foreshadowing">
<p>Ooh, foreshadowing. Spooky!</p>
</aside>
<p>In theory, we can now read properties on objects. But since there’s no way to
actually stuff any state into an instance, there are no fields to access. Before
we can test out reading, we must support writing.</p>
<h3><a href="#set-expressions" name="set-expressions"><small>12 . 3 . 2</small>Set expressions</a></h3>
<p>Setters use the same syntax as getters, except they appear on the left side of
an assignment:</p>
<div class="codehilite"><pre>
<span class="i">someObject</span>.<span class="i">someProperty</span> = <span class="i">value</span>;
</pre></div>
<p>In grammar land, we extend the rule for assignment to allow dotted identifiers
on the left-hand side:</p>
<div class="codehilite"><pre>
<span class="i">assignment</span> → ( <span class="i">call</span> <span class="s">"."</span> )? <span class="t">IDENTIFIER</span> <span class="s">"="</span> <span class="i">assignment</span>
| <span class="i">logic_or</span> ;
</pre></div>
<p>Unlike getters, setters don’t chain. The reference to <code>call</code> allows any high
precedence expression before the last <code>.</code>, including a series of property
accesses, as in:</p><img src="image/classes/setter.png" alt="breakfast.omelette.filling.meat = ham" />
<p>Note here that only the <em>last</em> part, the <code>.meat</code> is the <em>setter</em>. The
<code>.omelette</code> and <code>.filling</code> parts are both <em>get</em> expressions.</p>
<p>Like we have two separate AST nodes for variable access and variable assignment,
we need a <span name="set-ast">second setter node</span> to complement our
getter node:</p>
<div class="codehilite"><pre class="insert-before">
"Logical : Expr left, Token operator, Expr right",
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">
<span class="s">"Set : Expr object, Token name, Expr value"</span>,
</pre><pre class="insert-after">
"Unary : Token operator, Expr right",
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>
<aside name="set-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#set-expression">Appendix II</a>.</p>
</aside>
<p>In case you don’t remember, the way we handle assignment in the parser is a
little funny. We can’t easily tell that a series of tokens is the left-hand side
of an assignment until we reach the <code>=</code>. Now that our assignment grammar rule
has <code>call</code> on the left side, which can expand to arbitrarily large expressions,
that final <code>=</code> may be many tokens away from the point where we need to know
we’re parsing an assignment.</p>
<p>Instead, the trick we do is to parse the left hand side as a normal expression.
Then, when we stumble onto the equals sign after it, we take the expression we
already parsed and transform it into the correct syntax tree node for the
assignment.</p>
<p>We add another clause to that transformation to handle turning an Expr.Get
expression on the left into the corresponding Expr.Set:</p>
<div class="codehilite"><pre class="insert-before">
return new Expr.Assign(name, value);
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>assignment</em>()</div>
<pre class="insert">
} <span class="k">else</span> <span class="k">if</span> (<span class="i">expr</span> <span class="k">instanceof</span> <span class="t">Expr</span>.<span class="t">Get</span>) {
<span class="t">Expr</span>.<span class="t">Get</span> <span class="i">get</span> = (<span class="t">Expr</span>.<span class="t">Get</span>)<span class="i">expr</span>;
<span class="k">return</span> <span class="k">new</span> <span class="t">Expr</span>.<span class="t">Set</span>(<span class="i">get</span>.<span class="i">object</span>, <span class="i">get</span>.<span class="i">name</span>, <span class="i">value</span>);
</pre><pre class="insert-after">
}
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>assignment</em>()</div>
<p>That’s our syntax. We push that through into the resolver:</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitLogicalExpr</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Void</span> <span class="i">visitSetExpr</span>(<span class="t">Expr</span>.<span class="t">Set</span> <span class="i">expr</span>) {
<span class="i">resolve</span>(<span class="i">expr</span>.<span class="i">value</span>);
<span class="i">resolve</span>(<span class="i">expr</span>.<span class="i">object</span>);
<span class="k">return</span> <span class="k">null</span>;
}
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitLogicalExpr</em>()</div>
<p>Again, like Expr.Get, the property itself is dynamically evaluated, so there’s
nothing to resolve there. All we need to do is recurse into the two
subexpressions of Expr.Set, the object whose property is being set, and the
value it’s being set to.</p>
<p>That leads us to the interpreter:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitLogicalExpr</em>()</div>
<pre>
<span class="a">@Override</span>
<span class="k">public</span> <span class="t">Object</span> <span class="i">visitSetExpr</span>(<span class="t">Expr</span>.<span class="t">Set</span> <span class="i">expr</span>) {
<span class="t">Object</span> <span class="i">object</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">object</span>);
<span class="k">if</span> (!(<span class="i">object</span> <span class="k">instanceof</span> <span class="t">LoxInstance</span>)) {<span name="order"> </span>
<span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">expr</span>.<span class="i">name</span>, <span class="s">"Only instances have fields."</span>);
}
<span class="t">Object</span> <span class="i">value</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">value</span>);
((<span class="t">LoxInstance</span>)<span class="i">object</span>).<span class="i">set</span>(<span class="i">expr</span>.<span class="i">name</span>, <span class="i">value</span>);
<span class="k">return</span> <span class="i">value</span>;
}
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitLogicalExpr</em>()</div>
<p>We evaluate the object whose property is being set and we check to see if it’s a
LoxInstance. If not, that’s a runtime error. Otherwise, we evaluate the value
being set and store it on the instance. That relies on:</p>
<aside name="order">
<p>This is another semantic edge case. There are three distinct operations:</p>
<ol>
<li>
<p>Evaluate the object.</p>
</li>
<li>
<p>Raise a runtime error if it’s not an instance of a class.</p>
</li>
<li>
<p>Evaluate the value.</p>
</li>
</ol>
<p>The order that those are performed could be user visible, which means we need to
carefully specify it and ensure our implementations do these in the same order.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/LoxInstance.java</em><br>
add after <em>get</em>()</div>
<pre>
<span class="t">void</span> <span class="i">set</span>(<span class="t">Token</span> <span class="i">name</span>, <span class="t">Object</span> <span class="i">value</span>) {
<span class="i">fields</span>.<span class="i">put</span>(<span class="i">name</span>.<span class="i">lexeme</span>, <span class="i">value</span>);
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, add after <em>get</em>()</div>
<p>No real magic here. We go straight to the Java map in the instance where fields
are stored. Since we allow freely creating new fields on instances, there’s no
need to see if the key is already present.</p>
<h2><a href="#methods-on-classes" name="methods-on-classes"><small>12 . 4</small>Methods on Classes</a></h2>
<p>You can create instances of classes and stuff data into them, but the class
itself doesn’t really <em>do</em> anything. Instances are just maps and all instances
are more or less the same. To make them feel like instances <em>of classes</em>, we
need behavior<span class="em">—</span>methods.</p>
<p>Our helpful parser already parses method declarations, so we’re good there. We
also don’t need to add any new parser support for method <em>calls</em>. We already
have <code>.</code> (getters) and <code>()</code> (function calls). A “method call” simply chains
those together:</p><img src="image/classes/method.png" alt="The syntax tree for 'object.method(argument)" />
<p>That raises an interesting question. What happens when those two expressions are
pulled apart? Assuming <code>method</code> is a method on the class of <code>object</code> and not a
field on the instance, what should this do:</p>
<div class="codehilite"><pre>
<span class="k">var</span> <span class="i">m</span> = <span class="i">object</span>.<span class="i">method</span>;
<span class="i">m</span>(<span class="i">argument</span>);
</pre></div>
<p>This program “looks up” the method and stores the result<span class="em">—</span>whatever that is<span class="em">—</span>in a variable and then calls that object later. Is this allowed? Can you treat a
method like it’s a function on the instance?</p>
<p>What about the other direction?</p>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">Box</span> {}
<span class="k">fun</span> <span class="i">notMethod</span>(<span class="i">argument</span>) {
<span class="k">print</span> <span class="s">"called function with "</span> + <span class="i">argument</span>;
}
<span class="k">var</span> <span class="i">box</span> = <span class="t">Box</span>();
<span class="i">box</span>.<span class="i">function</span> = <span class="i">notMethod</span>;
<span class="i">box</span>.<span class="i">function</span>(<span class="s">"argument"</span>);
</pre></div>
<p>This program creates an instance and then stores a function in a field on it.
Then it calls that function using the same syntax as a method call. Does that
work?</p>
<p>Different languages have different answers to these questions. One could write a
treatise on it. For Lox, we’ll say the answer to both of these is that, yes, it
does work. We have a couple of reasons to justify that. For the second
example<span class="em">—</span>calling a function stored in a field<span class="em">—</span>we want to support that
because first class functions are useful and storing them in fields is a
perfectly normal thing to do.</p>
<p>The first example is more obscure. One motivation is that users generally expect
to be able to hoist a subexpression out into a local variable without changing
the meaning of the program. You can take this:</p>
<div class="codehilite"><pre>
<span class="i">breakfast</span>(<span class="i">omelette</span>.<span class="i">filledWith</span>(<span class="i">cheese</span>), <span class="i">sausage</span>);
</pre></div>
<p>And turn it into this:</p>
<div class="codehilite"><pre>
<span class="k">var</span> <span class="i">eggs</span> = <span class="i">omelette</span>.<span class="i">filledWith</span>(<span class="i">cheese</span>);
<span class="i">breakfast</span>(<span class="i">eggs</span>, <span class="i">sausage</span>);
</pre></div>
<p>And it does the same thing. Likewise, since the <code>.</code> and the <code>()</code> in a method
call <em>are</em> two separate expressions, it seems you should be able to hoist the
<em>lookup</em> part into a variable and then call it <span
name="callback">later</span>. We need to think carefully about what the <em>thing</em>
you get when you look up a method is, and how it behaves, even in weird cases
like:</p>
<aside name="callback">
<p>A motivating use for this is callbacks. Often, you want to pass a callback whose
body simply invokes a method on some object. Being able to lookup the method and
pass it directly saves you the chore of manually declaring a function to wrap
it. Compare this:</p>
<div class="codehilite"><pre>
<span class="k">fun</span> <span class="i">callback</span>(<span class="i">a</span>, <span class="i">b</span>, <span class="i">c</span>) {
<span class="i">object</span>.<span class="i">method</span>(<span class="i">a</span>, <span class="i">b</span>, <span class="i">c</span>);
}
<span class="i">takeCallback</span>(<span class="i">callback</span>);
</pre></div>
<p>Versus this:</p>
<div class="codehilite"><pre>
<span class="i">takeCallback</span>(<span class="i">object</span>.<span class="i">method</span>);
</pre></div>
</aside>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">Person</span> {
<span class="i">sayName</span>() {
<span class="k">print</span> <span class="k">this</span>.<span class="i">name</span>;
}
}
<span class="k">var</span> <span class="i">jane</span> = <span class="t">Person</span>();
<span class="i">jane</span>.<span class="i">name</span> = <span class="s">"Jane"</span>;
<span class="k">var</span> <span class="i">method</span> = <span class="i">jane</span>.<span class="i">sayName</span>;
<span class="i">method</span>(); <span class="c">// ?</span>
</pre></div>
<p>If you grab a handle to a method on some instance and call it later, does it
“remember” the instance it was pulled off from? Does <code>this</code> inside the method
still refer to that original object?</p>
<p>Here’s a more pathological example to bend your brain:</p>
<div class="codehilite"><pre>
<span class="k">class</span> <span class="t">Person</span> {
<span class="i">sayName</span>() {
<span class="k">print</span> <span class="k">this</span>.<span class="i">name</span>;
}
}
<span class="k">var</span> <span class="i">jane</span> = <span class="t">Person</span>();
<span class="i">jane</span>.<span class="i">name</span> = <span class="s">"Jane"</span>;
<span class="k">var</span> <span class="i">bill</span> = <span class="t">Person</span>();
<span class="i">bill</span>.<span class="i">name</span> = <span class="s">"Bill"</span>;
<span class="i">bill</span>.<span class="i">sayName</span> = <span class="i">jane</span>.<span class="i">sayName</span>;
<span class="i">bill</span>.<span class="i">sayName</span>(); <span class="c">// ?</span>
</pre></div>
<p>Does that last line print “Bill” because that’s the instance that we <em>called</em>
the method through, or “Jane” because it’s the instance where we first grabbed
the method?</p>
<p>Equivalent code in Lua and JavaScript would print “Bill”. Those languages don’t
really have a notion of “methods”. Everything is sort of functions-in-fields, so
it’s not clear that <code>jane</code> “owns” <code>sayName</code> any more than <code>bill</code> does.</p>
<p>Lox, though, has real class syntax so we do know which callable things are
methods and which are functions. Thus, like Python, C#, and others, we will have
methods “bind” <code>this</code> to the original instance when the method is first grabbed.
Python calls <span name="bound">these</span> “bound methods”.</p>
<aside name="bound">
<p>I know, imaginative name, right?</p>
</aside>
<p>In practice, that’s usually what you want. If you take a reference to a method
on some object so you can use it as a callback later, you want to remember the
instance it belonged to, even if that callback happens to be stored in a field
on some other object.</p>
<p>OK, that’s a lot of semantics to load into your head. Forget about the edge
cases for a bit. We’ll get back to those. For now, let’s get basic method calls
working. We’re already parsing the method declarations inside the class body, so
the next step is to resolve them:</p>
<div class="codehilite"><pre class="insert-before">
define(stmt.name);
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">
<span class="k">for</span> (<span class="t">Stmt</span>.<span class="t">Function</span> <span class="i">method</span> : <span class="i">stmt</span>.<span class="i">methods</span>) {
<span class="t">FunctionType</span> <span class="i">declaration</span> = <span class="t">FunctionType</span>.<span class="i">METHOD</span>;
<span class="i">resolveFunction</span>(<span class="i">method</span>, <span class="i">declaration</span>);<span name="local"> </span>
}
</pre><pre class="insert-after">
return null;
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>
<aside name="local">
<p>Storing the function type in a local variable is pointless right now, but we’ll
expand this code before too long and it will make more sense.</p>
</aside>
<p>We iterate through the methods in the class body and call the
<code>resolveFunction()</code> method we wrote for handling function declarations already.
The only difference is that we pass in a new FunctionType enum value:</p>
<div class="codehilite"><pre class="insert-before">
NONE,
</pre><pre class="insert-before">
<span class="i">FUNCTION</span><span class="insert-comma">,</span>
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in enum <em>FunctionType</em><br>
add <em>“,”</em> to previous line</div>
<pre class="insert">
<span class="i">METHOD</span>
</pre><pre class="insert-after">
}
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in enum <em>FunctionType</em>, add <em>“,”</em> to previous line</div>
<p>That’s going to be important when we resolve <code>this</code> expressions. For now, don’t
worry about it. The interesting stuff is in the interpreter:</p>
<div class="codehilite"><pre class="insert-before">
environment.define(stmt.name.lexeme, null);
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitClassStmt</em>()<br>
replace 1 line</div>
<pre class="insert">
<span class="t">Map</span><<span class="t">String</span>, <span class="t">LoxFunction</span>> <span class="i">methods</span> = <span class="k">new</span> <span class="t">HashMap</span><>();
<span class="k">for</span> (<span class="t">Stmt</span>.<span class="t">Function</span> <span class="i">method</span> : <span class="i">stmt</span>.<span class="i">methods</span>) {
<span class="t">LoxFunction</span> <span class="i">function</span> = <span class="k">new</span> <span class="t">LoxFunction</span>(<span class="i">method</span>, <span class="i">environment</span>);
<span class="i">methods</span>.<span class="i">put</span>(<span class="i">method</span>.<span class="i">name</span>.<span class="i">lexeme</span>, <span class="i">function</span>);
}
<span class="t">LoxClass</span> <span class="i">klass</span> = <span class="k">new</span> <span class="t">LoxClass</span>(<span class="i">stmt</span>.<span class="i">name</span>.<span class="i">lexeme</span>, <span class="i">methods</span>);
</pre><pre class="insert-after">
environment.assign(stmt.name, klass);
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitClassStmt</em>(), replace 1 line</div>
<p>When we interpret a class declaration statement, we turn the syntactic
representation of the class<span class="em">—</span>its AST node<span class="em">—</span>into its runtime representation.
Now, we need to do that for the methods contained in the class as well. Each
method declaration blossoms into a LoxFunction object.</p>
<p>We take all of those and wrap them up into a map, keyed by the method names.
That gets stored in LoxClass:</p>
<div class="codehilite"><pre class="insert-before">
final String name;
</pre><div class="source-file"><em>lox/LoxClass.java</em><br>
in class <em>LoxClass</em><br>
replace 4 lines</div>
<pre class="insert">
<span class="k">private</span> <span class="k">final</span> <span class="t">Map</span><<span class="t">String</span>, <span class="t">LoxFunction</span>> <span class="i">methods</span>;
<span class="t">LoxClass</span>(<span class="t">String</span> <span class="i">name</span>, <span class="t">Map</span><<span class="t">String</span>, <span class="t">LoxFunction</span>> <span class="i">methods</span>) {
<span class="k">this</span>.<span class="i">name</span> = <span class="i">name</span>;
<span class="k">this</span>.<span class="i">methods</span> = <span class="i">methods</span>;
}
</pre><pre class="insert-after">
@Override
public String toString() {
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, in class <em>LoxClass</em>, replace 4 lines</div>
<p>Where an instance stores state, the class stores behavior. LoxInstance has its
map of fields, and LoxClass gets a map of methods. Even though methods are
owned by the class, they are still accessed through instances of that class:</p>
<div class="codehilite"><pre class="insert-before">
Object get(Token name) {
if (fields.containsKey(name.lexeme)) {
return fields.get(name.lexeme);
}
</pre><div class="source-file"><em>lox/LoxInstance.java</em><br>
in <em>get</em>()</div>
<pre class="insert">
<span class="t">LoxFunction</span> <span class="i">method</span> = <span class="i">klass</span>.<span class="i">findMethod</span>(<span class="i">name</span>.<span class="i">lexeme</span>);
<span class="k">if</span> (<span class="i">method</span> != <span class="k">null</span>) <span class="k">return</span> <span class="i">method</span>;
</pre><pre class="insert-after">
throw new RuntimeError(name,<span name="hidden"> </span>
"Undefined property '" + name.lexeme + "'.");
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, in <em>get</em>()</div>
<p>When looking up a property on an instance, if we don’t <span
name="shadow">find</span> a matching field, we look for a method with that name
on the instance’s class. If found, we return that. This is where the distinction
between “field” and “property” becomes meaningful. When accessing a property,
you might get a field<span class="em">—</span>a bit of state stored on the instance<span class="em">—</span>or you could
hit a method defined on the instance’s class.</p>
<p>The method is looked up using this:</p>
<aside name="shadow">
<p>Looking for a field first implies that fields shadow methods, a subtle but
important semantic point.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/LoxClass.java</em><br>
add after <em>LoxClass</em>()</div>
<pre>