Comparison

doc/coding_style.md @ 9858:54147de1d1b1

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