Просмотр исходного кода

Document our practices around using auto and naming variable types (#5663)

We use `auto` for most local variables, and we put the type name into
the variable name in common cases, especially for our ID types.

This was discussed in `#style`:
https://discord.com/channels/655572317891461132/821113559755784242/1380091326900469801
Dana Jansens 10 месяцев назад
Родитель
Сommit
4a96799e1f
1 измененных файлов с 17 добавлено и 0 удалено
  1. 17 0
      docs/project/cpp_style_guide.md

+ 17 - 0
docs/project/cpp_style_guide.md

@@ -16,6 +16,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
     -   [General naming rules](#general-naming-rules)
     -   [File names](#file-names)
     -   [Syntax and formatting](#syntax-and-formatting)
+    -   [Naming variable types and the use of `auto`](#naming-variable-types-and-the-use-of-auto)
     -   [Copyable and movable types](#copyable-and-movable-types)
     -   [Static and global variables](#static-and-global-variables)
     -   [Foundational libraries and data types](#foundational-libraries-and-data-types)
@@ -197,6 +198,22 @@ these.
     `protected`. This is motivated by the
     `misc-non-private-member-variables-in-classes` tidy check.
 
+### Naming variable types and the use of `auto`
+
+We generally use `auto` for most local variables when a type can be inferred,
+except for primitive types such as `bool` and `int`. It is not required to use
+`auto`, and shorter type names such as `SemIR::InstId` are sometimes named even
+though they could be inferred. Naming the type can be helpful in cases where the
+type would be obscure and can not be explained with the variable name. Function
+parameters generally name the type of each parameter, though lambdas may use
+`auto` if it's helpful.
+
+When naming variables, we typically suffix `_id` for ID types. When needed, we
+can also resolve ambiguity by referring to the full type name in the variable
+name; for example, if there's a `ClassId`, `InstId`, and `TypeId` for the same
+class entity, we might call these `class_id`, `class_inst_id`, and
+`class_type_id`. Similarly, we might call an `Inst` `class_inst`.
+
 ### Copyable and movable types
 
 -   Types should have value semantics and support both move and copy where