1 Concepts
2 ========
3
4 This document describes the underlying concepts employed in micropython.
5
6 * Namespaces and attribute definition
7 * Contexts and values
8 * Tables, attributes and lookups
9 * Objects and structures
10 * Parameters and lookups
11 * Instantiation
12 * Register usage
13 * List and tuple representations
14
15 Namespaces and Attribute Definition
16 ===================================
17
18 Namespaces are any objects which can retain attributes.
19
20 * Module attributes are defined either at the module level or by global
21 statements.
22 * Class attributes are defined only within class statements.
23 * Instance attributes are defined only by assignments to attributes of self
24 within __init__ methods.
25
26 These restrictions apply because such attributes are thus explicitly declared,
27 permitting the use of tables (described below). Module and class attributes
28 can also be finalised in this way in order to permit certain optimisations.
29
30 An additional restriction required for the current implementation of tables
31 (as described below) applies to class definitions: each class must be defined
32 using a unique name; repeated definition of classes having the same name is
33 thus not permitted. This restriction arises from the use of the "full name" of
34 a class as a key to the object table, where the full name is a qualified path
35 via the module hierarchy ending with the name of the class.
36
37 See rejected.txt for complicating mechanisms which could be applied to
38 mitigate the effects of these restrictions on optimisations.
39
40 Contexts and Values
41 ===================
42
43 Values are used as the common reference representation in micropython: as
44 stored representations of attributes (of classes, instances, modules, and
45 other objects supporting attribute-like entities) as well as the stored values
46 associated with names in functions and methods.
47
48 Unlike other implementations, micropython does not create things like bound
49 method objects for individual instances. Instead, all objects are referenced
50 using a context, reference pair:
51
52 Value Layout
53 ------------
54
55 0 1
56 context object
57 reference reference
58
59 Specific implementations might reverse this ordering for optimisation
60 purposes.
61
62 Rationale
63 ---------
64
65 To reduce the number of created objects whilst retaining the ability to
66 support bound method invocations. The context indicates the context in which
67 an invocation is performed, typically the owner of the method.
68
69 Usage
70 -----
71
72 The context may be inserted as the first argument when a value is involved in
73 an invocation. This argument may then be omitted from the invocation if its
74 usage is not appropriate.
75
76 See invocation.txt for details.
77
78 Context Value Types
79 -------------------
80
81 The following types of context value exist:
82
83 Type Usage Transformations
84 ---- ----- ---------------
85
86 Replaceable With functions (not methods) May be replaced with an
87 instance or a class when a
88 value is stored on an
89 instance or class
90
91 Placeholder With classes May not be replaced
92
93 Instance With instances (and constants) May not be replaced
94 or functions as methods
95
96 Class With functions as methods May be replaced when a
97 value is loaded from a
98 class attribute via an
99 instance
100
101 Contexts in Acquired Values
102 ---------------------------
103
104 There are four classes of instructions which provide values:
105
106 Instruction Purpose Context Operations
107 ----------- ------- ------------------
108
109 1) LoadConst Load module, constant Use loaded object with itself
110 as context
111
112 2) LoadFunction Load function Combine replaceable context
113 with loaded object
114
115 3) LoadClass Load class Combine placeholder context
116 with loaded object
117
118 4) LoadAddress* Load attribute from Preserve or override stored
119 LoadAttr* class, module, context (as described in
120 instance assignment.txt)
121
122 In order to comply with traditional Python behaviour, contexts may or may not
123 represent the object from which an attribute has been acquired.
124
125 See assignment.txt for details.
126
127 Contexts in Stored Values
128 -------------------------
129
130 There are two classes of instruction for storing values:
131
132 Instruction Purpose Context Operations
133 ----------- ------- ------------------
134
135 1) StoreAddress Store attribute in a Preserve context; note that no
136 known object test for class attribute
137 assignment should be necessary
138 since this instruction should only
139 be generated for module globals
140
141 StoreAttr Store attribute in an Preserve context; note that no
142 instance test for class attribute
143 assignment should be necessary
144 since this instruction should only
145 be generated for self accesses
146
147 StoreAttrIndex Store attribute in an Preserve context; since the index
148 unknown object lookup could yield a class
149 attribute, a test of the nature of
150 the nature of the structure is
151 necessary in order to prevent
152 assignments to classes
153
154 2) StoreAddressContext Store attribute in a Override context if appropriate;
155 known object if the value has a replaceable
156 context, permit the target to
157 take ownership of the value
158
159 See assignment.txt for details.
160
161 Tables, Attributes and Lookups
162 ==============================
163
164 Attribute lookups, where the exact location of an object attribute is deduced,
165 are performed differently in micropython than in other implementations.
166 Instead of providing attribute dictionaries, in which attributes are found,
167 attributes are located at fixed places in object structures (described below)
168 and their locations are stored using a special representation known as a
169 table.
170
171 For a given program, a table can be considered as being like a matrix mapping
172 classes to attribute names. For example:
173
174 class A:
175 # instances have attributes x, y
176
177 class B(A):
178 # introduces attribute z for instances
179
180 class C:
181 # instances have attributes a, b, z
182
183 This would provide the following table, referred to as an object table in the
184 context of classes and instances:
185
186 Class/attr a b x y z
187
188 A 1 2
189 B 1 2 3
190 C 1 2 3
191
192 A limitation of this representation is that instance attributes may not shadow
193 class attributes: if an attribute with a given name is not defined on an
194 instance, an attribute with the same name cannot be provided by the class of
195 the instance or any superclass of the instance's class. The exception to this
196 restriction is the __class__ attribute, as described below.
197
198 The table can be compacted using a representation known as a displacement
199 list (referred to as an object list in this context):
200
201 Classes with attribute offsets
202
203 classcode A
204 attrcode a b x y z
205
206 B
207 a b x y z
208
209 C
210 a b x y z
211
212 List . . 1 2 1 2 3 1 2 . . 3
213
214 Here, the classcode refers to the offset in the list at which a class's
215 attributes are defined, whereas the attrcode defines the offset within a
216 region of attributes corresponding to a single attribute of a given name.
217
218 Attribute Locations
219 -------------------
220
221 The locations stored in table/list elements are generally for instance
222 attributes relative to the location of the instance, whereas those for class
223 attributes and module attributes are generally absolute addresses. Thus, each
224 occupied table cell has the following structure:
225
226 attrcode, uses-absolute-address, address (or location)
227
228 This could be given instead as follows:
229
230 attrcode, is-class-or-module, location
231
232 Since uses-absolute-address corresponds to is-class-or-module, and since there
233 is a need to test for classes and modules to prevent assignment to attributes
234 of such objects, this particular information is always required.
235
236 The __class__ Attribute
237 -----------------------
238
239 The exception to the above general rules about relative locations and absolute
240 addresses involves the __class__ attribute which is defined differently for
241 each class and its instances. Since the table elements can only refer to a
242 single absolute address, thus providing only a single value, such absolute
243 references which are sufficient for most class attributes would not be
244 appropriate for the __class__ attribute. Using a common object-relative
245 location of 0 permits the first attribute to be accessed via an object address
246 regardless of whether a class or instance is involved.
247
248 Obviously, this requires both classes and instances to retain an attribute
249 location specifically to hold the value appropriate for each object type,
250 whereas a scheme which omits the __class__ attribute on classes would be able
251 to employ an absolute address in the table and maintain only a single address
252 to refer to the class for all instances.
253
254 Comparing Tables as Matrices with Displacement Lists
255 ----------------------------------------------------
256
257 Although displacement lists can provide reasonable levels of compaction for
258 attribute data, the element size is larger than that required for a simple
259 matrix: the attribute code (attrcode) need not be stored since each element
260 unambiguously refers to the availability of an attribute for a particular
261 class or instance of that class, and so the data at a given element need not
262 be tested for relevance to a given attribute access operation.
263
264 Given a program with 20 object types and 100 attribute types, a matrix would
265 occupy the following amount of space:
266
267 number of object types * number of attribute types * element size
268 = 20 * 100 * 1 (assuming that a single location is sufficient for an element)
269 = 2000
270
271 In contrast, given a compaction to 40% of the matrix size (without considering
272 element size) in a displacement list, the amount of space would be as follows:
273
274 number of elements * element size
275 = 40% * (20 * 100) * 2 (assuming that one additional location is required)
276 = 1600
277
278 Consequently, the principal overhead of using a displacement list is likely to
279 be in the need to check element relevance when retrieving values from such a
280 list.
281
282 Objects and Structures
283 ======================
284
285 As well as references, micropython needs to have actual objects to refer to.
286 Since classes, functions and instances are all objects, it is desirable that
287 certain common features and operations are supported in the same way for all
288 of these things. To permit this, a common data structure format is used.
289
290 Header.................................................... Attributes.................
291
292 Identifier Identifier Address Identifier Size Object Object ...
293
294 0 1 2 3 4 5 6 7
295 classcode attrcode/ invocation funccode size __class__ attribute ...
296 instance reference reference reference
297 status
298
299 Classcode
300 ---------
301
302 Used in attribute lookup.
303
304 Here, the classcode refers to the attribute lookup table for the object (as
305 described above). Classes and instances share the same classcode, and their
306 structures reflect this. Functions all belong to the same type and thus employ
307 the classcode for the function built-in type, whereas modules have distinct
308 types since they must support different sets of attributes.
309
310 Attrcode
311 --------
312
313 Used to test instances for membership of classes (or descendants of classes).
314
315 Since, in traditional Python, classes are only ever instances of some generic
316 built-in type, support for testing such a relationship directly has been
317 removed and the attrcode is not specified for classes: the presence of an
318 attrcode indicates that a given object is an instance. In addition, support
319 has also been removed for testing modules in the same way, meaning that the
320 attrcode is also not specified for modules.
321
322 See the "Testing Instance Compatibility with Classes (Attrcode)" section below
323 for details of attrcodes.
324
325 Invocation Reference
326 --------------------
327
328 Used when an object is called.
329
330 This is the address of the code to be executed when an invocation is performed
331 on the object.
332
333 Funccode
334 --------
335
336 Used to look up argument positions by name.
337
338 The strategy with keyword arguments in micropython is to attempt to position
339 such arguments in the invocation frame as it is being constructed.
340
341 See the "Parameters and Lookups" section for more information.
342
343 Size
344 ----
345
346 Used to indicate the size of an object including attributes.
347
348 Attributes
349 ----------
350
351 For classes, modules and instances, the attributes in the structure correspond
352 to the attributes of each kind of object. For functions, however, the
353 attributes in the structure correspond to the default arguments for each
354 function, if any.
355
356 Structure Types
357 ---------------
358
359 Class C:
360
361 0 1 2 3 4 5 6 7
362 classcode (unused) __new__ funccode size class type attribute ...
363 for C reference for reference reference
364 instantiator
365
366 Instance of C:
367
368 0 1 2 3 4 5 6 7
369 classcode attrcode C.__call__ funccode size class C attribute ...
370 for C for C reference for reference reference
371 (if exists) C.__call__
372
373 Function f:
374
375 0 1 2 3 4 5 6 7
376 classcode attrcode code funccode size class attribute ...
377 for for reference function (default)
378 function function reference reference
379
380 Module m:
381
382 0 1 2 3 4 5 6 7
383 classcode attrcode (unused) (unused) (unused) module type attribute ...
384 for m for m reference (global)
385 reference
386
387 The __class__ Attribute
388 -----------------------
389
390 All objects support the __class__ attribute and this is illustrated above with
391 the first attribute.
392
393 Class: refers to the type class (type.__class__ also refers to the type class)
394 Function: refers to the function class
395 Instance: refers to the class instantiated to make the object
396
397 Lists and Tuples
398 ----------------
399
400 The built-in list and tuple sequences employ variable length structures using
401 the attribute locations to store their elements, where each element is a
402 reference to a separately stored object.
403
404 Testing Instance Compatibility with Classes (Attrcode)
405 ------------------------------------------------------
406
407 Although it would be possible to have a data structure mapping classes to
408 compatible classes, such as a matrix indicating the subclasses (or
409 superclasses) of each class, the need to retain the key to such a data
410 structure for each class might introduce a noticeable overhead.
411
412 Instead of having a separate structure, descendant classes of each class are
413 inserted as special attributes into the object table. This requires an extra
414 key to be retained, since each class must provide its own attribute code such
415 that upon an instance/class compatibility test, the code may be obtained and
416 used in the object table.
417
418 Invocation and Code References
419 ------------------------------
420
421 Modules: there is no meaningful invocation reference since modules cannot be
422 explicitly called.
423
424 Functions: a simple code reference is employed pointing to code implementing
425 the function. Note that the function locals are completely distinct from this
426 structure and are not comparable to attributes. Instead, attributes are
427 reserved for default parameter values, although they do not appear in the
428 object table described above, appearing instead in a separate parameter table
429 described below.
430
431 Classes: given that classes must be invoked in order to create instances, a
432 reference must be provided in class structures. However, this reference does
433 not point directly at the __init__ method of the class. Instead, the
434 referenced code belongs to a special initialiser function, __new__, consisting
435 of the following instructions:
436
437 create instance for C
438 call C.__init__(instance, ...)
439 return instance
440
441 Instances: each instance employs a reference to any __call__ method defined in
442 the class hierarchy for the instance, thus maintaining its callable nature.
443
444 Both classes and modules may contain code in their definitions - the former in
445 the "body" of the class, potentially defining attributes, and the latter as
446 the "top-level" code in the module, potentially defining attributes/globals -
447 but this code is not associated with any invocation target. It is thus
448 generated in order of appearance and is not referenced externally.
449
450 Invocation Operation
451 --------------------
452
453 Consequently, regardless of the object an invocation is always done as
454 follows:
455
456 get invocation reference from the header
457 jump to reference
458
459 Additional preparation is necessary before the above code: positional
460 arguments must be saved in the invocation frame, and keyword arguments must be
461 resolved and saved to the appropriate position in the invocation frame.
462
463 See invocation.txt for details.
464
465 Parameters and Lookups
466 ======================
467
468 Since Python supports keyword arguments when making invocations, it becomes
469 necessary to record the parameter names associated with each function or
470 method. Just as object tables record attributes positions on classes and
471 instances, parameter tables record parameter positions in function or method
472 parameter lists.
473
474 For a given program, a parameter table can be considered as being like a
475 matrix mapping functions/methods to parameter names. For example:
476
477 def f(x, y, z):
478 pass
479
480 def g(a, b, c):
481 pass
482
483 def h(a, x):
484 pass
485
486 This would provide the following table, referred to as a parameter table in
487 the context of functions and methods:
488
489 Function/param a b c x y z
490
491 f 1 2 3
492 g 1 2 3
493 h 1 2
494
495 Confusion can occur when functions are adopted as methods, since the context
496 then occupies the first slot in the invocation frame:
497
498 def f(x, y, z):
499 pass
500
501 f(x=1, y=2, z=3) -> f(<context>, 1, 2, 3)
502 -> f(1, 2, 3)
503
504 class C:
505 f = f
506
507 def g(x, y, z):
508 pass
509
510 c = C()
511
512 c.f(y=2, z=3) -> f(<context>, 2, 3)
513 c.g(y=2, z=3) -> C.g(<context>, 2, 3)
514
515 Just as with parameter tables, a displacement list can be prepared from a
516 parameter table:
517
518 Functions with parameter (attribute) offsets
519
520 funccode f
521 attrcode a b c x y z
522
523 g
524 a b c x y z
525
526 h
527 a b c x y z
528
529 List . . . 1 2 3 1 2 3 1 . . 2 . .
530
531 Here, the funccode refers to the offset in the list at which a function's
532 parameters are defined, whereas the attrcode defines the offset within a
533 region of attributes corresponding to a single parameter of a given name.
534
535 Instantiation
536 =============
537
538 When instantiating classes, memory must be reserved for the header of the
539 resulting instance, along with locations for the attributes of the instance.
540 Since the instance header contains data common to all instances of a class, a
541 template header is copied to the start of the newly reserved memory region.
542 The __class__ attribute is also an essential part of instances, and this is
543 also copied to the new memory region.
544
545 Register Usage
546 ==============
547
548 During code generation, much of the evaluation produces results which are
549 implicitly recorded in the "active value" register, and various instructions
550 will consume the active value. In addition, some instructions will consume a
551 separate "active source value" from a register, typically those which are
552 assigning the result of an expression to an assignment target.
553
554 Since values often need to be retained for later use, a set of temporary
555 storage locations are typically employed. However, optimisations may reduce
556 the need to use such temporary storage where instructions which provide the
557 "active value" can be re-executed and will produce the same result.
558
559 List and Tuple Representations
560 ==============================
561
562 Since tuples have a fixed size, the representation of a tuple instance is
563 merely a header describing the size of the entire object, together with a
564 sequence of references to the object "stored" at each position in the
565 structure. Such references consist of the usual context and reference pair.
566
567 Lists, however, have a variable size and must be accessible via an unchanging
568 location even as more memory is allocated elsewhere to accommodate the
569 contents of the list. Consequently, the representation must resemble the
570 following:
571
572 Structure header for list (size == header plus special attribute)
573 Special attribute referencing the underlying sequence
574
575 The underlying sequence has a fixed size, like a tuple, but may contain fewer
576 elements than the size of the sequence permits:
577
578 Special header indicating the current size and allocated size
579 Element
580 ... <-- current size
581 (Unused space)
582 ... <-- allocated size
583
584 This representation permits the allocation of a new sequence when space is
585 exhausted in an existing sequence, with the new sequence address stored in the
586 main list structure. Since access to the contents of the list must go through
587 the main list structure, underlying allocation activities may take place
588 without the users of a list having to be aware of such activities.