Skip to content

Commit

Permalink
[forgive] Init
Browse files Browse the repository at this point in the history
Init basic LSP. At the moment the extension doesn't do anything interesting, but it does compile successfully.
Summary:

Test Plan:

Reviewers:

Subscribers:

Tasks:

Tags:
Summary:

Test Plan:

Reviewers:

Subscribers:

Tasks:

Tags:
  • Loading branch information
poteto committed Feb 25, 2025
1 parent 4768315 commit 17de979
Show file tree
Hide file tree
Showing 16 changed files with 1,183 additions and 49 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,4 @@ packages/react-devtools-fusebox/dist
packages/react-devtools-inline/dist
packages/react-devtools-shell/dist
packages/react-devtools-timeline/dist

6 changes: 5 additions & 1 deletion compiler/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,8 @@ dist
.spr.yml
testfilter.txt

bundle-oss.sh
bundle-oss.sh

# forgive
*.vsix
.vscode-test
3 changes: 3 additions & 0 deletions compiler/packages/react-forgive/.vscode-test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {defineConfig} from '@vscode/test-cli';

export default defineConfig({files: 'dist/test/**/*.test.js'});
1 change: 1 addition & 0 deletions compiler/packages/react-forgive/.yarnrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ignore-engines true
21 changes: 21 additions & 0 deletions compiler/packages/react-forgive/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Meta Platforms, Inc. and affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion compiler/packages/react-forgive/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"repository": {
"type": "git",
"url": "git+https://github.com/facebook/react.git",
"directory": "compiler/packages/react-forgive-client"
"directory": "compiler/packages/react-forgive"
},
"dependencies": {
"vscode-languageclient": "^9.0.1"
Expand Down
60 changes: 60 additions & 0 deletions compiler/packages/react-forgive/client/src/extension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import * as path from 'path';
import {ExtensionContext, window as Window} from 'vscode';

import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
TransportKind,
} from 'vscode-languageclient/node';

let client: LanguageClient;

export function activate(context: ExtensionContext) {
const serverModule = context.asAbsolutePath(path.join('dist', 'server.js'));

// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
const serverOptions: ServerOptions = {
run: {
module: serverModule,
transport: TransportKind.ipc,
},
debug: {
module: serverModule,
transport: TransportKind.ipc,
},
};

const clientOptions: LanguageClientOptions = {
documentSelector: [
{scheme: 'file', language: 'javascriptreact'},
{scheme: 'file', language: 'typescriptreact'},
],
progressOnInitialization: true,
};

// Create the language client and start the client.
try {
client = new LanguageClient(
'react-forgive',
'React Analyzer',
serverOptions,
clientOptions,
);
} catch {
Window.showErrorMessage(
`React Analyzer couldn't be started. See the output channel for details.`,
);
return;
}

client.registerProposedFeatures();
client.start();
}

export function deactivate(): Thenable<void> | undefined {
if (client !== undefined) {
return client.stop();
}
}
8 changes: 6 additions & 2 deletions compiler/packages/react-forgive/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
],
"publisher": "Meta",
"engines": {
"vscode": "^1.75.0"
"vscode": "^1.96.0"
},
"activationEvents": [
"onLanguage:javascriptreact",
Expand Down Expand Up @@ -49,10 +49,14 @@
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@types/mocha": "^10.0.10",
"@types/node": "^20",
"@types/vscode": "^1.96.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"esbuild": "^0.24.0",
"eslint": "^9.13.0",
"typescript": "^5.7.2",
"mocha": "^11.0.1",
"typescript-eslint": "^8.16.0",
"yargs": "^17.7.2"
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/packages/react-forgive/scripts/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export const entryPoint = path.join(__dirname, '../server/src/index.ts');
export const outfile = path.join(__dirname, '../dist/extension.js');
export const outfile = path.join(__dirname, '../dist/server.js');
export const config = {
entryPoints: [entryPoint],
outfile,
Expand Down
10 changes: 8 additions & 2 deletions compiler/packages/react-forgive/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,21 @@
"description": "Experimental LSP server",
"license": "MIT",
"scripts": {
"build": "echo 'no build'",
"build": "rimraf dist && rollup --config --bundleConfigAsCjs",
"test": "echo 'no tests'"
},
"repository": {
"type": "git",
"url": "git+https://github.com/facebook/react.git",
"directory": "compiler/packages/react-forgive-server"
"directory": "compiler/packages/react-forgive"
},
"dependencies": {
"@babel/core": "^7.26.0",
"@babel/parser": "^7.26.0",
"@babel/plugin-syntax-typescript": "^7.25.9",
"@babel/types": "^7.26.0",
"cosmiconfig": "^9.0.0",
"prettier": "^3.3.3",
"vscode-languageserver": "^9.0.1",
"vscode-languageserver-textdocument": "^1.0.12"
}
Expand Down
58 changes: 58 additions & 0 deletions compiler/packages/react-forgive/server/src/compiler/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import type * as BabelCore from '@babel/core';
import {parseAsync, transformFromAstAsync} from '@babel/core';
import BabelPluginReactCompiler, {
type PluginOptions,
} from 'babel-plugin-react-compiler/src';
import * as babelParser from 'prettier/plugins/babel.js';
import * as estreeParser from 'prettier/plugins/estree';
import * as typescriptParser from 'prettier/plugins/typescript';
import * as prettier from 'prettier/standalone';

type CompileOptions = {
text: string;
file: string;
options: PluginOptions | null;
};
export async function compile({
text,
file,
options,
}: CompileOptions): Promise<BabelCore.BabelFileResult> {
const ast = await parseAsync(text, {
sourceFileName: file,
parserOpts: {
plugins: ['typescript', 'jsx'],
},
sourceType: 'module',
});
const plugins =
options != null
? [[BabelPluginReactCompiler, options]]
: [[BabelPluginReactCompiler]];
const result = await transformFromAstAsync(ast, text, {
filename: file,
highlightCode: false,
retainLines: true,
plugins,
sourceType: 'module',
sourceFileName: file,
});
if (result?.code == null) {
throw new Error(
`Expected BabelPluginReactCompiler to compile successfully, got ${result}`,
);
}
result.code = await prettier.format(result.code, {
semi: false,
parser: 'babel-ts',
plugins: [babelParser, estreeParser, typescriptParser],
});
return result;
}
25 changes: 25 additions & 0 deletions compiler/packages/react-forgive/server/src/compiler/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {
parsePluginOptions,
type PluginOptions,
} from 'babel-plugin-react-compiler/src';
import {cosmiconfigSync} from 'cosmiconfig';

export function resolveReactConfig(projectPath: string): PluginOptions | null {
const explorerSync = cosmiconfigSync('react', {
searchStrategy: 'project',
cache: true,
});
const result = explorerSync.search(projectPath);
if (result != null) {
return parsePluginOptions(result.config);
} else {
return null;
}
}
87 changes: 87 additions & 0 deletions compiler/packages/react-forgive/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,90 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {TextDocument} from 'vscode-languageserver-textdocument';
import {
createConnection,
type InitializeParams,
type InitializeResult,
ProposedFeatures,
TextDocuments,
TextDocumentSyncKind,
} from 'vscode-languageserver/node';
import {compile} from './compiler';
import {type PluginOptions} from 'babel-plugin-react-compiler/src';
import {resolveReactConfig} from './compiler/options';
import {type BabelFileResult} from '@babel/core';

const SUPPORTED_LANGUAGE_IDS = new Set([
'javascript',
'javascriptreact',
'typescript',
'typescriptreact',
]);

const connection = createConnection(ProposedFeatures.all);
const documents = new TextDocuments(TextDocument);

let compilerOptions: PluginOptions | null = null;
let lastResult: BabelFileResult | null = null;

connection.onInitialize((_params: InitializeParams) => {
// TODO(@poteto) get config fr
compilerOptions = resolveReactConfig('.');
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
codeLensProvider: {resolveProvider: true},
},
};
return result;
});

connection.onInitialized(() => {
connection.console.log('initialized');
});

documents.onDidOpen(async event => {
if (SUPPORTED_LANGUAGE_IDS.has(event.document.languageId)) {
const text = event.document.getText();
const result = await compile({
text,
file: event.document.uri,
options: compilerOptions,
});
if (result.code != null) {
lastResult = result;
}
}
});

documents.onDidChangeContent(async event => {
if (SUPPORTED_LANGUAGE_IDS.has(event.document.languageId)) {
const text = event.document.getText();
const result = await compile({
text,
file: event.document.uri,
options: compilerOptions,
});
if (result.code != null) {
lastResult = result;
}
}
});

connection.onDidChangeWatchedFiles(change => {
connection.console.log(
change.changes.map(c => `File changed: ${c.uri}`).join('\n'),
);
});

connection.onCodeLens(params => {
connection.console.log('lastResult: ' + JSON.stringify(lastResult, null, 2));
connection.console.log('params: ' + JSON.stringify(params, null, 2));
return [];
});

documents.listen(connection);
connection.listen();
connection.console.info(`React Analyzer running in node ${process.version}`);
14 changes: 8 additions & 6 deletions compiler/packages/react-forgive/server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
{
"extends": "@tsconfig/strictest/tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"outDir": "dist",
"module": "ES2015",
"moduleResolution": "Bundler",
"rootDir": "../../..",
"noEmit": true,
"jsx": "react-jsxdev",
"lib": ["ES2020"],
"target": "ES2020",
"target": "ES2015",
"sourceMap": false,
"removeComments": true,
},
"exclude": ["node_modules", ".vscode-test"],
"include": ["src/**/*.ts"],
"include": ["src/**/*.ts"]
}
Loading

0 comments on commit 17de979

Please sign in to comment.