question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

The sourceFile getters are not retreiving all targeted objects from their sourceFile

See original GitHub issue

The sourceFile getters are not retrieving all targeted objects from their sourceFile:

  • sourceFile.getFunctions() only retrieves some functions of the given sourceFile
  • sourceFile.getVariableDeclarations() only retrieves some variable declarations of the given sourceFile

Here is my testing script ( tsm.ts ):

import * as ts from "typescript";
import * as fs from "fs";
import * as tsm from "ts-morph";

function generateDocumentation(fileNames: string[],options: ts.CompilerOptions): void {
	const project = new tsm.Project();
	const checker = project.getTypeChecker();
	for (const fileName of fileNames){
		const sourceFile = project.addSourceFileAtPath(fileName);
		console.log("printing all functions of the given sourceFile:");
		sourceFile.getFunctions().forEach((f) => console.log("name: " + f.getName() + " - type: "+ f.getType().getText()));
		console.log("\nPrinting all variables of the given sourceFile");
		sourceFile.getVariableDeclarations().forEach((v) => console.log("name: " + v.getName() + " - type: "+ v.getType().getText() ));
	}
}

generateDocumentation(process.argv.slice(2), {
	target: ts.ScriptTarget.ES5,
	module: ts.ModuleKind.CommonJS
});

Here is the source code I use for my tests: test.ts

//Sourcecode test
// WS for Workspace
var WS = (function ($) {
    "use strict";
	/**
     * This is just a test-function
     * @param {boolean} bool
     * @return {string}
     */
	function functionTest(bool) {
		return "abc";
	}
	
    /* Variables */
    var var0 = [];
    var var1 = {},
        var2 = 0,
        var3 = '',
        var4 = null,
        var5;

	/**
     * This is just an anonymous test-function
     * @return {int}
     */
    var anonFunc0 = function () {
        return 42;
    }

    /** Retrieve UserGroups from the server, store them in the variable Grouptest.
	 * This is just an anonymous test-function with an AJAX style promise
     **/
    var anonFunc1 = function () {
        return new Promise(function (resolve, reject) {
            let DataObject = {
                "RequestType": "request",
                "Session_ID": SessionID
            };

            let successAjax = function (data) {
                data = data.d;             
                resolve(data);
            }

            ajax({
                url: "WebServices/Workspace_Ajax.asmx/WebMethodSimple",
                data: JSON.stringify(DataObject),
                origin: "anonFunc1"
            }).then(successAjax, reject);
        });
    };
	return {// This dictionnary contains is what is inside the WS object, so it contains references to public methods
		anonFunc0 : anonFunc0,
		anonFunc1 : anonFunc1,
	}
})(jQuery);
$(document).on("click", '#Button1', WS.anonFunc1);

const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}`;
const MonthToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}`;

/**
 * This is just a test-function outide WS
 * @param {boolean} bool
 * @return {boolean}
 */
function func0(bool){
	console.log("DoSomething");
	return bool;
}

/**
 * This is just a test-function outide WS returning a promise
 */
function func1() {
    return new Promise(function (resolve) {
            console.log("DoSomething");
            resolve(true);
    });
}

To launch the script in cmd (windows 10), I use this command: tsc tsm.ts --m commonjs && node tsm.js test.ts

Current output printing all functions of the given sourceFile: name: func0 - type: typeof func0 name: func1 - type: typeof func1

Printing all variables of the given sourceFile name: WS - type: ($: any) => void name: dateToString - type: (d: any) => string name: MonthToString - type: (d: any) => string

Expected output Printing all functions of the given sourceFile: [Every functions printed: at least functionTest, func0, func1 and maybe the anonymous function (I don’t know about the anonymous functions, I didn’t find anything about them in the documentation)]

Printing all variables of the given sourceFile [Every variables printed : at least var0, var1, var2, var3, var4, var5 and maybe the anonymous function]

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
dsherretcommented, Feb 28, 2020

I am actually making an automated-documentation tool for a big project I am working on. I had previously made a script in pure Typescript in order to recover every function and class declaration, but I decided to try out ts-morph for its findReferences() functionality (as this seems hard to implement without a specialized library). Is findReferences also limited to a particular context (only getting its results in the child source files)?

findReferences() and findReferencesAsNodes() is just a wrapper around the LanguageService’s findReferences() method. It will find all references within the “program” (so it should return all references and not be limited).

Also I want to parse JSDoc parameters whenever possible, if I understand this correctly, I will have to use getChildren instead of getDescendantsOfKind, right ?

I think getDescendantsOfKind can be used to get JSDoc parameters. Open an issue if not as it would be good to change it to do that. Generally though you can get jsdoc information by having a node (say a FunctionDeclaration) then calling #getJsDocs() on it. From there, you can call #getTags() then filter by Node.isJSDocParameterTag(tag).

Also, what is the point of getFunctions and getVariableDeclarations being Source Files methods? Wouldn’t it make more sense to have themas node methods, in order to not be restricted to the AST root ?

They’re on any node that can have statements. So those methods also exist on FunctionDeclaration, NamespaceDeclaration, MethodDeclaration, etc. It’s not on every node because not all nodes can have children that are functions, for example.

0reactions
dsherretcommented, Apr 26, 2020

@pierregallard sorry for my delay. It will be slower to do that. You’ll want to exclusively use the AST to be fast.

Something like:

if (Node.isVariableDeclaration(node)) {
    const initializer = node.getInitializer();
    if (initializer != null && (Node.isFunctionExpression(initializer) || Node.isArrowFunction(initializer))) {
        // use initializer here
    }
}

Also, see my answer here for another scenario: https://github.com/dsherret/ts-morph/issues/800#issuecomment-619630622

Read more comments on GitHub >

github_iconTop Results From Across the Web

tools/gn/substitution_writer.h - chromium/src - Git at Google
It includes all source substitutions (since they depend on the various. // parts of the source file) as well as the target substitutions....
Read more >
Lombok is not generating getter and setter - Stack Overflow
Quickly, I noticed that Lombok is not generating getters and setters for my classes, although the @Getter and @Setter are being correctly recognised...
Read more >
ProGuard Manual: Usage - Guardsquare
Specifies not to optimize the input class files. By default, ProGuard optimizes all code. It inlines and merges classes and class members, and...
Read more >
Solidity Documentation - Read the Docs
Solidity is an object-oriented, high-level language for implementing smart contracts. Smart contracts are programs.
Read more >
getter - JavaScript - MDN Web Docs - Mozilla
In the following example, the object has a getter as its own property. On getting the property, the property is removed from the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found