宣言マクロは、反復的な構文構造をパターンセットに変換するのに適しています。例えば、複数の実装を生成したり、可変長の式を受け取ったり、簡潔なドメイン固有言語を提供したりする場合です。すでに型が確定されている値に対してアルゴリズムを実行するだけであれば、通常の関数とジェネリクスの方が理解しやすく、デバッグや検査も容易です。
マクロはコンパイル時に展開されますが、生成されたコードは実行時に割り当て、ループを実行、副作用を発生させる可能性があります。const fn もコンパイル時に評価できるため、「コンパイル時対実行時」という区別だけでマクロと関数を分類することはできません。
呼び出し中のトークンツリー 括弧によるグループ化と構文断片であり、任意の文字列置換ではありません 1 ルール順にマッチ 最初にマッチしたルールを選択し、反復と置換を実行 2 呼び出し位置に展開 式、項目、パターンなどの有効な構文を形成 3 名前、型、借用チェッカー マクロが生成したコードも通常のRustルールに従う必要がある 4 宣言マクロ: まず構文にマッチし、次に展開後のコードを検査する マクロ展開は所有権ルールを免除せず、引数が1回だけ評価されることも自動的に保証されません。
評価回数を示す小さなマクロ
macro_rules! list {
( ) => { :: std:: vec:: Vec:: new( ) } ;
( $ ( $value :expr) ,+ $ ( ,)?) => {{
let mut output = ::std::vec::Vec::new();
$(output.push($value );) *
output
}};
}
fn main() {
let mut n = 0 ;
let values = list! [ { n + = 1 ; n } , { n + = 1 ; n } , ] ;
assert_eq! ( values, [ 1 , 2 ] ) ;
assert_eq! ( n, 2 ) ;
let empty: Vec< u8 > = list! [ ] ;
assert! ( empty.is_empty ( ) ) ;
}
反復部分により、各式は生成された push の中に1回ずつ現れるため、各項目は1回だけ評価され、記述順に実行されます。もし $value を2箇所に書くと、副作用が重複したり、ムーブ後の使用エラーを引き起こしたりする可能性があります。マクロシステムは結果をキャッシュしてくれません。
二重中括弧内の内部ブロックにより、全体が1つの式として展開され、一時変数のスコープがブロック内に制限されます。ここでは ::std パスを使用しており、例が std に依存していることを明確にしています。no_std ライブラリからエクスポートされるマクロでは、alloc パスを適切に処理する必要があり、そのままコピーすることはできません。
1 回の展開でも式は 2 回実行され得る
副作用のある引数で展開と実行を区別できます。next() は通常の実行時操作で、マクロが決めるのは生成構文での登場回数です。先に束縛すると評価回数は制御できますが、その後の再利用は Copy・借用・ムーブの規則に従います。
図を準備しています 再読み込み
1 回の展開でも式は 2 回実行され得る $e の繰り返しは式も繰り返し評価し、先に let value=$e と束縛すると 1 回になります。
{"id":"rust-macro-evaluation","title":"1 回の展開でも式は 2 回実行され得る","summary":"$e の繰り返しは式も繰り返し評価し、先に let value=$e と束縛すると 1 回になります。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><div class=\"presets\" role=\"group\" data-i18n-label=\"mode\"><button data-mode=\"repeat\" data-i18n=\"repeat\"></button><button data-mode=\"bind\" data-i18n=\"bind\"></button></div><section class=\"panel\"><h3 data-i18n=\"source\"></h3><div id=\"source\"></div></section><section class=\"panel\"><h3 data-i18n=\"expanded\"></h3><div id=\"expanded\"></div></section><div class=\"metrics\"><div><span data-i18n=\"calls\"></span><strong id=\"calls\"></strong></div><div><span data-i18n=\"result\"></span><strong id=\"result\"></strong></div></div><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"bad\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"ok\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n.panel>div{min-height:4em;font:14px/1.8 ui-monospace,monospace;white-space:pre-line}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));let mode='repeat';function draw(){pressed(mode);let b=mode==='bind';set('source','twice!(next())');set('expanded',b?'{ let value = next();\\n value + value }':'{ next() + next() }');set('calls',b?1:2);set('result',b?2:3);set('explanation',t(b?'ok':'bad'));}document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{mode=b.dataset.mode;draw()});draw();","audio":false,"strings":{"bad":"2 回の next() が 1 と 2 を返し、結果は 3 です。コンパイル時の展開は実行時の副作用を消しません。","bind":"先に束縛して使う","calls":"next() 回数","expanded":"展開後の式","heading":"1 回の展開でも式は 2 回実行され得る","intro":"展開内での引数の使い方を変え、next() の回数と値を確認します。","mode":"展開の形式","ok":"next() は一度だけ 1 を返し、Copy な局所値を 2 回使って結果は 2 です。","repeat":"$e を直接繰り返す","reset":"リセット","result":"結果","scope":"next() は 1 から増える u32 を返します。任意の非 Copy 値の再利用を保証するものではありません。","scopeLabel":"モデルの範囲と前提","source":"マクロ入力"}}
フラグメントは構文カテゴリであり、Rustの型ではない
フラグメント マッチする内容 混同しやすい境界
expr 式 推論される型が u32 なのか String なのか不明
ty 型構文 エイリアスを自動的に展開しない、トレイト実装を判断しない
ident 識別子の形状 任意の複数セグメントパスではない
path パス 限定名などの対応する構文に使用可能
pat / pat_param パターン トップレベルまたはパターンルールは edition に依存
tt 1つのトークンツリー 1つのトークン、またはバランスの取れた区切り文字で囲まれたツリーであり、任意の長さの入力ではない
item 項目 関数、構造体、impl など
meta / vis 属性内容 / 可視性 vis は空の可視性にマッチ可能
任意の数のトークンツリーが必要ない場合は、通常 $($tokens:tt)* と書きます。expr などの既に解析されたフラグメントを別のマクロに渡す際、それは対応するカテゴリの不透明なフラグメントとなり、任意のリテラルトークンとして分解してマッチすることはできません。ident、lifetime、tt には特定の例外があります。マクロマッチルール
expr と tt を渡した後、次層で見るものが異なる
macro_rules! inspect {
( 3) => { " リテラルトークン" } ;
( $value : expr ) => { " 式フラグメント" } ;
}
macro_rules! pass_expr { ( $value : expr ) => { inspect! ( $value ) } ; }
macro_rules! pass_tt { ( $value : tt ) => { inspect! ( $value ) } ; }
fn main ( ) {
assert_eq! ( inspect! ( 3 ) , " リテラルトークン" ) ;
assert_eq! ( pass_tt! ( 3 ) , " リテラルトークン" ) ;
assert_eq! ( pass_expr! ( 3 ) , " 式フラグメント" ) ;
}
pass_expr は 3 を式フラグメントとして既に解析しているため、後続の inspect はこの不透明なフラグメントをリテラルの 3 として再マッチさせることができず、expr ルールに進みます。tt はマッチ可能なトークンツリーの形状を保持します。次にトークンレベルの構文解析を行う必要がある場合は、インターフェースに対応するトークンを保持します。式を使用するコードを生成するだけであれば、expr の方が構文制約が明確です。
pass_tt!(1 + 2) は「式も1つのトークンツリーである」という意味ではありません。これはグループ化されていない複数のトークンを含んでおり、単一の $value:tt にはマッチしません。明示的にグループ化するか、必要に応じて繰り返されるトークンを受け取る必要があります。フラグメントの選択は後続の処理に影響し、単に入力を受け付けるプレースホルダーを適当に選ぶものではありません。
反復、ルール順序、曖昧さ
$()* は0回以上の繰り返し、$()+ は1回以上の繰り返し、$()? はオプションの1回を意味します。カンマ区切りとオプションの末尾カンマは通常 $($x:expr),* $(,)? のように組み合わされます。反復出力のネスト構造はキャプチャと一致する必要があり、複数の変数が同時に反復する場合、その数も一致しなければなりません。
ルールは定義順に試行され、最初にマッチしたルールが選択されます。展開コードが失敗した場合、別のルールを試すために自動的にバックトラックすることはありません。より具体的なルールを、それらをキャプチャできる広範なルールの前に配置してください。
マッチングは任意のバックトラックを行う汎用パーサではありません。例えば、反復された ident の直後に別の ident が続くと、現在のトークンではそれがどの部分に属するかが判断できず、局所的な曖昧さが発生する可能性があります。区切り文字、明示的なキーワード、またはグループ化を使用して境界を明確にすることが、再帰を増やすよりも安全です。
対データを同じ反復層でキャプチャする
macro_rules! pairs {
( $ ( $key :expr => $value :expr) ,* $ ( ,)?) => {{
let mut output = ::std::vec::Vec::new();
$(output.push(($key , $value ));) *
output
}};
}
fn main() {
let mut calls = 0 ;
let entries = pairs! (
" first" => { calls + = 1 ; calls } ,
" second" => { calls + = 1 ; calls } ,
) ;
assert_eq! ( entries, [ ( " first" , 1 ) , ( " second" , 2 ) ] ) ;
assert_eq! ( calls, 2 ) ;
}
各反復ユニットは key と value の両方を同時にキャプチャするため、1組のデータが自然に対応します。2つの独立した反復として設計し、出力でそれらを同じ反復層に配置する場合、2つのキャプチャ数が一致することを保証する必要があります。マクロ展開は、欠落している項目を呼び出し側に補完したり、自動的にデカルト積を行ったりしません。
この pairs は Vec を生成するだけで、キーの重複をチェックしたり、Map を作成したりしません。構文糖は、提供される能力を正確に命名すべきです。重複キーの戦略、型変換、リソース上限などの要件がある場合は、対応するコードを生成するか、通常の関数に任せる必要があります。
区切り文字も構文の長期互換性の境界
マクロフラグメントの後に許可されるトークンは、follow-set ルールによって制限されます。例えば、expr の後に =>、,、または ; が続くのは一般的な有効な境界ですが、式に直後に続く任意の記号シーケンスを独自に発明し、パーサが常に明確に区別することを期待することはできません。明示的なグループ化とキーワードは、エラー位置をユーザー入力の近くに保つことができます。また、複数の再帰層を経た後にマッチしないというエラーを報告するよりも優れています。
境界が明確な再帰的トークン処理の例
以下では、text 式を順序通りに String に書き込み、セミコロンで1つのコマンドを区切ります。これは小型の TT muncher であり、完全な HTML/XML パーサを装うものではありません。
macro_rules! text_script {
( @step $out : ident ;) => { } ;
( @step $out : ident ; text $value : expr ; $ ( $rest :tt) * ) => {
{
use :: std:: fmt:: Write as _ ;
:: std:: write! ( & mut $out , " {}" , $value ) .expect ( " write String" ) ;
}
text_script! ( @ step $out ; $ ( $rest ) * ) ;
} ;
( @step $out : ident ; $ ( $invalid :tt) + ) => {
compile_error! ( " expected: text <expression>;" ) ;
} ;
( ) => { :: std:: string:: String:: new( ) } ;
( $ ( $input :tt) + ) => { {
let mut output = :: std:: string:: String:: new( ) ;
text_script! ( @ step output; $ ( $input ) * ) ;
output
} } ;
}
fn main ( ) {
assert_eq! ( text_script! ( text " value=" ; text 42 ; ) , " value=42" ) ;
assert_eq! ( text_script! ( ) , " " ) ;
}
各ステップは1つの text コマンドを消費し、残りのトークンを転送します。終了ルールは必ず存在する必要があります。専用の @step エラールールを広範なエントリ前に配置することで、無効な入力がエントリに繰り返し入って再帰深度エラーのみを報告するのを防ぎます。長い入力で末尾全体に繰り返しマッチすると、高い、場合によっては二次的なマクロ展開コストを引き起こす可能性があります。
<$tag:ident> ... </$tag:ident> は「同じ名前のタグにマッチする」テクニックとして有効ではありません。同じマッチャー内で同じ名前の変数を反復バインドするとエラーになり、無制限の children 反復で終了タグに遭遇すると曖昧さが生じやすくなります。複雑なネスト構文は明示的なグループ化に変更するか、プロシージャルマクロを使用して実際に解析してください。
衛生性と跨 crate 参照
macro_rules は混合位置衛生性を持ちます。マクロ内部で生成されたローカル変数などは、テキスト的に呼び出し側の変数と単純に混同されることはありませんが、項目パスなどの名前解決はルールに従って理解する必要があります。「完全に衛生なので、すべての名前に関する問題は消える」と言うことはできません。
エクスポートされたマクロ内で定義元 crate の補助項目を参照する場合、呼び出し側が依存関係を特定の固定文字列に命名していることを想定せず、$crate::helper を使用してください。$crate は可視性ルールを迂回せず、外部展開でアクセスする必要がある補助項目は、適切な可視性を持っている必要があります。
通常の macro_rules は、任意の安定した文字列連結による識別子の生成機能を提供しません。呼び出し側から提供された ident を受け取る、固定名を参照する、2つのトークンから新しい名前を連結する、これらは異なる要件です。後者の場合、プロシージャルマクロまたは特別なサポートが必要です。
マクロ定義内の value マクロ内の局所束縛 呼び出しで渡された $input 呼び出し側の文脈で解決 生成結果 同名でも異なる束縛 衛生性は名前を処理し、繰り返し評価やビジネス副作用は処理しない ローカル一時名と呼び出し側の入力は、異なる名前ソースを保持する 入力式が何回書かれ、いつ実行されるかは、依然として展開コードによって決定される macro_rules は混合位置衛生性である。項目パスと跨 crate の補助関数は明示的な参照が必要。
同名のローカル変数は単純なテキスト置換ではない
macro_rules! offset {
( $input : expr ) => { {
let value = 10 ;
$input + value
} } ;
}
fn main ( ) {
let value = 7 ;
assert_eq! ( offset! ( value) , 17 ) ;
assert_eq! ( value, 7 ) ;
}
渡された value は依然として呼び出し場所の 7 を指しており、マクロが導入した一時 value は 10 です。これは、マクロが呼び出し側の任意の同名変数を読み取れることを意味しません。呼び出し側が後続で使用するためのバインディングを生成したい場合は、対応する ident を受け取り、展開位置とスコープを明確に規定する必要があります。
エクスポートされたマクロの補助項目は定義元 crate から位置指定する
# [ doc ( hidden ) ]
pub fn __decorate ( text : & str ) -> String { format! ( " [{text} ]" ) }
# [ macro_export ]
macro_rules! decorated {
( $text : expr ) => { $crate :: __decorate( $text ) } ;
}
fn main ( ) {
assert_eq! ( decorated! ( " ready" ) , " [ready]" ) ;
}
$crate はマクロを定義した crate を指し、使用側が依存関係をリネームしても位置指定できます。これはプライベート関数をパブリック関数に変えるものではありません。ここでは補助関数が外部に可視である必要があり、doc(hidden) は生成されたドキュメントでの通常の表示を隠すだけで、アクセス権限ではありません。パブリックマクロが生成するコードに必要な補助インターフェースも、互換性の責任を負う必要があり、安易に削除することはできません。
edition と検査戦略
マクロ定義の edition は、expr、pat などのフラグメントのマッチ範囲に影響します。Rust 2024 では expr が拡張され、マッチ可能な式形状が増えました。expr_2021 は対応する旧ルールを保持します。edition をアップグレードする際は、以前複数のブランチを選択していた部分がどうなるか確認してください。
マクロを検証するには、成功例だけでなく、空の入力、末尾区切り文字、副作用のある引数、無効な構文、および跨モジュール/跨 crate での使用をカバーする必要があります。展開出力は構造を理解するのに適していますが、最終的には呼び出しコードのコンパイル動作が基準となります。
2024 の expr はルール選択を変更する
以下の完全な例は edition 2024 でコンパイルされます:
macro_rules! broad_first {
( $value : expr ) => { " expression" } ;
( const $value : expr ) => { " special const" } ;
}
macro_rules! legacy_first {
( $value : expr _2021) => { " expression" } ;
( const $value : expr ) => { " special const" } ;
}
fn main ( ) {
assert_eq! ( broad_first! ( const { 1 } ) , " expression" ) ;
assert_eq! ( legacy_first! ( const { 1 } ) , " special const" ) ;
}
2024 の expr はトップレベルの const ブロックを受け取ることができるため、broad_first の最初のルールですでにマッチします。expr_2021 は旧フラグメント範囲を保持し、2番目の const ルールが選択される機会を維持します。移行時は、旧動作を保持するか、ルール順序を調整して新構文を受け入れるかを決める必要があります。最終的にコンパイルできるかどうかだけでなく、マッチ範囲を決定するのはマクロ定義時の edition であり、マクロ呼び出し側の edition ではありません。2024 フラグメント移行
マクロの失敗ケースもインターフェース説明の一部です。無効な入力でどのカスタムエラーをトリガーするかを記録し、反復回数が一致しない場合に拒否されることを確認し、外部 crate でエクスポートされたマクロをテストしてください。同じソースファイル内の成功呼び出しだけでは、依存関係のリネーム、可視性、パスの衛生性をカバーすることはできません。