]> git.lizzy.rs Git - rust.git/blob - src/etc/vim/syntax/rust.vim
Vim syntax file types and traits cleanup
[rust.git] / src / etc / vim / syntax / rust.vim
1 " Vim syntax file
2 " Language:     Rust
3 " Maintainer:   Patrick Walton <pcwalton@mozilla.com>
4 " Maintainer:   Ben Blum <bblum@cs.cmu.edu>
5 " Maintainer:   Chris Morgan <me@chrismorgan.info>
6 " Last Change:  2014 Feb 27
7
8 if version < 600
9   syntax clear
10 elseif exists("b:current_syntax")
11   finish
12 endif
13
14 " Syntax definitions {{{1
15 " Basic keywords {{{2
16 syn keyword   rustConditional match if else
17 syn keyword   rustOperator    as
18
19 syn match     rustAssert      "\<assert\(\w\)*!" contained
20 syn match     rustFail        "\<fail\(\w\)*!" contained
21 syn keyword   rustKeyword     break
22 syn keyword   rustKeyword     box nextgroup=rustBoxPlacement skipwhite skipempty
23 syn keyword   rustKeyword     continue
24 syn keyword   rustKeyword     extern nextgroup=rustExternCrate,rustObsoleteExternMod skipwhite skipempty
25 syn keyword   rustKeyword     fn nextgroup=rustFuncName skipwhite skipempty
26 syn keyword   rustKeyword     for in if impl let
27 syn keyword   rustKeyword     loop once proc pub
28 syn keyword   rustKeyword     return super
29 syn keyword   rustKeyword     unsafe virtual while
30 syn keyword   rustKeyword     use nextgroup=rustModPath skipwhite skipempty
31 " FIXME: Scoped impl's name is also fallen in this category
32 syn keyword   rustKeyword     mod trait struct enum type nextgroup=rustIdentifier skipwhite skipempty
33 syn keyword   rustStorage     mut ref static const
34
35 syn keyword   rustInvalidBareKeyword crate
36
37 syn keyword   rustExternCrate crate contained nextgroup=rustIdentifier skipwhite skipempty
38 syn keyword   rustObsoleteExternMod mod contained nextgroup=rustIdentifier skipwhite skipempty
39
40 syn match     rustIdentifier  contains=rustIdentifierPrime "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained
41 syn match     rustFuncName    "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained
42
43 syn region    rustBoxPlacement matchgroup=rustBoxPlacementParens start="(" end=")" contains=TOP contained
44 syn keyword   rustBoxPlacementExpr GC containedin=rustBoxPlacement
45 " Ideally we'd have syntax rules set up to match arbitrary expressions. Since
46 " we don't, we'll just define temporary contained rules to handle balancing
47 " delimiters.
48 syn region    rustBoxPlacementBalance start="(" end=")" containedin=rustBoxPlacement transparent
49 syn region    rustBoxPlacementBalance start="\[" end="\]" containedin=rustBoxPlacement transparent
50 " {} are handled by rustFoldBraces
51
52 " Reserved (but not yet used) keywords {{{2
53 syn keyword   rustReservedKeyword alignof be do offsetof priv pure sizeof typeof unsized yield
54
55 " Built-in types {{{2
56 syn keyword   rustType        int uint float char bool u8 u16 u32 u64 f32
57 syn keyword   rustType        f64 i8 i16 i32 i64 str Self
58
59 " Things from the prelude (src/libstd/prelude.rs) {{{2
60 " This section is just straight transformation of the contents of the prelude,
61 " to make it easy to update.
62
63 " Core operators {{{3
64 syn keyword   rustTrait       Copy Send Sized Share
65 syn keyword   rustTrait       Add Sub Mul Div Rem Neg Not
66 syn keyword   rustTrait       BitAnd BitOr BitXor
67 syn keyword   rustTrait       Drop Deref DerefMut
68 syn keyword   rustTrait       Shl Shr Index
69 syn keyword   rustEnum        Option
70 syn keyword   rustEnumVariant Some None
71 syn keyword   rustEnum        Result
72 syn keyword   rustEnumVariant Ok Err
73
74 " Functions {{{3
75 "syn keyword rustFunction from_str
76 "syn keyword rustFunction range
77 "syn keyword rustFunction drop
78
79 " Types and traits {{{3
80 syn keyword rustTrait Ascii AsciiCast OwnedAsciiCast AsciiStr
81 syn keyword rustTrait IntoBytes
82 syn keyword rustTrait ToCStr
83 syn keyword rustTrait Char
84 syn keyword rustTrait Clone
85 syn keyword rustTrait PartialEq PartialOrd Eq Ord Equiv
86 syn keyword rustEnum Ordering
87 syn keyword rustEnumVariant Less Equal Greater
88 syn keyword rustTrait Collection Mutable Map MutableMap
89 syn keyword rustTrait Set MutableSet
90 syn keyword rustTrait FromIterator Extendable ExactSize
91 syn keyword rustTrait Iterator DoubleEndedIterator
92 syn keyword rustTrait RandomAccessIterator CloneableIterator
93 syn keyword rustTrait OrdIterator MutableDoubleEndedIterator
94 syn keyword rustTrait Num NumCast CheckedAdd CheckedSub CheckedMul CheckedDiv
95 syn keyword rustTrait Signed Unsigned Primitive Int Float
96 syn keyword rustTrait FloatMath ToPrimitive FromPrimitive
97 syn keyword rustTrait Box
98 syn keyword rustTrait GenericPath Path PosixPath WindowsPath
99 syn keyword rustTrait RawPtr
100 syn keyword rustTrait Buffer Writer Reader Seek
101 syn keyword rustTrait Str StrVector StrSlice OwnedStr
102 syn keyword rustTrait IntoMaybeOwned StrAllocating
103 syn keyword rustTrait ToStr IntoStr
104 syn keyword rustTrait Tuple1 Tuple2 Tuple3 Tuple4
105 syn keyword rustTrait Tuple5 Tuple6 Tuple7 Tuple8
106 syn keyword rustTrait Tuple9 Tuple10 Tuple11 Tuple12
107 syn keyword rustTrait CloneableVector ImmutableCloneableVector
108 syn keyword rustTrait MutableCloneableVector MutableOrdVector
109 syn keyword rustTrait ImmutableVector MutableVector
110 syn keyword rustTrait ImmutableEqVector ImmutableOrdVector
111 syn keyword rustTrait Vector VectorVector
112 syn keyword rustTrait MutableVectorAllocating
113 syn keyword rustTrait String
114 syn keyword rustTrait Vec
115
116 "syn keyword rustFunction sync_channel channel
117 syn keyword rustTrait SyncSender Sender Receiver
118 "syn keyword rustFunction spawn
119
120 "syn keyword rustConstant GC
121
122 syn keyword   rustSelf        self
123 syn keyword   rustBoolean     true false
124
125 " Other syntax {{{2
126
127 " If foo::bar changes to foo.bar, change this ("::" to "\.").
128 " If foo::bar changes to Foo::bar, change this (first "\w" to "\u").
129 syn match     rustModPath     "\w\(\w\)*::[^<]"he=e-3,me=e-3
130 syn match     rustModPath     "\w\(\w\)*" contained " only for 'use path;'
131 syn match     rustModPathSep  "::"
132
133 syn match     rustFuncCall    "\w\(\w\)*("he=e-1,me=e-1
134 syn match     rustFuncCall    "\w\(\w\)*::<"he=e-3,me=e-3 " foo::<T>();
135
136 " This is merely a convention; note also the use of [A-Z], restricting it to
137 " latin identifiers rather than the full Unicode uppercase. I have not used
138 " [:upper:] as it depends upon 'noignorecase'
139 "syn match     rustCapsIdent    display "[A-Z]\w\(\w\)*"
140
141 syn match     rustOperator     display "\%(+\|-\|/\|*\|=\|\^\|&\||\|!\|>\|<\|%\)=\?"
142 " This one isn't *quite* right, as we could have binary-& with a reference
143 syn match     rustSigil        display /&\s\+[&~@*][^)= \t\r\n]/he=e-1,me=e-1
144 syn match     rustSigil        display /[&~@*][^)= \t\r\n]/he=e-1,me=e-1
145 " This isn't actually correct; a closure with no arguments can be `|| { }`.
146 " Last, because the & in && isn't a sigil
147 syn match     rustOperator     display "&&\|||"
148
149 syn match     rustMacro       '\w\(\w\)*!' contains=rustAssert,rustFail
150 syn match     rustMacro       '#\w\(\w\)*' contains=rustAssert,rustFail
151
152 syn match     rustEscapeError   display contained /\\./
153 syn match     rustEscape        display contained /\\\([nrt0\\'"]\|x\x\{2}\)/
154 syn match     rustEscapeUnicode display contained /\\\(u\x\{4}\|U\x\{8}\)/
155 syn match     rustStringContinuation display contained /\\\n\s*/
156 syn region    rustString      start=+b"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeError,rustStringContinuation
157 syn region    rustString      start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustStringContinuation,@Spell
158 syn region    rustString      start='b\?r\z(#*\)"' end='"\z1' contains=@Spell
159
160 syn region    rustAttribute   start="#!\?\[" end="\]" contains=rustString,rustDeriving
161 syn region    rustDeriving    start="deriving(" end=")" contained contains=rustTrait
162
163 " Number literals
164 syn match     rustDecNumber   display "\<[0-9][0-9_]*\%([iu]\%(8\|16\|32\|64\)\=\)\="
165 syn match     rustHexNumber   display "\<0x[a-fA-F0-9_]\+\%([iu]\%(8\|16\|32\|64\)\=\)\="
166 syn match     rustOctNumber   display "\<0o[0-7_]\+\%([iu]\%(8\|16\|32\|64\)\=\)\="
167 syn match     rustBinNumber   display "\<0b[01_]\+\%([iu]\%(8\|16\|32\|64\)\=\)\="
168
169 " Special case for numbers of the form "1." which are float literals, unless followed by
170 " an identifier, which makes them integer literals with a method call or field access.
171 " (This must go first so the others take precedence.)
172 syn match     rustFloat       display "\<[0-9][0-9_]*\.\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\@!"
173 " To mark a number as a normal float, it must have at least one of the three things integral values don't have:
174 " a decimal point and more numbers; an exponent; and a type suffix.
175 syn match     rustFloat       display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\%([eE][+-]\=[0-9_]\+\)\=\(f32\|f64\)\="
176 syn match     rustFloat       display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE][+-]\=[0-9_]\+\)\(f32\|f64\)\="
177 syn match     rustFloat       display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE][+-]\=[0-9_]\+\)\=\(f32\|f64\)"
178
179 " For the benefit of delimitMate
180 syn region rustLifetimeCandidate display start=/&'\%(\([^'\\]\|\\\(['nrt0\\\"]\|x\x\{2}\|u\x\{4}\|U\x\{8}\)\)'\)\@!/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime
181 syn region rustGenericRegion display start=/<\%('\|[^[cntrl:][:space:][:punct:]]\)\@=')\S\@=/ end=/>/ contains=rustGenericLifetimeCandidate
182 syn region rustGenericLifetimeCandidate display start=/\%(<\|,\s*\)\@<='/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime
183
184 "rustLifetime must appear before rustCharacter, or chars will get the lifetime highlighting
185 syn match     rustLifetime    display "\'\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*"
186 syn match   rustCharacterInvalid   display contained /b\?'\zs[\n\r\t']\ze'/
187 " The groups negated here add up to 0-255 but nothing else (they do not seem to go beyond ASCII).
188 syn match   rustCharacterInvalidUnicode   display contained /b'\zs[^[:cntrl:][:graph:][:alnum:][:space:]]\ze'/
189 syn match   rustCharacter   /b'\([^\\]\|\\\(.\|x\x\{2}\)\)'/ contains=rustEscape,rustEscapeError,rustCharacterInvalid,rustCharacterInvalidUnicode
190 syn match   rustCharacter   /'\([^\\]\|\\\(.\|x\x\{2}\|u\x\{4}\|U\x\{8}\)\)'/ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustCharacterInvalid
191
192 syn region rustCommentLine                                        start="//"                      end="$"   contains=rustTodo,@Spell
193 syn region rustCommentLineDoc                                     start="//\%(//\@!\|!\)"         end="$"   contains=rustTodo,@Spell
194 syn region rustCommentBlock    matchgroup=rustCommentBlock        start="/\*\%(!\|\*[*/]\@!\)\@!" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell
195 syn region rustCommentBlockDoc matchgroup=rustCommentBlockDoc     start="/\*\%(!\|\*[*/]\@!\)"    end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell
196 syn region rustCommentBlockNest matchgroup=rustCommentBlock       start="/\*"                     end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell contained transparent
197 syn region rustCommentBlockDocNest matchgroup=rustCommentBlockDoc start="/\*"                     end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell contained transparent
198 " FIXME: this is a really ugly and not fully correct implementation. Most
199 " importantly, a case like ``/* */*`` should have the final ``*`` not being in
200 " a comment, but in practice at present it leaves comments open two levels
201 " deep. But as long as you stay away from that particular case, I *believe*
202 " the highlighting is correct. Due to the way Vim's syntax engine works
203 " (greedy for start matches, unlike Rust's tokeniser which is searching for
204 " the earliest-starting match, start or end), I believe this cannot be solved.
205 " Oh you who would fix it, don't bother with things like duplicating the Block
206 " rules and putting ``\*\@<!`` at the start of them; it makes it worse, as
207 " then you must deal with cases like ``/*/**/*/``. And don't try making it
208 " worse with ``\%(/\@<!\*\)\@<!``, either...
209
210 syn keyword rustTodo contained TODO FIXME XXX NB NOTE
211
212 " Folding rules {{{2
213 " Trivial folding rules to begin with.
214 " TODO: use the AST to make really good folding
215 syn region rustFoldBraces start="{" end="}" transparent fold
216 " If you wish to enable this, setlocal foldmethod=syntax
217 " It's not enabled by default as it would drive some people mad.
218
219 " Default highlighting {{{1
220 hi def link rustDecNumber       rustNumber
221 hi def link rustHexNumber       rustNumber
222 hi def link rustOctNumber       rustNumber
223 hi def link rustBinNumber       rustNumber
224 hi def link rustIdentifierPrime rustIdentifier
225 hi def link rustTrait           rustType
226
227 hi def link rustSigil         StorageClass
228 hi def link rustEscape        Special
229 hi def link rustEscapeUnicode rustEscape
230 hi def link rustEscapeError   Error
231 hi def link rustStringContinuation Special
232 hi def link rustString        String
233 hi def link rustCharacterInvalid Error
234 hi def link rustCharacterInvalidUnicode rustCharacterInvalid
235 hi def link rustCharacter     Character
236 hi def link rustNumber        Number
237 hi def link rustBoolean       Boolean
238 hi def link rustEnum          rustType
239 hi def link rustEnumVariant   rustConstant
240 hi def link rustConstant      Constant
241 hi def link rustSelf          Constant
242 hi def link rustFloat         Float
243 hi def link rustOperator      Operator
244 hi def link rustKeyword       Keyword
245 hi def link rustReservedKeyword Error
246 hi def link rustConditional   Conditional
247 hi def link rustIdentifier    Identifier
248 hi def link rustCapsIdent     rustIdentifier
249 hi def link rustModPath       Include
250 hi def link rustModPathSep    Delimiter
251 hi def link rustFunction      Function
252 hi def link rustFuncName      Function
253 hi def link rustFuncCall      Function
254 hi def link rustCommentLine   Comment
255 hi def link rustCommentLineDoc SpecialComment
256 hi def link rustCommentBlock  rustCommentLine
257 hi def link rustCommentBlockDoc rustCommentLineDoc
258 hi def link rustAssert        PreCondit
259 hi def link rustFail          PreCondit
260 hi def link rustMacro         Macro
261 hi def link rustType          Type
262 hi def link rustTodo          Todo
263 hi def link rustAttribute     PreProc
264 hi def link rustDeriving      PreProc
265 hi def link rustStorage       StorageClass
266 hi def link rustObsoleteStorage Error
267 hi def link rustLifetime      Special
268 hi def link rustInvalidBareKeyword Error
269 hi def link rustExternCrate   rustKeyword
270 hi def link rustObsoleteExternMod Error
271 hi def link rustBoxPlacementParens Delimiter
272 hi def link rustBoxPlacementExpr rustKeyword
273
274 " Other Suggestions:
275 " hi rustAttribute ctermfg=cyan
276 " hi rustDeriving ctermfg=cyan
277 " hi rustAssert ctermfg=yellow
278 " hi rustFail ctermfg=red
279 " hi rustMacro ctermfg=magenta
280
281 syn sync minlines=200
282 syn sync maxlines=500
283
284 let b:current_syntax = "rust"