Indenting for nasm directives and macros

时间:2019-03-17 22:34:21

标签: assembly x86 nasm code-formatting

In generally accepted nasm syntax, instructions are indented relative to labels, like so:

.top:
    dec eax
    jnz .top

How about assembly directives and macros, like %rep? Should it be like:

.top:
    %rep 10
    dec eax
    %endrep
    jnz .top

or

.top:
%rep 10
    dec eax
%endrep
    jnz .top

or perhaps even something else where the directives themselves imply an additional level of indentation - but this would only be applicable to "scoped" directives with open close parts, like %rep and %endrep, not to standalone or non-nested ones.

.top:
    %rep 10
        dec eax
    %endrep
    jnz .top

Or something else?

2 个答案:

答案 0 :(得分:1)

Traditionally, assembly code was written in a four column layout. The columns were:

  1. label
  2. mnemonic
  3. operand
  4. comment

Traditional assemblers dating back to punched cards recognised the meaning of each word by what column it appeared on. Modern assemblers use more sophisticated parsers, allowing for assembler programs to have a free form layout. Nevertheless, it is a good idea to stick with the traditional layout for readability.

As you can see, the second column says “mnemonic.” This indicates both assembler directives and instructions. So to answer your question, the directive goes into the same column as other instructions go. I recommend to highlight bracing like in your %rep ... %endrep example by means of blank lines:

.top:   %rep 10
        dec eax
        %endrep

        jnz .top

答案 1 :(得分:1)

我想在这里从C预处理程序样式中获取线索,然后将NASM预处理程序指令缩进到最左侧。 (或者在嵌套%if和其他影响块的指令时,缩进2个空格,因此即使嵌套的%if通常也通常从指令助记符开始的列的左侧开始。)

%rep / %endrep预处理器指令会影响它们之间的指令助记符,因此,您绝对希望它们脱颖而出,而不是混入并迷失在周围的指令中。看到一个时,您希望能够在视觉上即时发现另一个,而不是向上或向下浏览助记符列以查找第一个匹配项。尤其是在存在任何嵌套或其他预处理器棘手的情况下。

通常,您只会在多条指令或数据的块上使用%rep;否则,您将使用time 10 dec eax。 (或者您正在%assign内使用%rep来创建类似dec r10d / dec r11d / dec r12d / ...的块。)因此,实际用例不会就像这个示例一样简单,匹配的%endrep / %rep会比2行远。

当标签和%if / %rep指令混合使用时,很难看到标签。您也不想%rep也使最左边的列混乱。

Michael Petch建议进一步缩进要重复的指令是一个很好的建议。无论如何,它们都很特别,读者务必注意这一点。但是它们类似于指令,因为它们扩展为一个指令块,因此在指令列中开始%rep很有意义,而缩进所包含的块使查找该块的开始/结束变得容易。

%if USE_SIMPLE_LOOP
.top:
    %rep 10
        imul     ecx, edx
        dec      edx
    %endrep
    sub      eax, 10
    jg      .top

请注意,我进一步缩进了操作数,为不超过3个字符的助记符留出了空间,而不会使操作数列参差不齐。

我故意将分支目标1列缩进得比其他操作数少,这使其在不难看的情况下略显突出。尤其是当目标是以.

开头的本地标签时

但是根据%rep的用例,将指令缩进普通列并在%rep的标签和指令之间使用一列似乎更好。

%if  USE_SIMPLE_LOOP
.top:                               ; could indent the label by a column or two inside %if
  %rep 10                           ;  unroll 
    imul     ecx, edx
  %endrep
    sub      eax, 10
    jg      .top
%endif