C++
代码风格
- 使用Google C/C++风格
- 面向公众的函数用doxygen格式记录
- 提倡具体类型声明,而不是自动声明
- 函数参数提倡通过const引用(如const Expr&)传递,而不是通过值传递。除非函数通过复制构造函数或移动来使用该值,在这种情况下,通过值传递比通过const 引用传递更好。
- 尽可能地使用常量成员函数
函数注释
/*!
* \brief Description of my function
* \param arg1 Description of arg1
* \param arg2 Descroption of arg2
* \returns describe return value
*/
int myfunction(int arg1, int arg2) {
// When necessary, also add comment to clarify internal logics
}
格式化
我们使用clang-format来执行代码风格。因为不同版本的clang-format可能会因其版本而改变,所以建议使用与主版本相同的clang-format。你也可以通过docker使用以下命令。docker/bash.sh tvmai/ci-lint clang-format-10 [path-to-file]
clang-format也不是完美的,在必要的时候,你可以在某些代码区域使用disble clang-format。
因为clang-format可能无法识别宏,所以建议像普通函数样式一样使用宏。 ```cpp// clang-format off
void Test() {
// clang-format will be disabled in this region.
}
// clang-format on
define MACRO_IMPL { custom impl; }
define MACRO_FUNC(x)
// not preferred, because clang-format might recognize it as types. virtual void Func1() MACRO_IMPL
// preferred virtual void Func2() MACRO_IMPL;
void Func3() { // preferred MACRO_FUNC(xyz); }
<a name="Og4w5"></a>
## 处理整数常量表达式
在TVM中,我们经常需要处理常数整数表达式。在这之前,我们首先要问的问题是,是否真的需要得到一个常数整数。如果符号表达式也能用,让逻辑流动起来,我们应该尽量使用符号表达式。所以生成的代码对于事先不知道的形状也能用。<br />需要注意的是,在某些情况下,我们无法知道某些信息,比如符号变量的符号,在某些情况下做假设是可以的。在增加精确支持的同时,如果变量是常数。<br />如果我们确实需要获取常量整数表达式,我们应该使用int64_t类型而不是int来获取常量值,以避免潜在的整数溢出。我们可以随时通过make_const来重建一个对应表达式类型的整数。下面的代码给出了一个例子。
```cpp
Expr CalculateExpr(Expr value) {
int64_t int_value = GetConstInt<int64_t>(value);
int_value = CalculateExprInInt64(int_value);
return make_const(value.type(), int_value);
}
Python
代码风格
- 函数和类都以numpydoc格式记录
- 使用make pylint检查你的代码风格
- 坚持Python 3.5中的语言特性
python注释
```python def myfunction(arg1, arg2, arg3=3): “””Briefly describe my function.
Parameters
arg1 : Type1
Description of arg1
arg2 : Type2 Description of arg2
arg3 : Type3, optional Description of arg3
Returns
rv1 : RType1
Description of return type one
Examples
.. code:: python
Example usage of myfunction
x = myfunction(1, 2)
"""
return rv1
```