├── .github
└── workflows
│ ├── golangci-lint.yml
│ └── test.yml
├── .gitignore
├── LICENSE
├── README.org
├── cache.go
├── default.nix
├── diff.go
├── diff_test.go
├── editor
└── jsonnet-language-server.el
├── example.jsonnet
├── example.libsonnet
├── example.txt
├── flake.lock
├── flake.nix
├── go.mod
├── go.sum
├── main.go
├── server.go
├── shell.nix
├── snitch.nix
├── stdio.go
└── symbols.go
/.github/workflows/golangci-lint.yml:
--------------------------------------------------------------------------------
1 | name: golangci-lint
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request: {}
7 | permissions:
8 | contents: read
9 | jobs:
10 | golangci:
11 | name: lint
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v2
15 |
16 | - name: golangci-lint
17 | uses: golangci/golangci-lint-action@v2
18 | with:
19 | # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
20 | version: v1.42
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: go test
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request: {}
7 | jobs:
8 | test:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - uses: actions/checkout@v2
12 | - uses: actions/setup-go@v2
13 | - run: go test ./...
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.direnv/
2 | /flake-profile*
3 | jsonnet-language-server
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | #+TITLE: Jsonnet Language Server
2 |
3 | *Warning: This project is no longer in active development*
4 | *Use the Grafana Labs maintained tool instead: https://github.com/grafana/jsonnet-language-server.*
5 |
6 | A *[[https://langserver.org][Language Server Protocol (LSP)]]* server for [[https://jsonnet.org][Jsonnet]].
7 |
8 | ** Demonstration
9 | [[https://user-images.githubusercontent.com/4599384/138060166-6ef56086-80c7-4d1a-9bcd-8de59e200b5e.mp4][LSP server demonstration]]
10 |
11 | ** Features
12 | - Jump to definition :: For local variables, import and importstr files, and index targets.
13 | - Workspace symbols :: Return a hierarchy of document symbols representing all desugared nodes of the Jsonnet AST.
14 | - Diagnostics :: Static errors and warnings of runtime errors.
15 | - Formatting :: Format document according to default options.
16 |
17 | Refer to [[file:example.jsonnet][example.jsonnet]] for a documented walkthrough.
18 |
19 | ** Installation
20 | To install the LSP server with Go into "${GOPATH}"/bin:
21 | #+NAME: Installation with Go
22 | #+BEGIN_SRC shell
23 | go get -u github.com/jdbaldry/jsonnet-language-server
24 | #+END_SRC
25 |
26 | To download the latest release binary from GitHub:
27 | #+NAME: Download from GitHub
28 | #+BEGIN_SRC shell
29 | curl -Lo jsonnet-language-server https://github.com/jdbaldry/jsonnet-language-server/releases/latest/download/jsonnet-language-server
30 | #+END_SRC
31 |
32 | #+RESULTS: Download from GitHub
33 |
34 | ** Contributing
35 | Contributions are more than welcome and I will try my best to be prompt with reviews.
36 |
37 | *** Commits
38 | Individual commits should be meaningful and have useful commit messages.
39 | For tips on writing commit messages, refer to [[https://chris.beams.io/posts/git-commit/][How to write a commit message]].
40 | Contributions will be rebased before merge to ensure a fast-forward merge.
41 |
42 | *** [[https://github.com/probot/dco#how-it-works][Developer Certificate of Origin (DCO)]]
43 | Contributors must sign the DCO for their contributions to be accepted.
44 |
45 | *** Code style
46 | Go code should be formatted with ~gofmt~ and linted with [[https://golangci-lint.run/][golangci-lint]].
47 |
48 | ** Editor integration
49 |
50 | *** Emacs
51 | Refer to [[file:editor/jsonnet-language-server.el][editor/jsonnet-language-server.el]] for an example of enabling the LSP server with lsp-mode.
52 |
53 | *** [[https://github.com/VSCodium/vscodium][VSCodium]] / VSCode
54 | Use the [[https://github.com/julienduchesne/vscode-jsonnet][vscode-jsonnet extension]]
55 |
--------------------------------------------------------------------------------
/cache.go:
--------------------------------------------------------------------------------
1 | // jsonnet-language-server: A Language Server Protocol server for Jsonnet.
2 | // Copyright (C) 2021 Jack Baldry
3 |
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU Affero General Public License as published
6 | // by the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 |
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU Affero General Public License for more details.
13 |
14 | // You should have received a copy of the GNU Affero General Public License
15 | // along with this program. If not, see .
16 |
17 | package main
18 |
19 | import (
20 | "errors"
21 | "sync"
22 |
23 | "github.com/google/go-jsonnet/ast"
24 | "github.com/jdbaldry/go-language-server-protocol/lsp/protocol"
25 | )
26 |
27 | type document struct {
28 | item protocol.TextDocumentItem
29 | val string
30 | ast ast.Node
31 | err error
32 | // Symbols are hierarchical and there is only ever a single root symbol.
33 | symbols protocol.DocumentSymbol
34 | }
35 |
36 | // newCache returns a document cache.
37 | func newCache() *cache {
38 | return &cache{
39 | mu: sync.RWMutex{},
40 | docs: make(map[protocol.DocumentURI]document),
41 | }
42 | }
43 |
44 | // cache caches documents.
45 | type cache struct {
46 | mu sync.RWMutex
47 | docs map[protocol.DocumentURI]document
48 | }
49 |
50 | // put adds or replaces a document in the cache.
51 | // Documents are only replaced if the new document version is greater than the currently
52 | // cached version.
53 | func (c *cache) put(new document) error {
54 | c.mu.Lock()
55 | defer c.mu.Unlock()
56 |
57 | uri := new.item.URI
58 | if old, ok := c.docs[uri]; ok {
59 | if old.item.Version > new.item.Version {
60 | return errors.New("newer version of the document is already in the cache")
61 | }
62 | }
63 | c.docs[uri] = new
64 |
65 | return nil
66 | }
67 |
68 | // get retrieves a document from the cache.
69 | func (c *cache) get(uri protocol.DocumentURI) (document, error) {
70 | c.mu.RLock()
71 | defer c.mu.RUnlock()
72 |
73 | doc, ok := c.docs[uri]
74 | if !ok {
75 | return document{}, errors.New("document not found")
76 | }
77 |
78 | return doc, nil
79 | }
80 |
--------------------------------------------------------------------------------
/default.nix:
--------------------------------------------------------------------------------
1 | { pkgs ? import }:
2 |
3 | with pkgs;
4 | buildGoModule rec {
5 | pname = "jsonnet-language-server";
6 | version = "0.3.0";
7 |
8 | buildFlagsArray = ''
9 | -ldflags=
10 | -X main.version=${version}
11 | '';
12 | src = lib.cleanSource ./.;
13 | vendorSha256 = "sha256-8jX2we1fpVmjhwcaLZ584MdbkvnrcDNAw9xKhT/z740=";
14 |
15 | meta = with lib; {
16 | description = "A Language Server Protocol server for Jsonnet";
17 | homepage = "https://github.com/jdbaldry/jsonnet-language-server";
18 | license = licenses.agpl3;
19 | maintainers = with maintainers; [ jdbaldry ];
20 | };
21 | }
22 |
--------------------------------------------------------------------------------
/diff.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/hexops/gotextdiff/myers"
5 | "github.com/hexops/gotextdiff/span"
6 | "github.com/jdbaldry/go-language-server-protocol/lsp/protocol"
7 | )
8 |
9 | func getTextEdits(before, after string) []protocol.TextEdit {
10 | edits := myers.ComputeEdits(span.URI("any"), before, after)
11 |
12 | var result []protocol.TextEdit
13 | for _, edit := range edits {
14 | result = append(result, protocol.TextEdit{
15 | Range: protocol.Range{
16 | Start: protocol.Position{Line: uint32(edit.Span.Start().Line()) - 1, Character: uint32(edit.Span.Start().Column()) - 1},
17 | End: protocol.Position{Line: uint32(edit.Span.End().Line()) - 1, Character: uint32(edit.Span.End().Column()) - 1},
18 | },
19 | NewText: edit.NewText,
20 | })
21 | }
22 |
23 | return result
24 | }
25 |
--------------------------------------------------------------------------------
/diff_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/jdbaldry/go-language-server-protocol/lsp/protocol"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestGetTextEdits(t *testing.T) {
11 | testCases := []struct {
12 | name string
13 | before, after string
14 | expected []protocol.TextEdit
15 | }{
16 | {
17 | name: "delete whole file",
18 | before: "one\ntwo\nthree",
19 | after: "",
20 | expected: []protocol.TextEdit{
21 | {
22 | Range: protocol.Range{
23 | Start: protocol.Position{Line: 0, Character: 0},
24 | End: protocol.Position{Line: 3, Character: 0},
25 | },
26 | NewText: "",
27 | },
28 | },
29 | },
30 | {
31 | name: "add one char (replaces the whole line)",
32 | before: "one\ntwo\nthree",
33 | after: "one\ntwoo\nthree",
34 | expected: []protocol.TextEdit{
35 | {
36 | Range: protocol.Range{
37 | Start: protocol.Position{Line: 1, Character: 0},
38 | End: protocol.Position{Line: 2, Character: 0},
39 | },
40 | NewText: "",
41 | },
42 | {
43 | Range: protocol.Range{
44 | Start: protocol.Position{Line: 2, Character: 0},
45 | End: protocol.Position{Line: 2, Character: 0},
46 | },
47 | NewText: "twoo\n",
48 | },
49 | },
50 | },
51 | {
52 | name: "delete a line",
53 | before: "one\ntwo\nthree",
54 | after: "one\nthree",
55 | expected: []protocol.TextEdit{
56 | {
57 | Range: protocol.Range{
58 | Start: protocol.Position{Line: 1, Character: 0},
59 | End: protocol.Position{Line: 2, Character: 0},
60 | },
61 | NewText: "",
62 | },
63 | },
64 | },
65 | }
66 |
67 | for _, tc := range testCases {
68 | t.Run(tc.name, func(t *testing.T) {
69 | got := getTextEdits(tc.before, tc.after)
70 | assert.Equal(t, tc.expected, got)
71 | })
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/editor/jsonnet-language-server.el:
--------------------------------------------------------------------------------
1 | ;;; jsonnet-language-server -- LSP registration for Emacs lsp-mode.
2 | ;;; Commentary:
3 | ;;; Code:
4 | (require 'jsonnet-mode)
5 | (require 'lsp-mode)
6 |
7 | (defcustom lsp-jsonnet-executable "jsonnet-language-server"
8 | "Command to start the Jsonnet language server."
9 | :group 'lsp-jsonnet
10 | :risky t
11 | :type 'file)
12 |
13 | ;; Configure lsp-mode language identifiers.
14 | (add-to-list 'lsp-language-id-configuration '(jsonnet-mode . "jsonnet"))
15 |
16 | ;; Register jsonnet-language-server with the LSP client.
17 | (lsp-register-client
18 | (make-lsp-client
19 | :new-connection (lsp-stdio-connection (lambda () lsp-jsonnet-executable))
20 | :activation-fn (lsp-activate-on "jsonnet")
21 | :server-id 'jsonnet))
22 |
23 | ;; Start the language server whenever jsonnet-mode is used.
24 | (add-hook 'jsonnet-mode-hook #'lsp-deferred)
25 |
26 | (provide 'jsonnet-language-server)
27 | ;;; jsonnet-language-server.el ends here
28 |
--------------------------------------------------------------------------------
/example.jsonnet:
--------------------------------------------------------------------------------
1 | // Jump to definition will jump to the imported file.
2 | // Try jumping from the import statement or the file name.
3 | local example = import 'example.libsonnet';
4 | // It also works with importstr.
5 | local str = import 'example.txt';
6 |
7 | // Jump to definition knows where the '$' references.
8 | // Try jump from each usage of '$'.
9 | // Unfortunately, it is not yet able to jump to the field within the referenced object.
10 | local obj = {
11 | y:: 25,
12 | a: $.y,
13 | };
14 | obj {
15 | z:: 26,
16 | b: $.z,
17 |
18 | // Jump to definition knows which local is relevant.
19 | // Try jumping from each usage of 'c'.
20 | local c = 1,
21 | c:
22 | [c]
23 | + local c = 2;
24 | [
25 | local c = 3;
26 | c,
27 | c,
28 | ],
29 |
30 | // Jump to definition knows where the super object begins.
31 | // Try jumping from the usage of 'super'.
32 | // Unfortunately, it is not yet able to jump to the field within the super object.
33 | d: super.a,
34 |
35 | // Jump to definition knows where the self object begins.
36 | // Try jump from the usage of 'self'.
37 | // Unfortunately, it is not yet able to jump to the field within the self object.
38 | e: self.b,
39 |
40 | // Jump to definition knows that a variable comes from a function parameter.
41 | f:: function(x, y, z) x + y + z,
42 |
43 | // Runtime errors are reported as a warning.
44 | err: import 'does-not-exist.libsonnet',
45 | // Static errors are reported as errors.
46 | // Uncomment this line to cause one.
47 | }
48 |
--------------------------------------------------------------------------------
/example.libsonnet:
--------------------------------------------------------------------------------
1 | // formatting can clean up the extraneous indentation
2 | // and all other formatting too.
3 | // Now jump back.
4 | {
5 | foo: "bar"
6 | }
7 |
--------------------------------------------------------------------------------
/example.txt:
--------------------------------------------------------------------------------
1 | tada
2 |
--------------------------------------------------------------------------------
/flake.lock:
--------------------------------------------------------------------------------
1 | {
2 | "nodes": {
3 | "flake-utils": {
4 | "locked": {
5 | "lastModified": 1631561581,
6 | "narHash": "sha256-3VQMV5zvxaVLvqqUrNz3iJelLw30mIVSfZmAaauM3dA=",
7 | "owner": "numtide",
8 | "repo": "flake-utils",
9 | "rev": "7e5bf3925f6fbdfaf50a2a7ca0be2879c4261d19",
10 | "type": "github"
11 | },
12 | "original": {
13 | "owner": "numtide",
14 | "repo": "flake-utils",
15 | "type": "github"
16 | }
17 | },
18 | "nixpkgs": {
19 | "locked": {
20 | "lastModified": 1633971123,
21 | "narHash": "sha256-WmI4NbH1IPGFWVkuBkKoYgOnxgwSfWDgdZplJlQ93vA=",
22 | "owner": "nixos",
23 | "repo": "nixpkgs",
24 | "rev": "e4ef597edfd8a0ba5f12362932fc9b1dd01a0aef",
25 | "type": "github"
26 | },
27 | "original": {
28 | "owner": "nixos",
29 | "ref": "nixos-unstable",
30 | "repo": "nixpkgs",
31 | "type": "github"
32 | }
33 | },
34 | "root": {
35 | "inputs": {
36 | "flake-utils": "flake-utils",
37 | "nixpkgs": "nixpkgs"
38 | }
39 | }
40 | },
41 | "root": "root",
42 | "version": 7
43 | }
44 |
--------------------------------------------------------------------------------
/flake.nix:
--------------------------------------------------------------------------------
1 | {
2 | description = "jsonnet-language-server shell development tooling";
3 |
4 | inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
5 | inputs.flake-utils.url = "github:numtide/flake-utils";
6 |
7 | outputs = { self, nixpkgs, flake-utils }:
8 | {
9 | overlay =
10 | (
11 | final: prev: {
12 | jsonnet-language-server = prev.callPackage ./default.nix { pkgs = prev; };
13 | snitch = prev.callPackage ./snitch.nix { pkgs = prev; };
14 | }
15 | );
16 | } // (
17 | flake-utils.lib.eachDefaultSystem (
18 | system:
19 | let
20 | pkgs = import nixpkgs { inherit system; overlays = [ self.overlay ]; };
21 | in
22 | {
23 | defaultPackage = pkgs.jsonnet-language-server;
24 | devShell = import ./shell.nix { inherit pkgs; };
25 | packages = {
26 | jsonnet-tool = pkgs.jsonnet-language-server;
27 | };
28 | }
29 | )
30 | );
31 | }
32 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/jdbaldry/jsonnet-language-server
2 |
3 | go 1.16
4 |
5 | require (
6 | github.com/google/go-jsonnet v0.17.0
7 | github.com/hexops/gotextdiff v1.0.3
8 | github.com/jdbaldry/go-language-server-protocol v0.0.0-20211013214444-3022da0884b2
9 | github.com/stretchr/testify v1.4.0
10 | )
11 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
5 | github.com/google/go-jsonnet v0.17.0 h1:/9NIEfhK1NQRKl3sP2536b2+x5HnZMdql7x3yK/l8JY=
6 | github.com/google/go-jsonnet v0.17.0/go.mod h1:sOcuej3UW1vpPTZOr8L7RQimqai1a57bt5j22LzGZCw=
7 | github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
8 | github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
9 | github.com/jdbaldry/go-language-server-protocol v0.0.0-20211013214444-3022da0884b2 h1:t0A10MAY8Z3eeBIBzlzrPpdjsag6Biuxq8iMCHmdGU8=
10 | github.com/jdbaldry/go-language-server-protocol v0.0.0-20211013214444-3022da0884b2/go.mod h1:Hp8QDOEcdn4aDZ+DFTda+smIB0b5MvII4Q0Jo0y2VkA=
11 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
12 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
13 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
14 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
15 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
16 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
17 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
18 | github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
19 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
20 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
21 | github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
22 | github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
23 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
24 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
25 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
26 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
27 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
28 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
29 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
30 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
31 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
32 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
33 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
34 | gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
35 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
36 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | // jsonnet-language-server: A Language Server Protocol server for Jsonnet.
2 | // Copyright (C) 2021 Jack Baldry
3 |
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU Affero General Public License as published
6 | // by the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 |
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU Affero General Public License for more details.
13 |
14 | // You should have received a copy of the GNU Affero General Public License
15 | // along with this program. If not, see .
16 |
17 | package main
18 |
19 | import (
20 | "context"
21 | "fmt"
22 | "io"
23 | "log"
24 | "os"
25 | "path/filepath"
26 |
27 | "github.com/jdbaldry/go-language-server-protocol/jsonrpc2"
28 | "github.com/jdbaldry/go-language-server-protocol/lsp/protocol"
29 | )
30 |
31 | const (
32 | name = "jsonnet-language-server"
33 | )
34 |
35 | var (
36 | // Set with `-ldflags="-X 'main.version='"`
37 | version = "dev"
38 | )
39 |
40 | // printVersion prints version text to the provided writer.
41 | func printVersion(w io.Writer) {
42 | fmt.Fprintf(w, "%s version %s\n", name, version)
43 | }
44 |
45 | // printVersion prints help text to the provided writer.
46 | func printHelp(w io.Writer) {
47 | printVersion(w)
48 | fmt.Fprintf(w, `
49 | Options:
50 | -h / --help Print this help message.
51 | -J / --jpath Specify an additional library search dir
52 | (right-most wins).
53 | -v / --version Print version.
54 |
55 | Environment variables:
56 | JSONNET_PATH is a %[2]q separated list of directories
57 | added in reverse order before the paths specified by --jpath
58 | These are equivalent:
59 | JSONNET_PATH=a%[2]cb %[1]s -J c -J d
60 | JSONNET_PATH=d%[2]cc%[2]ca%[2]cb %[1]s\n
61 | %[1]s -J b -J a -J c -J d
62 | `, name, filepath.ListSeparator)
63 | }
64 |
65 | func main() {
66 | jpaths := filepath.SplitList(os.Getenv("JSONNET_PATH"))
67 |
68 | for i, arg := range os.Args {
69 | if arg == "-h" || arg == "--help" {
70 | printHelp(os.Stdout)
71 | os.Exit(0)
72 | } else if arg == "-v" || arg == "--version" {
73 | printVersion(os.Stdout)
74 | os.Exit(0)
75 | } else if arg == "-J" || arg == "--jpath" {
76 | if i == len(os.Args)-1 {
77 | fmt.Printf("Expected value for option %s but found none.\n", arg)
78 | fmt.Println()
79 | printHelp(os.Stdout)
80 | os.Exit(1)
81 | }
82 |
83 | jpaths = append([]string{os.Args[i+1]}, jpaths...)
84 | }
85 | }
86 |
87 | log.Println("Starting the language server")
88 |
89 | ctx := context.Background()
90 | stream := jsonrpc2.NewHeaderStream(stdio{})
91 | conn := jsonrpc2.NewConn(stream)
92 | client := protocol.ClientDispatcher(conn)
93 |
94 | s, err := newServer(client, jpaths)
95 | if err != nil {
96 | fmt.Fprintln(os.Stderr, err)
97 | }
98 | conn.Go(ctx, protocol.Handlers(
99 | protocol.ServerHandler(s, jsonrpc2.MethodNotFound)))
100 | <-conn.Done()
101 | if err := conn.Err(); err != nil {
102 | fmt.Fprintln(os.Stderr, err)
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/server.go:
--------------------------------------------------------------------------------
1 | // jsonnet-language-server: A Language Server Protocol server for Jsonnet.
2 | // Copyright (C) 2021 Jack Baldry
3 |
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU Affero General Public License as published
6 | // by the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 |
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU Affero General Public License for more details.
13 |
14 | // You should have received a copy of the GNU Affero General Public License
15 | // along with this program. If not, see .
16 |
17 | package main
18 |
19 | import (
20 | "context"
21 | "fmt"
22 | "log"
23 | "os"
24 | "regexp"
25 | "strconv"
26 | "strings"
27 |
28 | "github.com/google/go-jsonnet"
29 | "github.com/google/go-jsonnet/formatter"
30 | "github.com/jdbaldry/go-language-server-protocol/jsonrpc2"
31 | "github.com/jdbaldry/go-language-server-protocol/lsp/protocol"
32 | )
33 |
34 | const (
35 | symbolTagDefinition protocol.SymbolTag = 100
36 | errorRetrievingDocument = "unable to retrieve document from the cache"
37 | )
38 |
39 | var (
40 | // errRegexp matches the various Jsonnet location formats in errors.
41 | // file:line msg
42 | // file:line:col-endCol msg
43 | // file:(line:endLine)-(col:endCol) msg
44 | // Has 10 matching groups.
45 | errRegexp = regexp.MustCompile(`/.*:(?:(\d+)|(?:(\d+):(\d+)-(\d+))|(?:\((\d+):(\d+)\)-\((\d+):(\d+))\))\s(.*)`)
46 | )
47 |
48 | // newServer returns a new language server.
49 | func newServer(client protocol.ClientCloser, jpaths []string) (*server, error) {
50 | log.Printf("Using the following jpaths: %v", jpaths)
51 |
52 | // TODO(#32): The language server VM has no support for Top Level Arguments (TLAs).
53 | // TODO(#33): The language server VM has no support for native functions.
54 | vm := jsonnet.MakeVM()
55 | importer := &jsonnet.FileImporter{JPaths: jpaths}
56 | vm.Importer(importer)
57 | return &server{
58 | cache: newCache(),
59 | client: client,
60 | vm: vm,
61 | }, nil
62 | }
63 |
64 | // server is the Jsonnet language server.
65 | type server struct {
66 | cache *cache
67 | client protocol.ClientCloser
68 | vm *jsonnet.VM
69 | }
70 |
71 | func (s *server) CodeAction(context.Context, *protocol.CodeActionParams) ([]protocol.CodeAction, error) {
72 | return nil, notImplemented("CodeAction")
73 | }
74 |
75 | func (s *server) CodeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) {
76 | return []protocol.CodeLens{}, nil
77 | }
78 |
79 | func (s *server) CodeLensRefresh(context.Context) error {
80 | return notImplemented("CodeLensRefresh")
81 | }
82 |
83 | func (s *server) ColorPresentation(context.Context, *protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {
84 | return nil, notImplemented("ColorPresentation")
85 | }
86 |
87 | // Completion is not implemented.
88 | // TODO(#6): Understand why the server capabilities includes completion.
89 | func (s *server) Completion(context.Context, *protocol.CompletionParams) (*protocol.CompletionList, error) {
90 | return nil, nil
91 | }
92 |
93 | func (s *server) Declaration(context.Context, *protocol.DeclarationParams) (protocol.Declaration, error) {
94 | return nil, notImplemented("Declaration")
95 | }
96 |
97 | // Definition returns the location of the definition of the symbol at point.
98 | // Looking up the symbol at point depends on only looking up nodes that have no children and are therefore terminal.
99 | // Potentially it could backtrack outwards to guess what was probably meant.
100 | // In the case of an index "obj.field", lookup would work when the point is on either "obj" or "field" but not the "."
101 | // as it is not a terminal node and is instead part of the "index" symbol which has the children "obj" and "field".
102 | // This works well in all cases where the Jsonnet parser has put correct location information. Unfortunately,
103 | // the literal string node "field" of "obj.field" does not have correct location information.
104 | // TODO(#8): Understand why the parser has not attached correct location range for indexes.
105 | func (s *server) Definition(ctx context.Context, params *protocol.DefinitionParams) (protocol.Definition, error) {
106 | doc, err := s.cache.get(params.TextDocument.URI)
107 | if err != nil {
108 | err = fmt.Errorf("Definition: %s: %w", errorRetrievingDocument, err)
109 | fmt.Fprintln(os.Stderr, err)
110 | return nil, err
111 | }
112 |
113 | var aux func([]protocol.DocumentSymbol, protocol.DocumentSymbol) (protocol.Definition, error)
114 | aux = func(stack []protocol.DocumentSymbol, ds protocol.DocumentSymbol) (protocol.Definition, error) {
115 | // If the symbol has no children, it must be a terminal symbol.
116 | if len(ds.Children) == 0 {
117 | // Check if the point is contained within the symbol.
118 | if params.Position.Line == ds.Range.Start.Line &&
119 | params.Position.Character >= ds.Range.Start.Character &&
120 | params.Position.Character <= ds.Range.End.Character {
121 |
122 | want := ds
123 | // The point is on a super keyword.
124 | // super can only be used in the right hand side object of a binary `+` operation.
125 | // The definition the "super" is referring to would be the left hand side.
126 | // Simplified stack:
127 | // + lhs obj ... field x index super
128 | if want.Name == "super" {
129 | prev := stack[len(stack)-1]
130 | for len(stack) != 0 {
131 | ds := stack[len(stack)-1]
132 | stack = stack[:len(stack)-1]
133 | if ds.Kind == protocol.Operator {
134 | return protocol.Definition{{
135 | URI: doc.item.URI,
136 | Range: prev.SelectionRange,
137 | }}, nil
138 | }
139 | prev = ds
140 | }
141 | }
142 |
143 | // The point is on a self keyword.
144 | // self can only be used in an object so we can jump to the start of that object.
145 | // I'm not sure that is very useful though.
146 | if want.Name == "self" {
147 | for len(stack) != 0 {
148 | ds := stack[len(stack)-1]
149 | stack = stack[:len(stack)-1]
150 | if ds.Kind == protocol.Object {
151 | return protocol.Definition{{
152 | URI: doc.item.URI,
153 | Range: ds.SelectionRange,
154 | }}, nil
155 | }
156 | }
157 | }
158 |
159 | // The point is on a file symbol which must be an import.
160 | if want.Kind == protocol.File {
161 | foundAt, err := s.vm.ResolveImport(doc.item.URI.SpanURI().Filename(), ds.Name)
162 | if err != nil {
163 | err = fmt.Errorf("Definition: unable to resolve import: %w", err)
164 | fmt.Fprintln(os.Stderr, err)
165 | return nil, err
166 | }
167 | return protocol.Definition{{URI: "file://" + protocol.DocumentURI(foundAt)}}, nil
168 | }
169 |
170 | // The point is on a variable, the definition of which is the first definition
171 | // with the same name that we find going back through the stack.
172 | if want.Kind == protocol.Variable && !isDefinition(want) {
173 | for len(stack) != 0 {
174 | ds := stack[len(stack)-1]
175 | stack = stack[:len(stack)-1]
176 | if ds.Kind == protocol.Variable && ds.Name == want.Name && isDefinition(ds) {
177 | return protocol.Definition{{
178 | URI: doc.item.URI,
179 | Range: ds.SelectionRange,
180 | }}, nil
181 | }
182 | }
183 | }
184 | }
185 | }
186 | stack = append(stack, ds.Children...)
187 | for i := len(ds.Children); i != 0; i-- {
188 | if def, err := aux(stack, ds.Children[i-1]); def != nil || err != nil {
189 | return def, err
190 | }
191 | stack = stack[:len(stack)-1]
192 | }
193 | return nil, nil
194 | }
195 |
196 | return aux([]protocol.DocumentSymbol{doc.symbols}, doc.symbols)
197 | }
198 |
199 | func (s *server) Diagnostic(context.Context, *string) (*string, error) {
200 | return nil, notImplemented("Diagnostic")
201 | }
202 |
203 | func (s *server) DiagnosticRefresh(context.Context) error {
204 | return notImplemented("DiagnosticRefresh")
205 | }
206 |
207 | func (s *server) DiagnosticWorkspace(context.Context, *protocol.WorkspaceDiagnosticParams) (*protocol.WorkspaceDiagnosticReport, error) {
208 | return nil, notImplemented("DiagnosticWorkspace")
209 | }
210 |
211 | func (s *server) publishDiagnostics(uri protocol.DocumentURI) {
212 | diags := []protocol.Diagnostic{}
213 | doc, err := s.cache.get(uri)
214 | if err != nil {
215 | fmt.Fprintf(os.Stderr, "publishDiagnostics: %s: %v\n", errorRetrievingDocument, err)
216 | return
217 | }
218 |
219 | diag := protocol.Diagnostic{Source: "jsonnet evaluation"}
220 | // Initialize with 1 because we indiscriminately subtract one to map error ranges to LSP ranges.
221 | line, col, endLine, endCol := 1, 1, 1, 1
222 | if doc.err != nil {
223 | lines := strings.Split(doc.err.Error(), "\n")
224 | if len(lines) == 0 {
225 | fmt.Fprintf(os.Stderr, "publishDiagnostics: expected at least two lines of Jsonnet evaluation error output, got: %v\n", lines)
226 | return
227 | }
228 |
229 | var match []string
230 | // TODO(#22): Runtime errors that come from imported files report an incorrect location
231 | runtimeErr := strings.HasPrefix(lines[0], "RUNTIME ERROR:")
232 | if runtimeErr {
233 | match = errRegexp.FindStringSubmatch(lines[1])
234 | } else {
235 | match = errRegexp.FindStringSubmatch(lines[0])
236 | }
237 | if len(match) == 10 {
238 | if match[1] != "" {
239 | line, _ = strconv.Atoi(match[1])
240 | endLine = line + 1
241 | }
242 | if match[2] != "" {
243 | line, _ = strconv.Atoi(match[2])
244 | col, _ = strconv.Atoi(match[3])
245 | endLine = line
246 | endCol, _ = strconv.Atoi(match[4])
247 | }
248 | if match[5] != "" {
249 | line, _ = strconv.Atoi(match[5])
250 | col, _ = strconv.Atoi(match[6])
251 | endLine, _ = strconv.Atoi(match[7])
252 | endCol, _ = strconv.Atoi(match[8])
253 | }
254 | }
255 |
256 | if runtimeErr {
257 | diag.Message = doc.err.Error()
258 | diag.Severity = protocol.SeverityWarning
259 | } else {
260 | diag.Message = match[9]
261 | diag.Severity = protocol.SeverityError
262 | }
263 |
264 | diag.Range = protocol.Range{
265 | Start: protocol.Position{Line: uint32(line - 1), Character: uint32(col - 1)},
266 | End: protocol.Position{Line: uint32(endLine - 1), Character: uint32(endCol - 1)},
267 | }
268 | diags = append(diags, diag)
269 | }
270 |
271 | // TODO(#9): Replace empty context with appropriate context.
272 | err = s.client.PublishDiagnostics(context.TODO(), &protocol.PublishDiagnosticsParams{
273 | URI: uri,
274 | Diagnostics: diags,
275 | })
276 | if err != nil {
277 | fmt.Fprintf(os.Stderr, "publishDiagnostics: unable to publish diagnostics: %v\n", err)
278 | }
279 | }
280 |
281 | func (s *server) DidChange(ctx context.Context, params *protocol.DidChangeTextDocumentParams) error {
282 | doc, err := s.cache.get(params.TextDocument.URI)
283 | if err != nil {
284 | err = fmt.Errorf("DidChange: %s: %w", errorRetrievingDocument, err)
285 | fmt.Fprintln(os.Stderr, err)
286 | return err
287 | }
288 |
289 | defer s.publishDiagnostics(params.TextDocument.URI)
290 |
291 | if params.TextDocument.Version > doc.item.Version && len(params.ContentChanges) != 0 {
292 | doc.item.Text = params.ContentChanges[len(params.ContentChanges)-1].Text
293 | doc.ast, doc.err = jsonnet.SnippetToAST(doc.item.URI.SpanURI().Filename(), doc.item.Text)
294 | if doc.err != nil {
295 | return s.cache.put(doc)
296 | }
297 | symbols := analyseSymbols(doc.ast)
298 | if len(symbols) != 1 {
299 | panic("There should only be a single root symbol for an AST")
300 | }
301 | doc.symbols = symbols[0]
302 | // TODO(#10): Work out better way to invalidate the VM cache.
303 | s.vm.Importer(&jsonnet.FileImporter{})
304 | // TODO(#11): Evaluate whether the raw AST is better for analysis than the desugared AST.
305 | doc.val, doc.err = s.vm.EvaluateAnonymousSnippet(doc.item.URI.SpanURI().Filename(), doc.item.Text)
306 | return s.cache.put(doc)
307 | }
308 | return nil
309 | }
310 |
311 | func (s *server) DidChangeConfiguration(context.Context, *protocol.DidChangeConfigurationParams) error {
312 | return notImplemented("DidChangeConfiguration")
313 | }
314 |
315 | func (s *server) DidChangeWatchedFiles(context.Context, *protocol.DidChangeWatchedFilesParams) error {
316 | return notImplemented("DidChangeWatchedFiles")
317 | }
318 |
319 | func (s *server) DidChangeWorkspaceFolders(context.Context, *protocol.DidChangeWorkspaceFoldersParams) error {
320 | return notImplemented("DidChangeWorkspaceFolders")
321 | }
322 |
323 | func (s *server) DidClose(context.Context, *protocol.DidCloseTextDocumentParams) error {
324 | return notImplemented("DidClose")
325 | }
326 |
327 | func (s *server) DidCreateFiles(context.Context, *protocol.CreateFilesParams) error {
328 | return notImplemented("DidCreateFiles")
329 | }
330 |
331 | func (s *server) DidDeleteFiles(context.Context, *protocol.DeleteFilesParams) error {
332 | return notImplemented("DidDeleteFiles")
333 | }
334 |
335 | func (s *server) DidOpen(ctx context.Context, params *protocol.DidOpenTextDocumentParams) (err error) {
336 | defer s.publishDiagnostics(params.TextDocument.URI)
337 | doc := document{item: params.TextDocument}
338 | if params.TextDocument.Text != "" {
339 | doc.ast, doc.err = jsonnet.SnippetToAST(params.TextDocument.URI.SpanURI().Filename(), params.TextDocument.Text)
340 | if doc.err != nil {
341 | return s.cache.put(doc)
342 | }
343 | symbols := analyseSymbols(doc.ast)
344 | if len(symbols) != 1 {
345 | panic("There should only be a single root symbol for an AST")
346 | }
347 | doc.symbols = symbols[0]
348 | // TODO(#12): Work out better way to invalidate the VM cache.
349 | doc.val, doc.err = s.vm.EvaluateAnonymousSnippet(params.TextDocument.URI.SpanURI().Filename(), params.TextDocument.Text)
350 | }
351 | return s.cache.put(doc)
352 | }
353 |
354 | func (s *server) DidRenameFiles(context.Context, *protocol.RenameFilesParams) error {
355 | return notImplemented("DidRenameFiles")
356 | }
357 |
358 | func (s *server) DidSave(context.Context, *protocol.DidSaveTextDocumentParams) error {
359 | return notImplemented("DidSave")
360 | }
361 |
362 | func (s *server) DocumentColor(context.Context, *protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {
363 | return nil, notImplemented("DocumentColor")
364 | }
365 |
366 | func (s *server) DocumentHighlight(context.Context, *protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {
367 | return nil, notImplemented("DocumentHighlight")
368 | }
369 |
370 | // DocumentLink is not implemented.
371 | // TODO(#13): Understand why the server capabilities includes documentlink.
372 | func (s *server) DocumentLink(context.Context, *protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {
373 | return nil, nil
374 | }
375 |
376 | func (s *server) DocumentSymbol(ctx context.Context, params *protocol.DocumentSymbolParams) ([]interface{}, error) {
377 | doc, err := s.cache.get(params.TextDocument.URI)
378 | if err != nil {
379 | err = fmt.Errorf("DocumentSymbol: %s: %w", errorRetrievingDocument, err)
380 | fmt.Fprintln(os.Stderr, err)
381 | return nil, err
382 | }
383 |
384 | return []interface{}{doc.symbols}, nil
385 | }
386 |
387 | func (s *server) ExecuteCommand(context.Context, *protocol.ExecuteCommandParams) (interface{}, error) {
388 | return nil, notImplemented("ExecuteCommand")
389 | }
390 |
391 | func (s *server) Exit(context.Context) error {
392 | return notImplemented("Exit")
393 | }
394 |
395 | func (s *server) FoldingRange(context.Context, *protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {
396 | return nil, notImplemented("FoldingRange")
397 | }
398 |
399 | func (s *server) Formatting(ctx context.Context, params *protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {
400 | doc, err := s.cache.get(params.TextDocument.URI)
401 | if err != nil {
402 | err = fmt.Errorf("Formatting: %s: %w", errorRetrievingDocument, err)
403 | fmt.Fprintln(os.Stderr, err)
404 | return nil, err
405 | }
406 | // TODO(#14): Formatting options should be user configurable.
407 | formatted, err := formatter.Format(params.TextDocument.URI.SpanURI().Filename(), doc.item.Text, formatter.DefaultOptions())
408 | if err != nil {
409 | err = fmt.Errorf("Formatting: unable to format document: %w", err)
410 | fmt.Fprintln(os.Stderr, err)
411 | return nil, err
412 | }
413 |
414 | return getTextEdits(doc.item.Text, formatted), nil
415 | }
416 |
417 | func (s *server) Hover(context.Context, *protocol.HoverParams) (*protocol.Hover, error) {
418 | return nil, notImplemented("Hover")
419 | }
420 |
421 | func (s *server) Implementation(context.Context, *protocol.ImplementationParams) (protocol.Definition, error) {
422 | return nil, notImplemented("Implementation")
423 | }
424 |
425 | func (s *server) IncomingCalls(context.Context, *protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {
426 | return nil, notImplemented("IncomingCalls")
427 | }
428 |
429 | func (s *server) Initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) {
430 | return &protocol.InitializeResult{
431 | Capabilities: protocol.ServerCapabilities{
432 | DefinitionProvider: true,
433 | DocumentSymbolProvider: true,
434 | DocumentFormattingProvider: true,
435 | TextDocumentSync: &protocol.TextDocumentSyncOptions{
436 | Change: protocol.Full,
437 | OpenClose: true,
438 | Save: protocol.SaveOptions{
439 | IncludeText: false,
440 | },
441 | },
442 | },
443 | ServerInfo: struct {
444 | Name string `json:"name"`
445 | Version string `json:"version,omitempty"`
446 | }{
447 | Name: "jsonnet-language-server",
448 | },
449 | }, nil
450 | }
451 |
452 | func (s *server) Initialized(context.Context, *protocol.InitializedParams) error {
453 | return nil
454 | }
455 |
456 | func (s *server) LinkedEditingRange(context.Context, *protocol.LinkedEditingRangeParams) (*protocol.LinkedEditingRanges, error) {
457 | return nil, notImplemented("LinkedEditingRange")
458 | }
459 |
460 | func (s *server) LogTrace(context.Context, *protocol.LogTraceParams) error {
461 | return notImplemented("LogTrace")
462 | }
463 |
464 | func (s *server) Moniker(context.Context, *protocol.MonikerParams) ([]protocol.Moniker, error) {
465 | return nil, notImplemented("Moniker")
466 | }
467 |
468 | func (s *server) NonstandardRequest(context.Context, string, interface{}) (interface{}, error) {
469 | return nil, notImplemented("NonstandardRequest")
470 | }
471 |
472 | func (s *server) OnTypeFormatting(context.Context, *protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {
473 | return nil, notImplemented("OnTypeFormatting")
474 | }
475 |
476 | func (s *server) OutgoingCalls(context.Context, *protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {
477 | return nil, notImplemented("OutgoingCalls")
478 | }
479 |
480 | func (s *server) PrepareCallHierarchy(context.Context, *protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {
481 | return nil, notImplemented("PrepareCallHierarchy")
482 | }
483 |
484 | func (s *server) PrepareRename(context.Context, *protocol.PrepareRenameParams) (*protocol.Range, error) {
485 | return nil, notImplemented("PrepareRange")
486 | }
487 |
488 | func (s *server) PrepareTypeHierarchy(context.Context, *protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {
489 | return nil, notImplemented("PrepareTypeHierarchy")
490 | }
491 |
492 | func (s *server) RangeFormatting(context.Context, *protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {
493 | return nil, notImplemented("RangeFormatting")
494 | }
495 |
496 | func (s *server) References(context.Context, *protocol.ReferenceParams) ([]protocol.Location, error) {
497 | return nil, notImplemented("References")
498 | }
499 |
500 | func (s *server) Rename(context.Context, *protocol.RenameParams) (*protocol.WorkspaceEdit, error) {
501 | return nil, notImplemented("Rename")
502 | }
503 |
504 | func (s *server) Resolve(context.Context, *protocol.CompletionItem) (*protocol.CompletionItem, error) {
505 | return nil, notImplemented("Resolve")
506 | }
507 |
508 | func (s *server) ResolveCodeAction(context.Context, *protocol.CodeAction) (*protocol.CodeAction, error) {
509 | return nil, notImplemented("ResolveCodeAction")
510 | }
511 |
512 | func (s *server) ResolveCodeLens(context.Context, *protocol.CodeLens) (*protocol.CodeLens, error) {
513 | return nil, notImplemented("ResolveCodeLens")
514 | }
515 |
516 | func (s *server) ResolveDocumentLink(context.Context, *protocol.DocumentLink) (*protocol.DocumentLink, error) {
517 | return nil, notImplemented("ResolveDocumentLink")
518 | }
519 |
520 | func (s *server) SelectionRange(context.Context, *protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {
521 | return nil, notImplemented("SelectionRange")
522 | }
523 |
524 | func (s *server) SemanticTokensFull(context.Context, *protocol.SemanticTokensParams) (*protocol.SemanticTokens, error) {
525 | return nil, notImplemented("SemanticTokensFull")
526 | }
527 |
528 | func (s *server) SemanticTokensFullDelta(context.Context, *protocol.SemanticTokensDeltaParams) (interface{}, error) {
529 | return nil, notImplemented("SemanticTokensFullDelta")
530 | }
531 |
532 | func (s *server) SemanticTokensRange(context.Context, *protocol.SemanticTokensRangeParams) (*protocol.SemanticTokens, error) {
533 | return nil, notImplemented("SemanticTokensRange")
534 | }
535 |
536 | func (s *server) SemanticTokensRefresh(context.Context) error {
537 | return notImplemented("SemanticTokensRefresh")
538 | }
539 |
540 | func (s *server) SetTrace(context.Context, *protocol.SetTraceParams) error {
541 | return notImplemented("SetTrace")
542 | }
543 |
544 | func (s *server) Shutdown(context.Context) error {
545 | return notImplemented("Shutdown")
546 | }
547 |
548 | func (s *server) SignatureHelp(context.Context, *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) {
549 | return nil, notImplemented("SignatureHelp")
550 | }
551 |
552 | func (s *server) Subtypes(context.Context, *protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {
553 | return nil, notImplemented("Subtypes")
554 | }
555 |
556 | func (s *server) Supertypes(context.Context, *protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {
557 | return nil, notImplemented("Supertypes")
558 | }
559 |
560 | func (s *server) Symbol(context.Context, *protocol.WorkspaceSymbolParams) ([]protocol.SymbolInformation, error) {
561 | return nil, notImplemented("Symbol")
562 | }
563 |
564 | func (s *server) TypeDefinition(context.Context, *protocol.TypeDefinitionParams) (protocol.Definition, error) {
565 | return nil, notImplemented("TypeDefinition")
566 | }
567 |
568 | func (s *server) WillCreateFiles(context.Context, *protocol.CreateFilesParams) (*protocol.WorkspaceEdit, error) {
569 | return nil, notImplemented("WillCreateFiles")
570 | }
571 |
572 | func (s *server) WillDeleteFiles(context.Context, *protocol.DeleteFilesParams) (*protocol.WorkspaceEdit, error) {
573 | return nil, notImplemented("WillDeleteFiles")
574 | }
575 |
576 | func (s *server) WillRenameFiles(context.Context, *protocol.RenameFilesParams) (*protocol.WorkspaceEdit, error) {
577 | return nil, notImplemented("WillRenameFiles")
578 | }
579 |
580 | func (s *server) WillSave(context.Context, *protocol.WillSaveTextDocumentParams) error {
581 | return notImplemented("WillSave")
582 | }
583 |
584 | func (s *server) WillSaveWaitUntil(context.Context, *protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {
585 | return nil, notImplemented("WillSaveWaitUntil")
586 | }
587 |
588 | func (s *server) WorkDoneProgressCancel(context.Context, *protocol.WorkDoneProgressCancelParams) error {
589 | return notImplemented("WorkDoneProgressCancel")
590 | }
591 |
592 | func notImplemented(method string) error {
593 | return fmt.Errorf("%w: %q not yet implemented", jsonrpc2.ErrMethodNotFound, method)
594 | }
595 |
--------------------------------------------------------------------------------
/shell.nix:
--------------------------------------------------------------------------------
1 | { pkgs ? import }:
2 |
3 | with pkgs;
4 | mkShell {
5 | buildInputs = [
6 | go_1_16
7 | golangci-lint
8 | gopls
9 | snitch
10 | ];
11 | shellHook = ''
12 | export PATH="$(pwd)":"$PATH"
13 | '';
14 | }
15 |
--------------------------------------------------------------------------------
/snitch.nix:
--------------------------------------------------------------------------------
1 | { pkgs ? import }:
2 |
3 | with pkgs;
4 | buildGoModule rec {
5 | pname = "snitch";
6 | version = "7c727e0b7919ea504c07c8af0e65b48f07a9e87c";
7 |
8 | src = fetchFromGitHub {
9 | owner = "tsoding";
10 | repo = pname;
11 | rev = version;
12 | sha256 = "sha256-bflHSWN/BH4TSTTP4M3DldVwkV8MUSVCO15eYJTtTi0=";
13 | };
14 | vendorSha256 = "sha256-QAbxld0UY7jO9ommX7VrPKOWEiFPmD/xw02EZL6628A=";
15 |
16 | meta = with lib; {
17 | description = "Language agnostic tool that collects TODOs in the source code and reports them as Issues";
18 | homepage = "https://github.com/tsoding/snitch";
19 | license = licenses.mit;
20 | maintainers = with maintainers; [ jdbaldry ];
21 | };
22 | }
23 |
--------------------------------------------------------------------------------
/stdio.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net"
5 | "os"
6 | "time"
7 | )
8 |
9 | type stdio struct{}
10 |
11 | // Read implements io.Reader interface.
12 | func (stdio) Read(b []byte) (int, error) { return os.Stdin.Read(b) }
13 |
14 | // Write implements io.Writer interface.
15 | func (stdio) Write(b []byte) (int, error) { return os.Stdout.Write(b) }
16 |
17 | // Close implements io.Closer interface.
18 | func (stdio) Close() error {
19 | if err := os.Stdin.Close(); err != nil {
20 | return err
21 | }
22 | return os.Stdout.Close()
23 | }
24 |
25 | // LocalAddr implements net.Conn interface.
26 | func (s stdio) LocalAddr() net.Addr { return s }
27 |
28 | // RemoteAddr implements net.Conn interface.
29 | func (s stdio) RemoteAddr() net.Addr { return s }
30 |
31 | // SetDeadline implements net.Conn interface.
32 | func (stdio) SetDeadline(t time.Time) error { return nil }
33 |
34 | // SetReadDeadline implements net.Conn interface.
35 | func (stdio) SetReadDeadline(t time.Time) error { return nil }
36 |
37 | // SetWriteDeadline implements net.Conn interface.
38 | func (stdio) SetWriteDeadline(t time.Time) error { return nil }
39 |
40 | // Network implements net.Addr interface.
41 | func (stdio) Network() string { return "stdio" }
42 |
43 | // String implements net.Addr interface.
44 | func (stdio) String() string { return "stdio" }
45 |
--------------------------------------------------------------------------------
/symbols.go:
--------------------------------------------------------------------------------
1 | // jsonnet-language-server: A Language Server Protocol server for Jsonnet.
2 | // Copyright (C) 2021 Jack Baldry
3 |
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU Affero General Public License as published
6 | // by the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 |
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU Affero General Public License for more details.
13 |
14 | // You should have received a copy of the GNU Affero General Public License
15 | // along with this program. If not, see .
16 |
17 | package main
18 |
19 | import (
20 | "fmt"
21 | "os"
22 |
23 | "github.com/google/go-jsonnet/ast"
24 | "github.com/jdbaldry/go-language-server-protocol/lsp/protocol"
25 | )
26 |
27 | // locationRangeToProtocolRange translates a ast.LocationRange to a protocol.Range.
28 | // The former is one indexed and the latter is zero indexed.
29 | func locationRangeToProtocolRange(lr ast.LocationRange) protocol.Range {
30 | return protocol.Range{
31 | Start: protocol.Position{Line: uint32(lr.Begin.Line - 1), Character: uint32(lr.Begin.Column - 1)},
32 | End: protocol.Position{Line: uint32(lr.End.Line - 1), Character: uint32(lr.End.Column - 1)},
33 | }
34 | }
35 |
36 | // analyseSymbols traverses the Jsonnet AST and produces a hierarchy of LSP symbols.
37 | func analyseSymbols(n ast.Node) (symbols []protocol.DocumentSymbol) {
38 | switch n := n.(type) {
39 |
40 | case *ast.Apply:
41 | args := make([]protocol.DocumentSymbol, len(n.Arguments.Named))
42 | for i, bind := range n.Arguments.Named {
43 | args[i] = protocol.DocumentSymbol{
44 | Name: string(bind.Name),
45 | Kind: protocol.Variable,
46 | Range: locationRangeToProtocolRange(*n.Loc()),
47 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
48 | Tags: []protocol.SymbolTag{symbolTagDefinition},
49 | Children: analyseSymbols(bind.Arg),
50 | }
51 | }
52 | for _, bind := range n.Arguments.Positional {
53 | // TODO(#17): Evaluate the bind expression to know what the argument is.
54 | args = append(args, protocol.DocumentSymbol{
55 | Name: "expr",
56 | Kind: protocol.Variable,
57 | Range: locationRangeToProtocolRange(*n.Loc()),
58 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
59 | Tags: []protocol.SymbolTag{symbolTagDefinition},
60 | Children: analyseSymbols(bind.Expr),
61 | })
62 | }
63 | symbols = append(symbols, protocol.DocumentSymbol{
64 | Name: "apply",
65 | Kind: protocol.Function,
66 | Range: locationRangeToProtocolRange(*n.Loc()),
67 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
68 | Children: append(args, analyseSymbols(n.Target)...),
69 | })
70 |
71 | case *ast.Array:
72 | children := []protocol.DocumentSymbol{}
73 | for _, elem := range n.Elements {
74 | children = append(children, analyseSymbols(elem.Expr)...)
75 | }
76 | symbols = append(symbols, protocol.DocumentSymbol{
77 | Name: "array",
78 | Kind: protocol.Array,
79 | Range: locationRangeToProtocolRange(*n.Loc()),
80 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
81 | Children: children,
82 | })
83 |
84 | case *ast.Binary:
85 | children := analyseSymbols(n.Left)
86 | children = append(children, analyseSymbols(n.Right)...)
87 | symbols = append(symbols, protocol.DocumentSymbol{
88 | Name: n.Op.String(),
89 | Kind: protocol.Operator,
90 | Range: locationRangeToProtocolRange(*n.Loc()),
91 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
92 | Children: children,
93 | })
94 |
95 | case *ast.Conditional:
96 | symbols = append(symbols, protocol.DocumentSymbol{
97 | Name: "cond",
98 | Deprecated: false,
99 | Range: locationRangeToProtocolRange(*n.Loc()),
100 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
101 | Children: append(append(analyseSymbols(n.Cond), analyseSymbols(n.BranchTrue)...), analyseSymbols(n.BranchFalse)...),
102 | })
103 |
104 | case *ast.DesugaredObject:
105 | locals := make([]protocol.DocumentSymbol, len(n.Locals))
106 | for i, bind := range n.Locals {
107 | // This variable is where `$` references for all children of this object.
108 | // Although this local has children, that is only a self reference and is currently ignored.
109 | if string(bind.Variable) == "$" {
110 | locals[i] = protocol.DocumentSymbol{
111 | Name: string(bind.Variable),
112 | Kind: protocol.Variable,
113 | Range: locationRangeToProtocolRange(*n.Loc()),
114 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
115 | Tags: []protocol.SymbolTag{symbolTagDefinition},
116 | }
117 | } else {
118 | locals[i] = protocol.DocumentSymbol{
119 | Name: string(bind.Variable),
120 | Kind: protocol.Variable,
121 | Range: locationRangeToProtocolRange(bind.LocRange),
122 | SelectionRange: locationRangeToProtocolRange(bind.LocRange),
123 | Tags: []protocol.SymbolTag{symbolTagDefinition},
124 | Children: analyseSymbols(bind.Body),
125 | }
126 | }
127 | }
128 |
129 | fields := make([]protocol.DocumentSymbol, len(n.Fields))
130 | for i, field := range n.Fields {
131 | fields[i] = protocol.DocumentSymbol{
132 | Name: "field",
133 | Kind: protocol.Field,
134 | Range: locationRangeToProtocolRange(field.LocRange),
135 | SelectionRange: locationRangeToProtocolRange(field.LocRange),
136 | Children: append(analyseSymbols(field.Name), analyseSymbols(field.Body)...),
137 | }
138 | }
139 | symbols = append(symbols, protocol.DocumentSymbol{
140 | Name: "object",
141 | Kind: protocol.Object,
142 | Range: locationRangeToProtocolRange(*n.Loc()),
143 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
144 | Children: append(locals, fields...),
145 | })
146 |
147 | case *ast.Error:
148 | symbols = append(symbols, protocol.DocumentSymbol{
149 | Name: "error",
150 | Kind: protocol.Event,
151 | Range: locationRangeToProtocolRange(*n.Loc()),
152 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
153 | Children: analyseSymbols(n.Expr),
154 | })
155 |
156 | case *ast.Function:
157 | params := make([]protocol.DocumentSymbol, len(n.Parameters))
158 | for i, param := range n.Parameters {
159 | params[i] = protocol.DocumentSymbol{
160 | Name: string(param.Name),
161 | Kind: protocol.Variable,
162 | Range: locationRangeToProtocolRange(param.LocRange),
163 | SelectionRange: locationRangeToProtocolRange(param.LocRange),
164 | Tags: []protocol.SymbolTag{symbolTagDefinition},
165 | }
166 | if param.DefaultArg != nil {
167 | params[i].Children = analyseSymbols(param.DefaultArg)
168 | }
169 | }
170 | symbols = append(symbols, protocol.DocumentSymbol{
171 | Name: "function",
172 | Kind: protocol.Function,
173 | Range: locationRangeToProtocolRange(*n.Loc()),
174 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
175 | Children: append(params, analyseSymbols(n.Body)...),
176 | })
177 |
178 | case *ast.Import:
179 | // Although the literal string is a child of an Import, it is ignored and the keyword
180 | // and the literal string are captured by a single File document.
181 | // This is one less symbol in the hierarchy and it means that go to definition works
182 | // from either the keyword or the literal string.
183 | // The same is true for ImportStr.
184 | symbols = append(symbols, protocol.DocumentSymbol{
185 | Name: n.File.Value,
186 | Kind: protocol.File,
187 | Range: locationRangeToProtocolRange(*n.Loc()),
188 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
189 | })
190 |
191 | case *ast.ImportStr:
192 | // See comment associated with Import.
193 | symbols = append(symbols, protocol.DocumentSymbol{
194 | Name: n.File.Value,
195 | Kind: protocol.File,
196 | Range: locationRangeToProtocolRange(*n.Loc()),
197 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
198 | })
199 |
200 | case *ast.Index:
201 | symbols = append(symbols, protocol.DocumentSymbol{
202 | Name: "index",
203 | Kind: protocol.Field,
204 | Range: locationRangeToProtocolRange(*n.Loc()),
205 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
206 | Tags: []protocol.SymbolTag{symbolTagDefinition},
207 | Children: append(analyseSymbols(n.Target), analyseSymbols(n.Index)...),
208 | })
209 |
210 | case *ast.InSuper:
211 | symbols = append(symbols, protocol.DocumentSymbol{
212 | Name: "index",
213 | Kind: protocol.Field,
214 | Range: locationRangeToProtocolRange(*n.Loc()),
215 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
216 | Tags: []protocol.SymbolTag{symbolTagDefinition},
217 | Children: analyseSymbols(n.Index),
218 | })
219 |
220 | case *ast.LiteralBoolean:
221 | symbols = append(symbols, protocol.DocumentSymbol{
222 | Name: fmt.Sprint(n.Value),
223 | Kind: protocol.Boolean,
224 | Range: locationRangeToProtocolRange(*n.Loc()),
225 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
226 | })
227 |
228 | case *ast.LiteralNull:
229 | symbols = append(symbols, protocol.DocumentSymbol{
230 | Name: "null",
231 | Kind: protocol.Null,
232 | Range: locationRangeToProtocolRange(*n.Loc()),
233 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
234 | })
235 |
236 | case *ast.LiteralNumber:
237 | symbols = append(symbols, protocol.DocumentSymbol{
238 | Name: n.OriginalString,
239 | Kind: protocol.Number,
240 | Range: locationRangeToProtocolRange(*n.Loc()),
241 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
242 | })
243 |
244 | case *ast.LiteralString:
245 | symbols = append(symbols, protocol.DocumentSymbol{
246 | Name: n.Value,
247 | Kind: protocol.String,
248 | Range: locationRangeToProtocolRange(*n.Loc()),
249 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
250 | })
251 |
252 | case *ast.Local:
253 | binds := make([]protocol.DocumentSymbol, len(n.Binds))
254 | for i, bind := range n.Binds {
255 | binds[i] = protocol.DocumentSymbol{
256 | Name: string(bind.Variable),
257 | Kind: protocol.Variable,
258 | Tags: []protocol.SymbolTag{symbolTagDefinition},
259 | Children: analyseSymbols(bind.Body),
260 | }
261 | // If the line is zero, it must be unset as Jsonnet location ranges are indexed at one.
262 | // This seems to only happen with local definitions of functions which are preceded with the token "local".
263 | // Adding five (five minus the one for zero indexing plus one for a space) to the location range of the local
264 | // symbol gets closer to the real location but any amount of whitespace could be inbetween.
265 | // Assuming a single space, this works perfectly.
266 | // TODO(#7): Understand why identifiers in local function binds are missing.
267 | if bind.LocRange.Begin.Line == 0 {
268 | binds[i].Range = protocol.Range{
269 | Start: protocol.Position{Line: uint32(n.Loc().Begin.Line - 1), Character: uint32(n.Loc().Begin.Column + 5)},
270 | End: protocol.Position{Line: uint32(n.Loc().End.Line - 1), Character: uint32(n.Loc().End.Column + 5)},
271 | }
272 | binds[i].SelectionRange = binds[i].Range
273 | } else {
274 | binds[i].Range = locationRangeToProtocolRange(bind.LocRange)
275 | binds[i].SelectionRange = locationRangeToProtocolRange(bind.LocRange)
276 | }
277 | }
278 | symbols = append(symbols, protocol.DocumentSymbol{
279 | Name: "local",
280 | Kind: protocol.Namespace,
281 | Range: locationRangeToProtocolRange(*n.Loc()),
282 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
283 | Children: append(binds, analyseSymbols(n.Body)...),
284 | })
285 |
286 | case *ast.Self:
287 | symbols = append(symbols, protocol.DocumentSymbol{
288 | Name: "self",
289 | Kind: protocol.Variable,
290 | Range: locationRangeToProtocolRange(*n.Loc()),
291 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
292 | Tags: []protocol.SymbolTag{symbolTagDefinition},
293 | })
294 |
295 | case *ast.SuperIndex:
296 | symbols = append(symbols, protocol.DocumentSymbol{
297 | Name: "index",
298 | Kind: protocol.Field,
299 | Range: locationRangeToProtocolRange(*n.Loc()),
300 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
301 | Children: append([]protocol.DocumentSymbol{{
302 | Name: "super",
303 | Kind: protocol.Variable,
304 | Range: locationRangeToProtocolRange(*n.Loc()),
305 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
306 | }}, analyseSymbols(n.Index)...),
307 | })
308 |
309 | case *ast.Unary:
310 | symbols = append(symbols, protocol.DocumentSymbol{
311 | Name: n.Op.String(),
312 | Kind: protocol.Operator,
313 | Range: locationRangeToProtocolRange(*n.Loc()),
314 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
315 | Children: analyseSymbols(n.Expr),
316 | })
317 |
318 | case *ast.Var:
319 | symbols = append(symbols, protocol.DocumentSymbol{
320 | Name: string(n.Id),
321 | Kind: protocol.Variable,
322 | Range: locationRangeToProtocolRange(*n.Loc()),
323 | SelectionRange: locationRangeToProtocolRange(*n.Loc()),
324 | })
325 |
326 | default:
327 | fmt.Fprintf(os.Stderr, "analyseSymbols: unhandled node: %T\n", n)
328 | }
329 | return
330 | }
331 |
332 | // isDefinition returns true if a symbol is tagged as a definition.
333 | func isDefinition(s protocol.DocumentSymbol) bool {
334 | for _, t := range s.Tags {
335 | if t == symbolTagDefinition {
336 | return true
337 | }
338 | }
339 | return false
340 | }
341 |
--------------------------------------------------------------------------------