Comparison

doc/coding_style.md @ 10061:5c71693c8345

Merge 0.11->trunk
author Kim Alvefur <zash@zash.se>
date Mon, 08 Jul 2019 02:44:32 +0200
parent 9939:3a7f822f6edd
child 11000:d9aae4734f38
comparison
equal deleted inserted replaced
10060:7a36b7ac309b 10061:5c71693c8345
1
2 # Prosody Coding Style Guide
3
4 This style guides lists the coding conventions used in the
5 [Prosody](https://prosody.im/) project. It is based heavily on the [style guide used by the LuaRocks project](https://github.com/luarocks/lua-style-guide).
6
7 ## Indentation and formatting
8
9 * Prosody code is indented with tabs at the start of the line, a single
10 tab per logical indent level:
11
12 ```lua
13 for i, pkg in ipairs(packages) do
14 for name, version in pairs(pkg) do
15 if name == searched then
16 print(version);
17 end
18 end
19 end
20 ```
21
22 Tab width is configurable in editors, so never assume a particular width.
23 Specically this means you should not mix tabs and spaces, or use tabs for
24 alignment of items at different indentation levels.
25
26 * Use LF (Unix) line endings.
27
28 ## Comments
29
30 * Comments are encouraged where necessary to explain non-obvious code.
31
32 * In general comments should be used to explain 'why', not 'how'
33
34 ### Comment tags
35
36 A comment may be prefixed with one of the following tags:
37
38 * **FIXME**: Indicates a serious problem with the code that should be addressed
39 * **TODO**: Indicates an open task, feature request or code restructuring that
40 is primarily of interest to developers (otherwise it should be in the
41 issue tracker).
42 * **COMPAT**: Must be used on all code that is present only for backwards-compatibility,
43 and may be removed one day. For example code that is added to support old
44 or buggy third-party software or dependencies.
45
46 **Example:**
47
48 ```lua
49 -- TODO: implement method
50 local function something()
51 -- FIXME: check conditions
52 end
53
54 ```
55
56 ## Variable names
57
58 * Variable names with larger scope should be more descriptive than those with
59 smaller scope. One-letter variable names should be avoided except for very
60 small scopes (less than ten lines) or for iterators.
61
62 * `i` should be used only as a counter variable in for loops (either numeric for
63 or `ipairs`).
64
65 * Prefer more descriptive names than `k` and `v` when iterating with `pairs`,
66 unless you are writing a function that operates on generic tables.
67
68 * Use `_` for ignored variables (e.g. in for loops:)
69
70 ```lua
71 for _, item in ipairs(items) do
72 do_something_with_item(item);
73 end
74 ```
75
76 * Generally all identifiers (variables and function names) should use `snake_case`,
77 i.e. lowercase words joined by `_`.
78
79 ```lua
80 -- bad
81 local OBJEcttsssss = {}
82 local thisIsMyObject = {}
83 local c = function()
84 -- ...stuff...
85 end
86
87 -- good
88 local this_is_my_object = {};
89
90 local function do_that_thing()
91 -- ...stuff...
92 end
93 ```
94
95 > **Rationale:** The standard library uses lowercase APIs, with `joinedlowercase`
96 names, but this does not scale too well for more complex APIs. `snake_case`
97 tends to look good enough and not too out-of-place along side the standard
98 APIs.
99
100 ```lua
101 for _, name in pairs(names) do
102 -- ...stuff...
103 end
104 ```
105
106 * Prefer using `is_` when naming boolean functions:
107
108 ```lua
109 -- bad
110 local function evil(alignment)
111 return alignment < 100
112 end
113
114 -- good
115 local function is_evil(alignment)
116 return alignment < 100;
117 end
118 ```
119
120 * `UPPER_CASE` is to be used sparingly, with "constants" only.
121
122 > **Rationale:** "Sparingly", since Lua does not have real constants. This
123 notation is most useful in libraries that bind C libraries, when bringing over
124 constants from C.
125
126 * Do not use uppercase names starting with `_`, they are reserved by Lua.
127
128 ## Tables
129
130 * When creating a table, prefer populating its fields all at once, if possible:
131
132 ```lua
133 local player = { name = "Jack", class = "Rogue" };
134 ```
135
136 * Items should be separated by commas. If there are many items, put each
137 key/value on a separate line and use a semi-colon after each item (including
138 the last one):
139
140 ```lua
141 local player = {
142 name = "Jack";
143 class = "Rogue";
144 }
145 ```
146
147 > **Rationale:** This makes the structure of your tables more evident at a glance.
148 Trailing semi-colons make it quicker to add new fields and produces shorter diffs.
149
150 * Use plain `key` syntax whenever possible, use `["key"]` syntax when using names
151 that can't be represented as identifiers and avoid mixing representations in
152 a declaration:
153
154 ```lua
155 local mytable = {
156 ["1394-E"] = val1;
157 ["UTF-8"] = val2;
158 ["and"] = val2;
159 }
160 ```
161
162 ## Strings
163
164 * Use `"double quotes"` for strings; use `'single quotes'` when writing strings
165 that contain double quotes.
166
167 ```lua
168 local name = "Prosody";
169 local sentence = 'The name of the program is "Prosody"';
170 ```
171
172 > **Rationale:** Double quotes are used as string delimiters in a larger number of
173 programming languages. Single quotes are useful for avoiding escaping when
174 using double quotes in literals.
175
176 ## Line lengths
177
178 * There are no hard or soft limits on line lengths. Line lengths are naturally
179 limited by using one statement per line. If that still produces lines that are
180 too long (e.g. an expression that produces a line over 256-characters long,
181 for example), this means the expression is too complex and would do better
182 split into subexpressions with reasonable names.
183
184 > **Rationale:** No one works on VT100 terminals anymore. If line lengths are a proxy
185 for code complexity, we should address code complexity instead of using line
186 breaks to fit mind-bending statements over multiple lines.
187
188 ## Function declaration syntax
189
190 * Prefer function syntax over variable syntax. This helps differentiate between
191 named and anonymous functions.
192
193 ```lua
194 -- bad
195 local nope = function(name, options)
196 -- ...stuff...
197 end
198
199 -- good
200 local function yup(name, options)
201 -- ...stuff...
202 end
203 ```
204
205 * Perform validation early and return as early as possible.
206
207 ```lua
208 -- bad
209 local function is_good_name(name, options, arg)
210 local is_good = #name > 3
211 is_good = is_good and #name < 30
212
213 -- ...stuff...
214
215 return is_good
216 end
217
218 -- good
219 local function is_good_name(name, options, args)
220 if #name < 3 or #name > 30 then
221 return false;
222 end
223
224 -- ...stuff...
225
226 return true;
227 end
228 ```
229
230 ## Function calls
231
232 * Even though Lua allows it, generally you should not omit parentheses
233 for functions that take a unique string literal argument.
234
235 ```lua
236 -- bad
237 local data = get_data"KRP"..tostring(area_number)
238 -- good
239 local data = get_data("KRP"..tostring(area_number));
240 local data = get_data("KRP")..tostring(area_number);
241 ```
242
243 > **Rationale:** It is not obvious at a glace what the precedence rules are
244 when omitting the parentheses in a function call. Can you quickly tell which
245 of the two "good" examples in equivalent to the "bad" one? (It's the second
246 one).
247
248 * You should not omit parenthesis for functions that take a unique table
249 argument on a single line. You may do so for table arguments that span several
250 lines.
251
252 ```lua
253 local an_instance = a_module.new {
254 a_parameter = 42;
255 another_parameter = "yay";
256 }
257 ```
258
259 > **Rationale:** The use as in `a_module.new` above occurs alone in a statement,
260 so there are no precedence issues.
261
262 ## Table attributes
263
264 * Use dot notation when accessing known properties.
265
266 ```lua
267 local luke = {
268 jedi = true;
269 age = 28;
270 }
271
272 -- bad
273 local is_jedi = luke["jedi"]
274
275 -- good
276 local is_jedi = luke.jedi;
277 ```
278
279 * Use subscript notation `[]` when accessing properties with a variable or if using a table as a list.
280
281 ```lua
282 local vehicles = load_vehicles_from_disk("vehicles.dat")
283
284 if vehicles["Porsche"] then
285 porsche_handler(vehicles["Porsche"]);
286 vehicles["Porsche"] = nil;
287 end
288 for name, cars in pairs(vehicles) do
289 regular_handler(cars);
290 end
291 ```
292
293 > **Rationale:** Using dot notation makes it clearer that the given key is meant
294 to be used as a record/object field.
295
296 ## Functions in tables
297
298 * When declaring modules and classes, declare functions external to the table definition:
299
300 ```lua
301 local my_module = {};
302
303 function my_module.a_function(x)
304 -- code
305 end
306 ```
307
308 * When declaring metatables, declare function internal to the table definition.
309
310 ```lua
311 local version_mt = {
312 __eq = function(a, b)
313 -- code
314 end;
315 __lt = function(a, b)
316 -- code
317 end;
318 }
319 ```
320
321 > **Rationale:** Metatables contain special behavior that affect the tables
322 they're assigned (and are used implicitly at the call site), so it's good to
323 be able to get a view of the complete behavior of the metatable at a glance.
324
325 This is not as important for objects and modules, which usually have way more
326 code, and which don't fit in a single screen anyway, so nesting them inside
327 the table does not gain much: when scrolling a longer file, it is more evident
328 that `check_version` is a method of `Api` if it says `function Api:check_version()`
329 than if it says `check_version = function()` under some indentation level.
330
331 ## Variable declaration
332
333 * Always use `local` to declare variables.
334
335 ```lua
336 -- bad
337 superpower = get_superpower()
338
339 -- good
340 local superpower = get_superpower();
341 ```
342
343 > **Rationale:** Not doing so will result in global variables to avoid polluting
344 the global namespace.
345
346 ## Variable scope
347
348 * Assign variables with the smallest possible scope.
349
350 ```lua
351 -- bad
352 local function good()
353 local name = get_name()
354
355 test()
356 print("doing stuff..")
357
358 --...other stuff...
359
360 if name == "test" then
361 return false
362 end
363
364 return name
365 end
366
367 -- good
368 local bad = function()
369 test();
370 print("doing stuff..");
371
372 --...other stuff...
373
374 local name = get_name();
375
376 if name == "test" then
377 return false;
378 end
379
380 return name;
381 end
382 ```
383
384 > **Rationale:** Lua has proper lexical scoping. Declaring the function later means that its
385 scope is smaller, so this makes it easier to check for the effects of a variable.
386
387 ## Conditional expressions
388
389 * False and nil are falsy in conditional expressions. Use shortcuts when you
390 can, unless you need to know the difference between false and nil.
391
392 ```lua
393 -- bad
394 if name ~= nil then
395 -- ...stuff...
396 end
397
398 -- good
399 if name then
400 -- ...stuff...
401 end
402 ```
403
404 * Avoid designing APIs which depend on the difference between `nil` and `false`.
405
406 * Use the `and`/`or` idiom for the pseudo-ternary operator when it results in
407 more straightforward code. When nesting expressions, use parentheses to make it
408 easier to scan visually:
409
410 ```lua
411 local function default_name(name)
412 -- return the default "Waldo" if name is nil
413 return name or "Waldo";
414 end
415
416 local function brew_coffee(machine)
417 return (machine and machine.is_loaded) and "coffee brewing" or "fill your water";
418 end
419 ```
420
421 Note that the `x and y or z` as a substitute for `x ? y : z` does not work if
422 `y` may be `nil` or `false` so avoid it altogether for returning booleans or
423 values which may be nil.
424
425 ## Blocks
426
427 * Use single-line blocks only for `then return`, `then break` and `function return` (a.k.a "lambda") constructs:
428
429 ```lua
430 -- good
431 if test then break end
432
433 -- good
434 if not ok then return nil, "this failed for this reason: " .. reason end
435
436 -- good
437 use_callback(x, function(k) return k.last end);
438
439 -- good
440 if test then
441 return false
442 end
443
444 -- bad
445 if test < 1 and do_complicated_function(test) == false or seven == 8 and nine == 10 then do_other_complicated_function() end
446
447 -- good
448 if test < 1 and do_complicated_function(test) == false or seven == 8 and nine == 10 then
449 do_other_complicated_function();
450 return false;
451 end
452 ```
453
454 * Separate statements onto multiple lines. Use semicolons as statement terminators.
455
456 ```lua
457 -- bad
458 local whatever = "sure"
459 a = 1 b = 2
460
461 -- good
462 local whatever = "sure";
463 a = 1;
464 b = 2;
465 ```
466
467 ## Spacing
468
469 * Use a space after `--`.
470
471 ```lua
472 --bad
473 -- good
474 ```
475
476 * Always put a space after commas and between operators and assignment signs:
477
478 ```lua
479 -- bad
480 local x = y*9
481 local numbers={1,2,3}
482 numbers={1 , 2 , 3}
483 numbers={1 ,2 ,3}
484 local strings = { "hello"
485 , "Lua"
486 , "world"
487 }
488 dog.set( "attr",{
489 age="1 year",
490 breed="Bernese Mountain Dog"
491 })
492
493 -- good
494 local x = y * 9;
495 local numbers = {1, 2, 3};
496 local strings = {
497 "hello";
498 "Lua";
499 "world";
500 }
501 dog.set("attr", {
502 age = "1 year";
503 breed = "Bernese Mountain Dog";
504 });
505 ```
506
507 * Indent tables and functions according to the start of the line, not the construct:
508
509 ```lua
510 -- bad
511 local my_table = {
512 "hello",
513 "world",
514 }
515 using_a_callback(x, function(...)
516 print("hello")
517 end)
518
519 -- good
520 local my_table = {
521 "hello";
522 "world";
523 }
524 using_a_callback(x, function(...)
525 print("hello");
526 end)
527 ```
528
529 > **Rationale:** This keep indentation levels aligned at predictable places. You don't
530 need to realign the entire block if something in the first line changes (such as
531 replacing `x` with `xy` in the `using_a_callback` example above).
532
533 * The concatenation operator gets a pass for avoiding spaces:
534
535 ```lua
536 -- okay
537 local message = "Hello, "..user.."! This is your day # "..day.." in our platform!";
538 ```
539
540 > **Rationale:** Being at the baseline, the dots already provide some visual spacing.
541
542 * No spaces after the name of a function in a declaration or in its arguments:
543
544 ```lua
545 -- bad
546 local function hello ( name, language )
547 -- code
548 end
549
550 -- good
551 local function hello(name, language)
552 -- code
553 end
554 ```
555
556 * Add blank lines between functions:
557
558 ```lua
559 -- bad
560 local function foo()
561 -- code
562 end
563 local function bar()
564 -- code
565 end
566
567 -- good
568 local function foo()
569 -- code
570 end
571
572 local function bar()
573 -- code
574 end
575 ```
576
577 * Avoid aligning variable declarations:
578
579 ```lua
580 -- bad
581 local a = 1
582 local long_identifier = 2
583
584 -- good
585 local a = 1;
586 local long_identifier = 2;
587 ```
588
589 > **Rationale:** This produces extra diffs which add noise to `git blame`.
590
591 * Alignment is occasionally useful when logical correspondence is to be highlighted:
592
593 ```lua
594 -- okay
595 sys_command(form, UI_FORM_UPDATE_NODE, "a", FORM_NODE_HIDDEN, false);
596 sys_command(form, UI_FORM_UPDATE_NODE, "sample", FORM_NODE_VISIBLE, false);
597 ```
598
599 ## Typing
600
601 * In non-performance critical code, it can be useful to add type-checking assertions
602 for function arguments:
603
604 ```lua
605 function manif.load_manifest(repo_url, lua_version)
606 assert(type(repo_url) == "string");
607 assert(type(lua_version) == "string" or not lua_version);
608
609 -- ...
610 end
611 ```
612
613 * Use the standard functions for type conversion, avoid relying on coercion:
614
615 ```lua
616 -- bad
617 local total_score = review_score .. ""
618
619 -- good
620 local total_score = tostring(review_score);
621 ```
622
623 ## Errors
624
625 * Functions that can fail for reasons that are expected (e.g. I/O) should
626 return `nil` and a (string) error message on error, possibly followed by other
627 return values such as an error code.
628
629 * On errors such as API misuse, an error should be thrown, either with `error()`
630 or `assert()`.
631
632 ## Modules
633
634 Follow [these guidelines](http://hisham.hm/2014/01/02/how-to-write-lua-modules-in-a-post-module-world/) for writing modules. In short:
635
636 * Always require a module into a local variable named after the last component of the module’s full name.
637
638 ```lua
639 local bar = require("foo.bar"); -- requiring the module
640
641 bar.say("hello"); -- using the module
642 ```
643
644 * Don’t rename modules arbitrarily:
645
646 ```lua
647 -- bad
648 local skt = require("socket")
649 ```
650
651 > **Rationale:** Code is much harder to read if we have to keep going back to the top
652 to check how you chose to call a module.
653
654 * Start a module by declaring its table using the same all-lowercase local
655 name that will be used to require it. You may use an LDoc comment to identify
656 the whole module path.
657
658 ```lua
659 --- @module foo.bar
660 local bar = {};
661 ```
662
663 * Try to use names that won't clash with your local variables. For instance, don't
664 name your module something like “size”.
665
666 * Use `local function` to declare _local_ functions only: that is, functions
667 that won’t be accessible from outside the module.
668
669 That is, `local function helper_foo()` means that `helper_foo` is really local.
670
671 * Public functions are declared in the module table, with dot syntax:
672
673 ```lua
674 function bar.say(greeting)
675 print(greeting);
676 end
677 ```
678
679 > **Rationale:** Visibility rules are made explicit through syntax.
680
681 * Do not set any globals in your module and always return a table in the end.
682
683 * If you would like your module to be used as a function, you may set the
684 `__call` metamethod on the module table instead.
685
686 > **Rationale:** Modules should return tables in order to be amenable to have their
687 contents inspected via the Lua interactive interpreter or other tools.
688
689 * Requiring a module should cause no side-effect other than loading other
690 modules and returning the module table.
691
692 * A module should not have state. If a module needs configuration, turn
693 it into a factory. For example, do not make something like this:
694
695 ```lua
696 -- bad
697 local mp = require "MessagePack"
698 mp.set_integer("unsigned")
699 ```
700
701 and do something like this instead:
702
703 ```lua
704 -- good
705 local messagepack = require("messagepack");
706 local mpack = messagepack.new({integer = "unsigned"});
707 ```
708
709 * The invocation of require may omit parentheses around the module name:
710
711 ```lua
712 local bla = require "bla";
713 ```
714
715 ## Metatables, classes and objects
716
717 If creating a new type of object that has a metatable and methods, the
718 metatable and methods table should be separate, and the metatable name
719 should end with `_mt`.
720
721 ```lua
722 local mytype_methods = {};
723 local mytype_mt = { __index = mytype_methods };
724
725 function mytype_methods:add_new_thing(thing)
726 end
727
728 local function new()
729 return setmetatable({}, mytype_mt);
730 end
731
732 return { new = new };
733 ```
734
735 * Use the method notation when invoking methods:
736
737 ```
738 -- bad
739 my_object.my_method(my_object)
740
741 -- good
742 my_object:my_method();
743 ```
744
745 > **Rationale:** This makes it explicit that the intent is to use the function as a method.
746
747 * Do not rely on the `__gc` metamethod to release resources other than memory.
748 If your object manage resources such as files, add a `close` method to their
749 APIs and do not auto-close via `__gc`. Auto-closing via `__gc` would entice
750 users of your module to not close resources as soon as possible. (Note that
751 the standard `io` library does not follow this recommendation, and users often
752 forget that not closing files immediately can lead to "too many open files"
753 errors when the program runs for a while.)
754
755 > **Rationale:** The garbage collector performs automatic *memory* management,
756 dealing with memory only. There is no guarantees as to when the garbage
757 collector will be invoked, and memory pressure does not correlate to pressure
758 on other resources.
759
760 ## File structure
761
762 * Lua files should be named in all lowercase.
763
764 * Tests should be in a top-level `spec` directory. Prosody uses
765 [Busted](http://olivinelabs.com/busted/) for testing.
766
767 ## Static checking
768
769 All code should pass [luacheck](https://github.com/mpeterv/luacheck) using
770 the `.luacheckrc` provided in the Prosody repository, and using miminal
771 inline exceptions.
772
773 * luacheck warnings of class 211, 212, 213 (unused variable, argument or loop
774 variable) may be ignored, if the unused variable was added explicitly: for
775 example, sometimes it is useful, for code understandability, to spell out what
776 the keys and values in a table are, even if you're only using one of them.
777 Another example is a function that needs to follow a given signature for API
778 reasons (e.g. a callback that follows a given format) but doesn't use some of
779 its arguments; it's better to spell out in the argument what the API the
780 function implements is, instead of adding `_` variables.
781
782 ```
783 local foo, bar = some_function(); --luacheck: ignore 212/foo
784 print(bar);
785 ```
786
787 * luacheck warning 542 (empty if branch) can also be ignored, when a sequence
788 of `if`/`elseif`/`else` blocks implements a "switch/case"-style list of cases,
789 and one of the cases is meant to mean "pass". For example:
790
791 ```lua
792 if warning >= 600 and warning <= 699 then
793 print("no whitespace warnings");
794 elseif warning == 542 then --luacheck: ignore 542
795 -- pass
796 else
797 print("got a warning: "..warning);
798 end
799 ```
800
801 > **Rationale:** This avoids writing negated conditions in the final fallback
802 case, and it's easy to add another case to the construct without having to
803 edit the fallback.
804