API for getting language server info from extension (bracket pairs, function begin/end, ...) - visual-studio-code

I'm currently writing an extension for VSCode which needs to have some good knowledge about the currently shown code in the editor and I'm wondering if there is some API available which can give me the needed information (e.g. from the current language server) or if I have to do the heavy lifting myself by implementing all the needed code parsing etc.
What I need in detail is the following:
Given is a position in code (line + col no)
What I'd like to know about the given position:
Is pos inside a function and if so, where does the function start & end?
Is pos inside a string and if so, where does the string start & end?
The extension is going to provide some kind of "vim selection light".

You can have only half of that via VS Code APIs.
Is pos inside a function and if so, where does the function start & end?
Using the vscode.executeDocumentSymbolProvider command, you can gather all functions from a file and check if the current position is inside one of the functions.
Something like this to retrieve the functions:
const symbolsToFind = [SymbolKind.Function, SymbolKind.Method, SymbolKind.Constructor];
const docSymbols = await commands.executeCommand(
'vscode.executeDocumentSymbolProvider',
window.activeTextEditor.document.uri
) as DocumentSymbol[];
const docSymbolsFunctionsMethods = docSymbols
? docSymbols.filter(symbol => symbolsToFind.includes(symbol.kind))
: undefined;
Each Symbol provides you with a Range, which defines the start and end of the function declaration and body.
Be aware that you will probably need a recursive approach (each Symbol can contain other Symbols). A complete sample is available on my Separators extension (https://github.com/alefragnani/vscode-separators/blob/b6d515847bbaccf6395b24f9fdf82c373cb24fd7/src/symbols.ts#L51)
Is pos inside a string and if so, where does the string start & end?
Unfortunately, there is no API for that, as VS Code does not expose language tokens or the AST. So, you will have to deal with it yourself, maybe using regex.
Hope this helps

Related

Cimplicity Screen - one object/button that is dependent on hundreds of points

So I have created a huge screen that essentially just shows the robot status for every robot in this factory (individually)… At the very end of the project, they decided they want one object on the screen that blinks if any of the 300 robots fault. I am trying to think of a way to make this work. Maybe a global script of some kind? Problem is, I do not do much scripting in Cimplicity, so any help is appreciated.
All the points that are currently used on this screen (to indicate a fault) have very similar names… as in, the beginning is the same… so I was thinking of a script that could maybe recognize if a bit is high based on PART of it's string name characteristic. The end will change a little each time, but I am sure there is a way to only look for part of a string and negate the rest. If the end has to be hard coded, that's fine.
You can use a Python script in Cimplicity.
I will not go into detail on the use of python in Cimplicity, which is well described in the documentation indicated above.
Here's an example of what can be done... note that I don't have a way to test it and, of course, this will work if the name of your robots in the declaration follows the format Robot_1, Robot_2, Robot_3 ... Robot_10 ... Robot_300 and it also depends on the Name and the Type of the fault variable... as you didn't define it, I imagine it can be an integer, with ZERO indicating no error. But if you use something other than that, you can easily change it.
import cimplicity
(...)
OneRobotWithFault = False
# Here you get the values and check for fault
for i in range(0, 300):
pointName = f'MyFactory.Robot_{i}.FaultCode'
robotFaultCode = cimplicity.point_get(pointName)
if robotFaultCode > 0:
OneRobotWithFault = True
break
# Set the status to the variable "WeHaveRobotWithFault"
cimplicity.point_set("WeHaveRobotWithFault", OneRobotWithFault)

VSCode Extension: Get outline of function for custom outliner

I'm trying to create a custom outliner for VSCode (currently only for python), but I don't find measures to get the information I needed.
I like to get information in this manner this:
Array:
[0]
label: "foo"
type: "Function"
parameters: [...]
Range: [...]
innerDefinitions: [0]
[1]
label: "myclass"
type: "Class"
base_class: ""
Range: [...]
innerDefinitions:
[0]:
[...]
[1]:
[...]
Currently I try to get outline information via vscode.commands.executeCommand( 'vscode.XXX'
What I've tried:
Here is what commands I've tried and what result I received.
vscode.executeImplementationProvider
half usable: range of functionname. Other information is missing
vscode.executeHoverProvider
half usable: string of function head (including def keyword)
vscode.executeDefinitionProvider
half usable: range of complete function. Individual information must be "parsed out"
vscode.executeTypeDefinitionProvider
Never provided any result
vscode.executeDeclarationProvider
Never provided any result
vscode.executeDocumentSymbolProvider
Goes in a good direction. However
(1) Does only work on the whole document (not single function)
(2) Does only return first-level entities (i.e. class methods are not included in result)
Is there any API call I've overseen?
I wonder how the built-in outliner works, as it contains all-level information.
You need to use vscode.commands.executeCommand<vscode.Location[]>("vscode.executeDocumentSymbolProvider", uri, position)
This will give you the full outline of one file. There is no way to receive a partial outline.
Note: innerDefinitions are called children here.
Regarding the detail of the outline:
How detailed (and correct) an outline is going to be, depends on the implementation of the provider. Also, provider's information is no necessarily consistent among languages. This is very important to keep in mind!
At the moment (2021/03), the standard SymbolProvider for...
... Python will have a child for each parameter and local variable of a function. They will not be distinguishable
... C++ will contain no children for parameters. But it will have the parameter types in its name. (e.g. name of void foo(string p) will be foo(string): void.
As you can see, both act differently with their own quirks.
You could create and register a DocumentSymbolProvider yourself, that would return a level of detail you need (see VSCode Providers)
Also see: https://stackoverflow.com/a/66486297/6702598

Exporting the output of MATLAB's methodsview

MATLAB's methodsview tool is handy when exploring the API provided by external classes (Java, COM, etc.). Below is an example of how this function works:
myApp = actxserver('Excel.Application');
methodsview(myApp)
I want to keep the information in this window for future reference, by exporting it to a table, a cell array of strings, a .csv or another similar format, preferably without using external tools.
Some things I tried:
This window allows selecting one line at a time and doing "Ctrl+c Ctrl+v" on it, which results in a tab-separated text that looks like this:
Variant GetCustomListContents (handle, int32)
Such a strategy can work when there are only several methods, but not viable for (the usually-encountered) long lists.
I could not find a way to access the table data via the figure handle (w/o using external tools like findjobj or uiinspect), as findall(0,'Type','Figure') "do not see" the methodsview window/figure at all.
My MATLAB version is R2015a.
Fortunately, methodsview.m file is accessible and allows to get some insight on how the function works. Inside is the following comment:
%// Internal use only: option is optional and if present and equal to
%// 'noUI' this function returns methods information without displaying
%// the table. `
After some trial and error, I saw that the following works:
[titles,data] = methodsview(myApp,'noui');
... and returns two arrays of type java.lang.String[][].
From there I found a couple of ways to present the data in a meaningful way:
Table:
dataTable = cell2table(cell(data));
dataTable.Properties.VariableNames = matlab.lang.makeValidName(cell(titles));
Cell array:
dataCell = [cell(titles).'; cell(data)];
Important note: In the table case, the "Return Type" column title gets renamed to ReturnType, since table titles have to be valid MATLAB identifiers, as mentioned in the docs.

Requesting member of node_element results in "undefined"

I'm using Opa for a school project in which there has to be some synchronization of a textfield between several users. The easy way to solve this, is to transmit the complete field whenever there is a change performed by one of the users. The better way is of course to only transmit the changes.
My idea was to use the caret position in the textfield. As a user types, one can get the last typed character based on the caret position (simply the character before the caret). A DOM element has an easy-to-use field for this called selectionStart. I have this small Javascript for this:
document.getElementById('content').selectionStart
which correctly returns 5 if the caret stands at the fifth character in the field. In Opa, I cannot use selectionStart on either a DOM or a dom_element so I thought I'd write a small plugin. The result is this:
##extern-type dom_element
##register jsGetCaretPosition: dom_element -> int
##args(node)
{
return node.selectionStart;
}
This compiles with the opp-builder without any problem and when I put this small line of code in my Opa script:
#pos = %%caret.jsGetCaretPosition%%(Dom.of_selection(Dom.select_id("content")));
that also compiles without problems. However, when I run the script, it always returns "undefined" and I have no idea what I'm doing wrong. I've looked in the API and Dom.of_selection(Dom.select_id("content")) looked like the correct way to get the corresponding dom_element typed data to give to the plugin. The fact that the plugin returns "undefined" seems to suggest that the selected element does not know the member "selectionStart" eventhough my testcode in Javascript suggest otherwise. Anyone can help?
In Opa dom_element are the results of jQuery selection (i.e. an array of dom nodes). So if I well understood your program you should write something like node[0].selectionStart instead of node.selectionStart.
Moreover you should take care of empty selection and selection which doesn't contains textarea node (without selectionStart property). Perhaps the right code is tmp == undefined ? -1 : tmp = node[0].selectionStart == undefined ? -1 : tmp

How do I Benchmark RESTful Service with Variable Parameters?

I'm currently working on benchmarking a RESTful service I've made, and part of that is making sure it runs in a reasonable amount of times for a large array of parameters. For example, let's say I have RESTful API of the form some_site.com/item?item_id=y. In that case to be sure my service is working as fast as I'd like it to work, I'd want to try out many values for y one by one, preferably coming from some text file. I can't figure out any way of doing this in ab or httperf. I'm open to using a different benchmarking program if I have, but would prefer something simple and light. What I want to do seems like something pretty standard, so I'm guessing there must already be a program that let's me do it, but an hour or so of googling hasn't gotten me an answer. Ideas?
Answer: Jmeter (which is apparently awesome). This faq explains how to do it. Hopefully this helps someone else, as it took me like a day of searching to figure this out.
I have just had some good experience with using JavaScript (via BSF/Rhino) in JMeter.
I have put one thread group in my test plan and stick a 'Simple Controller' with two elements under it - 'HTTP Request' sampler and 'BSF PreProcessor'.
Set BSF language to 'javascript' and either type the code into the text box or point it to a file (use full path or relative to CWD of JMeter process).
/* Since `Math.random()` gives us float, we use `java.util.Random()`
* see: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html */
var Random = new Packages.java.util.Random();
var min = 10-1;
var max = 2;
var maxLines = (min)+Random.nextInt(max-min);
var s = '';
for (var d = 0; d <= maxLines; d++) {
s += d.toString()+','+Random.nextInt(1000).toString()+'\n';
}
// s => '0,312\n1,104\n2,608\n'
vars.put('PAYLOAD', s);
Now I can refer to ${PAYLOAD} in the HTTP request!
You can generate JSON, but you will need to upgrade jakarta-jmeter-2.5.1/lib/js-1.6R5.jar with the newest version of Rhino to get JSON.stringify and JSON.parse. That worked perfectly for me also, though I thought I'd put a simple example here.
You can use BSF pre-processor for URL params as well, just set another variable with vars.put('X', 'some value') and pass it as ${X} in the request parameter.
This blog post helped quite a bit, by the way.