✨ Added scala、powershell、groovy prettier plugin
This commit is contained in:
109
frontend/src/common/prettier/plugins/scala/index.ts
Normal file
109
frontend/src/common/prettier/plugins/scala/index.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import { createScalaPrinter } from "./printer";
|
||||
import { parse, type ScalaCstNode, type IToken } from "./scala-parser";
|
||||
import { type Plugin, type SupportOption } from "prettier";
|
||||
|
||||
/**
|
||||
* Prettierがサポートする言語の定義
|
||||
*/
|
||||
const languages = [
|
||||
{
|
||||
name: "Scala",
|
||||
parsers: ["scala"],
|
||||
extensions: [".scala", ".sc"],
|
||||
vscodeLanguageIds: ["scala"],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Scalaパーサーの定義
|
||||
*/
|
||||
const parsers = {
|
||||
scala: {
|
||||
parse: (text: string) => {
|
||||
const result = parse(text);
|
||||
|
||||
// シンプルなコメント保持: ASTに格納してvisitorで処理
|
||||
const ast = {
|
||||
...result.cst,
|
||||
comments: [], // Prettierの検証を回避
|
||||
originalComments: result.comments || [], // プラグイン独自のコメント格納
|
||||
type: "compilationUnit",
|
||||
};
|
||||
return ast;
|
||||
},
|
||||
astFormat: "scala-cst",
|
||||
locStart: (node: ScalaCstNode | IToken) => {
|
||||
// Handle comment tokens (from Chevrotain lexer)
|
||||
if ("startOffset" in node && node.startOffset !== undefined) {
|
||||
return node.startOffset;
|
||||
}
|
||||
// Handle CST nodes
|
||||
if ("location" in node && node.location?.startOffset !== undefined) {
|
||||
return node.location.startOffset;
|
||||
}
|
||||
return 0;
|
||||
},
|
||||
locEnd: (node: ScalaCstNode | IToken) => {
|
||||
// Handle comment tokens (from Chevrotain lexer)
|
||||
if ("endOffset" in node && node.endOffset !== undefined) {
|
||||
return node.endOffset + 1; // Chevrotain endOffset is inclusive, Prettier expects exclusive
|
||||
}
|
||||
// Handle CST nodes
|
||||
if ("location" in node && node.location?.endOffset !== undefined) {
|
||||
return node.location.endOffset + 1; // Chevrotain endOffset is inclusive, Prettier expects exclusive
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
hasPragma: () => false,
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* プリンターの定義
|
||||
*/
|
||||
const printers = {
|
||||
"scala-cst": createScalaPrinter(),
|
||||
};
|
||||
|
||||
/**
|
||||
* プラグインオプション(scalafmt互換性 - フェーズ1)
|
||||
*/
|
||||
const options: Record<string, SupportOption> = {
|
||||
// Prettier standard options with Scala-specific defaults
|
||||
semi: {
|
||||
type: "boolean",
|
||||
default: false, // Scala convention: omit semicolons
|
||||
description: "Add semicolons at the end of statements",
|
||||
category: "Global",
|
||||
} as const,
|
||||
|
||||
// Deprecated options (backward compatibility)
|
||||
scalaLineWidth: {
|
||||
type: "int",
|
||||
default: 80,
|
||||
description: "Maximum line width (DEPRECATED: use printWidth instead)",
|
||||
category: "Scala",
|
||||
} as const,
|
||||
scalaIndentStyle: {
|
||||
type: "choice",
|
||||
default: "spaces",
|
||||
choices: [
|
||||
{ value: "spaces", description: "Use spaces for indentation" },
|
||||
{ value: "tabs", description: "Use tabs for indentation" },
|
||||
],
|
||||
description: "Indentation style (DEPRECATED: use useTabs instead)",
|
||||
category: "Scala",
|
||||
} as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Prettierプラグインのエクスポート
|
||||
*/
|
||||
const plugin: Plugin = {
|
||||
languages,
|
||||
parsers,
|
||||
printers,
|
||||
options,
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
91
frontend/src/common/prettier/plugins/scala/printer.ts
Normal file
91
frontend/src/common/prettier/plugins/scala/printer.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { CstNodeVisitor, type CSTNode } from "./visitor";
|
||||
import type { ScalaCstNode, IToken } from "./scala-parser";
|
||||
import { type Doc, type Printer, type AstPath, type Options } from "prettier";
|
||||
|
||||
/**
|
||||
* Scala用のPrettierプリンターを作成
|
||||
* @returns Prettierプリンターオブジェクト
|
||||
*/
|
||||
export function createScalaPrinter(): Printer {
|
||||
return {
|
||||
/**
|
||||
* ASTノードをフォーマット済みのテキストに変換
|
||||
* @param path - 現在のノードへのパス
|
||||
* @param options - Prettierオプション
|
||||
* @param print - 子ノードを印刷するための関数
|
||||
* @returns フォーマット済みのDoc
|
||||
*/
|
||||
print(
|
||||
path: AstPath<ScalaCstNode>,
|
||||
options: Options,
|
||||
print: (path: AstPath) => Doc,
|
||||
): Doc {
|
||||
const node = path.getValue();
|
||||
|
||||
const visitor = new CstNodeVisitor();
|
||||
const result = visitor.visit(node, {
|
||||
path,
|
||||
options: {
|
||||
printWidth: options.printWidth,
|
||||
tabWidth: options.tabWidth,
|
||||
useTabs: options.useTabs,
|
||||
semi: options.semi,
|
||||
singleQuote: options.singleQuote,
|
||||
trailingComma:
|
||||
options.trailingComma === "es5" ? "all" : options.trailingComma,
|
||||
},
|
||||
print: (childNode: CSTNode) => {
|
||||
// 子ノード用のモックパスを作成
|
||||
const mockPath = {
|
||||
getValue: () => childNode,
|
||||
call: (fn: () => unknown) => fn(),
|
||||
};
|
||||
return String(print(mockPath as AstPath<unknown>));
|
||||
},
|
||||
indentLevel: 0,
|
||||
});
|
||||
|
||||
// 文字列結果をPrettierのDocに変換
|
||||
return result;
|
||||
},
|
||||
/**
|
||||
* コメントを印刷
|
||||
* @param path - コメントトークンへのパス
|
||||
* @returns フォーマット済みのコメント
|
||||
*/
|
||||
printComment(path: AstPath<IToken>): Doc {
|
||||
const comment = path.getValue();
|
||||
if (!comment) return "";
|
||||
|
||||
// Chevrotainのimageプロパティを使用
|
||||
if (typeof comment.image === "string") {
|
||||
return comment.image;
|
||||
}
|
||||
|
||||
// fallback
|
||||
if (typeof comment.image === "string") {
|
||||
return comment.image;
|
||||
}
|
||||
|
||||
// デバッグ: コメント構造を確認
|
||||
console.log("Unexpected comment structure in printComment:", comment);
|
||||
return "";
|
||||
},
|
||||
canAttachComment(): boolean {
|
||||
// コメント機能を一時的に無効化
|
||||
return false;
|
||||
},
|
||||
willPrintOwnComments(): boolean {
|
||||
return false; // Prettier標準のコメント処理を使用しない
|
||||
},
|
||||
insertPragma(text: string): string {
|
||||
return text;
|
||||
},
|
||||
hasPrettierIgnore(): boolean {
|
||||
return false;
|
||||
},
|
||||
isBlockComment(comment: IToken): boolean {
|
||||
return comment.tokenType?.name === "BlockComment";
|
||||
},
|
||||
};
|
||||
}
|
||||
206
frontend/src/common/prettier/plugins/scala/scala-parser/index.ts
Normal file
206
frontend/src/common/prettier/plugins/scala/scala-parser/index.ts
Normal file
@@ -0,0 +1,206 @@
|
||||
import { ScalaLexer } from "./lexer";
|
||||
import { parserInstance } from "./parser";
|
||||
import type {
|
||||
ParseResult,
|
||||
ScalaCstNode,
|
||||
TokenBounds,
|
||||
LineColumn,
|
||||
} from "./types";
|
||||
import type { IToken, CstElement } from "chevrotain";
|
||||
|
||||
export { ScalaLexer, allTokens } from "./lexer";
|
||||
export { ScalaParser, parserInstance } from "./parser";
|
||||
export type {
|
||||
ParseResult,
|
||||
ScalaCstNode,
|
||||
TokenBounds,
|
||||
LineColumn,
|
||||
} from "./types";
|
||||
export type { IToken } from "chevrotain";
|
||||
|
||||
/**
|
||||
* CSTノードに位置情報を自動設定するヘルパー関数
|
||||
* @param cst - 処理対象のCSTノード
|
||||
* @param tokens - 解析で使用されたトークンの配列
|
||||
* @param text - 元のソースコードテキスト
|
||||
* @returns 位置情報が付与されたCSTノード
|
||||
*/
|
||||
function addLocationToCST(
|
||||
cst: ScalaCstNode,
|
||||
tokens: IToken[],
|
||||
text: string,
|
||||
): ScalaCstNode {
|
||||
if (!cst || !tokens) return cst;
|
||||
|
||||
// テキストから行の開始位置を計算
|
||||
const lineStarts = [0]; // 最初の行は0から始まる
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
if (text[i] === "\n") {
|
||||
lineStarts.push(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// オフセットから行番号と列番号を取得
|
||||
function getLineAndColumn(offset: number): LineColumn {
|
||||
let line = 1;
|
||||
for (let i = 0; i < lineStarts.length - 1; i++) {
|
||||
if (offset >= lineStarts[i] && offset < lineStarts[i + 1]) {
|
||||
line = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (offset >= lineStarts[lineStarts.length - 1]) {
|
||||
line = lineStarts.length;
|
||||
}
|
||||
|
||||
const column = offset - lineStarts[line - 1] + 1;
|
||||
return { line, column };
|
||||
}
|
||||
|
||||
// トークンから最小・最大位置を計算
|
||||
function findTokenBounds(node: ScalaCstNode): TokenBounds | null {
|
||||
if (!node) return null;
|
||||
|
||||
let minStart = Infinity;
|
||||
let maxEnd = -1;
|
||||
|
||||
function findTokensInNode(n: ScalaCstNode | IToken): void {
|
||||
if (!n) return;
|
||||
|
||||
// トークンの場合
|
||||
if (
|
||||
"startOffset" in n &&
|
||||
"endOffset" in n &&
|
||||
n.startOffset !== undefined &&
|
||||
n.endOffset !== undefined
|
||||
) {
|
||||
minStart = Math.min(minStart, n.startOffset);
|
||||
maxEnd = Math.max(maxEnd, n.endOffset);
|
||||
return;
|
||||
}
|
||||
|
||||
// CSTノードの場合
|
||||
if ("children" in n && n.children) {
|
||||
for (const children of Object.values(n.children)) {
|
||||
if (Array.isArray(children)) {
|
||||
children.forEach((child) => {
|
||||
// CstElementをScalaCstNode | ITokenに安全に変換
|
||||
if ("children" in child) {
|
||||
findTokensInNode(child as ScalaCstNode);
|
||||
} else {
|
||||
findTokensInNode(child as IToken);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
findTokensInNode(node);
|
||||
|
||||
if (minStart === Infinity || maxEnd === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { start: minStart, end: maxEnd };
|
||||
}
|
||||
|
||||
// 再帰的にCSTノードに位置情報を設定
|
||||
function setCSTLocation(node: ScalaCstNode): ScalaCstNode {
|
||||
if (!node) return node;
|
||||
|
||||
// トークンの場合はそのまま返す
|
||||
if (node.startOffset !== undefined) {
|
||||
return node;
|
||||
}
|
||||
|
||||
// CSTノードの場合
|
||||
if (node.children) {
|
||||
// 子ノードを先に処理
|
||||
const processedChildren: Record<string, CstElement[]> = {};
|
||||
for (const [key, children] of Object.entries(node.children)) {
|
||||
if (Array.isArray(children)) {
|
||||
processedChildren[key] = children.map((child) => {
|
||||
if ("children" in child) {
|
||||
return setCSTLocation(child as ScalaCstNode);
|
||||
}
|
||||
return child; // IToken
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// このノードの位置を計算
|
||||
const bounds = findTokenBounds({ ...node, children: processedChildren });
|
||||
|
||||
if (bounds) {
|
||||
const startLoc = getLineAndColumn(bounds.start);
|
||||
const endLoc = getLineAndColumn(bounds.end);
|
||||
|
||||
return {
|
||||
...node,
|
||||
children: processedChildren,
|
||||
location: {
|
||||
startOffset: bounds.start,
|
||||
endOffset: bounds.end,
|
||||
startLine: startLoc.line,
|
||||
endLine: endLoc.line,
|
||||
startColumn: startLoc.column,
|
||||
endColumn: endLoc.column,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
...node,
|
||||
children: processedChildren,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
return setCSTLocation(cst);
|
||||
}
|
||||
|
||||
export function parse(text: string): ParseResult {
|
||||
// Use legacy parser for now until modular parser is fixed
|
||||
return parseLegacy(text);
|
||||
}
|
||||
|
||||
// Legacy parser function (has left recursion issues)
|
||||
export function parseLegacy(text: string): ParseResult {
|
||||
// Tokenize
|
||||
const lexResult = ScalaLexer.tokenize(text);
|
||||
|
||||
if (lexResult.errors.length > 0) {
|
||||
throw new Error(
|
||||
`Lexing errors: ${lexResult.errors.map((e) => e.message).join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse
|
||||
parserInstance.input = lexResult.tokens;
|
||||
const cst = parserInstance.compilationUnit();
|
||||
|
||||
if (parserInstance.errors.length > 0) {
|
||||
throw new Error(
|
||||
`Parsing errors: ${parserInstance.errors.map((e) => e.message).join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// CSTに位置情報を追加
|
||||
const cstWithLocation = addLocationToCST(
|
||||
cst as ScalaCstNode,
|
||||
lexResult.tokens,
|
||||
text,
|
||||
);
|
||||
|
||||
return {
|
||||
cst: cstWithLocation,
|
||||
errors: [],
|
||||
comments: lexResult.groups.comments || [],
|
||||
};
|
||||
}
|
||||
|
||||
// Note: parseModular function was removed as the modular parser integration
|
||||
// is still in development. Use the main parse() function instead.
|
||||
479
frontend/src/common/prettier/plugins/scala/scala-parser/lexer.ts
Normal file
479
frontend/src/common/prettier/plugins/scala/scala-parser/lexer.ts
Normal file
@@ -0,0 +1,479 @@
|
||||
import { createToken, Lexer, ILexingResult } from "chevrotain";
|
||||
|
||||
// Keywords
|
||||
export const Val = createToken({ name: "Val", pattern: /val\b/ });
|
||||
export const Var = createToken({ name: "Var", pattern: /var\b/ });
|
||||
export const Def = createToken({ name: "Def", pattern: /def\b/ });
|
||||
export const Class = createToken({ name: "Class", pattern: /class\b/ });
|
||||
export const ObjectKeyword = createToken({
|
||||
name: "Object",
|
||||
pattern: /object\b/,
|
||||
});
|
||||
export const Trait = createToken({ name: "Trait", pattern: /trait\b/ });
|
||||
export const Extends = createToken({ name: "Extends", pattern: /extends\b/ });
|
||||
export const With = createToken({ name: "With", pattern: /with\b/ });
|
||||
export const If = createToken({ name: "If", pattern: /if\b/ });
|
||||
export const Else = createToken({ name: "Else", pattern: /else\b/ });
|
||||
export const While = createToken({ name: "While", pattern: /while\b/ });
|
||||
export const For = createToken({ name: "For", pattern: /for\b/ });
|
||||
export const Yield = createToken({ name: "Yield", pattern: /yield\b/ });
|
||||
export const Return = createToken({ name: "Return", pattern: /return\b/ });
|
||||
export const New = createToken({ name: "New", pattern: /new\b/ });
|
||||
export const This = createToken({ name: "This", pattern: /this\b/ });
|
||||
export const Super = createToken({ name: "Super", pattern: /super\b/ });
|
||||
export const Package = createToken({ name: "Package", pattern: /package\b/ });
|
||||
export const Import = createToken({ name: "Import", pattern: /import\b/ });
|
||||
export const Case = createToken({ name: "Case", pattern: /case\b/ });
|
||||
export const Match = createToken({ name: "Match", pattern: /match\b/ });
|
||||
export const Try = createToken({ name: "Try", pattern: /try\b/ });
|
||||
export const Catch = createToken({ name: "Catch", pattern: /catch\b/ });
|
||||
export const Finally = createToken({ name: "Finally", pattern: /finally\b/ });
|
||||
export const Throw = createToken({ name: "Throw", pattern: /throw\b/ });
|
||||
export const Null = createToken({ name: "Null", pattern: /null\b/ });
|
||||
export const True = createToken({ name: "True", pattern: /true\b/ });
|
||||
export const False = createToken({ name: "False", pattern: /false\b/ });
|
||||
export const NotImplemented = createToken({
|
||||
name: "NotImplemented",
|
||||
pattern: /\?\?\?/,
|
||||
});
|
||||
export const Type = createToken({ name: "Type", pattern: /type\b/ });
|
||||
export const Private = createToken({ name: "Private", pattern: /private\b/ });
|
||||
export const Protected = createToken({
|
||||
name: "Protected",
|
||||
pattern: /protected\b/,
|
||||
});
|
||||
export const Public = createToken({ name: "Public", pattern: /public\b/ });
|
||||
export const Abstract = createToken({
|
||||
name: "Abstract",
|
||||
pattern: /abstract\b/,
|
||||
});
|
||||
export const Final = createToken({ name: "Final", pattern: /final\b/ });
|
||||
export const Sealed = createToken({ name: "Sealed", pattern: /sealed\b/ });
|
||||
export const Implicit = createToken({
|
||||
name: "Implicit",
|
||||
pattern: /implicit\b/,
|
||||
});
|
||||
export const Lazy = createToken({ name: "Lazy", pattern: /lazy\b/ });
|
||||
export const Override = createToken({
|
||||
name: "Override",
|
||||
pattern: /override\b/,
|
||||
});
|
||||
export const Given = createToken({ name: "Given", pattern: /given\b/ });
|
||||
export const Using = createToken({ name: "Using", pattern: /using\b/ });
|
||||
export const To = createToken({ name: "To", pattern: /to\b/ });
|
||||
export const Enum = createToken({ name: "Enum", pattern: /enum\b/ });
|
||||
export const Array = createToken({ name: "Array", pattern: /Array\b/ });
|
||||
export const Extension = createToken({
|
||||
name: "Extension",
|
||||
pattern: /extension\b/,
|
||||
});
|
||||
export const Export = createToken({ name: "Export", pattern: /export\b/ });
|
||||
export const Opaque = createToken({ name: "Opaque", pattern: /opaque\b/ });
|
||||
export const Inline = createToken({ name: "Inline", pattern: /inline\b/ });
|
||||
export const Transparent = createToken({
|
||||
name: "Transparent",
|
||||
pattern: /transparent\b/,
|
||||
});
|
||||
|
||||
// Identifiers (must come after keywords)
|
||||
// Enhanced Unicode identifier support following Scala Language Specification
|
||||
// Operator identifier for custom operators (e.g., +++, <~>, etc.)
|
||||
export const OperatorIdentifier = createToken({
|
||||
name: "OperatorIdentifier",
|
||||
pattern: /[+\-*/%:&|^<>=!~?#@$\\]+/,
|
||||
});
|
||||
|
||||
// Backward compatible with existing implementation, enhanced mathematical symbol support
|
||||
// Supports: Latin, Greek, Cyrillic, CJK, Arabic, Hebrew, Mathematical symbols, Emojis (via surrogate pairs)
|
||||
export const Identifier = createToken({
|
||||
name: "Identifier",
|
||||
pattern:
|
||||
/(?:_[a-zA-Z0-9_$\u00C0-\u00FF\u0370-\u03FF\u0400-\u04FF\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u0590-\u05FF\u0600-\u06FF\u2200-\u22FF\u27C0-\u27EF\u2980-\u29FF\u2A00-\u2AFF]+|[a-zA-Z$\u00C0-\u00FF\u0370-\u03FF\u0400-\u04FF\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u0590-\u05FF\u0600-\u06FF\u2200-\u22FF\u27C0-\u27EF\u2980-\u29FF\u2A00-\u2AFF][a-zA-Z0-9_$\u00C0-\u00FF\u0370-\u03FF\u0400-\u04FF\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u0590-\u05FF\u0600-\u06FF\u2200-\u22FF\u27C0-\u27EF\u2980-\u29FF\u2A00-\u2AFF]*)/u,
|
||||
});
|
||||
|
||||
// Literals
|
||||
export const IntegerLiteral = createToken({
|
||||
name: "IntegerLiteral",
|
||||
pattern: /-?\d+[lLiIsSbB]?/,
|
||||
});
|
||||
|
||||
// Scientific notation literal (must come before FloatingPointLiteral)
|
||||
export const ScientificNotationLiteral = createToken({
|
||||
name: "ScientificNotationLiteral",
|
||||
pattern: /-?\d+(\.\d+)?[eE][+-]?\d+[fFdD]?/,
|
||||
});
|
||||
|
||||
export const FloatingPointLiteral = createToken({
|
||||
name: "FloatingPointLiteral",
|
||||
pattern: /-?\d+\.\d+[fFdD]?|-?\.\d+[fFdD]?/,
|
||||
});
|
||||
|
||||
export const StringLiteral = createToken({
|
||||
name: "StringLiteral",
|
||||
pattern: /"""[\s\S]*?"""|"([^"\\]|\\.|\\u[0-9A-Fa-f]{4})*"/,
|
||||
});
|
||||
|
||||
export const InterpolatedStringLiteral = createToken({
|
||||
name: "InterpolatedStringLiteral",
|
||||
pattern:
|
||||
/[a-zA-Z_][a-zA-Z0-9_]*"""[\s\S]*?"""|[a-zA-Z_][a-zA-Z0-9_]*"([^"\\]|\\.|\\u[0-9A-Fa-f]{4}|\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{[^}]*\})*"/,
|
||||
});
|
||||
|
||||
export const CharLiteral = createToken({
|
||||
name: "CharLiteral",
|
||||
pattern: /'([^'\\]|\\.|\\u[0-9A-Fa-f]{4})'/,
|
||||
});
|
||||
|
||||
// Operators
|
||||
export const Equals = createToken({ name: "Equals", pattern: /=/ });
|
||||
export const Plus = createToken({ name: "Plus", pattern: /\+/ });
|
||||
export const Minus = createToken({ name: "Minus", pattern: /-/ });
|
||||
export const Star = createToken({ name: "Star", pattern: /\*/ });
|
||||
export const Slash = createToken({ name: "Slash", pattern: /\// });
|
||||
export const Backslash = createToken({ name: "Backslash", pattern: /\\/ });
|
||||
export const Percent = createToken({ name: "Percent", pattern: /%/ });
|
||||
export const LessThan = createToken({ name: "LessThan", pattern: /</ });
|
||||
export const GreaterThan = createToken({ name: "GreaterThan", pattern: />/ });
|
||||
export const LessThanEquals = createToken({
|
||||
name: "LessThanEquals",
|
||||
pattern: /<=/,
|
||||
});
|
||||
export const GreaterThanEquals = createToken({
|
||||
name: "GreaterThanEquals",
|
||||
pattern: />=/,
|
||||
});
|
||||
export const EqualsEquals = createToken({
|
||||
name: "EqualsEquals",
|
||||
pattern: /==/,
|
||||
});
|
||||
export const DoubleEquals = EqualsEquals; // Alias for modular parser compatibility
|
||||
export const NotEquals = createToken({ name: "NotEquals", pattern: /!=/ });
|
||||
export const LogicalAnd = createToken({ name: "LogicalAnd", pattern: /&&/ });
|
||||
export const LogicalOr = createToken({ name: "LogicalOr", pattern: /\|\|/ });
|
||||
export const Exclamation = createToken({ name: "Exclamation", pattern: /!/ });
|
||||
export const Arrow = createToken({ name: "Arrow", pattern: /=>/ });
|
||||
export const TypeLambdaArrow = createToken({
|
||||
name: "TypeLambdaArrow",
|
||||
pattern: /=>>/,
|
||||
});
|
||||
export const DoubleArrow = TypeLambdaArrow; // Alias for modular parser compatibility
|
||||
export const LeftArrow = createToken({ name: "LeftArrow", pattern: /<-/ });
|
||||
export const RightArrow = createToken({ name: "RightArrow", pattern: /->/ });
|
||||
export const ContextArrow = createToken({
|
||||
name: "ContextArrow",
|
||||
pattern: /\?=>/,
|
||||
});
|
||||
export const SubtypeOf = createToken({ name: "SubtypeOf", pattern: /<:/ });
|
||||
export const ColonLess = SubtypeOf; // Alias for modular parser compatibility
|
||||
export const SupertypeOf = createToken({ name: "SupertypeOf", pattern: />:/ });
|
||||
export const GreaterColon = SupertypeOf; // Alias for modular parser compatibility
|
||||
export const AppendOp = createToken({ name: "AppendOp", pattern: /:\+/ });
|
||||
export const PlusColon = AppendOp; // Alias for modular parser compatibility
|
||||
export const ColonPlus = createToken({ name: "ColonPlus", pattern: /:\+/ }); // Same as AppendOp but separate token for parser
|
||||
export const PrependOp = createToken({ name: "PrependOp", pattern: /::/ });
|
||||
export const ColonColon = PrependOp; // Alias for modular parser compatibility
|
||||
export const ConcatOp = createToken({ name: "ConcatOp", pattern: /\+\+/ });
|
||||
export const DoublePlus = ConcatOp; // Alias for modular parser compatibility
|
||||
export const AppendEquals = createToken({
|
||||
name: "AppendEquals",
|
||||
pattern: /\+\+=/,
|
||||
});
|
||||
// Compound assignment operators
|
||||
export const PlusEquals = createToken({ name: "PlusEquals", pattern: /\+=/ });
|
||||
export const MinusEquals = createToken({ name: "MinusEquals", pattern: /-=/ });
|
||||
export const StarEquals = createToken({ name: "StarEquals", pattern: /\*=/ });
|
||||
export const SlashEquals = createToken({ name: "SlashEquals", pattern: /\/=/ });
|
||||
export const PercentEquals = createToken({
|
||||
name: "PercentEquals",
|
||||
pattern: /%=/,
|
||||
});
|
||||
// sbt DSL operators
|
||||
export const DoublePercent = createToken({
|
||||
name: "DoublePercent",
|
||||
pattern: /%%/,
|
||||
});
|
||||
// Bitwise operators
|
||||
export const BitwiseAnd = createToken({ name: "BitwiseAnd", pattern: /&/ });
|
||||
export const BitwiseOr = createToken({ name: "BitwiseOr", pattern: /\|/ });
|
||||
export const BitwiseXor = createToken({ name: "BitwiseXor", pattern: /\^/ });
|
||||
export const BitwiseTilde = createToken({ name: "BitwiseTilde", pattern: /~/ });
|
||||
export const LeftShift = createToken({ name: "LeftShift", pattern: /<</ });
|
||||
export const RightShift = createToken({ name: "RightShift", pattern: />>/ });
|
||||
export const UnsignedRightShift = createToken({
|
||||
name: "UnsignedRightShift",
|
||||
pattern: />>>/,
|
||||
});
|
||||
export const Colon = createToken({ name: "Colon", pattern: /:/ });
|
||||
export const ColonEquals = createToken({ name: "ColonEquals", pattern: /:=/ });
|
||||
export const SbtAssign = ColonEquals; // Alias for sbt compatibility
|
||||
export const Semicolon = createToken({ name: "Semicolon", pattern: /;/ });
|
||||
export const Comma = createToken({ name: "Comma", pattern: /,/ });
|
||||
export const Dot = createToken({ name: "Dot", pattern: /\./ });
|
||||
export const Underscore = createToken({
|
||||
name: "Underscore",
|
||||
pattern: /_/,
|
||||
});
|
||||
export const At = createToken({ name: "At", pattern: /@/ });
|
||||
export const Question = createToken({ name: "Question", pattern: /\?/ });
|
||||
|
||||
// Quote and Splice tokens for Scala 3 macros
|
||||
export const QuoteStart = createToken({ name: "QuoteStart", pattern: /'\{/ });
|
||||
export const SpliceStart = createToken({
|
||||
name: "SpliceStart",
|
||||
pattern: /\$\{/,
|
||||
});
|
||||
|
||||
// Additional tokens for modular parser
|
||||
export const Quote = createToken({ name: "Quote", pattern: /'/ });
|
||||
export const Dollar = createToken({ name: "Dollar", pattern: /\$/ });
|
||||
// QuestionArrow is now alias for ContextArrow to avoid duplicate patterns
|
||||
export const QuestionArrow = ContextArrow;
|
||||
|
||||
// String interpolation tokens
|
||||
export const InterpolatedString = createToken({
|
||||
name: "InterpolatedString",
|
||||
pattern: /s"([^"\\]|\\.|\\u[0-9A-Fa-f]{4})*"/,
|
||||
});
|
||||
export const FormattedString = createToken({
|
||||
name: "FormattedString",
|
||||
pattern: /f"([^"\\]|\\.|\\u[0-9A-Fa-f]{4})*"/,
|
||||
});
|
||||
export const RawString = createToken({
|
||||
name: "RawString",
|
||||
pattern: /raw"([^"\\]|\\.|\\u[0-9A-Fa-f]{4})*"/,
|
||||
});
|
||||
export const CustomInterpolatedString = createToken({
|
||||
name: "CustomInterpolatedString",
|
||||
pattern: /[a-zA-Z_][a-zA-Z0-9_]*"([^"\\]|\\.|\\u[0-9A-Fa-f]{4})*"/,
|
||||
});
|
||||
|
||||
// Numeric suffix tokens
|
||||
export const LongSuffix = createToken({ name: "LongSuffix", pattern: /[lL]/ });
|
||||
export const IntSuffix = createToken({ name: "IntSuffix", pattern: /[iI]/ });
|
||||
export const ShortSuffix = createToken({
|
||||
name: "ShortSuffix",
|
||||
pattern: /[sS]/,
|
||||
});
|
||||
export const ByteSuffix = createToken({ name: "ByteSuffix", pattern: /[bB]/ });
|
||||
export const FloatSuffix = createToken({
|
||||
name: "FloatSuffix",
|
||||
pattern: /[fF]/,
|
||||
});
|
||||
export const DoubleSuffix = createToken({
|
||||
name: "DoubleSuffix",
|
||||
pattern: /[dD]/,
|
||||
});
|
||||
|
||||
// Additional missing tokens
|
||||
export const Hash = createToken({ name: "Hash", pattern: /#/ });
|
||||
|
||||
// Delimiters
|
||||
export const LeftParen = createToken({ name: "LeftParen", pattern: /\(/ });
|
||||
export const RightParen = createToken({ name: "RightParen", pattern: /\)/ });
|
||||
export const LeftBracket = createToken({ name: "LeftBracket", pattern: /\[/ });
|
||||
export const RightBracket = createToken({
|
||||
name: "RightBracket",
|
||||
pattern: /\]/,
|
||||
});
|
||||
export const LeftBrace = createToken({ name: "LeftBrace", pattern: /\{/ });
|
||||
export const RightBrace = createToken({ name: "RightBrace", pattern: /\}/ });
|
||||
|
||||
// Whitespace and Comments
|
||||
export const WhiteSpace = createToken({
|
||||
name: "WhiteSpace",
|
||||
pattern: /\s+/,
|
||||
group: Lexer.SKIPPED,
|
||||
});
|
||||
|
||||
export const LineComment = createToken({
|
||||
name: "LineComment",
|
||||
pattern: /\/\/[^\n\r]*/,
|
||||
group: "comments",
|
||||
});
|
||||
|
||||
export const BlockComment = createToken({
|
||||
name: "BlockComment",
|
||||
pattern: /\/\*([^*]|\*(?!\/))*\*\//,
|
||||
group: "comments",
|
||||
});
|
||||
|
||||
// All tokens in order
|
||||
export const allTokens = [
|
||||
// Comments (must come before operators)
|
||||
LineComment,
|
||||
BlockComment,
|
||||
|
||||
// Whitespace
|
||||
WhiteSpace,
|
||||
|
||||
// Keywords (must come before Identifier)
|
||||
Val,
|
||||
Var,
|
||||
Def,
|
||||
Class,
|
||||
ObjectKeyword,
|
||||
Trait,
|
||||
Extends,
|
||||
With,
|
||||
If,
|
||||
Else,
|
||||
While,
|
||||
For,
|
||||
Yield,
|
||||
Return,
|
||||
New,
|
||||
This,
|
||||
Super,
|
||||
Package,
|
||||
Import,
|
||||
Case,
|
||||
Match,
|
||||
Try,
|
||||
Catch,
|
||||
Finally,
|
||||
Throw,
|
||||
Null,
|
||||
True,
|
||||
False,
|
||||
NotImplemented,
|
||||
Type,
|
||||
Private,
|
||||
Protected,
|
||||
Public,
|
||||
Abstract,
|
||||
Final,
|
||||
Sealed,
|
||||
Implicit,
|
||||
Lazy,
|
||||
Override,
|
||||
Given,
|
||||
Using,
|
||||
To,
|
||||
Enum,
|
||||
Array,
|
||||
Extension,
|
||||
Export,
|
||||
Opaque,
|
||||
Inline,
|
||||
Transparent,
|
||||
|
||||
// Literals
|
||||
ScientificNotationLiteral, // Must come before FloatingPointLiteral
|
||||
FloatingPointLiteral, // Must come before IntegerLiteral
|
||||
IntegerLiteral,
|
||||
// String interpolation literals (must come before StringLiteral)
|
||||
CustomInterpolatedString,
|
||||
InterpolatedString,
|
||||
FormattedString,
|
||||
RawString,
|
||||
InterpolatedStringLiteral, // Must come before StringLiteral
|
||||
StringLiteral,
|
||||
CharLiteral,
|
||||
|
||||
// Multi-character operators (must come before single-character)
|
||||
TypeLambdaArrow, // Must come before Arrow to avoid ambiguity
|
||||
ContextArrow, // Must come before Arrow to avoid ambiguity
|
||||
Arrow,
|
||||
LeftArrow,
|
||||
RightArrow,
|
||||
SubtypeOf,
|
||||
SupertypeOf,
|
||||
LessThanEquals,
|
||||
GreaterThanEquals,
|
||||
EqualsEquals,
|
||||
NotEquals,
|
||||
LogicalAnd,
|
||||
LogicalOr,
|
||||
ColonEquals, // := must come before :
|
||||
AppendOp,
|
||||
PrependOp,
|
||||
AppendEquals, // ++= must come before ++
|
||||
ConcatOp,
|
||||
// Quote and splice tokens (must come before single-character)
|
||||
QuoteStart, // '{ must come before single '
|
||||
SpliceStart, // ${ must come before single $
|
||||
// Compound assignment operators
|
||||
PlusEquals,
|
||||
MinusEquals,
|
||||
StarEquals,
|
||||
SlashEquals,
|
||||
PercentEquals,
|
||||
// Bitwise shift operators (must come before single-character)
|
||||
UnsignedRightShift, // >>> must come before >>
|
||||
LeftShift,
|
||||
RightShift,
|
||||
|
||||
// Single-character operators
|
||||
Equals,
|
||||
Plus,
|
||||
Minus,
|
||||
Star,
|
||||
Slash,
|
||||
Backslash,
|
||||
DoublePercent, // %% must come before single %
|
||||
Percent,
|
||||
LessThan,
|
||||
GreaterThan,
|
||||
Exclamation,
|
||||
BitwiseAnd,
|
||||
BitwiseOr,
|
||||
BitwiseXor,
|
||||
BitwiseTilde,
|
||||
Colon,
|
||||
Semicolon,
|
||||
Comma,
|
||||
Dot,
|
||||
At,
|
||||
// QuestionArrow removed - now an alias for ContextArrow
|
||||
Question,
|
||||
Quote,
|
||||
Dollar,
|
||||
Hash,
|
||||
|
||||
// Delimiters
|
||||
LeftParen,
|
||||
RightParen,
|
||||
LeftBracket,
|
||||
RightBracket,
|
||||
LeftBrace,
|
||||
RightBrace,
|
||||
|
||||
// Operator identifier (before regular identifier)
|
||||
OperatorIdentifier,
|
||||
|
||||
// Identifier (must come before underscore)
|
||||
Identifier,
|
||||
|
||||
// Underscore (must come after identifier to not interfere with _identifier patterns)
|
||||
Underscore,
|
||||
];
|
||||
|
||||
// レキサーの作成(インポート時の問題を回避するための遅延初期化)
|
||||
let scalaLexerInstance: Lexer | null = null;
|
||||
|
||||
/**
|
||||
* Scalaコードの字句解析を行うレキサー
|
||||
*/
|
||||
export const ScalaLexer = {
|
||||
/**
|
||||
* レキサーインスタンスを取得(遅延初期化)
|
||||
* @returns Chevrotainレキサーのインスタンス
|
||||
*/
|
||||
get instance(): Lexer {
|
||||
if (!scalaLexerInstance) {
|
||||
scalaLexerInstance = new Lexer(allTokens);
|
||||
}
|
||||
return scalaLexerInstance;
|
||||
},
|
||||
/**
|
||||
* 入力文字列をトークン化
|
||||
* @param input - 字句解析対象のScalaソースコード
|
||||
* @returns トークン化の結果(トークン、エラー、グループ化されたトークン)
|
||||
*/
|
||||
tokenize(input: string): ILexingResult {
|
||||
return this.instance.tokenize(input);
|
||||
},
|
||||
};
|
||||
|
||||
// Export lexer instance for backward compatibility with tests
|
||||
export const lexerInstance = ScalaLexer;
|
||||
1929
frontend/src/common/prettier/plugins/scala/scala-parser/parser.ts
Normal file
1929
frontend/src/common/prettier/plugins/scala/scala-parser/parser.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Base parser module with shared utilities and interfaces
|
||||
*/
|
||||
import * as tokens from "../lexer";
|
||||
import { CstParser, ParserMethod, CstNode } from "chevrotain";
|
||||
import type { TokenType } from "chevrotain";
|
||||
|
||||
export interface ParserRuleMixin {
|
||||
// Utility methods for parser rules - these need to match CstParser access levels
|
||||
RULE: CstParser["RULE"];
|
||||
SUBRULE: CstParser["SUBRULE"];
|
||||
CONSUME: CstParser["CONSUME"];
|
||||
MANY: CstParser["MANY"];
|
||||
MANY_SEP: CstParser["MANY_SEP"];
|
||||
OPTION: CstParser["OPTION"];
|
||||
OR: CstParser["OR"];
|
||||
AT_LEAST_ONE: CstParser["AT_LEAST_ONE"];
|
||||
AT_LEAST_ONE_SEP: CstParser["AT_LEAST_ONE_SEP"];
|
||||
LA: CstParser["LA"];
|
||||
performSelfAnalysis: CstParser["performSelfAnalysis"];
|
||||
}
|
||||
|
||||
export abstract class BaseParserModule {
|
||||
protected parser: ParserRuleMixin;
|
||||
|
||||
constructor(parser: ParserRuleMixin) {
|
||||
this.parser = parser;
|
||||
}
|
||||
|
||||
// Helper methods for common patterns
|
||||
protected consumeTokenType(tokenType: TokenType) {
|
||||
return this.parser.CONSUME(tokenType);
|
||||
}
|
||||
|
||||
protected optionalConsume(tokenType: TokenType) {
|
||||
return this.parser.OPTION(() => this.parser.CONSUME(tokenType));
|
||||
}
|
||||
|
||||
protected manyOf(rule: () => void) {
|
||||
return this.parser.MANY(rule);
|
||||
}
|
||||
|
||||
protected oneOf(
|
||||
alternatives: Array<{ ALT: () => void; GATE?: () => boolean }>,
|
||||
) {
|
||||
return this.parser.OR(alternatives);
|
||||
}
|
||||
|
||||
protected subrule(rule: ParserMethod<unknown[], CstNode>) {
|
||||
return this.parser.SUBRULE(rule);
|
||||
}
|
||||
|
||||
protected lookahead(offset: number) {
|
||||
return this.parser.LA(offset);
|
||||
}
|
||||
}
|
||||
|
||||
export { tokens };
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Definition parsing module for class, object, trait, method, and variable definitions
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
import type { ParserMethod, CstNode } from "chevrotain";
|
||||
|
||||
export class DefinitionParserMixin extends BaseParserModule {
|
||||
// Dependencies from other modules
|
||||
annotation!: ParserMethod<unknown[], CstNode>;
|
||||
modifier!: ParserMethod<unknown[], CstNode>;
|
||||
typeParameters!: ParserMethod<unknown[], CstNode>;
|
||||
classParameters!: ParserMethod<unknown[], CstNode>;
|
||||
extendsClause!: ParserMethod<unknown[], CstNode>;
|
||||
classBody!: ParserMethod<unknown[], CstNode>;
|
||||
type!: ParserMethod<unknown[], CstNode>;
|
||||
expression!: ParserMethod<unknown[], CstNode>;
|
||||
pattern!: ParserMethod<unknown[], CstNode>;
|
||||
parameterLists!: ParserMethod<unknown[], CstNode>;
|
||||
|
||||
// Class definition
|
||||
classDefinition = this.parser.RULE("classDefinition", () => {
|
||||
this.consumeTokenType(tokens.Class);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
// Constructor annotations (for DI patterns like @Inject())
|
||||
this.manyOf(() => this.subrule(this.annotation));
|
||||
// Constructor parameters (multiple parameter lists supported)
|
||||
this.parser.MANY(() => this.subrule(this.classParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.extendsClause));
|
||||
this.parser.OPTION(() => this.subrule(this.classBody));
|
||||
});
|
||||
|
||||
// Object definition
|
||||
objectDefinition = this.parser.RULE("objectDefinition", () => {
|
||||
this.consumeTokenType(tokens.ObjectKeyword);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.extendsClause));
|
||||
this.parser.OPTION(() => this.subrule(this.classBody));
|
||||
});
|
||||
|
||||
// Trait definition
|
||||
traitDefinition = this.parser.RULE("traitDefinition", () => {
|
||||
this.consumeTokenType(tokens.Trait);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.extendsClause));
|
||||
this.parser.OPTION(() => this.subrule(this.classBody));
|
||||
});
|
||||
|
||||
// Enum definition (Scala 3)
|
||||
enumDefinition = this.parser.RULE("enumDefinition", () => {
|
||||
this.consumeTokenType(tokens.Enum);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.classParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.extendsClause));
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.manyOf(() => this.subrule(this.enumCaseDef));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
enumCaseDef = this.parser.RULE("enumCaseDef", () => {
|
||||
this.consumeTokenType(tokens.Case);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.classParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.extendsClause));
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
|
||||
// Extension definition (Scala 3)
|
||||
extensionDefinition = this.parser.RULE("extensionDefinition", () => {
|
||||
this.consumeTokenType(tokens.Extension);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.manyOf(() => this.subrule(this.extensionMemberDef));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
extensionMemberDef = this.parser.RULE("extensionMemberDef", () => {
|
||||
this.manyOf(() => this.subrule(this.modifier));
|
||||
this.subrule(this.defDefinition);
|
||||
});
|
||||
|
||||
// Val definition
|
||||
valDefinition = this.parser.RULE("valDefinition", () => {
|
||||
this.consumeTokenType(tokens.Val);
|
||||
this.oneOf([
|
||||
{
|
||||
// Simple variable with optional type: val x: Type = expr or val x: Type (abstract)
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
},
|
||||
GATE: () => {
|
||||
// This alternative is for simple identifier patterns only
|
||||
// Must handle: val x = ..., val x: Type = ..., val x: Type (abstract)
|
||||
// Must NOT handle: val (x, y) = ..., val SomeClass(...) = ...
|
||||
const first = this.lookahead(1);
|
||||
const second = this.lookahead(2);
|
||||
|
||||
// If first token is not identifier, this is not a simple val
|
||||
if (!first || first.tokenType !== tokens.Identifier) return false;
|
||||
|
||||
// If second token is left paren, this is a constructor pattern
|
||||
if (second && second.tokenType === tokens.LeftParen) return false;
|
||||
|
||||
// Otherwise, this is a simple identifier (with or without type, with or without assignment)
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
// Pattern matching: val (x, y) = expr or val SomeClass(...) = expr
|
||||
ALT: () => {
|
||||
this.subrule(this.pattern);
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
},
|
||||
]);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
|
||||
// Var definition
|
||||
varDefinition = this.parser.RULE("varDefinition", () => {
|
||||
this.consumeTokenType(tokens.Var);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
|
||||
// Method definition
|
||||
defDefinition = this.parser.RULE("defDefinition", () => {
|
||||
this.consumeTokenType(tokens.Def);
|
||||
this.oneOf([
|
||||
// Regular method name
|
||||
{ ALT: () => this.consumeTokenType(tokens.Identifier) },
|
||||
// Constructor (this keyword)
|
||||
{ ALT: () => this.consumeTokenType(tokens.This) },
|
||||
]);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.parameterLists));
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
|
||||
// Type definition
|
||||
typeDefinition = this.parser.RULE("typeDefinition", () => {
|
||||
this.consumeTokenType(tokens.Type);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.type);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
/**
|
||||
* Expression parsing module for all types of expressions in Scala
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
import type { ParserMethod, CstNode } from "chevrotain";
|
||||
|
||||
export class ExpressionParserMixin extends BaseParserModule {
|
||||
// Dependencies from other modules
|
||||
annotation!: ParserMethod<unknown[], CstNode>;
|
||||
modifier!: ParserMethod<unknown[], CstNode>;
|
||||
type!: ParserMethod<unknown[], CstNode>;
|
||||
literal!: ParserMethod<unknown[], CstNode>;
|
||||
qualifiedIdentifier!: ParserMethod<unknown[], CstNode>;
|
||||
pattern!: ParserMethod<unknown[], CstNode>;
|
||||
parameterLists!: ParserMethod<unknown[], CstNode>;
|
||||
typeArgument!: ParserMethod<unknown[], CstNode>;
|
||||
caseClause!: ParserMethod<unknown[], CstNode>;
|
||||
generator!: ParserMethod<unknown[], CstNode>;
|
||||
|
||||
// Main expression rule
|
||||
expression = this.parser.RULE("expression", () => {
|
||||
this.parser.OR([
|
||||
// Polymorphic function literal (Scala 3)
|
||||
{
|
||||
ALT: () => this.subrule(this.polymorphicFunctionLiteral),
|
||||
GATE: () => {
|
||||
const la1 = this.parser.LA(1);
|
||||
return la1?.tokenType === tokens.LeftBracket;
|
||||
},
|
||||
},
|
||||
// Regular expressions
|
||||
{ ALT: () => this.subrule(this.assignmentOrInfixExpression) },
|
||||
]);
|
||||
});
|
||||
|
||||
// Assignment or infix expression
|
||||
assignmentOrInfixExpression = this.parser.RULE(
|
||||
"assignmentOrInfixExpression",
|
||||
() => {
|
||||
this.subrule(this.postfixExpression);
|
||||
this.parser.MANY(() => {
|
||||
this.subrule(this.infixOperator);
|
||||
this.subrule(this.postfixExpression);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Postfix expression
|
||||
postfixExpression = this.parser.RULE("postfixExpression", () => {
|
||||
this.subrule(this.primaryExpression);
|
||||
this.parser.MANY(() => {
|
||||
this.parser.OR([
|
||||
// Method call with parentheses
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.expression),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
// Type arguments
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.typeArgument),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
},
|
||||
},
|
||||
// Member access
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Dot);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
},
|
||||
},
|
||||
// Postfix operator (like Ask pattern ?)
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Question);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// Primary expression
|
||||
primaryExpression = this.parser.RULE("primaryExpression", () => {
|
||||
this.parser.OR([
|
||||
// Literals
|
||||
{ ALT: () => this.subrule(this.literal) },
|
||||
// Identifier
|
||||
{ ALT: () => this.consumeTokenType(tokens.Identifier) },
|
||||
// This and super
|
||||
{ ALT: () => this.consumeTokenType(tokens.This) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Super) },
|
||||
// Underscore (placeholder)
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
// Parenthesized expression
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.OPTION(() => this.subrule(this.expression));
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
// Block expression
|
||||
{ ALT: () => this.subrule(this.blockExpression) },
|
||||
// New expression
|
||||
{ ALT: () => this.subrule(this.newExpression) },
|
||||
// Partial function literal
|
||||
{ ALT: () => this.subrule(this.partialFunctionLiteral) },
|
||||
// Quote expression (Scala 3)
|
||||
{ ALT: () => this.subrule(this.quoteExpression) },
|
||||
// Splice expression (Scala 3)
|
||||
{ ALT: () => this.subrule(this.spliceExpression) },
|
||||
// If expression
|
||||
{ ALT: () => this.subrule(this.ifExpression) },
|
||||
// While expression
|
||||
{ ALT: () => this.subrule(this.whileExpression) },
|
||||
// Try expression
|
||||
{ ALT: () => this.subrule(this.tryExpression) },
|
||||
// For expression
|
||||
{ ALT: () => this.subrule(this.forExpression) },
|
||||
// Match expression
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.expression);
|
||||
this.consumeTokenType(tokens.Match);
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => this.subrule(this.caseClause));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
// Lambda expression
|
||||
{
|
||||
ALT: () => {
|
||||
this.parser.OR([
|
||||
// Simple identifier lambda: x =>
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
},
|
||||
},
|
||||
// Multiple parameters with optional types: (x, y) =>
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
},
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
]);
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
GATE: () => {
|
||||
const la1 = this.parser.LA(1);
|
||||
const la2 = this.parser.LA(2);
|
||||
|
||||
// Simple lambda: identifier =>
|
||||
if (
|
||||
la1?.tokenType === tokens.Identifier &&
|
||||
la2?.tokenType === tokens.Arrow
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Parenthesized lambda: ( ... ) =>
|
||||
if (la1?.tokenType === tokens.LeftParen) {
|
||||
let i = 2;
|
||||
let parenCount = 1;
|
||||
while (parenCount > 0 && this.parser.LA(i)) {
|
||||
const token = this.parser.LA(i);
|
||||
if (token?.tokenType === tokens.LeftParen) parenCount++;
|
||||
if (token?.tokenType === tokens.RightParen) parenCount--;
|
||||
i++;
|
||||
}
|
||||
return this.parser.LA(i)?.tokenType === tokens.Arrow;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Infix operator
|
||||
infixOperator = this.parser.RULE("infixOperator", () => {
|
||||
this.parser.OR([
|
||||
// Special compound assignment operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.PlusEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.MinusEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.StarEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.SlashEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.PercentEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.AppendEquals) },
|
||||
// sbt-specific operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.SbtAssign) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.DoublePercent) },
|
||||
// Basic operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.Plus) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Minus) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Star) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Slash) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Percent) },
|
||||
// Comparison operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.Equals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.EqualsEquals) }, // Use EqualsEquals instead of DoubleEquals
|
||||
{ ALT: () => this.consumeTokenType(tokens.NotEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.LessThan) }, // Use LessThan instead of Less
|
||||
{ ALT: () => this.consumeTokenType(tokens.GreaterThan) }, // Use GreaterThan instead of Greater
|
||||
{ ALT: () => this.consumeTokenType(tokens.LessThanEquals) }, // Use LessThanEquals instead of LessEquals
|
||||
{ ALT: () => this.consumeTokenType(tokens.GreaterThanEquals) }, // Use GreaterThanEquals instead of GreaterEquals
|
||||
// Logical operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.LogicalAnd) }, // Use LogicalAnd instead of DoubleAmpersand
|
||||
{ ALT: () => this.consumeTokenType(tokens.LogicalOr) }, // Use LogicalOr instead of DoublePipe
|
||||
// Bitwise operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.BitwiseAnd) }, // Use BitwiseAnd instead of Ampersand
|
||||
{ ALT: () => this.consumeTokenType(tokens.BitwiseOr) }, // Use BitwiseOr instead of Pipe
|
||||
{ ALT: () => this.consumeTokenType(tokens.BitwiseXor) }, // Use BitwiseXor instead of Caret
|
||||
// Shift operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.LeftShift) }, // Use LeftShift instead of DoubleLeftAngle
|
||||
{ ALT: () => this.consumeTokenType(tokens.RightShift) }, // Use RightShift instead of DoubleRightAngle
|
||||
{ ALT: () => this.consumeTokenType(tokens.UnsignedRightShift) }, // Use UnsignedRightShift instead of TripleRightAngle
|
||||
// Type operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.Colon) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.ColonEquals) },
|
||||
// Collection operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.ConcatOp) }, // Use ConcatOp instead of DoublePlus
|
||||
{ ALT: () => this.consumeTokenType(tokens.PrependOp) }, // Use PrependOp instead of ColonColon
|
||||
{ ALT: () => this.consumeTokenType(tokens.AppendOp) }, // Use AppendOp instead of ColonPlus/PlusColon
|
||||
// XML operators
|
||||
{ ALT: () => this.consumeTokenType(tokens.Backslash) },
|
||||
// General operator
|
||||
{ ALT: () => this.consumeTokenType(tokens.OperatorIdentifier) },
|
||||
// Identifier as operator (for named methods used as infix)
|
||||
{
|
||||
ALT: () => this.consumeTokenType(tokens.Identifier),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Polymorphic function literal (Scala 3)
|
||||
polymorphicFunctionLiteral = this.parser.RULE(
|
||||
"polymorphicFunctionLiteral",
|
||||
() => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.polymorphicTypeParameter),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
);
|
||||
|
||||
// New expression
|
||||
newExpression = this.parser.RULE("newExpression", () => {
|
||||
this.consumeTokenType(tokens.New);
|
||||
this.parser.OR([
|
||||
// New with class instantiation
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.type);
|
||||
this.parser.MANY(() => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.expression),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
});
|
||||
},
|
||||
},
|
||||
// New with anonymous class
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
// Class body content
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Block expression
|
||||
blockExpression = this.parser.RULE("blockExpression", () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => {
|
||||
this.subrule(this.blockStatement);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
// Partial function literal
|
||||
partialFunctionLiteral = this.parser.RULE("partialFunctionLiteral", () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.AT_LEAST_ONE(() => this.subrule(this.caseClause));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
// Quote expression (Scala 3)
|
||||
quoteExpression = this.parser.RULE("quoteExpression", () => {
|
||||
this.consumeTokenType(tokens.Quote);
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.subrule(this.expression);
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
// Splice expression (Scala 3)
|
||||
spliceExpression = this.parser.RULE("spliceExpression", () => {
|
||||
this.consumeTokenType(tokens.Dollar);
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.subrule(this.expression);
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
// If expression
|
||||
ifExpression = this.parser.RULE("ifExpression", () => {
|
||||
this.consumeTokenType(tokens.If);
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.subrule(this.expression);
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
this.subrule(this.expression);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Else);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
});
|
||||
|
||||
// While expression
|
||||
whileExpression = this.parser.RULE("whileExpression", () => {
|
||||
this.consumeTokenType(tokens.While);
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.subrule(this.expression);
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
|
||||
// Try expression
|
||||
tryExpression = this.parser.RULE("tryExpression", () => {
|
||||
this.consumeTokenType(tokens.Try);
|
||||
this.subrule(this.expression);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Catch);
|
||||
this.parser.OR([
|
||||
// Pattern-based catch
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => this.subrule(this.caseClause));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
// Expression-based catch
|
||||
{
|
||||
ALT: () => this.subrule(this.expression),
|
||||
},
|
||||
]);
|
||||
});
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Finally);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
});
|
||||
|
||||
// For expression/comprehension
|
||||
forExpression = this.parser.RULE("forExpression", () => {
|
||||
this.consumeTokenType(tokens.For);
|
||||
this.parser.OR([
|
||||
// For with parentheses
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.AT_LEAST_ONE_SEP({
|
||||
SEP: tokens.Semicolon,
|
||||
DEF: () => this.subrule(this.generator),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
// For with braces
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => this.subrule(this.generator));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
]);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Yield));
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
|
||||
// Helper rule dependencies (to be implemented in other modules)
|
||||
polymorphicTypeParameter = this.parser.RULE(
|
||||
"polymorphicTypeParameter",
|
||||
() => {
|
||||
// Placeholder - should be in types.ts
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
},
|
||||
);
|
||||
|
||||
blockStatement = this.parser.RULE("blockStatement", () => {
|
||||
// Placeholder - should be in statements.ts
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Literal parsing module for all Scala literal types
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
|
||||
// Module for literal parsing - no additional imports needed
|
||||
|
||||
export class LiteralParserMixin extends BaseParserModule {
|
||||
// Main literal rule
|
||||
literal = this.parser.RULE("literal", () => {
|
||||
this.parser.OR([
|
||||
// Numeric literals
|
||||
{ ALT: () => this.consumeTokenType(tokens.IntegerLiteral) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.FloatingPointLiteral) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.ScientificNotationLiteral) },
|
||||
|
||||
// Boolean literals
|
||||
{ ALT: () => this.consumeTokenType(tokens.True) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.False) },
|
||||
|
||||
// Character literal
|
||||
{ ALT: () => this.consumeTokenType(tokens.CharLiteral) },
|
||||
|
||||
// String literals
|
||||
{ ALT: () => this.consumeTokenType(tokens.StringLiteral) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.InterpolatedStringLiteral) },
|
||||
|
||||
// Interpolated strings
|
||||
{ ALT: () => this.subrule(this.interpolatedString) },
|
||||
|
||||
// Null literal
|
||||
{ ALT: () => this.consumeTokenType(tokens.Null) },
|
||||
|
||||
// Unit literal ()
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Interpolated string
|
||||
interpolatedString = this.parser.RULE("interpolatedString", () => {
|
||||
this.parser.OR([
|
||||
// s-interpolator
|
||||
{ ALT: () => this.consumeTokenType(tokens.InterpolatedString) },
|
||||
// f-interpolator
|
||||
{ ALT: () => this.consumeTokenType(tokens.FormattedString) },
|
||||
// raw-interpolator
|
||||
{ ALT: () => this.consumeTokenType(tokens.RawString) },
|
||||
// Custom interpolator
|
||||
{ ALT: () => this.consumeTokenType(tokens.CustomInterpolatedString) },
|
||||
]);
|
||||
});
|
||||
|
||||
// Numeric literal with suffix
|
||||
numericLiteral = this.parser.RULE("numericLiteral", () => {
|
||||
this.parser.OR([
|
||||
// Integer types
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.IntegerLiteral);
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.consumeTokenType(tokens.LongSuffix) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.IntSuffix) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.ShortSuffix) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.ByteSuffix) },
|
||||
]);
|
||||
});
|
||||
},
|
||||
},
|
||||
// Floating point types
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.FloatingPointLiteral);
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.consumeTokenType(tokens.FloatSuffix) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.DoubleSuffix) },
|
||||
]);
|
||||
});
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// XML literal (if XML support is needed)
|
||||
xmlLiteral = this.parser.RULE("xmlLiteral", () => {
|
||||
// Placeholder for XML literals
|
||||
// This would require XML-specific lexing
|
||||
this.consumeTokenType(tokens.StringLiteral);
|
||||
});
|
||||
|
||||
// Collection literal patterns (syntactic sugar)
|
||||
collectionLiteral = this.parser.RULE("collectionLiteral", () => {
|
||||
this.parser.OR([
|
||||
// List literal: List(1, 2, 3)
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Identifier); // List, Set, etc.
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.literal),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
// Array literal: Array(1, 2, 3)
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Array);
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.literal),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Pattern matching parsing module
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
import type { ParserMethod, CstNode } from "chevrotain";
|
||||
|
||||
export class PatternParserMixin extends BaseParserModule {
|
||||
// Dependencies from other modules
|
||||
literal!: ParserMethod<unknown[], CstNode>;
|
||||
qualifiedIdentifier!: ParserMethod<unknown[], CstNode>;
|
||||
type!: ParserMethod<unknown[], CstNode>;
|
||||
expression!: ParserMethod<unknown[], CstNode>;
|
||||
|
||||
// Pattern rule
|
||||
pattern = this.parser.RULE("pattern", () => {
|
||||
this.parser.OR([
|
||||
// Wildcard pattern: _
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
// Literal pattern
|
||||
{ ALT: () => this.subrule(this.literal) },
|
||||
// Variable pattern (lowercase identifier)
|
||||
{
|
||||
ALT: () => this.consumeTokenType(tokens.Identifier),
|
||||
GATE: () => {
|
||||
const la1 = this.parser.LA(1);
|
||||
if (la1?.tokenType !== tokens.Identifier) return false;
|
||||
const firstChar = la1.image[0];
|
||||
return (
|
||||
firstChar === firstChar.toLowerCase() &&
|
||||
firstChar !== firstChar.toUpperCase()
|
||||
);
|
||||
},
|
||||
},
|
||||
// Stable identifier pattern (uppercase or qualified)
|
||||
{
|
||||
ALT: () => this.subrule(this.qualifiedIdentifier),
|
||||
},
|
||||
// Constructor pattern: Type(patterns...)
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.qualifiedIdentifier);
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.pattern),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
GATE: () => {
|
||||
// Look for Constructor(...)
|
||||
let i = 1;
|
||||
while (this.parser.LA(i)?.tokenType === tokens.Identifier) {
|
||||
if (this.parser.LA(i + 1)?.tokenType === tokens.Dot) {
|
||||
i += 2;
|
||||
} else {
|
||||
return this.parser.LA(i + 1)?.tokenType === tokens.LeftParen;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
// Tuple pattern: (p1, p2, ...)
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.pattern),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
// Typed pattern: pattern : Type
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.pattern);
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
GATE: () => {
|
||||
// Complex lookahead for typed patterns
|
||||
let i = 1;
|
||||
let parenDepth = 0;
|
||||
while (i < 20) {
|
||||
const token = this.parser.LA(i);
|
||||
if (!token) return false;
|
||||
if (token.tokenType === tokens.LeftParen) parenDepth++;
|
||||
if (token.tokenType === tokens.RightParen) parenDepth--;
|
||||
if (parenDepth === 0 && token.tokenType === tokens.Colon) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
parenDepth === 0 &&
|
||||
(token.tokenType === tokens.Arrow ||
|
||||
token.tokenType === tokens.Equals ||
|
||||
token.tokenType === tokens.If)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
// Alternative pattern: p1 | p2 | ...
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.pattern);
|
||||
this.parser.MANY(() => {
|
||||
this.consumeTokenType(tokens.BitwiseOr);
|
||||
this.subrule(this.pattern);
|
||||
});
|
||||
},
|
||||
GATE: () => {
|
||||
// Look for | in patterns
|
||||
let i = 1;
|
||||
let parenDepth = 0;
|
||||
while (i < 20) {
|
||||
const token = this.parser.LA(i);
|
||||
if (!token) return false;
|
||||
if (token.tokenType === tokens.LeftParen) parenDepth++;
|
||||
if (token.tokenType === tokens.RightParen) parenDepth--;
|
||||
if (parenDepth === 0 && token.tokenType === tokens.BitwiseOr) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
parenDepth === 0 &&
|
||||
(token.tokenType === tokens.Arrow ||
|
||||
token.tokenType === tokens.Equals)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Case clause (used in match expressions and partial functions)
|
||||
caseClause = this.parser.RULE("caseClause", () => {
|
||||
this.consumeTokenType(tokens.Case);
|
||||
this.subrule(this.pattern);
|
||||
|
||||
// Optional guard
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.If);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
|
||||
// Case body - can be expression or block
|
||||
this.parser.OR([
|
||||
// Block of statements
|
||||
{
|
||||
ALT: () => {
|
||||
this.parser.MANY(() => {
|
||||
this.subrule(this.expression);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
},
|
||||
GATE: () => {
|
||||
// If next token is 'case' or '}', this is the end
|
||||
const la1 = this.parser.LA(1);
|
||||
return (
|
||||
la1?.tokenType !== tokens.Case &&
|
||||
la1?.tokenType !== tokens.RightBrace
|
||||
);
|
||||
},
|
||||
},
|
||||
// Empty case (rare but valid)
|
||||
{ ALT: () => {} },
|
||||
]);
|
||||
});
|
||||
|
||||
// Generator (used in for comprehensions)
|
||||
generator = this.parser.RULE("generator", () => {
|
||||
this.parser.OR([
|
||||
// Pattern generator: pattern <- expression
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.pattern);
|
||||
this.consumeTokenType(tokens.LeftArrow);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
},
|
||||
// Value definition: pattern = expression
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.pattern);
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
},
|
||||
// Guard: if expression
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.If);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Extractor pattern (for advanced pattern matching)
|
||||
extractorPattern = this.parser.RULE("extractorPattern", () => {
|
||||
this.subrule(this.qualifiedIdentifier);
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => {
|
||||
this.parser.OR([
|
||||
// Regular pattern
|
||||
{ ALT: () => this.subrule(this.pattern) },
|
||||
// Sequence pattern: _*
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Underscore);
|
||||
this.consumeTokenType(tokens.Star);
|
||||
},
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
});
|
||||
|
||||
// Infix pattern (for pattern matching with infix operators)
|
||||
infixPattern = this.parser.RULE("infixPattern", () => {
|
||||
this.subrule(this.pattern);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.subrule(this.pattern);
|
||||
});
|
||||
|
||||
// XML pattern (if XML support is needed)
|
||||
xmlPattern = this.parser.RULE("xmlPattern", () => {
|
||||
// Placeholder for XML patterns
|
||||
// This would require XML-specific tokens
|
||||
this.consumeTokenType(tokens.StringLiteral);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* Scala 3 specific features parsing module
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
import type { ParserMethod, CstNode } from "chevrotain";
|
||||
|
||||
export class Scala3ParserMixin extends BaseParserModule {
|
||||
// Dependencies from other modules
|
||||
annotation!: ParserMethod<unknown[], CstNode>;
|
||||
modifier!: ParserMethod<unknown[], CstNode>;
|
||||
typeParameters!: ParserMethod<unknown[], CstNode>;
|
||||
type!: ParserMethod<unknown[], CstNode>;
|
||||
expression!: ParserMethod<unknown[], CstNode>;
|
||||
pattern!: ParserMethod<unknown[], CstNode>;
|
||||
parameterLists!: ParserMethod<unknown[], CstNode>;
|
||||
classBody!: ParserMethod<unknown[], CstNode>;
|
||||
extendsClause!: ParserMethod<unknown[], CstNode>;
|
||||
qualifiedIdentifier!: ParserMethod<unknown[], CstNode>;
|
||||
valDefinition!: ParserMethod<unknown[], CstNode>;
|
||||
defDefinition!: ParserMethod<unknown[], CstNode>;
|
||||
typeDefinition!: ParserMethod<unknown[], CstNode>;
|
||||
|
||||
// Enum definition (Scala 3)
|
||||
enumDefinition = this.parser.RULE("enumDefinition", () => {
|
||||
this.consumeTokenType(tokens.Enum);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
this.parser.OPTION(() => this.subrule(this.extendsClause));
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.subrule(this.enumCase) },
|
||||
{ ALT: () => this.subrule(this.classMember) },
|
||||
]);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
// Enum case
|
||||
enumCase = this.parser.RULE("enumCase", () => {
|
||||
this.consumeTokenType(tokens.Case);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
});
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Extends);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
});
|
||||
|
||||
// Extension definition (Scala 3)
|
||||
extensionDefinition = this.parser.RULE("extensionDefinition", () => {
|
||||
this.consumeTokenType(tokens.Extension);
|
||||
|
||||
// Optional type parameters before the extended type
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
|
||||
// Extended type with parameters
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
|
||||
// Optional using/given clauses
|
||||
this.parser.MANY(() => this.subrule(this.parameterLists));
|
||||
|
||||
// Extension body
|
||||
this.parser.OR([
|
||||
// Single method
|
||||
{ ALT: () => this.subrule(this.extensionMember) },
|
||||
// Multiple methods in braces
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => {
|
||||
this.subrule(this.extensionMember);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Extension member
|
||||
extensionMember = this.parser.RULE("extensionMember", () => {
|
||||
this.parser.MANY(() => this.subrule(this.annotation));
|
||||
this.parser.MANY(() => this.subrule(this.modifier));
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.subrule(this.defDefinition) },
|
||||
{ ALT: () => this.subrule(this.valDefinition) },
|
||||
{ ALT: () => this.subrule(this.typeDefinition) },
|
||||
]);
|
||||
});
|
||||
|
||||
// Given definition (Scala 3)
|
||||
givenDefinition = this.parser.RULE("givenDefinition", () => {
|
||||
this.consumeTokenType(tokens.Given);
|
||||
|
||||
// Optional given name
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
});
|
||||
|
||||
// Optional type parameters
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
|
||||
// Optional parameter lists (for given with parameters)
|
||||
this.parser.MANY(() => this.subrule(this.parameterLists));
|
||||
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
|
||||
// Implementation
|
||||
this.parser.OR([
|
||||
// With implementation
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.With);
|
||||
this.parser.OR([
|
||||
// Block implementation
|
||||
{ ALT: () => this.subrule(this.classBody) },
|
||||
// Expression implementation
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
},
|
||||
]);
|
||||
},
|
||||
},
|
||||
// Direct implementation with =
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.expression);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Opaque type definition (Scala 3)
|
||||
opaqueTypeDefinition = this.parser.RULE("opaqueTypeDefinition", () => {
|
||||
this.consumeTokenType(tokens.Opaque);
|
||||
this.consumeTokenType(tokens.Type);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => this.subrule(this.typeParameters));
|
||||
|
||||
// Optional type bounds
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.ColonLess);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
},
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.GreaterColon);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
this.consumeTokenType(tokens.Equals);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Inline modifier handling (Scala 3)
|
||||
inlineDefinition = this.parser.RULE("inlineDefinition", () => {
|
||||
this.consumeTokenType(tokens.Inline);
|
||||
this.parser.OR([
|
||||
{
|
||||
ALT: () => this.subrule(this.defDefinition),
|
||||
},
|
||||
{
|
||||
ALT: () => this.subrule(this.valDefinition),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Transparent modifier handling (Scala 3)
|
||||
transparentDefinition = this.parser.RULE("transparentDefinition", () => {
|
||||
this.consumeTokenType(tokens.Transparent);
|
||||
this.consumeTokenType(tokens.Inline);
|
||||
this.subrule(this.defDefinition);
|
||||
});
|
||||
|
||||
// Export clause (already implemented in statements, but Scala 3 specific)
|
||||
// Moved from statements module for better organization
|
||||
exportClause = this.parser.RULE("exportClause", () => {
|
||||
this.consumeTokenType(tokens.Export);
|
||||
this.subrule(this.exportExpression);
|
||||
this.parser.OPTION(() => this.consumeTokenType(tokens.Semicolon));
|
||||
});
|
||||
|
||||
exportExpression = this.parser.RULE("exportExpression", () => {
|
||||
this.subrule(this.qualifiedIdentifier);
|
||||
this.consumeTokenType(tokens.Dot);
|
||||
this.parser.MANY(() => {
|
||||
this.consumeTokenType(tokens.Dot);
|
||||
this.parser.OR([
|
||||
{
|
||||
ALT: () => this.consumeTokenType(tokens.Identifier),
|
||||
},
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Given) },
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.exportSelector),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
exportSelector = this.parser.RULE("exportSelector", () => {
|
||||
this.parser.OR([
|
||||
// given selector
|
||||
{ ALT: () => this.consumeTokenType(tokens.Given) },
|
||||
// Regular selector with optional rename
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
// Rename: x => y
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
},
|
||||
},
|
||||
// Hide: x => _
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.consumeTokenType(tokens.Underscore);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Using clause (Scala 3 - for context parameters)
|
||||
usingClause = this.parser.RULE("usingClause", () => {
|
||||
this.consumeTokenType(tokens.Using);
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
});
|
||||
|
||||
// Helper rule placeholder
|
||||
classMember = this.parser.RULE("classMember", () => {
|
||||
// Placeholder - should be in definitions.ts
|
||||
this.parser.OR([
|
||||
{
|
||||
ALT: () => this.subrule(this.valDefinition),
|
||||
},
|
||||
{
|
||||
ALT: () => this.subrule(this.defDefinition),
|
||||
},
|
||||
{
|
||||
ALT: () => this.subrule(this.typeDefinition),
|
||||
},
|
||||
]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Statement parsing module for package, import, and export declarations
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
import type { ParserMethod, CstNode } from "chevrotain";
|
||||
|
||||
export class StatementParserMixin extends BaseParserModule {
|
||||
// Dependencies from other modules
|
||||
qualifiedIdentifier!: ParserMethod<unknown[], CstNode>;
|
||||
expression!: ParserMethod<unknown[], CstNode>;
|
||||
|
||||
// Package declaration
|
||||
packageClause = this.parser.RULE("packageClause", () => {
|
||||
this.consumeTokenType(tokens.Package);
|
||||
this.subrule(this.qualifiedIdentifier);
|
||||
this.optionalConsume(tokens.Semicolon);
|
||||
});
|
||||
|
||||
// Import declaration
|
||||
importClause = this.parser.RULE("importClause", () => {
|
||||
this.consumeTokenType(tokens.Import);
|
||||
this.subrule(this.importExpression);
|
||||
this.optionalConsume(tokens.Semicolon);
|
||||
});
|
||||
|
||||
importExpression = this.parser.RULE("importExpression", () => {
|
||||
// Parse the base path (e.g., "scala.collection")
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.manyOf(() => {
|
||||
this.consumeTokenType(tokens.Dot);
|
||||
this.oneOf([
|
||||
// Next identifier in path
|
||||
{
|
||||
ALT: () =>
|
||||
this.parser.CONSUME(tokens.Identifier, { LABEL: "Identifier2" }),
|
||||
},
|
||||
// Wildcard import
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
// Multiple import selectors
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.AT_LEAST_ONE_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.importSelector),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
importSelector = this.parser.RULE("importSelector", () => {
|
||||
this.oneOf([
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.oneOf([
|
||||
{
|
||||
ALT: () =>
|
||||
this.parser.CONSUME(tokens.Identifier, {
|
||||
LABEL: "Identifier2",
|
||||
}),
|
||||
},
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
]);
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
ALT: () =>
|
||||
this.parser.CONSUME(tokens.Underscore, { LABEL: "Underscore2" }),
|
||||
}, // Allow wildcard import in selectors
|
||||
]);
|
||||
});
|
||||
|
||||
// Export declaration (Scala 3)
|
||||
exportClause = this.parser.RULE("exportClause", () => {
|
||||
this.consumeTokenType(tokens.Export);
|
||||
this.subrule(this.exportExpression);
|
||||
this.optionalConsume(tokens.Semicolon);
|
||||
});
|
||||
|
||||
exportExpression = this.parser.RULE("exportExpression", () => {
|
||||
// Parse the base path (e.g., "mypackage")
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.manyOf(() => {
|
||||
this.consumeTokenType(tokens.Dot);
|
||||
this.oneOf([
|
||||
// Next identifier in path
|
||||
{
|
||||
ALT: () =>
|
||||
this.parser.CONSUME(tokens.Identifier, { LABEL: "Identifier2" }),
|
||||
},
|
||||
// Given keyword for given exports
|
||||
{ ALT: () => this.consumeTokenType(tokens.Given) },
|
||||
// Wildcard export
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
// Multiple export selectors
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.AT_LEAST_ONE_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.exportSelector),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
exportSelector = this.parser.RULE("exportSelector", () => {
|
||||
this.oneOf([
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.oneOf([
|
||||
{
|
||||
ALT: () =>
|
||||
this.parser.CONSUME(tokens.Identifier, {
|
||||
LABEL: "Identifier2",
|
||||
}),
|
||||
},
|
||||
{ ALT: () => this.consumeTokenType(tokens.Underscore) },
|
||||
]);
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
ALT: () =>
|
||||
this.parser.CONSUME(tokens.Underscore, { LABEL: "Underscore2" }),
|
||||
},
|
||||
{ ALT: () => this.consumeTokenType(tokens.Given) },
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Given);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Assignment statement (for sbt files and general assignments)
|
||||
assignmentStatement = this.parser.RULE("assignmentStatement", () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.oneOf([
|
||||
{ ALT: () => this.consumeTokenType(tokens.SbtAssign) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.PlusEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.MinusEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.StarEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.SlashEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.PercentEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.AppendEquals) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Equals) },
|
||||
]);
|
||||
this.subrule(this.expression);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
/**
|
||||
* Type system parsing module for Scala types
|
||||
*/
|
||||
import { BaseParserModule, tokens } from "./base";
|
||||
import type { ParserMethod, CstNode } from "chevrotain";
|
||||
|
||||
export class TypeParserMixin extends BaseParserModule {
|
||||
// Dependencies from other modules
|
||||
qualifiedIdentifier!: ParserMethod<unknown[], CstNode>;
|
||||
expression!: ParserMethod<unknown[], CstNode>;
|
||||
literal!: ParserMethod<unknown[], CstNode>;
|
||||
|
||||
// Main type rule
|
||||
type = this.parser.RULE("type", () => {
|
||||
this.subrule(this.unionType);
|
||||
});
|
||||
|
||||
// Union types (Scala 3)
|
||||
unionType = this.parser.RULE("unionType", () => {
|
||||
this.subrule(this.intersectionType);
|
||||
this.parser.MANY(() => {
|
||||
this.consumeTokenType(tokens.BitwiseOr);
|
||||
this.subrule(this.intersectionType);
|
||||
});
|
||||
});
|
||||
|
||||
// Intersection types (Scala 3)
|
||||
intersectionType = this.parser.RULE("intersectionType", () => {
|
||||
this.subrule(this.baseType);
|
||||
this.parser.MANY(() => {
|
||||
this.consumeTokenType(tokens.BitwiseAnd);
|
||||
this.subrule(this.baseType);
|
||||
});
|
||||
});
|
||||
|
||||
// Base type
|
||||
baseType = this.parser.RULE("baseType", () => {
|
||||
this.parser.OR([
|
||||
// Simple type
|
||||
{ ALT: () => this.subrule(this.simpleType) },
|
||||
// Function type: A => B or (A, B) => C
|
||||
{
|
||||
ALT: () => {
|
||||
this.parser.OR([
|
||||
// Single parameter without parentheses
|
||||
{
|
||||
ALT: () => this.subrule(this.simpleType),
|
||||
},
|
||||
// Multiple parameters or single with parentheses
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.type),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
]);
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
GATE: () => {
|
||||
// Look ahead to detect function types
|
||||
let i = 1;
|
||||
const la1 = this.parser.LA(i);
|
||||
|
||||
// Simple function type: Type =>
|
||||
if (la1?.tokenType === tokens.Identifier) {
|
||||
const la2 = this.parser.LA(2);
|
||||
if (la2?.tokenType === tokens.Arrow) return true;
|
||||
if (la2?.tokenType === tokens.Dot) {
|
||||
// Handle qualified types like A.B =>
|
||||
i = 3;
|
||||
while (
|
||||
this.parser.LA(i)?.tokenType === tokens.Identifier &&
|
||||
this.parser.LA(i + 1)?.tokenType === tokens.Dot
|
||||
) {
|
||||
i += 2;
|
||||
}
|
||||
return this.parser.LA(i + 1)?.tokenType === tokens.Arrow;
|
||||
}
|
||||
}
|
||||
|
||||
// Parenthesized function type: (...) =>
|
||||
if (la1?.tokenType === tokens.LeftParen) {
|
||||
let parenCount = 1;
|
||||
i = 2;
|
||||
while (parenCount > 0 && i < 50) {
|
||||
const token = this.parser.LA(i);
|
||||
if (token?.tokenType === tokens.LeftParen) parenCount++;
|
||||
if (token?.tokenType === tokens.RightParen) parenCount--;
|
||||
i++;
|
||||
}
|
||||
return this.parser.LA(i)?.tokenType === tokens.Arrow;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
},
|
||||
// Context function type (Scala 3): A ?=> B
|
||||
{
|
||||
ALT: () => this.subrule(this.contextFunctionType),
|
||||
GATE: () => {
|
||||
// Look for ?=> pattern
|
||||
let i = 1;
|
||||
while (i < 20) {
|
||||
const token = this.parser.LA(i);
|
||||
if (token?.tokenType === tokens.QuestionArrow) return true;
|
||||
if (!token) return false;
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
// Dependent function type (Scala 3)
|
||||
{
|
||||
ALT: () => this.subrule(this.dependentFunctionType),
|
||||
GATE: () => {
|
||||
const la1 = this.parser.LA(1);
|
||||
const la2 = this.parser.LA(2);
|
||||
const la3 = this.parser.LA(3);
|
||||
return (
|
||||
la1?.tokenType === tokens.LeftParen &&
|
||||
la2?.tokenType === tokens.Identifier &&
|
||||
la3?.tokenType === tokens.Colon
|
||||
);
|
||||
},
|
||||
},
|
||||
// Polymorphic function type (Scala 3): [T] => T => T
|
||||
{
|
||||
ALT: () => this.subrule(this.polymorphicFunctionType),
|
||||
GATE: () => {
|
||||
const la1 = this.parser.LA(1);
|
||||
if (la1?.tokenType !== tokens.LeftBracket) return false;
|
||||
|
||||
// Look for ] =>> pattern
|
||||
let i = 2;
|
||||
let bracketCount = 1;
|
||||
while (bracketCount > 0 && i < 30) {
|
||||
const token = this.parser.LA(i);
|
||||
if (token?.tokenType === tokens.LeftBracket) bracketCount++;
|
||||
if (token?.tokenType === tokens.RightBracket) bracketCount--;
|
||||
i++;
|
||||
}
|
||||
return this.parser.LA(i)?.tokenType === tokens.DoubleArrow;
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Simple type
|
||||
simpleType = this.parser.RULE("simpleType", () => {
|
||||
this.parser.OR([
|
||||
// Literal type
|
||||
{
|
||||
ALT: () => this.subrule(this.literal),
|
||||
GATE: () => {
|
||||
const la1 = this.parser.LA(1);
|
||||
return (
|
||||
la1?.tokenType === tokens.IntegerLiteral ||
|
||||
la1?.tokenType === tokens.FloatingPointLiteral ||
|
||||
la1?.tokenType === tokens.True ||
|
||||
la1?.tokenType === tokens.CharLiteral ||
|
||||
la1?.tokenType === tokens.StringLiteral ||
|
||||
la1?.tokenType === tokens.Null
|
||||
);
|
||||
},
|
||||
},
|
||||
// Tuple type or parenthesized type
|
||||
{ ALT: () => this.subrule(this.tupleTypeOrParenthesized) },
|
||||
// Type projection: T#U
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.simpleType);
|
||||
this.consumeTokenType(tokens.Hash);
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
},
|
||||
GATE: () => {
|
||||
// Complex lookahead for type projection
|
||||
let i = 1;
|
||||
while (i < 20) {
|
||||
const token = this.parser.LA(i);
|
||||
if (token?.tokenType === tokens.Hash) return true;
|
||||
if (
|
||||
!token ||
|
||||
token.tokenType === tokens.Arrow ||
|
||||
token.tokenType === tokens.Comma
|
||||
)
|
||||
return false;
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
// Singleton type: x.type
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.qualifiedIdentifier);
|
||||
this.consumeTokenType(tokens.Dot);
|
||||
this.consumeTokenType(tokens.Type);
|
||||
},
|
||||
GATE: () => {
|
||||
let i = 1;
|
||||
while (
|
||||
this.parser.LA(i)?.tokenType === tokens.Identifier &&
|
||||
this.parser.LA(i + 1)?.tokenType === tokens.Dot
|
||||
) {
|
||||
i += 2;
|
||||
}
|
||||
return (
|
||||
this.parser.LA(i)?.tokenType === tokens.Identifier &&
|
||||
this.parser.LA(i + 1)?.tokenType === tokens.Dot &&
|
||||
this.parser.LA(i + 2)?.tokenType === tokens.Type
|
||||
);
|
||||
},
|
||||
},
|
||||
// Wildcard type: _
|
||||
{
|
||||
ALT: () => this.consumeTokenType(tokens.Underscore),
|
||||
},
|
||||
// Kind projector: * or ?
|
||||
{
|
||||
ALT: () => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.consumeTokenType(tokens.Star) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Question) },
|
||||
]);
|
||||
},
|
||||
},
|
||||
// Array type constructor
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.Array);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.typeArgument),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
});
|
||||
},
|
||||
},
|
||||
// Regular type with optional type arguments
|
||||
{
|
||||
ALT: () => {
|
||||
this.subrule(this.qualifiedIdentifier);
|
||||
this.parser.OPTION(() => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.typeArgument),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
});
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// Type argument
|
||||
typeArgument = this.parser.RULE("typeArgument", () => {
|
||||
// Optional variance annotation
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.consumeTokenType(tokens.Plus) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Minus) },
|
||||
]);
|
||||
});
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Tuple type or parenthesized type
|
||||
tupleTypeOrParenthesized = this.parser.RULE(
|
||||
"tupleTypeOrParenthesized",
|
||||
() => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.OPTION(() => {
|
||||
this.subrule(this.type);
|
||||
this.parser.MANY(() => {
|
||||
this.consumeTokenType(tokens.Comma);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
);
|
||||
|
||||
// Context function type (Scala 3)
|
||||
contextFunctionType = this.parser.RULE("contextFunctionType", () => {
|
||||
this.parser.OR([
|
||||
// Single parameter
|
||||
{ ALT: () => this.subrule(this.simpleType) },
|
||||
// Multiple parameters
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.type),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
},
|
||||
},
|
||||
]);
|
||||
this.consumeTokenType(tokens.QuestionArrow);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Dependent function type (Scala 3)
|
||||
dependentFunctionType = this.parser.RULE("dependentFunctionType", () => {
|
||||
this.consumeTokenType(tokens.LeftParen);
|
||||
this.parser.AT_LEAST_ONE_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.dependentParameter),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightParen);
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Dependent parameter
|
||||
dependentParameter = this.parser.RULE("dependentParameter", () => {
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
this.consumeTokenType(tokens.Colon);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Polymorphic function type (Scala 3)
|
||||
polymorphicFunctionType = this.parser.RULE("polymorphicFunctionType", () => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.typeLambdaParameter),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
this.consumeTokenType(tokens.DoubleArrow);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Type lambda (Scala 3)
|
||||
typeLambda = this.parser.RULE("typeLambda", () => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.typeLambdaParameter),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
this.consumeTokenType(tokens.DoubleArrow);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
|
||||
// Type lambda parameter
|
||||
typeLambdaParameter = this.parser.RULE("typeLambdaParameter", () => {
|
||||
// Optional variance
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.consumeTokenType(tokens.Plus) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Minus) },
|
||||
]);
|
||||
});
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
// Optional type bounds
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.ColonLess);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
},
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.GreaterColon);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// Type parameters
|
||||
typeParameters = this.parser.RULE("typeParameters", () => {
|
||||
this.consumeTokenType(tokens.LeftBracket);
|
||||
this.parser.MANY_SEP({
|
||||
SEP: tokens.Comma,
|
||||
DEF: () => this.subrule(this.typeParameter),
|
||||
});
|
||||
this.consumeTokenType(tokens.RightBracket);
|
||||
});
|
||||
|
||||
// Type parameter
|
||||
typeParameter = this.parser.RULE("typeParameter", () => {
|
||||
// Optional variance annotation
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{ ALT: () => this.consumeTokenType(tokens.Plus) },
|
||||
{ ALT: () => this.consumeTokenType(tokens.Minus) },
|
||||
]);
|
||||
});
|
||||
this.consumeTokenType(tokens.Identifier);
|
||||
// Optional type bounds
|
||||
this.parser.OPTION(() => {
|
||||
this.parser.OR([
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.ColonLess);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
},
|
||||
{
|
||||
ALT: () => {
|
||||
this.consumeTokenType(tokens.GreaterColon);
|
||||
this.subrule(this.type);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// Match type (Scala 3)
|
||||
matchType = this.parser.RULE("matchType", () => {
|
||||
this.subrule(this.type);
|
||||
this.consumeTokenType(tokens.Match);
|
||||
this.consumeTokenType(tokens.LeftBrace);
|
||||
this.parser.MANY(() => this.subrule(this.matchTypeCase));
|
||||
this.consumeTokenType(tokens.RightBrace);
|
||||
});
|
||||
|
||||
// Match type case
|
||||
matchTypeCase = this.parser.RULE("matchTypeCase", () => {
|
||||
this.consumeTokenType(tokens.Case);
|
||||
this.subrule(this.type);
|
||||
this.consumeTokenType(tokens.Arrow);
|
||||
this.subrule(this.type);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type {
|
||||
CstNode,
|
||||
IToken,
|
||||
ILexingError,
|
||||
IRecognitionException,
|
||||
CstElement,
|
||||
} from "chevrotain";
|
||||
|
||||
export interface SourceLocation {
|
||||
startOffset: number;
|
||||
endOffset: number;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
startColumn: number;
|
||||
endColumn: number;
|
||||
}
|
||||
|
||||
export interface ScalaCstNode extends CstNode {
|
||||
name: string;
|
||||
children: Record<string, CstElement[]>;
|
||||
location?: SourceLocation;
|
||||
// Additional properties for compatibility
|
||||
image?: string;
|
||||
type?: string;
|
||||
originalComments?: string[];
|
||||
startLine?: number;
|
||||
value?: string;
|
||||
startOffset?: number;
|
||||
endOffset?: number;
|
||||
}
|
||||
|
||||
export interface ParseResult {
|
||||
cst: ScalaCstNode;
|
||||
errors: IRecognitionException[];
|
||||
comments: IToken[];
|
||||
}
|
||||
|
||||
export interface LexResult {
|
||||
tokens: IToken[];
|
||||
errors: ILexingError[];
|
||||
groups: {
|
||||
comments?: IToken[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface TokenBounds {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export interface LineColumn {
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
// Chevrotain パーサーメソッドの戻り値型
|
||||
export interface ParserMethodResult extends CstNode {
|
||||
name: string;
|
||||
children: Record<string, (CstNode | IToken)[]>;
|
||||
}
|
||||
|
||||
// パーサールールの型定義
|
||||
export type ParserRule<T = ParserMethodResult> = () => T;
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Unicode utilities for Scala parser
|
||||
* Handles Unicode normalization and character validation
|
||||
*/
|
||||
|
||||
/**
|
||||
* Normalizes Unicode strings using NFC (Canonical Decomposition, followed by Canonical Composition)
|
||||
* This ensures consistent representation of Unicode characters.
|
||||
*
|
||||
* @param text - The input text to normalize
|
||||
* @returns The normalized text
|
||||
*/
|
||||
export function normalizeUnicode(text: string): string {
|
||||
return text.normalize("NFC");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a character is a valid Scala identifier start character
|
||||
* Follows Unicode identifier specification for Scala
|
||||
*
|
||||
* @param char - The character to check
|
||||
* @returns True if the character can start an identifier
|
||||
*/
|
||||
export function isIdentifierStart(char: string): boolean {
|
||||
if (char.length !== 1) return false;
|
||||
|
||||
const codePoint = char.codePointAt(0);
|
||||
if (codePoint === undefined) return false;
|
||||
|
||||
// Basic ASCII identifier characters
|
||||
if (
|
||||
(codePoint >= 0x41 && codePoint <= 0x5a) || // A-Z
|
||||
(codePoint >= 0x61 && codePoint <= 0x7a) || // a-z
|
||||
codePoint === 0x5f || // _
|
||||
codePoint === 0x24
|
||||
) {
|
||||
// $
|
||||
return true;
|
||||
}
|
||||
|
||||
// Mathematical symbols range (extended)
|
||||
if (
|
||||
(codePoint >= 0x2200 && codePoint <= 0x22ff) || // Mathematical Operators
|
||||
(codePoint >= 0x27c0 && codePoint <= 0x27ef) || // Miscellaneous Mathematical Symbols-A
|
||||
(codePoint >= 0x2980 && codePoint <= 0x29ff) || // Miscellaneous Mathematical Symbols-B
|
||||
(codePoint >= 0x2a00 && codePoint <= 0x2aff)
|
||||
) {
|
||||
// Supplemental Mathematical Operators
|
||||
return true;
|
||||
}
|
||||
|
||||
// Use Unicode property test for other characters (excluding digits for start characters)
|
||||
const testRegex = /\p{L}|\p{Mn}|\p{Mc}|\p{Pc}/u;
|
||||
return testRegex.test(char);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a character is a valid Scala identifier continuation character
|
||||
*
|
||||
* @param char - The character to check
|
||||
* @returns True if the character can continue an identifier
|
||||
*/
|
||||
export function isIdentifierContinue(char: string): boolean {
|
||||
if (char.length !== 1) return false;
|
||||
|
||||
const codePoint = char.codePointAt(0);
|
||||
if (codePoint === undefined) return false;
|
||||
|
||||
// Basic ASCII identifier characters
|
||||
if (
|
||||
(codePoint >= 0x41 && codePoint <= 0x5a) || // A-Z
|
||||
(codePoint >= 0x61 && codePoint <= 0x7a) || // a-z
|
||||
(codePoint >= 0x30 && codePoint <= 0x39) || // 0-9
|
||||
codePoint === 0x5f || // _
|
||||
codePoint === 0x24
|
||||
) {
|
||||
// $
|
||||
return true;
|
||||
}
|
||||
|
||||
// Mathematical symbols range (extended)
|
||||
if (
|
||||
(codePoint >= 0x2200 && codePoint <= 0x22ff) || // Mathematical Operators
|
||||
(codePoint >= 0x27c0 && codePoint <= 0x27ef) || // Miscellaneous Mathematical Symbols-A
|
||||
(codePoint >= 0x2980 && codePoint <= 0x29ff) || // Miscellaneous Mathematical Symbols-B
|
||||
(codePoint >= 0x2a00 && codePoint <= 0x2aff)
|
||||
) {
|
||||
// Supplemental Mathematical Operators
|
||||
return true;
|
||||
}
|
||||
|
||||
// Use Unicode property test for other characters (including format characters)
|
||||
const testRegex = /\p{L}|\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}|\p{Cf}/u;
|
||||
return testRegex.test(char);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a string is a valid Scala identifier
|
||||
*
|
||||
* @param identifier - The identifier string to validate
|
||||
* @returns True if the string is a valid identifier
|
||||
*/
|
||||
export function isValidIdentifier(identifier: string): boolean {
|
||||
if (!identifier || identifier.length === 0) return false;
|
||||
|
||||
// Normalize the identifier
|
||||
const normalized = normalizeUnicode(identifier);
|
||||
|
||||
// Check first character
|
||||
if (!isIdentifierStart(normalized[0])) return false;
|
||||
|
||||
// Check remaining characters
|
||||
for (let i = 1; i < normalized.length; i++) {
|
||||
if (!isIdentifierContinue(normalized[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Unicode escape sequences in strings to actual Unicode characters
|
||||
* Handles \uXXXX patterns in string literals
|
||||
*
|
||||
* @param text - The text containing Unicode escapes
|
||||
* @returns The text with Unicode escapes converted to actual characters
|
||||
*/
|
||||
export function processUnicodeEscapes(text: string): string {
|
||||
return text.replace(/\\u([0-9A-Fa-f]{4})/g, (_, hex) => {
|
||||
const codePoint = parseInt(hex, 16);
|
||||
return String.fromCharCode(codePoint);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes Unicode characters in strings for safe output
|
||||
* Converts non-ASCII characters back to \uXXXX format if needed
|
||||
*
|
||||
* @param text - The text to escape
|
||||
* @param escapeNonAscii - Whether to escape all non-ASCII characters
|
||||
* @returns The escaped text
|
||||
*/
|
||||
export function escapeUnicode(text: string, escapeNonAscii = false): string {
|
||||
if (!escapeNonAscii) return text;
|
||||
|
||||
return text.replace(/[\u0080-\uFFFF]/g, (char) => {
|
||||
const codePoint = char.charCodeAt(0);
|
||||
return `\\u${codePoint.toString(16).padStart(4, "0").toUpperCase()}`;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended mathematical symbols commonly used in Scala functional programming
|
||||
*/
|
||||
export const MATHEMATICAL_SYMBOLS = {
|
||||
// Greek letters commonly used in functional programming
|
||||
ALPHA: "α", // U+03B1
|
||||
BETA: "β", // U+03B2
|
||||
GAMMA: "γ", // U+03B3
|
||||
DELTA: "δ", // U+03B4
|
||||
LAMBDA: "λ", // U+03BB
|
||||
MU: "μ", // U+03BC
|
||||
PI: "π", // U+03C0
|
||||
SIGMA: "σ", // U+03C3
|
||||
TAU: "τ", // U+03C4
|
||||
PHI: "φ", // U+03C6
|
||||
|
||||
// Mathematical operators
|
||||
FORALL: "∀", // U+2200
|
||||
EXISTS: "∃", // U+2203
|
||||
ELEMENT_OF: "∈", // U+2208
|
||||
NOT_ELEMENT_OF: "∉", // U+2209
|
||||
SUBSET: "⊂", // U+2282
|
||||
SUPERSET: "⊃", // U+2283
|
||||
UNION: "∪", // U+222A
|
||||
INTERSECTION: "∩", // U+2229
|
||||
|
||||
// Arrows and other symbols
|
||||
RIGHTWARDS_ARROW: "→", // U+2192
|
||||
LEFTWARDS_ARROW: "←", // U+2190
|
||||
UP_ARROW: "↑", // U+2191
|
||||
DOWN_ARROW: "↓", // U+2193
|
||||
} as const;
|
||||
538
frontend/src/common/prettier/plugins/scala/visitor.ts
Normal file
538
frontend/src/common/prettier/plugins/scala/visitor.ts
Normal file
@@ -0,0 +1,538 @@
|
||||
/**
|
||||
* CSTノードビジターのメインモジュール
|
||||
* 各種ビジターモジュールを統合して使用
|
||||
*/
|
||||
import {
|
||||
DeclarationVisitorMethods,
|
||||
type DeclarationVisitor,
|
||||
} from "./visitor/declarations";
|
||||
import {
|
||||
ExpressionVisitorMethods,
|
||||
type ExpressionVisitor,
|
||||
} from "./visitor/expressions";
|
||||
import { Scala3VisitorMethods, type Scala3Visitor } from "./visitor/scala3";
|
||||
import {
|
||||
StatementVisitorMethods,
|
||||
type StatementVisitor,
|
||||
} from "./visitor/statements";
|
||||
import { TypeVisitorMethods, type TypeVisitor } from "./visitor/types";
|
||||
import {
|
||||
getPrintWidth,
|
||||
getTabWidth,
|
||||
formatStatement,
|
||||
formatStringLiteral,
|
||||
createIndent,
|
||||
attachOriginalComments,
|
||||
} from "./visitor/utils";
|
||||
import type { PrintContext, CSTNode } from "./visitor/utils";
|
||||
import type { ScalaCstNode } from "@/common/prettier/plugins/scala/scala-parser";
|
||||
|
||||
// 外部使用のためのユーティリティ型の再エクスポート
|
||||
export type { PrintContext, CSTNode, PrettierOptions } from "./visitor/utils";
|
||||
|
||||
// 後方互換性のための型エイリアス
|
||||
type VisitorContext = PrintContext;
|
||||
|
||||
/**
|
||||
* CSTノードを訪問してフォーマット済みのテキストに変換するビジター
|
||||
* 各種言語構造に対応するビジターモジュールを統合
|
||||
*/
|
||||
export class CstNodeVisitor
|
||||
implements
|
||||
DeclarationVisitor,
|
||||
ExpressionVisitor,
|
||||
StatementVisitor,
|
||||
TypeVisitor,
|
||||
Scala3Visitor
|
||||
{
|
||||
// ビジターモジュールの初期化
|
||||
private declarations = new DeclarationVisitorMethods(this);
|
||||
private expressions = new ExpressionVisitorMethods(this);
|
||||
private statements = new StatementVisitorMethods(this);
|
||||
private types = new TypeVisitorMethods(this);
|
||||
private scala3 = new Scala3VisitorMethods(this);
|
||||
|
||||
/**
|
||||
* CSTノードを訪問してフォーマット済みテキストに変換
|
||||
* @param node - 訪問対象のCSTノード
|
||||
* @param ctx - 印刷コンテキスト(オプション、パスなど)
|
||||
* @returns フォーマット済みの文字列
|
||||
*/
|
||||
visit(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
if (!node) return "";
|
||||
|
||||
try {
|
||||
// オリジナルコメントを含むルートノードの処理
|
||||
if (
|
||||
"type" in node &&
|
||||
node.type === "compilationUnit" &&
|
||||
"originalComments" in node &&
|
||||
node.originalComments
|
||||
) {
|
||||
const nodeResult = this.visitCore(node, ctx);
|
||||
// originalCommentsの安全な型変換
|
||||
const comments = Array.isArray(node.originalComments)
|
||||
? (node.originalComments as unknown as CSTNode[])
|
||||
: [];
|
||||
return attachOriginalComments(nodeResult, comments);
|
||||
}
|
||||
|
||||
return this.visitCore(node, ctx);
|
||||
} catch (error) {
|
||||
const nodeName = "name" in node ? node.name : "unknown";
|
||||
console.error(`Error visiting node ${nodeName}:`, error);
|
||||
|
||||
// フォーマットエラー時の安全なフォールバック
|
||||
if ("image" in node && node.image) {
|
||||
return String(node.image);
|
||||
}
|
||||
|
||||
return `/* FORMAT ERROR: ${nodeName} */`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CSTノード訪問のコアロジック
|
||||
* @param node - 訪問対象のCSTノード
|
||||
* @param ctx - 印刷コンテキスト
|
||||
* @returns フォーマット済みの文字列
|
||||
*/
|
||||
private visitCore(node: CSTNode, ctx: PrintContext): string {
|
||||
try {
|
||||
// トークンノードの処理
|
||||
if ("image" in node && node.image !== undefined) {
|
||||
return node.image;
|
||||
}
|
||||
|
||||
// ルール名によるCSTノードの処理
|
||||
if ("name" in node && node.name) {
|
||||
// ルール名の最初の文字を大文字化
|
||||
const ruleName = node.name.charAt(0).toUpperCase() + node.name.slice(1);
|
||||
const methodName = `visit${ruleName}`;
|
||||
if (
|
||||
typeof (this as Record<string, unknown>)[methodName] === "function"
|
||||
) {
|
||||
return (
|
||||
(this as Record<string, unknown>)[methodName] as (
|
||||
node: ScalaCstNode,
|
||||
ctx: VisitorContext,
|
||||
) => string
|
||||
)(node, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
// If no specific visitor method exists, try default handling by type
|
||||
if ("children" in node && node.children) {
|
||||
return this.visitChildren(node, ctx);
|
||||
}
|
||||
|
||||
return "";
|
||||
} catch (error) {
|
||||
const nodeName = "name" in node ? node.name : "unknown";
|
||||
console.error(`Error in visitCore for ${nodeName}:`, error);
|
||||
|
||||
// Try to recover by visiting children directly
|
||||
if ("children" in node && node.children) {
|
||||
try {
|
||||
return this.visitChildren(node, ctx);
|
||||
} catch (childError) {
|
||||
console.error(`Error visiting children of ${nodeName}:`, childError);
|
||||
return `/* ERROR: ${nodeName} */`;
|
||||
}
|
||||
}
|
||||
|
||||
return "image" in node && node.image ? node.image : "";
|
||||
}
|
||||
}
|
||||
|
||||
visitChildren(node: CSTNode, ctx: PrintContext): string {
|
||||
const parts: string[] = [];
|
||||
|
||||
if (!("children" in node) || !node.children) return "";
|
||||
|
||||
try {
|
||||
for (const [key, children] of Object.entries(node.children)) {
|
||||
if (Array.isArray(children)) {
|
||||
for (const child of children) {
|
||||
try {
|
||||
// Type guard for ScalaCstNode
|
||||
if ("children" in child && "name" in child) {
|
||||
const part = this.visit(child as ScalaCstNode, ctx);
|
||||
if (part) {
|
||||
parts.push(part);
|
||||
}
|
||||
} else {
|
||||
// Handle IToken
|
||||
const tokenImage = "image" in child ? child.image : "";
|
||||
if (tokenImage) {
|
||||
parts.push(tokenImage);
|
||||
}
|
||||
}
|
||||
} catch (childError) {
|
||||
const childName = "name" in child ? child.name : "token";
|
||||
console.error(
|
||||
`Error visiting child ${childName || "unknown"} in ${key}:`,
|
||||
childError,
|
||||
);
|
||||
// Continue with next child instead of failing completely
|
||||
parts.push(`/* ERROR: ${childName || "unknown"} */`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error visiting children of ${node.name || "unknown"}:`,
|
||||
error,
|
||||
);
|
||||
return `/* ERROR: ${node.name || "unknown"} children */`;
|
||||
}
|
||||
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
// Utility methods for shared functionality
|
||||
getIndentation(ctx: PrintContext): string {
|
||||
return createIndent(1, ctx);
|
||||
}
|
||||
|
||||
getPrintWidth(ctx: PrintContext): number {
|
||||
return getPrintWidth(ctx);
|
||||
}
|
||||
|
||||
getTabWidth(ctx: PrintContext): number {
|
||||
return getTabWidth(ctx);
|
||||
}
|
||||
|
||||
formatStatement(statement: string, ctx: PrintContext): string {
|
||||
return formatStatement(statement, ctx);
|
||||
}
|
||||
|
||||
formatStringLiteral(content: string, ctx: PrintContext): string {
|
||||
return formatStringLiteral(content, ctx);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Delegation methods to modular visitors
|
||||
// ==========================================
|
||||
|
||||
// Compilation unit and top-level structure
|
||||
visitCompilationUnit(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitCompilationUnit(node, ctx);
|
||||
}
|
||||
|
||||
// Package and imports/exports
|
||||
visitPackageClause(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.statements.visitPackageClause(node, ctx);
|
||||
}
|
||||
|
||||
visitImportClause(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.statements.visitImportClause(node, ctx);
|
||||
}
|
||||
|
||||
visitImportExpression(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.statements.visitImportExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitImportSelector(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.statements.visitImportSelector(node, ctx);
|
||||
}
|
||||
|
||||
visitExportClause(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitExportClause(node, ctx);
|
||||
}
|
||||
|
||||
visitExportExpression(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitExportExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitExportSelector(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitExportSelector(node, ctx);
|
||||
}
|
||||
|
||||
// Definitions and declarations
|
||||
visitTopLevelDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitTopLevelDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitAnnotations(annotations: CSTNode[], ctx: PrintContext): string {
|
||||
return this.statements.visitAnnotations(annotations, ctx);
|
||||
}
|
||||
|
||||
visitAnnotation(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitAnnotation(node, ctx);
|
||||
}
|
||||
|
||||
visitAnnotationArgument(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitAnnotationArgument(node, ctx);
|
||||
}
|
||||
|
||||
visitModifiers(modifiers: CSTNode[], ctx: PrintContext): string {
|
||||
return this.statements.visitModifiers(modifiers, ctx);
|
||||
}
|
||||
|
||||
// Class-related declarations
|
||||
visitClassDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitClassDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitObjectDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitObjectDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitTraitDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitTraitDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitValDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitValDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitVarDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitVarDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitDefDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitDefDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitTypeDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitAuxiliaryConstructor(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitAuxiliaryConstructor(node, ctx);
|
||||
}
|
||||
|
||||
visitClassParameters(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitClassParameters(node, ctx);
|
||||
}
|
||||
|
||||
visitClassParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitClassParameter(node, ctx);
|
||||
}
|
||||
|
||||
visitParameterLists(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitParameterLists(node, ctx);
|
||||
}
|
||||
|
||||
visitParameterList(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitParameterList(node, ctx);
|
||||
}
|
||||
|
||||
visitParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitParameter(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeParameters(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitTypeParameters(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitTypeParameter(node, ctx);
|
||||
}
|
||||
|
||||
visitExtendsClause(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitExtendsClause(node, ctx);
|
||||
}
|
||||
|
||||
visitClassBody(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitClassBody(node, ctx);
|
||||
}
|
||||
|
||||
visitClassMember(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.declarations.visitClassMember(node, ctx);
|
||||
}
|
||||
|
||||
// Type system
|
||||
visitType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitType(node, ctx);
|
||||
}
|
||||
|
||||
visitMatchType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitMatchType(node, ctx);
|
||||
}
|
||||
|
||||
visitMatchTypeCase(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitMatchTypeCase(node, ctx);
|
||||
}
|
||||
|
||||
visitUnionType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitUnionType(node, ctx);
|
||||
}
|
||||
|
||||
visitIntersectionType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitIntersectionType(node, ctx);
|
||||
}
|
||||
|
||||
visitBaseType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitBaseType(node, ctx);
|
||||
}
|
||||
|
||||
visitTupleTypeOrParenthesized(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTupleTypeOrParenthesized(node, ctx);
|
||||
}
|
||||
|
||||
visitSimpleType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitSimpleType(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeArgument(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTypeArgument(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeArgumentUnion(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTypeArgumentUnion(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeArgumentIntersection(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTypeArgumentIntersection(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeArgumentSimple(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTypeArgumentSimple(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeLambda(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTypeLambda(node, ctx);
|
||||
}
|
||||
|
||||
visitTypeLambdaParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitTypeLambdaParameter(node, ctx);
|
||||
}
|
||||
|
||||
visitDependentFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitDependentFunctionType(node, ctx);
|
||||
}
|
||||
|
||||
visitDependentParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitDependentParameter(node, ctx);
|
||||
}
|
||||
|
||||
// Expressions
|
||||
visitExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitPostfixExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitPostfixExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitPrimaryExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitPrimaryExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitAssignmentStatement(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitAssignmentStatement(node, ctx);
|
||||
}
|
||||
|
||||
visitAssignmentOrInfixExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitAssignmentOrInfixExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitInfixOperator(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitInfixOperator(node, ctx);
|
||||
}
|
||||
|
||||
visitLiteral(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitLiteral(node, ctx);
|
||||
}
|
||||
|
||||
visitQualifiedIdentifier(node: ScalaCstNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitQualifiedIdentifier(node, ctx);
|
||||
}
|
||||
|
||||
visitNewExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitNewExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitIfExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitIfExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitWhileExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitWhileExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitTryExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitTryExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitForExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitForExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitGenerator(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitGenerator(node, ctx);
|
||||
}
|
||||
|
||||
visitCaseClause(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitCaseClause(node, ctx);
|
||||
}
|
||||
|
||||
visitBlockExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitBlockExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitPartialFunctionLiteral(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.expressions.visitPartialFunctionLiteral(node, ctx);
|
||||
}
|
||||
|
||||
// Statements
|
||||
visitBlockStatement(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitBlockStatement(node, ctx);
|
||||
}
|
||||
|
||||
visitPattern(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.statements.visitPattern(node, ctx);
|
||||
}
|
||||
|
||||
// Scala 3 specific features
|
||||
visitEnumDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitEnumDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitEnumCase(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitEnumCase(node, ctx);
|
||||
}
|
||||
|
||||
visitExtensionDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitExtensionDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitExtensionMember(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitExtensionMember(node, ctx);
|
||||
}
|
||||
|
||||
visitGivenDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitGivenDefinition(node, ctx);
|
||||
}
|
||||
|
||||
visitQuoteExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitQuoteExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitSpliceExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitSpliceExpression(node, ctx);
|
||||
}
|
||||
|
||||
visitPolymorphicFunctionLiteral(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitPolymorphicFunctionLiteral(node, ctx);
|
||||
}
|
||||
|
||||
visitPolymorphicFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitPolymorphicFunctionType(node, ctx);
|
||||
}
|
||||
|
||||
visitPolymorphicTypeParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.types.visitPolymorphicTypeParameter(node, ctx);
|
||||
}
|
||||
|
||||
visitContextFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
return this.scala3.visitContextFunctionType(node, ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,640 @@
|
||||
/**
|
||||
* Declaration visitor methods for class, object, trait, method, and other definitions
|
||||
*/
|
||||
import {
|
||||
formatStatement,
|
||||
getPrintWidth,
|
||||
getChildNodes,
|
||||
getFirstChild,
|
||||
createIndent,
|
||||
getNodeImage,
|
||||
} from "./utils";
|
||||
import type { PrintContext, CSTNode } from "./utils";
|
||||
|
||||
export interface DeclarationVisitor {
|
||||
visit(node: CSTNode, ctx: PrintContext): string;
|
||||
visitModifiers(modifiers: CSTNode[], ctx: PrintContext): string;
|
||||
getIndentation(ctx: PrintContext): string;
|
||||
}
|
||||
|
||||
export class DeclarationVisitorMethods {
|
||||
private visitor: DeclarationVisitor;
|
||||
|
||||
constructor(visitor: DeclarationVisitor) {
|
||||
this.visitor = visitor;
|
||||
}
|
||||
|
||||
visitClassDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Add class keyword (don't duplicate if already handled by modifiers)
|
||||
const classToken = getFirstChild(node, "Class");
|
||||
if (classToken) {
|
||||
result += getNodeImage(classToken) + " ";
|
||||
}
|
||||
|
||||
// Add class name
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
if (identifierToken) {
|
||||
result += getNodeImage(identifierToken);
|
||||
}
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
// Add constructor annotations
|
||||
const annotations = getChildNodes(node, "annotation");
|
||||
if (annotations.length > 0) {
|
||||
result +=
|
||||
" " +
|
||||
annotations
|
||||
.map((ann: CSTNode) => this.visitor.visit(ann, ctx))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
const classParameters = getFirstChild(node, "classParameters");
|
||||
if (classParameters) {
|
||||
result += this.visitor.visit(classParameters, ctx);
|
||||
}
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
const classBody = getFirstChild(node, "classBody");
|
||||
if (classBody) {
|
||||
result += " " + this.visitor.visit(classBody, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitObjectDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
let result =
|
||||
"object " + (identifierToken ? getNodeImage(identifierToken) : "");
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
const classBody = getFirstChild(node, "classBody");
|
||||
if (classBody) {
|
||||
result += " " + this.visitor.visit(classBody, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTraitDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifier = getFirstChild(node, "Identifier");
|
||||
let result = "trait " + (identifier ? getNodeImage(identifier) : "");
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
const traitBody = getFirstChild(node, "classBody");
|
||||
if (traitBody) {
|
||||
result += " " + this.visitor.visit(traitBody, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitEnumDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
let result =
|
||||
"enum " + (identifierToken ? getNodeImage(identifierToken) : "");
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const classParameters = getFirstChild(node, "classParameters");
|
||||
if (classParameters) {
|
||||
result += this.visitor.visit(classParameters, ctx);
|
||||
}
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
result += " {\n";
|
||||
|
||||
const enumCases = getChildNodes(node, "enumCase");
|
||||
if (enumCases.length > 0) {
|
||||
const indent = this.visitor.getIndentation(ctx);
|
||||
const cases = enumCases.map(
|
||||
(c: CSTNode) => indent + this.visitor.visit(c, ctx),
|
||||
);
|
||||
result += cases.join("\n");
|
||||
}
|
||||
|
||||
result += "\n}";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitEnumCase(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
let result =
|
||||
"case " + (identifierToken ? getNodeImage(identifierToken) : "");
|
||||
|
||||
const classParameters = getFirstChild(node, "classParameters");
|
||||
if (classParameters) {
|
||||
result += this.visitor.visit(classParameters, ctx);
|
||||
}
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExtensionDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "extension";
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
result +=
|
||||
" (" + (identifierToken ? getNodeImage(identifierToken) : "") + ": ";
|
||||
if (typeNode) {
|
||||
result += this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
result += ") {\n";
|
||||
|
||||
const extensionMembers = getChildNodes(node, "extensionMember");
|
||||
if (extensionMembers.length > 0) {
|
||||
const members = extensionMembers.map(
|
||||
(m: CSTNode) => " " + this.visitor.visit(m, ctx),
|
||||
);
|
||||
result += members.join("\n");
|
||||
}
|
||||
|
||||
result += "\n}";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExtensionMember(node: CSTNode, ctx: PrintContext): string {
|
||||
const modifierNodes = getChildNodes(node, "modifier");
|
||||
const modifiers = this.visitor.visitModifiers(modifierNodes, ctx);
|
||||
|
||||
const defDefinition = getFirstChild(node, "defDefinition");
|
||||
const definition = defDefinition
|
||||
? this.visitor.visit(defDefinition, ctx)
|
||||
: "";
|
||||
|
||||
return modifiers ? modifiers + " " + definition : definition;
|
||||
}
|
||||
|
||||
visitValDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "val ";
|
||||
|
||||
// Handle pattern or identifier
|
||||
const pattern = getFirstChild(node, "pattern");
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
|
||||
if (pattern) {
|
||||
result += this.visitor.visit(pattern, ctx);
|
||||
} else if (identifierToken) {
|
||||
result += getNodeImage(identifierToken);
|
||||
}
|
||||
|
||||
const colonToken = getFirstChild(node, "Colon");
|
||||
if (colonToken) {
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += ": " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const equalsToken = getFirstChild(node, "Equals");
|
||||
if (equalsToken) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return formatStatement(result, ctx);
|
||||
}
|
||||
|
||||
visitVarDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
let result =
|
||||
"var " + (identifierToken ? getNodeImage(identifierToken) : "");
|
||||
|
||||
const colonToken = getFirstChild(node, "Colon");
|
||||
if (colonToken) {
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += ": " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
|
||||
return formatStatement(result, ctx);
|
||||
}
|
||||
|
||||
visitDefDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "def ";
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
const thisToken = getFirstChild(node, "This");
|
||||
|
||||
if (identifierToken) {
|
||||
result += getNodeImage(identifierToken);
|
||||
} else if (thisToken) {
|
||||
result += "this";
|
||||
}
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const parameterLists = getFirstChild(node, "parameterLists");
|
||||
if (parameterLists) {
|
||||
result += this.visitor.visit(parameterLists, ctx);
|
||||
}
|
||||
|
||||
const colonToken = getFirstChild(node, "Colon");
|
||||
if (colonToken) {
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += ": " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const equalsToken = getFirstChild(node, "Equals");
|
||||
if (equalsToken) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
return formatStatement(result, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitGivenDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "given";
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
if (identifierToken) {
|
||||
// Named given with potential parameters: given name[T](using ord: Type): Type
|
||||
result += " " + getNodeImage(identifierToken);
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const parameterLists = getFirstChild(node, "parameterLists");
|
||||
if (parameterLists) {
|
||||
result += this.visitor.visit(parameterLists, ctx);
|
||||
}
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += ": " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
} else {
|
||||
// Anonymous given: given Type = expression
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += " " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const equalsToken = getFirstChild(node, "Equals");
|
||||
if (equalsToken) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTypeDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle opaque types
|
||||
const opaqueToken = getFirstChild(node, "Opaque");
|
||||
if (opaqueToken) {
|
||||
result += "opaque ";
|
||||
}
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
result += "type " + (identifierToken ? getNodeImage(identifierToken) : "");
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += " = " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitAuxiliaryConstructor(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "def this";
|
||||
|
||||
// CST uses "parameterList" (singular) for auxiliary constructors
|
||||
const parameterList = getFirstChild(node, "parameterList");
|
||||
if (parameterList) {
|
||||
result += this.visitor.visit(parameterList, ctx);
|
||||
}
|
||||
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitClassParameters(node: CSTNode, ctx: PrintContext): string {
|
||||
const params = getChildNodes(node, "classParameter");
|
||||
if (params.length === 0) {
|
||||
return "()";
|
||||
}
|
||||
|
||||
const paramStrings = params.map((p: CSTNode) => this.visitor.visit(p, ctx));
|
||||
const printWidth = getPrintWidth(ctx);
|
||||
|
||||
// Check if single line is appropriate
|
||||
const singleLine = `(${paramStrings.join(", ")})`;
|
||||
// Use single line if it fits within printWidth and is reasonably short
|
||||
if (
|
||||
params.length === 1 &&
|
||||
singleLine.length <= Math.min(printWidth * 0.6, 40)
|
||||
) {
|
||||
return singleLine;
|
||||
}
|
||||
|
||||
// Use multi-line format for multiple parameters or long single parameter
|
||||
const indent = this.visitor.getIndentation(ctx);
|
||||
|
||||
// Format each parameter on its own line without trailing comma for class parameters
|
||||
const indentedParams = paramStrings.map((param: string) => indent + param);
|
||||
return `(\n${indentedParams.join(",\n")}\n)`;
|
||||
}
|
||||
|
||||
visitClassParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
const modifierNodes = getChildNodes(node, "modifier");
|
||||
if (modifierNodes.length > 0) {
|
||||
const modifiers = this.visitor.visitModifiers(modifierNodes, ctx);
|
||||
result += modifiers + " ";
|
||||
}
|
||||
|
||||
const valToken = getFirstChild(node, "Val");
|
||||
const varToken = getFirstChild(node, "Var");
|
||||
|
||||
if (valToken) {
|
||||
result += "val ";
|
||||
} else if (varToken) {
|
||||
result += "var ";
|
||||
}
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
if (identifierToken) {
|
||||
result += getNodeImage(identifierToken);
|
||||
}
|
||||
result += ": ";
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
|
||||
const equalsToken = getFirstChild(node, "Equals");
|
||||
if (equalsToken) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitParameterLists(node: CSTNode, ctx: PrintContext): string {
|
||||
const parameterLists = getChildNodes(node, "parameterList");
|
||||
return parameterLists
|
||||
.map((list: CSTNode) => this.visitor.visit(list, ctx))
|
||||
.join("");
|
||||
}
|
||||
|
||||
visitParameterList(node: CSTNode, ctx: PrintContext): string {
|
||||
const params = getChildNodes(node, "parameter");
|
||||
if (params.length === 0) {
|
||||
return "()";
|
||||
}
|
||||
|
||||
const paramStrings = params.map((p: CSTNode) => this.visitor.visit(p, ctx));
|
||||
return "(" + paramStrings.join(", ") + ")";
|
||||
}
|
||||
|
||||
visitParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
const usingToken = getFirstChild(node, "Using");
|
||||
const implicitToken = getFirstChild(node, "Implicit");
|
||||
|
||||
if (usingToken) {
|
||||
result += "using ";
|
||||
} else if (implicitToken) {
|
||||
result += "implicit ";
|
||||
}
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
if (identifierToken) {
|
||||
result += getNodeImage(identifierToken);
|
||||
}
|
||||
result += ": ";
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
|
||||
const equalsToken = getFirstChild(node, "Equals");
|
||||
if (equalsToken) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTypeParameters(node: CSTNode, ctx: PrintContext): string {
|
||||
const params = getChildNodes(node, "typeParameter");
|
||||
if (params.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const paramStrings = params.map((p: CSTNode) => this.visitor.visit(p, ctx));
|
||||
return "[" + paramStrings.join(", ") + "]";
|
||||
}
|
||||
|
||||
visitTypeParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle variance annotations
|
||||
const plusToken = getFirstChild(node, "Plus");
|
||||
const minusToken = getFirstChild(node, "Minus");
|
||||
|
||||
if (plusToken) {
|
||||
result += "+";
|
||||
} else if (minusToken) {
|
||||
result += "-";
|
||||
}
|
||||
|
||||
const identifierToken = getFirstChild(node, "Identifier");
|
||||
if (identifierToken) {
|
||||
result += getNodeImage(identifierToken);
|
||||
}
|
||||
|
||||
// Add bounds
|
||||
const subtypeOfToken = getFirstChild(node, "SubtypeOf");
|
||||
const supertypeOfToken = getFirstChild(node, "SupertypeOf");
|
||||
const typeNodes = getChildNodes(node, "type");
|
||||
|
||||
if (subtypeOfToken && typeNodes.length > 0) {
|
||||
result += " <: " + this.visitor.visit(typeNodes[0], ctx);
|
||||
}
|
||||
if (supertypeOfToken && typeNodes.length > 1) {
|
||||
result += " >: " + this.visitor.visit(typeNodes[1], ctx);
|
||||
} else if (supertypeOfToken && typeNodes.length === 1 && !subtypeOfToken) {
|
||||
result += " >: " + this.visitor.visit(typeNodes[0], ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExtendsClause(node: CSTNode, ctx: PrintContext): string {
|
||||
const typeNodes = getChildNodes(node, "type");
|
||||
if (typeNodes.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let result = "extends " + this.visitor.visit(typeNodes[0], ctx);
|
||||
|
||||
const withToken = getFirstChild(node, "With");
|
||||
if (withToken && typeNodes.length > 1) {
|
||||
const withTypes = typeNodes
|
||||
.slice(1)
|
||||
.map((t: CSTNode) => this.visitor.visit(t, ctx));
|
||||
result += " with " + withTypes.join(" with ");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitClassBody(node: CSTNode, ctx: PrintContext): string {
|
||||
const classMembers = getChildNodes(node, "classMember");
|
||||
if (classMembers.length === 0) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
// Increase indent level for class members
|
||||
const nestedCtx = {
|
||||
...ctx,
|
||||
indentLevel: ctx.indentLevel + 1,
|
||||
};
|
||||
|
||||
const members = classMembers.map((m: CSTNode) =>
|
||||
this.visitor.visit(m, nestedCtx),
|
||||
);
|
||||
|
||||
const indent = createIndent(1, ctx);
|
||||
return "{\n" + members.map((m: string) => indent + m).join("\n") + "\n}";
|
||||
}
|
||||
|
||||
visitClassMember(node: CSTNode, ctx: PrintContext): string {
|
||||
// Handle different types of class members
|
||||
const defDefinition = getFirstChild(node, "defDefinition");
|
||||
if (defDefinition) {
|
||||
return this.visitor.visit(defDefinition, ctx);
|
||||
}
|
||||
|
||||
const auxiliaryConstructor = getFirstChild(node, "auxiliaryConstructor");
|
||||
if (auxiliaryConstructor) {
|
||||
return this.visitor.visit(auxiliaryConstructor, ctx);
|
||||
}
|
||||
|
||||
const valDefinition = getFirstChild(node, "valDefinition");
|
||||
if (valDefinition) {
|
||||
return this.visitor.visit(valDefinition, ctx);
|
||||
}
|
||||
|
||||
const varDefinition = getFirstChild(node, "varDefinition");
|
||||
if (varDefinition) {
|
||||
return this.visitor.visit(varDefinition, ctx);
|
||||
}
|
||||
|
||||
const classDefinition = getFirstChild(node, "classDefinition");
|
||||
if (classDefinition) {
|
||||
return this.visitor.visit(classDefinition, ctx);
|
||||
}
|
||||
|
||||
const objectDefinition = getFirstChild(node, "objectDefinition");
|
||||
if (objectDefinition) {
|
||||
return this.visitor.visit(objectDefinition, ctx);
|
||||
}
|
||||
|
||||
const traitDefinition = getFirstChild(node, "traitDefinition");
|
||||
if (traitDefinition) {
|
||||
return this.visitor.visit(traitDefinition, ctx);
|
||||
}
|
||||
|
||||
const typeDefinition = getFirstChild(node, "typeDefinition");
|
||||
if (typeDefinition) {
|
||||
return this.visitor.visit(typeDefinition, ctx);
|
||||
}
|
||||
|
||||
const definition = getFirstChild(node, "definition");
|
||||
if (definition) {
|
||||
return this.visitor.visit(definition, ctx);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,836 @@
|
||||
/**
|
||||
* Expression visitor methods for handling various expression types
|
||||
*/
|
||||
import {
|
||||
formatStringLiteral,
|
||||
getChildNodes,
|
||||
getFirstChild,
|
||||
createIndent,
|
||||
getNodeImage,
|
||||
} from "./utils";
|
||||
import type { PrintContext, CSTNode } from "./utils";
|
||||
|
||||
export interface ExpressionVisitor {
|
||||
visit(node: CSTNode, ctx: PrintContext): string;
|
||||
}
|
||||
|
||||
export class ExpressionVisitorMethods {
|
||||
private visitor: ExpressionVisitor;
|
||||
|
||||
constructor(visitor: ExpressionVisitor) {
|
||||
this.visitor = visitor;
|
||||
}
|
||||
|
||||
visitExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
// Handle PartialFunction literals: { case ... }
|
||||
const partialFunctionLiteral = getFirstChild(
|
||||
node,
|
||||
"partialFunctionLiteral",
|
||||
);
|
||||
if (partialFunctionLiteral) {
|
||||
return this.visitor.visit(partialFunctionLiteral, ctx);
|
||||
}
|
||||
|
||||
// Handle lambda expressions with parameter list: (x: Int, y: Int) => x + y
|
||||
const parameterList = getFirstChild(node, "parameterList");
|
||||
const arrow = getChildNodes(node, "Arrow");
|
||||
if (parameterList && arrow.length > 0) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
return (
|
||||
this.visitor.visit(parameterList, ctx) +
|
||||
" => " +
|
||||
(expression ? this.visitor.visit(expression, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
// Handle block lambda expressions: { x => ... }
|
||||
const leftBrace = getChildNodes(node, "LeftBrace");
|
||||
const identifier = getChildNodes(node, "Identifier");
|
||||
const arrowNodes = getChildNodes(node, "Arrow");
|
||||
|
||||
if (
|
||||
leftBrace.length > 0 &&
|
||||
identifier.length > 0 &&
|
||||
arrowNodes.length > 0
|
||||
) {
|
||||
let result = "{ " + getNodeImage(identifier[0]) + " =>";
|
||||
|
||||
const statements: string[] = [];
|
||||
|
||||
// Create nested context for lambda body
|
||||
const nestedCtx = {
|
||||
...ctx,
|
||||
indentLevel: ctx.indentLevel + 1,
|
||||
};
|
||||
|
||||
// Add statements (val/var/def definitions)
|
||||
const blockStatements = getChildNodes(node, "blockStatement");
|
||||
if (blockStatements.length > 0) {
|
||||
statements.push(
|
||||
...blockStatements.map((stmt: CSTNode) =>
|
||||
this.visitor.visit(stmt, nestedCtx),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Add final expression
|
||||
const finalExpression = getFirstChild(node, "expression");
|
||||
if (finalExpression) {
|
||||
statements.push(this.visitor.visit(finalExpression, nestedCtx));
|
||||
}
|
||||
|
||||
if (statements.length === 0) {
|
||||
result += " }";
|
||||
} else if (statements.length === 1) {
|
||||
// Single expression - keep on same line if short
|
||||
const stmt = statements[0];
|
||||
if (stmt.length < 50) {
|
||||
result += " " + stmt + " }";
|
||||
} else {
|
||||
const indent = createIndent(1, ctx);
|
||||
result += "\n" + indent + stmt + "\n}";
|
||||
}
|
||||
} else {
|
||||
// Multiple statements - use multiple lines
|
||||
const indent = createIndent(1, ctx);
|
||||
const indentedStmts = statements.map((stmt) => indent + stmt);
|
||||
result += "\n" + indentedStmts.join("\n") + "\n}";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle polymorphic function literal: [T] => (x: T) => x
|
||||
const polymorphicFunctionLiteral = getFirstChild(
|
||||
node,
|
||||
"polymorphicFunctionLiteral",
|
||||
);
|
||||
if (polymorphicFunctionLiteral) {
|
||||
return this.visitor.visit(polymorphicFunctionLiteral, ctx);
|
||||
}
|
||||
|
||||
// Handle simple lambda expressions: x => x * 2
|
||||
const simpleIdentifier = getChildNodes(node, "Identifier");
|
||||
const simpleArrow = getChildNodes(node, "Arrow");
|
||||
if (simpleIdentifier.length > 0 && simpleArrow.length > 0) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
return (
|
||||
getNodeImage(simpleIdentifier[0]) +
|
||||
" => " +
|
||||
(expression ? this.visitor.visit(expression, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
// Handle assignmentOrInfixExpression
|
||||
const assignmentOrInfixExpression = getFirstChild(
|
||||
node,
|
||||
"assignmentOrInfixExpression",
|
||||
);
|
||||
if (assignmentOrInfixExpression) {
|
||||
return this.visitor.visit(assignmentOrInfixExpression, ctx);
|
||||
}
|
||||
|
||||
// Handle regular expressions (fallback for older structure)
|
||||
const postfixExpressions = getChildNodes(node, "postfixExpression");
|
||||
if (postfixExpressions.length > 0) {
|
||||
let result = this.visitor.visit(postfixExpressions[0], ctx);
|
||||
|
||||
const infixOperators = getChildNodes(node, "infixOperator");
|
||||
if (infixOperators.length > 0) {
|
||||
for (let i = 0; i < infixOperators.length; i++) {
|
||||
result +=
|
||||
" " +
|
||||
this.visitor.visit(infixOperators[i], ctx) +
|
||||
" " +
|
||||
(postfixExpressions[i + 1]
|
||||
? this.visitor.visit(postfixExpressions[i + 1], ctx)
|
||||
: "");
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitPostfixExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const primaryExpression = getFirstChild(node, "primaryExpression");
|
||||
let result = primaryExpression
|
||||
? this.visitor.visit(primaryExpression, ctx)
|
||||
: "";
|
||||
|
||||
// Handle method calls and member access
|
||||
const dots = getChildNodes(node, "Dot");
|
||||
if (dots.length > 0) {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
|
||||
for (let i = 0; i < dots.length; i++) {
|
||||
result += ".";
|
||||
|
||||
// Handle member access or method call
|
||||
// Identifiers after the first one correspond to members after dots
|
||||
if (identifiers.length > i) {
|
||||
result += getNodeImage(identifiers[i]);
|
||||
}
|
||||
|
||||
// Add arguments if this is a method call
|
||||
const leftParens = getChildNodes(node, "LeftParen");
|
||||
if (leftParens.length > i) {
|
||||
result += "(";
|
||||
|
||||
// Find expressions for this argument list
|
||||
const startIdx = i * 10; // Rough heuristic for argument grouping
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
const relevantExpressions = expressions.slice(
|
||||
startIdx,
|
||||
startIdx + 10,
|
||||
);
|
||||
|
||||
if (relevantExpressions.length > 0) {
|
||||
const args = relevantExpressions.map((e: CSTNode) =>
|
||||
this.visitor.visit(e, ctx),
|
||||
);
|
||||
result += args.join(", ");
|
||||
}
|
||||
|
||||
result += ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle type arguments
|
||||
const leftBrackets = getChildNodes(node, "LeftBracket");
|
||||
if (leftBrackets.length > 0) {
|
||||
result += "[";
|
||||
const types = getChildNodes(node, "type");
|
||||
if (types.length > 0) {
|
||||
const typeStrings = types.map((t: CSTNode) =>
|
||||
this.visitor.visit(t, ctx),
|
||||
);
|
||||
result += typeStrings.join(", ");
|
||||
}
|
||||
result += "]";
|
||||
}
|
||||
|
||||
// Handle match expressions
|
||||
const matchTokens = getChildNodes(node, "Match");
|
||||
if (matchTokens.length > 0) {
|
||||
result += " match {\n";
|
||||
const caseClauses = getChildNodes(node, "caseClause");
|
||||
if (caseClauses.length > 0) {
|
||||
const cases = caseClauses.map(
|
||||
(c: CSTNode) => " " + this.visitor.visit(c, ctx),
|
||||
);
|
||||
result += cases.join("\n");
|
||||
result += "\n";
|
||||
}
|
||||
result += "}";
|
||||
}
|
||||
|
||||
// Handle method application without dot
|
||||
const methodLeftParens = getChildNodes(node, "LeftParen");
|
||||
const methodDots = getChildNodes(node, "Dot");
|
||||
if (methodLeftParens.length > 0 && methodDots.length === 0) {
|
||||
result += "(";
|
||||
const methodExpressions = getChildNodes(node, "expression");
|
||||
if (methodExpressions.length > 0) {
|
||||
const args = methodExpressions.map((e: CSTNode) =>
|
||||
this.visitor.visit(e, ctx),
|
||||
);
|
||||
result += args.join(", ");
|
||||
}
|
||||
result += ")";
|
||||
}
|
||||
|
||||
// Handle block lambda expressions: method { param => ... }
|
||||
const leftBrace = getChildNodes(node, "LeftBrace");
|
||||
const arrowNodes = getChildNodes(node, "Arrow");
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
|
||||
if (
|
||||
leftBrace.length > 0 &&
|
||||
arrowNodes.length > 0 &&
|
||||
identifiers.length > 1
|
||||
) {
|
||||
// The lambda parameter is the second identifier (first is method name)
|
||||
const lambdaParam = getNodeImage(identifiers[1]);
|
||||
result += " { " + lambdaParam + " =>";
|
||||
|
||||
// Create nested context for lambda body
|
||||
const nestedCtx = {
|
||||
...ctx,
|
||||
indentLevel: ctx.indentLevel + 1,
|
||||
};
|
||||
|
||||
// Process block statements
|
||||
const blockStatements = getChildNodes(node, "blockStatement");
|
||||
const statements: string[] = [];
|
||||
|
||||
for (const stmt of blockStatements) {
|
||||
statements.push(this.visitor.visit(stmt, nestedCtx));
|
||||
}
|
||||
|
||||
if (statements.length === 0) {
|
||||
result += " }";
|
||||
} else if (statements.length === 1) {
|
||||
// Single statement - keep on same line if short
|
||||
const stmt = statements[0];
|
||||
if (stmt.length < 50) {
|
||||
result += " " + stmt + " }";
|
||||
} else {
|
||||
const indent = createIndent(1, ctx);
|
||||
result += "\n" + indent + stmt + "\n}";
|
||||
}
|
||||
} else {
|
||||
// Multiple statements - use multiple lines
|
||||
const indent = createIndent(1, ctx);
|
||||
const indentedStmts = statements.map((stmt) => indent + stmt);
|
||||
result += "\n" + indentedStmts.join("\n") + "\n}";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitPrimaryExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const literal = getFirstChild(node, "literal");
|
||||
if (literal) {
|
||||
return this.visitor.visit(literal, ctx);
|
||||
}
|
||||
|
||||
const identifier = getFirstChild(node, "Identifier");
|
||||
if (identifier) {
|
||||
return getNodeImage(identifier);
|
||||
}
|
||||
|
||||
const thisToken = getChildNodes(node, "This");
|
||||
if (thisToken.length > 0) {
|
||||
return "this";
|
||||
}
|
||||
|
||||
const partialFunctionLiteral = getFirstChild(
|
||||
node,
|
||||
"partialFunctionLiteral",
|
||||
);
|
||||
if (partialFunctionLiteral) {
|
||||
return this.visitor.visit(partialFunctionLiteral, ctx);
|
||||
}
|
||||
|
||||
const newExpression = getFirstChild(node, "newExpression");
|
||||
if (newExpression) {
|
||||
return this.visitor.visit(newExpression, ctx);
|
||||
}
|
||||
|
||||
const forExpression = getFirstChild(node, "forExpression");
|
||||
if (forExpression) {
|
||||
return this.visitor.visit(forExpression, ctx);
|
||||
}
|
||||
|
||||
const ifExpression = getFirstChild(node, "ifExpression");
|
||||
if (ifExpression) {
|
||||
return this.visitor.visit(ifExpression, ctx);
|
||||
}
|
||||
|
||||
const whileExpression = getFirstChild(node, "whileExpression");
|
||||
if (whileExpression) {
|
||||
return this.visitor.visit(whileExpression, ctx);
|
||||
}
|
||||
|
||||
const tryExpression = getFirstChild(node, "tryExpression");
|
||||
if (tryExpression) {
|
||||
return this.visitor.visit(tryExpression, ctx);
|
||||
}
|
||||
|
||||
const exclamation = getChildNodes(node, "Exclamation");
|
||||
if (exclamation.length > 0) {
|
||||
// Handle negation operator
|
||||
const postfixExpression = getFirstChild(node, "postfixExpression");
|
||||
if (postfixExpression) {
|
||||
const result = this.visitor.visit(postfixExpression, ctx);
|
||||
return "!" + result;
|
||||
}
|
||||
return "!";
|
||||
}
|
||||
|
||||
const bitwiseTilde = getChildNodes(node, "BitwiseTilde");
|
||||
if (bitwiseTilde.length > 0) {
|
||||
// Handle bitwise complement operator
|
||||
const postfixExpression = getFirstChild(node, "postfixExpression");
|
||||
return (
|
||||
"~" +
|
||||
(postfixExpression ? this.visitor.visit(postfixExpression, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
const leftParen = getChildNodes(node, "LeftParen");
|
||||
if (leftParen.length > 0) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
const assignmentOrInfixExpression = getFirstChild(
|
||||
node,
|
||||
"assignmentOrInfixExpression",
|
||||
);
|
||||
|
||||
// Try expression first, then assignmentOrInfixExpression
|
||||
const content = expression
|
||||
? this.visitor.visit(expression, ctx)
|
||||
: assignmentOrInfixExpression
|
||||
? this.visitor.visit(assignmentOrInfixExpression, ctx)
|
||||
: "";
|
||||
|
||||
return "(" + content + ")";
|
||||
}
|
||||
|
||||
const blockExpression = getFirstChild(node, "blockExpression");
|
||||
if (blockExpression) {
|
||||
return this.visitor.visit(blockExpression, ctx);
|
||||
}
|
||||
|
||||
const quoteExpression = getFirstChild(node, "quoteExpression");
|
||||
if (quoteExpression) {
|
||||
return this.visitor.visit(quoteExpression, ctx);
|
||||
}
|
||||
|
||||
const spliceExpression = getFirstChild(node, "spliceExpression");
|
||||
if (spliceExpression) {
|
||||
return this.visitor.visit(spliceExpression, ctx);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitAssignmentOrInfixExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const postfixExpressions = getChildNodes(node, "postfixExpression");
|
||||
let result =
|
||||
postfixExpressions.length > 0
|
||||
? this.visitor.visit(postfixExpressions[0], ctx)
|
||||
: "";
|
||||
|
||||
// Handle assignment operators (including named arguments)
|
||||
const equals = getChildNodes(node, "Equals");
|
||||
const plusEquals = getChildNodes(node, "PlusEquals");
|
||||
const minusEquals = getChildNodes(node, "MinusEquals");
|
||||
const starEquals = getChildNodes(node, "StarEquals");
|
||||
const slashEquals = getChildNodes(node, "SlashEquals");
|
||||
const percentEquals = getChildNodes(node, "PercentEquals");
|
||||
const sbtAssign = getChildNodes(node, "SbtAssign");
|
||||
|
||||
const operator =
|
||||
equals[0] ||
|
||||
plusEquals[0] ||
|
||||
minusEquals[0] ||
|
||||
starEquals[0] ||
|
||||
slashEquals[0] ||
|
||||
percentEquals[0] ||
|
||||
sbtAssign[0];
|
||||
|
||||
if (operator) {
|
||||
result += " " + getNodeImage(operator) + " ";
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length > 0) {
|
||||
result += this.visitor.visit(expressions[0], ctx);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle infix operators
|
||||
const infixOperators = getChildNodes(node, "infixOperator");
|
||||
if (infixOperators.length > 0) {
|
||||
for (let i = 0; i < infixOperators.length; i++) {
|
||||
result += " " + this.visitor.visit(infixOperators[i], ctx) + " ";
|
||||
if (postfixExpressions.length > i + 1) {
|
||||
result += this.visitor.visit(postfixExpressions[i + 1], ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
visitInfixOperator(node: CSTNode, _ctx: PrintContext): string {
|
||||
// Handle all possible infix operators
|
||||
const operators = [
|
||||
"Plus",
|
||||
"Minus",
|
||||
"Star",
|
||||
"Slash",
|
||||
"Percent",
|
||||
"DoubleStar",
|
||||
"LeftShift",
|
||||
"RightShift",
|
||||
"UnsignedRightShift",
|
||||
"BitwiseAnd",
|
||||
"BitwiseOr",
|
||||
"BitwiseXor",
|
||||
"EqualsEquals",
|
||||
"NotEquals",
|
||||
"LessThan",
|
||||
"LessThanOrEqual",
|
||||
"GreaterThan",
|
||||
"GreaterThanOrEqual",
|
||||
"LogicalAnd",
|
||||
"LogicalOr",
|
||||
"DoublePercent",
|
||||
"Ask",
|
||||
"To",
|
||||
"Until",
|
||||
"PrependOp",
|
||||
"AppendOp",
|
||||
"ConcatOp",
|
||||
"RightArrow",
|
||||
];
|
||||
|
||||
for (const op of operators) {
|
||||
const tokens = getChildNodes(node, op);
|
||||
if (tokens.length > 0) {
|
||||
return getNodeImage(tokens[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to identifier for custom operators
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
return getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitLiteral(node: CSTNode, ctx: PrintContext): string {
|
||||
// Handle all possible literal types
|
||||
const literalTypes = [
|
||||
"StringLiteral",
|
||||
"InterpolatedStringLiteral",
|
||||
"IntegerLiteral",
|
||||
"NumberLiteral",
|
||||
"FloatLiteral",
|
||||
"BooleanLiteral",
|
||||
"True",
|
||||
"False",
|
||||
"CharLiteral",
|
||||
"NullLiteral",
|
||||
"Null",
|
||||
"ScientificNumber",
|
||||
];
|
||||
|
||||
for (const literalType of literalTypes) {
|
||||
const tokens = getChildNodes(node, literalType);
|
||||
if (tokens.length > 0) {
|
||||
const tokenImage = getNodeImage(tokens[0]);
|
||||
|
||||
// Apply singleQuote formatting to string literals
|
||||
if (tokenImage.startsWith('"') || tokenImage.startsWith("'")) {
|
||||
return formatStringLiteral(tokenImage, ctx);
|
||||
}
|
||||
|
||||
return tokenImage;
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
visitQualifiedIdentifier(node: CSTNode, _ctx: PrintContext): string {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let result = getNodeImage(identifiers[0]);
|
||||
|
||||
const dots = getChildNodes(node, "Dot");
|
||||
if (dots.length > 0) {
|
||||
// Handle mixed identifiers and type keywords
|
||||
const types = getChildNodes(node, "Type");
|
||||
|
||||
for (let i = 0; i < dots.length; i++) {
|
||||
result += ".";
|
||||
|
||||
// Determine which token comes next (identifier or type keyword)
|
||||
if (i + 1 < identifiers.length) {
|
||||
result += getNodeImage(identifiers[i + 1]);
|
||||
} else if (types.length > 0) {
|
||||
// Use the type keyword (e.g., "type" for .type syntax)
|
||||
result += getNodeImage(types[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitNewExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
let result = "new " + (typeNode ? this.visitor.visit(typeNode, ctx) : "");
|
||||
|
||||
const leftParens = getChildNodes(node, "LeftParen");
|
||||
if (leftParens.length > 0) {
|
||||
result += "(";
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length > 0) {
|
||||
const args = expressions.map((e: CSTNode) =>
|
||||
this.visitor.visit(e, ctx),
|
||||
);
|
||||
result += args.join(", ");
|
||||
}
|
||||
result += ")";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitIfExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length < 2) {
|
||||
return "if";
|
||||
}
|
||||
|
||||
let result = "if (";
|
||||
result += this.visitor.visit(expressions[0], ctx);
|
||||
result += ") ";
|
||||
result += this.visitor.visit(expressions[1], ctx);
|
||||
|
||||
const elseTokens = getChildNodes(node, "Else");
|
||||
if (elseTokens.length > 0 && expressions.length > 2) {
|
||||
result += " else ";
|
||||
result += this.visitor.visit(expressions[2], ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitWhileExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length < 2) {
|
||||
return "while";
|
||||
}
|
||||
|
||||
let result = "while (";
|
||||
result += this.visitor.visit(expressions[0], ctx);
|
||||
result += ") ";
|
||||
result += this.visitor.visit(expressions[1], ctx);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTryExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length === 0) {
|
||||
return "try";
|
||||
}
|
||||
|
||||
let result = "try ";
|
||||
result += this.visitor.visit(expressions[0], ctx);
|
||||
|
||||
const catchTokens = getChildNodes(node, "Catch");
|
||||
if (catchTokens.length > 0) {
|
||||
result += " catch {\n";
|
||||
const caseClauses = getChildNodes(node, "caseClause");
|
||||
if (caseClauses.length > 0) {
|
||||
const cases = caseClauses.map(
|
||||
(c: CSTNode) => " " + this.visitor.visit(c, ctx),
|
||||
);
|
||||
result += cases.join("\n");
|
||||
}
|
||||
result += "\n}";
|
||||
}
|
||||
|
||||
const finallyTokens = getChildNodes(node, "Finally");
|
||||
if (finallyTokens.length > 0) {
|
||||
result += " finally ";
|
||||
// If there's a catch block, expression[1] is the finally expression
|
||||
// Otherwise, expression[1] would be the finally expression (no catch)
|
||||
const finallyExprIndex = catchTokens.length > 0 ? 1 : 1;
|
||||
if (expressions.length > finallyExprIndex) {
|
||||
result += this.visitor.visit(expressions[finallyExprIndex], ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitForExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "for ";
|
||||
|
||||
const leftParens = getChildNodes(node, "LeftParen");
|
||||
const leftBraces = getChildNodes(node, "LeftBrace");
|
||||
const generators = getChildNodes(node, "generator");
|
||||
|
||||
if (leftParens.length > 0) {
|
||||
result += "(";
|
||||
if (generators.length > 0) {
|
||||
const gens = generators.map((g: CSTNode) => this.visitor.visit(g, ctx));
|
||||
result += gens.join("; ");
|
||||
}
|
||||
result += ")";
|
||||
} else if (leftBraces.length > 0) {
|
||||
result += "{\n";
|
||||
if (generators.length > 0) {
|
||||
const gens = generators.map(
|
||||
(g: CSTNode) => " " + this.visitor.visit(g, ctx),
|
||||
);
|
||||
result += gens.join("\n");
|
||||
}
|
||||
result += "\n}";
|
||||
}
|
||||
|
||||
const yieldTokens = getChildNodes(node, "Yield");
|
||||
if (yieldTokens.length > 0) {
|
||||
result += " yield ";
|
||||
} else {
|
||||
result += " ";
|
||||
}
|
||||
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length > 0) {
|
||||
result += this.visitor.visit(expressions[0], ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitGenerator(node: CSTNode, ctx: PrintContext): string {
|
||||
const patterns = getChildNodes(node, "pattern");
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
|
||||
if (patterns.length === 0 || expressions.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let result = this.visitor.visit(patterns[0], ctx);
|
||||
result += " <- " + this.visitor.visit(expressions[0], ctx);
|
||||
|
||||
const ifTokens = getChildNodes(node, "If");
|
||||
if (ifTokens.length > 0) {
|
||||
for (let i = 0; i < ifTokens.length; i++) {
|
||||
if (expressions.length > i + 1) {
|
||||
result += " if " + this.visitor.visit(expressions[i + 1], ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitCaseClause(node: CSTNode, ctx: PrintContext): string {
|
||||
const patterns = getChildNodes(node, "pattern");
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
|
||||
if (patterns.length === 0) {
|
||||
return "case";
|
||||
}
|
||||
|
||||
let result = "case " + this.visitor.visit(patterns[0], ctx);
|
||||
|
||||
const ifTokens = getChildNodes(node, "If");
|
||||
if (ifTokens.length > 0 && expressions.length > 0) {
|
||||
result += " if " + this.visitor.visit(expressions[0], ctx);
|
||||
}
|
||||
|
||||
const expressionIndex = ifTokens.length > 0 ? 1 : 0;
|
||||
if (expressions.length > expressionIndex) {
|
||||
result += " => " + this.visitor.visit(expressions[expressionIndex], ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitBlockExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const blockStatements = getChildNodes(node, "blockStatement");
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
|
||||
if (blockStatements.length === 0 && expressions.length === 0) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
let result = "{\n";
|
||||
const statements: string[] = [];
|
||||
|
||||
// Create nested context for block contents
|
||||
const nestedCtx = {
|
||||
...ctx,
|
||||
indentLevel: ctx.indentLevel + 1,
|
||||
};
|
||||
|
||||
if (blockStatements.length > 0) {
|
||||
statements.push(
|
||||
...blockStatements.map((stmt: CSTNode) =>
|
||||
this.visitor.visit(stmt, nestedCtx),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (expressions.length > 0) {
|
||||
statements.push(this.visitor.visit(expressions[0], nestedCtx));
|
||||
}
|
||||
|
||||
const indent = createIndent(1, ctx);
|
||||
result += statements.map((stmt) => indent + stmt).join("\n");
|
||||
|
||||
result += "\n}";
|
||||
return result;
|
||||
}
|
||||
|
||||
visitPartialFunctionLiteral(node: CSTNode, ctx: PrintContext): string {
|
||||
const caseClauses = getChildNodes(node, "caseClause");
|
||||
|
||||
if (caseClauses.length === 0) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
// Single case - try to format on one line if short
|
||||
if (caseClauses.length === 1) {
|
||||
const caseStr = this.visitor.visit(caseClauses[0], ctx);
|
||||
if (caseStr.length < 50) {
|
||||
return `{ ${caseStr} }`;
|
||||
}
|
||||
}
|
||||
|
||||
// Multi-line format for long cases or multiple cases
|
||||
let result = "{\n";
|
||||
const cases = caseClauses.map(
|
||||
(c: CSTNode) => " " + this.visitor.visit(c, ctx),
|
||||
);
|
||||
result += cases.join("\n");
|
||||
result += "\n}";
|
||||
return result;
|
||||
}
|
||||
|
||||
visitAssignmentStatement(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let result = getNodeImage(identifiers[0]);
|
||||
|
||||
// Find the assignment operator
|
||||
const equals = getChildNodes(node, "Equals");
|
||||
const plusEquals = getChildNodes(node, "PlusEquals");
|
||||
const minusEquals = getChildNodes(node, "MinusEquals");
|
||||
const starEquals = getChildNodes(node, "StarEquals");
|
||||
const slashEquals = getChildNodes(node, "SlashEquals");
|
||||
const percentEquals = getChildNodes(node, "PercentEquals");
|
||||
const sbtAssign = getChildNodes(node, "SbtAssign");
|
||||
|
||||
const operator =
|
||||
equals[0] ||
|
||||
plusEquals[0] ||
|
||||
minusEquals[0] ||
|
||||
starEquals[0] ||
|
||||
slashEquals[0] ||
|
||||
percentEquals[0] ||
|
||||
sbtAssign[0];
|
||||
|
||||
if (operator) {
|
||||
result += " " + getNodeImage(operator) + " ";
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length > 0) {
|
||||
result += this.visitor.visit(expressions[0], ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
433
frontend/src/common/prettier/plugins/scala/visitor/scala3.ts
Normal file
433
frontend/src/common/prettier/plugins/scala/visitor/scala3.ts
Normal file
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* Scala 3 specific visitor methods for modern language features
|
||||
*/
|
||||
import { getChildNodes, getFirstChild, getNodeImage } from "./utils";
|
||||
import type { PrintContext, CSTNode } from "./utils";
|
||||
|
||||
export interface Scala3Visitor {
|
||||
visit(node: CSTNode, ctx: PrintContext): string;
|
||||
getIndentation(ctx: PrintContext): string;
|
||||
visitModifiers(modifiers: CSTNode[], ctx: PrintContext): string;
|
||||
}
|
||||
|
||||
export class Scala3VisitorMethods {
|
||||
private visitor: Scala3Visitor;
|
||||
|
||||
constructor(visitor: Scala3Visitor) {
|
||||
this.visitor = visitor;
|
||||
}
|
||||
|
||||
// Quote and splice expressions for macros
|
||||
visitQuoteExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
return (
|
||||
"'{ " + (expression ? this.visitor.visit(expression, ctx) : "") + " }"
|
||||
);
|
||||
}
|
||||
|
||||
visitSpliceExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
return (
|
||||
"${ " + (expression ? this.visitor.visit(expression, ctx) : "") + " }"
|
||||
);
|
||||
}
|
||||
|
||||
// Polymorphic function literals
|
||||
visitPolymorphicFunctionLiteral(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "[";
|
||||
|
||||
const polymorphicTypeParams = getChildNodes(
|
||||
node,
|
||||
"polymorphicTypeParameter",
|
||||
);
|
||||
if (polymorphicTypeParams.length > 0) {
|
||||
const parameters = polymorphicTypeParams.map((param: CSTNode) =>
|
||||
this.visitor.visit(param, ctx),
|
||||
);
|
||||
result += parameters.join(", ");
|
||||
}
|
||||
|
||||
result += "] => ";
|
||||
const expression = getFirstChild(node, "expression");
|
||||
result += expression ? this.visitor.visit(expression, ctx) : "";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Polymorphic function types
|
||||
visitPolymorphicFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "[";
|
||||
|
||||
const polymorphicTypeParams = getChildNodes(
|
||||
node,
|
||||
"polymorphicTypeParameter",
|
||||
);
|
||||
if (polymorphicTypeParams.length > 0) {
|
||||
const parameters = polymorphicTypeParams.map((param: CSTNode) =>
|
||||
this.visitor.visit(param, ctx),
|
||||
);
|
||||
result += parameters.join(", ");
|
||||
}
|
||||
|
||||
result += "] => ";
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitPolymorphicTypeParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Add variance annotation if present
|
||||
const plusTokens = getChildNodes(node, "Plus");
|
||||
const minusTokens = getChildNodes(node, "Minus");
|
||||
if (plusTokens.length > 0) {
|
||||
result += "+";
|
||||
} else if (minusTokens.length > 0) {
|
||||
result += "-";
|
||||
}
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
result += getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Handle type bounds
|
||||
const subtypeOf = getChildNodes(node, "SubtypeOf");
|
||||
const supertypeOf = getChildNodes(node, "SupertypeOf");
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
|
||||
if (subtypeOf.length > 0 && typeNode) {
|
||||
result += " <: " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
if (supertypeOf.length > 0 && typeNode) {
|
||||
result += " >: " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Enum definitions
|
||||
visitEnumDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
let result =
|
||||
"enum " + (identifiers.length > 0 ? getNodeImage(identifiers[0]) : "");
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const classParameters = getFirstChild(node, "classParameters");
|
||||
if (classParameters) {
|
||||
result += this.visitor.visit(classParameters, ctx);
|
||||
}
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
result += " {\n";
|
||||
|
||||
const enumCases = getChildNodes(node, "enumCase");
|
||||
if (enumCases.length > 0) {
|
||||
const indent = this.visitor.getIndentation(ctx);
|
||||
const cases = enumCases.map(
|
||||
(c: CSTNode) => indent + this.visitor.visit(c, ctx),
|
||||
);
|
||||
result += cases.join("\n");
|
||||
}
|
||||
|
||||
result += "\n}";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitEnumCase(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
let result =
|
||||
"case " + (identifiers.length > 0 ? getNodeImage(identifiers[0]) : "");
|
||||
|
||||
const classParameters = getFirstChild(node, "classParameters");
|
||||
if (classParameters) {
|
||||
result += this.visitor.visit(classParameters, ctx);
|
||||
}
|
||||
|
||||
const extendsClause = getFirstChild(node, "extendsClause");
|
||||
if (extendsClause) {
|
||||
result += " " + this.visitor.visit(extendsClause, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Extension methods
|
||||
visitExtensionDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "extension";
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
result +=
|
||||
" (" +
|
||||
(identifiers.length > 0 ? getNodeImage(identifiers[0]) : "") +
|
||||
": ";
|
||||
if (typeNode) {
|
||||
result += this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
result += ") {\n";
|
||||
|
||||
const extensionMembers = getChildNodes(node, "extensionMember");
|
||||
if (extensionMembers.length > 0) {
|
||||
const members = extensionMembers.map(
|
||||
(m: CSTNode) => " " + this.visitor.visit(m, ctx),
|
||||
);
|
||||
result += members.join("\n");
|
||||
}
|
||||
|
||||
result += "\n}";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExtensionMember(node: CSTNode, ctx: PrintContext): string {
|
||||
const modifierNodes = getChildNodes(node, "modifier");
|
||||
const modifiers = this.visitor.visitModifiers(modifierNodes, ctx);
|
||||
const defDefinition = getFirstChild(node, "defDefinition");
|
||||
const definition = defDefinition
|
||||
? this.visitor.visit(defDefinition, ctx)
|
||||
: "";
|
||||
|
||||
return modifiers ? modifiers + " " + definition : definition;
|
||||
}
|
||||
|
||||
// Given definitions
|
||||
visitGivenDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "given";
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
// Named given with potential parameters: given name[T](using ord: Type): Type
|
||||
result += " " + getNodeImage(identifiers[0]);
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const parameterLists = getFirstChild(node, "parameterLists");
|
||||
if (parameterLists) {
|
||||
result += this.visitor.visit(parameterLists, ctx);
|
||||
}
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += ": " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
} else {
|
||||
// Anonymous given: given Type = expression
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += " " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const equalsTokens = getChildNodes(node, "Equals");
|
||||
if (equalsTokens.length > 0) {
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += " = " + this.visitor.visit(expression, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Type definitions including opaque types
|
||||
visitTypeDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle opaque types
|
||||
const opaqueTokens = getChildNodes(node, "Opaque");
|
||||
if (opaqueTokens.length > 0) {
|
||||
result += "opaque ";
|
||||
}
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
result +=
|
||||
"type " + (identifiers.length > 0 ? getNodeImage(identifiers[0]) : "");
|
||||
|
||||
const typeParameters = getFirstChild(node, "typeParameters");
|
||||
if (typeParameters) {
|
||||
result += this.visitor.visit(typeParameters, ctx);
|
||||
}
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += " = " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Export clauses and expressions
|
||||
visitExportClause(node: CSTNode, ctx: PrintContext): string {
|
||||
const exportExpression = getFirstChild(node, "exportExpression");
|
||||
return (
|
||||
"export " +
|
||||
(exportExpression ? this.visitor.visit(exportExpression, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
visitExportExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Build the export path
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const dots = getChildNodes(node, "Dot");
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
const givens = getChildNodes(node, "Given");
|
||||
const leftBraces = getChildNodes(node, "LeftBrace");
|
||||
|
||||
// Add first identifier
|
||||
if (identifiers.length > 0) {
|
||||
result = getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Process remaining parts
|
||||
let identifierIndex = 1;
|
||||
for (let i = 0; i < dots.length; i++) {
|
||||
result += ".";
|
||||
|
||||
// Check what follows this dot
|
||||
if (underscores.length > 0 && i === dots.length - 1) {
|
||||
// Wildcard export
|
||||
result += "_";
|
||||
} else if (givens.length > 0 && i === dots.length - 1) {
|
||||
// Given export
|
||||
result += "given";
|
||||
} else if (leftBraces.length > 0 && i === dots.length - 1) {
|
||||
// Multiple export selectors
|
||||
result += "{";
|
||||
const exportSelectors = getChildNodes(node, "exportSelector");
|
||||
if (exportSelectors.length > 0) {
|
||||
const selectors = exportSelectors.map((sel: CSTNode) =>
|
||||
this.visitor.visit(sel, ctx),
|
||||
);
|
||||
result += selectors.join(", ");
|
||||
}
|
||||
result += "}";
|
||||
} else if (identifierIndex < identifiers.length) {
|
||||
// Next identifier in path
|
||||
result += getNodeImage(identifiers[identifierIndex]);
|
||||
identifierIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
visitExportSelector(node: CSTNode, _ctx: PrintContext): string {
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const givens = getChildNodes(node, "Given");
|
||||
const arrows = getChildNodes(node, "Arrow");
|
||||
|
||||
// Handle wildcard export
|
||||
if (underscores.length > 0 && identifiers.length === 0) {
|
||||
return "_";
|
||||
}
|
||||
|
||||
// Handle given export
|
||||
if (givens.length > 0 && identifiers.length === 0) {
|
||||
return "given";
|
||||
}
|
||||
|
||||
let result = "";
|
||||
|
||||
// Handle regular identifiers
|
||||
if (identifiers.length > 0) {
|
||||
result = getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Handle given with specific identifiers: given SpecificType
|
||||
if (givens.length > 0 && identifiers.length > 0) {
|
||||
result = "given " + getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
if (arrows.length > 0) {
|
||||
result += " => ";
|
||||
if (underscores.length > 0) {
|
||||
result += "_";
|
||||
} else if (identifiers.length > 1) {
|
||||
result += getNodeImage(identifiers[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Context function types
|
||||
visitContextFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle parenthesized types
|
||||
const leftParens = getChildNodes(node, "LeftParen");
|
||||
if (leftParens.length > 0) {
|
||||
const tupleType = getFirstChild(node, "tupleTypeOrParenthesized");
|
||||
if (tupleType) {
|
||||
result += "(" + this.visitor.visit(tupleType, ctx) + ")";
|
||||
}
|
||||
} else {
|
||||
// Handle simple types
|
||||
const simpleType = getFirstChild(node, "simpleType");
|
||||
if (simpleType) {
|
||||
result += this.visitor.visit(simpleType, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += " ?=> " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Inline and transparent modifiers
|
||||
visitInlineModifier(): string {
|
||||
return "inline";
|
||||
}
|
||||
|
||||
visitTransparentModifier(): string {
|
||||
return "transparent";
|
||||
}
|
||||
|
||||
// Using clauses
|
||||
visitUsingClause(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "using ";
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
result += getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
const colonTokens = getChildNodes(node, "Colon");
|
||||
if (colonTokens.length > 0) {
|
||||
const typeNode = getFirstChild(node, "type");
|
||||
if (typeNode) {
|
||||
result += ": " + this.visitor.visit(typeNode, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
658
frontend/src/common/prettier/plugins/scala/visitor/statements.ts
Normal file
658
frontend/src/common/prettier/plugins/scala/visitor/statements.ts
Normal file
@@ -0,0 +1,658 @@
|
||||
/**
|
||||
* Statement visitor methods for import/export, package, and other statements
|
||||
*/
|
||||
import { getChildNodes, getFirstChild, getNodeImage } from "./utils";
|
||||
import type { PrintContext, CSTNode } from "./utils";
|
||||
|
||||
export interface StatementVisitor {
|
||||
visit(node: CSTNode, ctx: PrintContext): string;
|
||||
}
|
||||
|
||||
export class StatementVisitorMethods {
|
||||
private visitor: StatementVisitor;
|
||||
|
||||
constructor(visitor: StatementVisitor) {
|
||||
this.visitor = visitor;
|
||||
}
|
||||
|
||||
visitPackageClause(node: CSTNode, ctx: PrintContext): string {
|
||||
const qualifiedIdentifier = getFirstChild(node, "qualifiedIdentifier");
|
||||
return (
|
||||
"package " +
|
||||
(qualifiedIdentifier ? this.visitor.visit(qualifiedIdentifier, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
visitImportClause(node: CSTNode, ctx: PrintContext): string {
|
||||
const importExpression = getFirstChild(node, "importExpression");
|
||||
return (
|
||||
"import " +
|
||||
(importExpression ? this.visitor.visit(importExpression, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
visitImportExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Build the import path
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const dots = getChildNodes(node, "Dot");
|
||||
|
||||
// Add first identifier
|
||||
if (identifiers.length > 0) {
|
||||
result = getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Process remaining parts
|
||||
let identifierIndex = 1;
|
||||
for (let i = 0; i < dots.length; i++) {
|
||||
result += ".";
|
||||
|
||||
// Check what follows this dot
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
const leftBraces = getChildNodes(node, "LeftBrace");
|
||||
|
||||
if (underscores.length > 0 && i === dots.length - 1) {
|
||||
// Wildcard import
|
||||
result += "_";
|
||||
} else if (leftBraces.length > 0 && i === dots.length - 1) {
|
||||
// Multiple import selectors
|
||||
result += "{";
|
||||
const importSelectors = getChildNodes(node, "importSelector");
|
||||
if (importSelectors.length > 0) {
|
||||
const selectors = importSelectors.map((sel: CSTNode) =>
|
||||
this.visitor.visit(sel, ctx),
|
||||
);
|
||||
result += selectors.join(", ");
|
||||
}
|
||||
result += "}";
|
||||
} else if (identifierIndex < identifiers.length) {
|
||||
// Next identifier in path
|
||||
result += getNodeImage(identifiers[identifierIndex]);
|
||||
identifierIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
visitImportSelector(node: CSTNode, _ctx: PrintContext): string {
|
||||
// Handle wildcard import
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
|
||||
if (underscores.length > 0 && identifiers.length === 0) {
|
||||
return "_";
|
||||
}
|
||||
|
||||
let result = "";
|
||||
if (identifiers.length > 0) {
|
||||
result = getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
const arrows = getChildNodes(node, "Arrow");
|
||||
if (arrows.length > 0) {
|
||||
result += " => ";
|
||||
const selectorUnderscores = getChildNodes(node, "Underscore");
|
||||
if (selectorUnderscores.length > 0) {
|
||||
result += "_";
|
||||
} else if (identifiers.length > 1) {
|
||||
result += getNodeImage(identifiers[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExportClause(node: CSTNode, ctx: PrintContext): string {
|
||||
const exportExpression = getFirstChild(node, "exportExpression");
|
||||
return (
|
||||
"export " +
|
||||
(exportExpression ? this.visitor.visit(exportExpression, ctx) : "")
|
||||
);
|
||||
}
|
||||
|
||||
visitExportExpression(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Build the export path
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const dots = getChildNodes(node, "Dot");
|
||||
|
||||
// Add first identifier
|
||||
if (identifiers.length > 0) {
|
||||
result = getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Process remaining parts
|
||||
let identifierIndex = 1;
|
||||
for (let i = 0; i < dots.length; i++) {
|
||||
result += ".";
|
||||
|
||||
// Check what follows this dot
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
const givens = getChildNodes(node, "Given");
|
||||
|
||||
if (underscores.length > 0 && i === dots.length - 1) {
|
||||
// Wildcard export
|
||||
result += "_";
|
||||
} else if (givens.length > 0 && i === dots.length - 1) {
|
||||
// Given export
|
||||
result += "given";
|
||||
} else if (
|
||||
getChildNodes(node, "LeftBrace").length > 0 &&
|
||||
i === dots.length - 1
|
||||
) {
|
||||
// Multiple export selectors
|
||||
result += "{";
|
||||
const exportSelectors = getChildNodes(node, "exportSelector");
|
||||
if (exportSelectors.length > 0) {
|
||||
const selectors = exportSelectors.map((sel: CSTNode) =>
|
||||
this.visitor.visit(sel, ctx),
|
||||
);
|
||||
result += selectors.join(", ");
|
||||
}
|
||||
result += "}";
|
||||
} else if (identifierIndex < identifiers.length) {
|
||||
// Next identifier in path
|
||||
result += getNodeImage(identifiers[identifierIndex]);
|
||||
identifierIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExportSelector(node: CSTNode): string {
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const givens = getChildNodes(node, "Given");
|
||||
|
||||
// Handle wildcard export
|
||||
if (underscores.length > 0 && identifiers.length === 0) {
|
||||
return "_";
|
||||
}
|
||||
|
||||
// Handle given export
|
||||
if (givens.length > 0 && identifiers.length === 0) {
|
||||
return "given";
|
||||
}
|
||||
|
||||
let result = "";
|
||||
|
||||
// Handle regular identifiers
|
||||
if (identifiers.length > 0) {
|
||||
result = getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Handle given with specific identifiers: given SpecificType
|
||||
if (givens.length > 0 && identifiers.length > 0) {
|
||||
result = "given " + getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
const arrows = getChildNodes(node, "Arrow");
|
||||
if (arrows.length > 0) {
|
||||
result += " => ";
|
||||
const arrowUnderscores = getChildNodes(node, "Underscore");
|
||||
if (arrowUnderscores.length > 0) {
|
||||
result += "_";
|
||||
} else if (identifiers.length > 1) {
|
||||
result += getNodeImage(identifiers[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTopLevelDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle modifiers (including 'case')
|
||||
const modifiers = getChildNodes(node, "modifier");
|
||||
if (modifiers.length > 0) {
|
||||
const modifierStr = this.visitModifiers(modifiers, ctx);
|
||||
result += modifierStr + " ";
|
||||
}
|
||||
|
||||
// Handle definitions at top level
|
||||
const definition = getFirstChild(node, "definition");
|
||||
if (definition) {
|
||||
result += this.visitor.visit(definition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle class definitions
|
||||
const classDefinition = getFirstChild(node, "classDefinition");
|
||||
if (classDefinition) {
|
||||
result += this.visitor.visit(classDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle object definitions
|
||||
const objectDefinition = getFirstChild(node, "objectDefinition");
|
||||
if (objectDefinition) {
|
||||
result += this.visitor.visit(objectDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle trait definitions
|
||||
const traitDefinition = getFirstChild(node, "traitDefinition");
|
||||
if (traitDefinition) {
|
||||
result += this.visitor.visit(traitDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle val definitions
|
||||
const valDefinition = getFirstChild(node, "valDefinition");
|
||||
if (valDefinition) {
|
||||
result += this.visitor.visit(valDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle var definitions
|
||||
const varDefinition = getFirstChild(node, "varDefinition");
|
||||
if (varDefinition) {
|
||||
result += this.visitor.visit(varDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle def definitions
|
||||
const defDefinition = getFirstChild(node, "defDefinition");
|
||||
if (defDefinition) {
|
||||
result += this.visitor.visit(defDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle enum definitions (Scala 3)
|
||||
const enumDefinition = getFirstChild(node, "enumDefinition");
|
||||
if (enumDefinition) {
|
||||
result += this.visitor.visit(enumDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle extension definitions (Scala 3)
|
||||
const extensionDefinition = getFirstChild(node, "extensionDefinition");
|
||||
if (extensionDefinition) {
|
||||
result += this.visitor.visit(extensionDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle given definitions (Scala 3)
|
||||
const givenDefinition = getFirstChild(node, "givenDefinition");
|
||||
if (givenDefinition) {
|
||||
result += this.visitor.visit(givenDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle type definitions (including opaque types)
|
||||
const typeDefinition = getFirstChild(node, "typeDefinition");
|
||||
if (typeDefinition) {
|
||||
result += this.visitor.visit(typeDefinition, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle assignment statements
|
||||
const assignmentStatement = getFirstChild(node, "assignmentStatement");
|
||||
if (assignmentStatement) {
|
||||
result += this.visitor.visit(assignmentStatement, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle expressions
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
result += this.visitor.visit(expression, ctx);
|
||||
return result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitBlockStatement(node: CSTNode, ctx: PrintContext): string {
|
||||
const valDefinition = getFirstChild(node, "valDefinition");
|
||||
if (valDefinition) {
|
||||
return this.visitor.visit(valDefinition, ctx);
|
||||
}
|
||||
|
||||
const varDefinition = getFirstChild(node, "varDefinition");
|
||||
if (varDefinition) {
|
||||
return this.visitor.visit(varDefinition, ctx);
|
||||
}
|
||||
|
||||
const defDefinition = getFirstChild(node, "defDefinition");
|
||||
if (defDefinition) {
|
||||
return this.visitor.visit(defDefinition, ctx);
|
||||
}
|
||||
|
||||
const assignmentStatement = getFirstChild(node, "assignmentStatement");
|
||||
if (assignmentStatement) {
|
||||
return this.visitor.visit(assignmentStatement, ctx);
|
||||
}
|
||||
|
||||
const expression = getFirstChild(node, "expression");
|
||||
if (expression) {
|
||||
return this.visitor.visit(expression, ctx);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitCompilationUnit(node: CSTNode, ctx: PrintContext): string {
|
||||
const parts: string[] = [];
|
||||
|
||||
// Add package clause if it exists
|
||||
const packageClause = getFirstChild(node, "packageClause");
|
||||
if (packageClause) {
|
||||
parts.push(this.visitor.visit(packageClause, ctx));
|
||||
}
|
||||
|
||||
// Add empty line after package
|
||||
if (parts.length > 0) {
|
||||
parts.push("");
|
||||
}
|
||||
|
||||
// Add import clauses
|
||||
const importClauses = getChildNodes(node, "importClause");
|
||||
if (importClauses.length > 0) {
|
||||
importClauses.forEach((importNode: CSTNode) => {
|
||||
parts.push(this.visitor.visit(importNode, ctx));
|
||||
});
|
||||
}
|
||||
|
||||
// Add empty line after imports
|
||||
if (importClauses.length > 0) {
|
||||
parts.push("");
|
||||
}
|
||||
|
||||
// Add export clauses
|
||||
const exportClauses = getChildNodes(node, "exportClause");
|
||||
if (exportClauses.length > 0) {
|
||||
exportClauses.forEach((exportNode: CSTNode) => {
|
||||
parts.push(this.visitor.visit(exportNode, ctx));
|
||||
});
|
||||
}
|
||||
|
||||
// Don't add empty line after exports unless there are subsequent elements
|
||||
if (exportClauses.length > 0) {
|
||||
// Only add empty line if there are other elements after exports
|
||||
const topLevelDefinitions = getChildNodes(node, "topLevelDefinition");
|
||||
const topLevelStatements = getChildNodes(node, "topLevelStatement");
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
const hasSubsequentElements =
|
||||
topLevelDefinitions.length > 0 ||
|
||||
topLevelStatements.length > 0 ||
|
||||
expressions.length > 0;
|
||||
if (hasSubsequentElements) {
|
||||
parts.push("");
|
||||
}
|
||||
}
|
||||
|
||||
// Add top-level definitions
|
||||
const topLevelDefinitions = getChildNodes(node, "topLevelDefinition");
|
||||
if (topLevelDefinitions.length > 0) {
|
||||
topLevelDefinitions.forEach((def: CSTNode) => {
|
||||
parts.push(this.visitor.visit(def, ctx));
|
||||
});
|
||||
}
|
||||
|
||||
// Add top-level statements
|
||||
const topLevelStatements = getChildNodes(node, "topLevelStatement");
|
||||
if (topLevelStatements.length > 0) {
|
||||
topLevelStatements.forEach((stmt: CSTNode) => {
|
||||
parts.push(this.visitor.visit(stmt, ctx));
|
||||
});
|
||||
}
|
||||
|
||||
// Add top-level expressions
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
if (expressions.length > 0) {
|
||||
expressions.forEach((expr: CSTNode) => {
|
||||
parts.push(this.visitor.visit(expr, ctx));
|
||||
});
|
||||
}
|
||||
|
||||
// Join parts and ensure proper file formatting
|
||||
if (parts.length === 0) return "";
|
||||
if (parts.length === 1) return parts[0] + "\n";
|
||||
|
||||
// For multiple parts, join with newlines and add trailing newline
|
||||
return parts.join("\n") + "\n";
|
||||
}
|
||||
|
||||
visitAnnotations(annotations: CSTNode[], ctx: PrintContext): string {
|
||||
return annotations.map((ann) => this.visitor.visit(ann, ctx)).join(" ");
|
||||
}
|
||||
|
||||
visitAnnotation(node: CSTNode, ctx: PrintContext): string {
|
||||
const qualifiedIdentifier = getFirstChild(node, "qualifiedIdentifier");
|
||||
let result =
|
||||
"@" +
|
||||
(qualifiedIdentifier ? this.visitor.visit(qualifiedIdentifier, ctx) : "");
|
||||
|
||||
// Handle multiple parameter lists: @Inject() or @Inject()(val x: Type)
|
||||
const leftParens = getChildNodes(node, "LeftParen");
|
||||
|
||||
if (leftParens.length > 0) {
|
||||
const annotationArguments = getChildNodes(node, "annotationArgument");
|
||||
let argIndex = 0;
|
||||
|
||||
// Process each parameter list
|
||||
for (let i = 0; i < leftParens.length; i++) {
|
||||
result += "(";
|
||||
|
||||
// Determine how many arguments are in this parameter list
|
||||
// We need to group arguments by parameter list
|
||||
const argsInThisList: CSTNode[] = [];
|
||||
|
||||
// For simplicity, distribute arguments evenly across parameter lists
|
||||
// In practice, this should be based on actual parsing structure
|
||||
const argsPerList = Math.ceil(
|
||||
annotationArguments.length / leftParens.length,
|
||||
);
|
||||
const endIndex = Math.min(
|
||||
argIndex + argsPerList,
|
||||
annotationArguments.length,
|
||||
);
|
||||
|
||||
for (let j = argIndex; j < endIndex; j++) {
|
||||
argsInThisList.push(annotationArguments[j]);
|
||||
}
|
||||
argIndex = endIndex;
|
||||
|
||||
if (argsInThisList.length > 0) {
|
||||
const args = argsInThisList.map((arg: CSTNode) =>
|
||||
this.visitor.visit(arg, ctx),
|
||||
);
|
||||
result += args.join(", ");
|
||||
}
|
||||
|
||||
result += ")";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitAnnotationArgument(node: CSTNode, ctx: PrintContext): string {
|
||||
const valTokens = getChildNodes(node, "Val");
|
||||
const varTokens = getChildNodes(node, "Var");
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
const colons = getChildNodes(node, "Colon");
|
||||
const equals = getChildNodes(node, "Equals");
|
||||
const expressions = getChildNodes(node, "expression");
|
||||
const types = getChildNodes(node, "type");
|
||||
|
||||
// Parameter declaration: val x: Type or var y: Type
|
||||
if (
|
||||
(valTokens.length > 0 || varTokens.length > 0) &&
|
||||
identifiers.length > 0 &&
|
||||
colons.length > 0 &&
|
||||
types.length > 0
|
||||
) {
|
||||
let result = valTokens.length > 0 ? "val " : "var ";
|
||||
result += getNodeImage(identifiers[0]);
|
||||
result += ": ";
|
||||
result += this.visitor.visit(types[0], ctx);
|
||||
|
||||
// Optional default value
|
||||
if (equals.length > 0 && expressions.length > 0) {
|
||||
result += " = " + this.visitor.visit(expressions[0], ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
// Named argument: name = value
|
||||
else if (
|
||||
identifiers.length > 0 &&
|
||||
equals.length > 0 &&
|
||||
expressions.length > 0
|
||||
) {
|
||||
return (
|
||||
getNodeImage(identifiers[0]) +
|
||||
" = " +
|
||||
this.visitor.visit(expressions[0], ctx)
|
||||
);
|
||||
}
|
||||
// Positional argument
|
||||
else if (expressions.length > 0) {
|
||||
return this.visitor.visit(expressions[0], ctx);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitModifiers(modifiers: CSTNode[], ctx: PrintContext): string {
|
||||
return modifiers.map((mod) => this.visitor.visit(mod, ctx)).join(" ");
|
||||
}
|
||||
|
||||
visitDefinition(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle annotations
|
||||
const annotations = getChildNodes(node, "annotation");
|
||||
if (annotations.length > 0) {
|
||||
const annotationStr = this.visitAnnotations(annotations, ctx);
|
||||
result += annotationStr + " ";
|
||||
}
|
||||
|
||||
// Handle modifiers
|
||||
const modifiers = getChildNodes(node, "modifier");
|
||||
if (modifiers.length > 0) {
|
||||
const modifierStr = this.visitModifiers(modifiers, ctx);
|
||||
result += modifierStr + " ";
|
||||
}
|
||||
|
||||
// Handle specific definition types
|
||||
const classDefinition = getFirstChild(node, "classDefinition");
|
||||
if (classDefinition) {
|
||||
result += this.visitor.visit(classDefinition, ctx);
|
||||
} else {
|
||||
const objectDefinition = getFirstChild(node, "objectDefinition");
|
||||
if (objectDefinition) {
|
||||
result += this.visitor.visit(objectDefinition, ctx);
|
||||
} else {
|
||||
const traitDefinition = getFirstChild(node, "traitDefinition");
|
||||
if (traitDefinition) {
|
||||
result += this.visitor.visit(traitDefinition, ctx);
|
||||
} else {
|
||||
const enumDefinition = getFirstChild(node, "enumDefinition");
|
||||
if (enumDefinition) {
|
||||
result += this.visitor.visit(enumDefinition, ctx);
|
||||
} else {
|
||||
const extensionDefinition = getFirstChild(
|
||||
node,
|
||||
"extensionDefinition",
|
||||
);
|
||||
if (extensionDefinition) {
|
||||
result += this.visitor.visit(extensionDefinition, ctx);
|
||||
} else {
|
||||
const valDefinition = getFirstChild(node, "valDefinition");
|
||||
if (valDefinition) {
|
||||
result += this.visitor.visit(valDefinition, ctx);
|
||||
} else {
|
||||
const varDefinition = getFirstChild(node, "varDefinition");
|
||||
if (varDefinition) {
|
||||
result += this.visitor.visit(varDefinition, ctx);
|
||||
} else {
|
||||
const defDefinition = getFirstChild(node, "defDefinition");
|
||||
if (defDefinition) {
|
||||
result += this.visitor.visit(defDefinition, ctx);
|
||||
} else {
|
||||
const givenDefinition = getFirstChild(
|
||||
node,
|
||||
"givenDefinition",
|
||||
);
|
||||
if (givenDefinition) {
|
||||
result += this.visitor.visit(givenDefinition, ctx);
|
||||
} else {
|
||||
const typeDefinition = getFirstChild(
|
||||
node,
|
||||
"typeDefinition",
|
||||
);
|
||||
if (typeDefinition) {
|
||||
result += this.visitor.visit(typeDefinition, ctx);
|
||||
} else {
|
||||
const assignmentStatement = getFirstChild(
|
||||
node,
|
||||
"assignmentStatement",
|
||||
);
|
||||
if (assignmentStatement) {
|
||||
result += this.visitor.visit(
|
||||
assignmentStatement,
|
||||
ctx,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitPattern(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
return getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
const underscores = getChildNodes(node, "Underscore");
|
||||
if (underscores.length > 0) {
|
||||
return "_";
|
||||
}
|
||||
|
||||
const literal = getFirstChild(node, "literal");
|
||||
if (literal) {
|
||||
return this.visitor.visit(literal, ctx);
|
||||
}
|
||||
|
||||
const leftParens = getChildNodes(node, "LeftParen");
|
||||
if (leftParens.length > 0) {
|
||||
// Tuple pattern or parenthesized pattern
|
||||
const patterns = getChildNodes(node, "pattern");
|
||||
if (patterns.length > 1) {
|
||||
const patternResults = patterns.map((p: CSTNode) =>
|
||||
this.visitor.visit(p, ctx),
|
||||
);
|
||||
return "(" + patternResults.join(", ") + ")";
|
||||
} else if (patterns.length === 1) {
|
||||
return "(" + this.visitor.visit(patterns[0], ctx) + ")";
|
||||
}
|
||||
}
|
||||
|
||||
const patterns = getChildNodes(node, "pattern");
|
||||
if (patterns.length > 0) {
|
||||
// Constructor pattern or other complex patterns
|
||||
return this.visitor.visit(patterns[0], ctx);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
474
frontend/src/common/prettier/plugins/scala/visitor/types.ts
Normal file
474
frontend/src/common/prettier/plugins/scala/visitor/types.ts
Normal file
@@ -0,0 +1,474 @@
|
||||
/**
|
||||
* Type-related visitor methods for handling type expressions, type parameters, and type systems
|
||||
*/
|
||||
import { getChildNodes, getFirstChild, getNodeImage } from "./utils";
|
||||
import type { PrintContext, CSTNode } from "./utils";
|
||||
|
||||
export interface TypeVisitor {
|
||||
visit(node: CSTNode, ctx: PrintContext): string;
|
||||
}
|
||||
|
||||
export class TypeVisitorMethods {
|
||||
private visitor: TypeVisitor;
|
||||
|
||||
constructor(visitor: TypeVisitor) {
|
||||
this.visitor = visitor;
|
||||
}
|
||||
|
||||
visitType(node: CSTNode, ctx: PrintContext): string {
|
||||
const matchType = getFirstChild(node, "matchType");
|
||||
return matchType ? this.visitor.visit(matchType, ctx) : "";
|
||||
}
|
||||
|
||||
visitMatchType(node: CSTNode, ctx: PrintContext): string {
|
||||
const unionType = getFirstChild(node, "unionType");
|
||||
let result = unionType ? this.visitor.visit(unionType, ctx) : "";
|
||||
|
||||
const matchTokens = getChildNodes(node, "Match");
|
||||
if (matchTokens.length > 0) {
|
||||
result += " match {";
|
||||
const matchTypeCases = getChildNodes(node, "matchTypeCase");
|
||||
if (matchTypeCases.length > 0) {
|
||||
for (const caseNode of matchTypeCases) {
|
||||
result += "\n " + this.visitor.visit(caseNode, ctx);
|
||||
}
|
||||
result += "\n";
|
||||
}
|
||||
result += "}";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitMatchTypeCase(node: CSTNode, ctx: PrintContext): string {
|
||||
const types = getChildNodes(node, "type");
|
||||
if (types.length >= 2) {
|
||||
const leftType = this.visitor.visit(types[0], ctx);
|
||||
const rightType = this.visitor.visit(types[1], ctx);
|
||||
return `case ${leftType} => ${rightType}`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
visitUnionType(node: CSTNode, ctx: PrintContext): string {
|
||||
const types = getChildNodes(node, "intersectionType");
|
||||
if (types.length === 1) {
|
||||
return this.visitor.visit(types[0], ctx);
|
||||
}
|
||||
|
||||
const typeStrings = types.map((t: CSTNode) => this.visitor.visit(t, ctx));
|
||||
return typeStrings.join(" | ");
|
||||
}
|
||||
|
||||
visitIntersectionType(node: CSTNode, ctx: PrintContext): string {
|
||||
const types = getChildNodes(node, "baseType");
|
||||
if (types.length === 1) {
|
||||
return this.visitor.visit(types[0], ctx);
|
||||
}
|
||||
|
||||
const typeStrings = types.map((t: CSTNode) => this.visitor.visit(t, ctx));
|
||||
return typeStrings.join(" & ");
|
||||
}
|
||||
|
||||
visitContextFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle parenthesized types
|
||||
const leftParen = getChildNodes(node, "LeftParen");
|
||||
if (leftParen.length > 0) {
|
||||
const tupleType = getFirstChild(node, "tupleTypeOrParenthesized");
|
||||
if (tupleType) {
|
||||
result += "(" + this.visitor.visit(tupleType, ctx) + ")";
|
||||
}
|
||||
} else {
|
||||
// Handle simple types
|
||||
const simpleType = getFirstChild(node, "simpleType");
|
||||
if (simpleType) {
|
||||
result += this.visitor.visit(simpleType, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
const type = getFirstChild(node, "type");
|
||||
if (type) {
|
||||
result += " ?=> " + this.visitor.visit(type, ctx);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
visitBaseType(node: CSTNode, ctx: PrintContext): string {
|
||||
// Handle type lambda: [X] =>> F[X]
|
||||
const typeLambda = getFirstChild(node, "typeLambda");
|
||||
if (typeLambda) {
|
||||
return this.visitor.visit(typeLambda, ctx);
|
||||
}
|
||||
|
||||
// Handle polymorphic function type: [T] => T => T
|
||||
const polymorphicFunctionType = getFirstChild(
|
||||
node,
|
||||
"polymorphicFunctionType",
|
||||
);
|
||||
if (polymorphicFunctionType) {
|
||||
return this.visitor.visit(polymorphicFunctionType, ctx);
|
||||
}
|
||||
|
||||
// Handle context function type: String ?=> Int
|
||||
const contextFunctionType = getFirstChild(node, "contextFunctionType");
|
||||
if (contextFunctionType) {
|
||||
return this.visitor.visit(contextFunctionType, ctx);
|
||||
}
|
||||
|
||||
// Handle dependent function type: (x: Int) => Vector[x.type]
|
||||
const dependentFunctionType = getFirstChild(node, "dependentFunctionType");
|
||||
if (dependentFunctionType) {
|
||||
return this.visitor.visit(dependentFunctionType, ctx);
|
||||
}
|
||||
|
||||
// Handle parenthesized types or tuple types: (String | Int) or (A, B)
|
||||
const leftParen = getChildNodes(node, "LeftParen");
|
||||
const tupleType = getFirstChild(node, "tupleTypeOrParenthesized");
|
||||
if (leftParen.length > 0 && tupleType) {
|
||||
return "(" + this.visitor.visit(tupleType, ctx) + ")";
|
||||
}
|
||||
|
||||
// Handle simple types with array notation
|
||||
const simpleType = getFirstChild(node, "simpleType");
|
||||
let result = "";
|
||||
|
||||
if (simpleType) {
|
||||
result = this.visitor.visit(simpleType, ctx);
|
||||
} else {
|
||||
// Handle direct token cases like Array, List, etc.
|
||||
if ("children" in node && node.children) {
|
||||
const children = node.children;
|
||||
for (const [key, tokens] of Object.entries(children)) {
|
||||
if (
|
||||
Array.isArray(tokens) &&
|
||||
tokens.length > 0 &&
|
||||
"image" in tokens[0]
|
||||
) {
|
||||
// Check if this is a type name token (not brackets or keywords)
|
||||
if (
|
||||
!["LeftBracket", "RightBracket", "typeArgument"].includes(key)
|
||||
) {
|
||||
result = getNodeImage(tokens[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Handle array types like Array[String]
|
||||
const leftBrackets = getChildNodes(node, "LeftBracket");
|
||||
const typeArguments = getChildNodes(node, "typeArgument");
|
||||
for (let i = 0; i < leftBrackets.length && i < typeArguments.length; i++) {
|
||||
result += "[" + this.visitor.visit(typeArguments[i], ctx) + "]";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTupleTypeOrParenthesized(node: CSTNode, ctx: PrintContext): string {
|
||||
const types = getChildNodes(node, "type");
|
||||
if (types.length === 1) {
|
||||
return this.visitor.visit(types[0], ctx);
|
||||
}
|
||||
|
||||
const typeStrings = types.map((t: CSTNode) => this.visitor.visit(t, ctx));
|
||||
return typeStrings.join(", ");
|
||||
}
|
||||
|
||||
visitSimpleType(node: CSTNode, ctx: PrintContext): string {
|
||||
const qualifiedId = getFirstChild(node, "qualifiedIdentifier");
|
||||
if (!qualifiedId) {
|
||||
return "";
|
||||
}
|
||||
let result = this.visitor.visit(qualifiedId, ctx);
|
||||
|
||||
// Handle type parameters like List[Int] or Kind Projector like Map[String, *]
|
||||
const leftBrackets = getChildNodes(node, "LeftBracket");
|
||||
if (leftBrackets.length > 0) {
|
||||
const typeArgs = getChildNodes(node, "typeArgument");
|
||||
const typeStrings = typeArgs.map((t: CSTNode) =>
|
||||
this.visitor.visit(t, ctx),
|
||||
);
|
||||
result += "[" + typeStrings.join(", ") + "]";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTypeArgument(node: CSTNode, ctx: PrintContext): string {
|
||||
// Handle Kind Projector notation: *
|
||||
const star = getChildNodes(node, "Star");
|
||||
if (star.length > 0) {
|
||||
return "*";
|
||||
}
|
||||
|
||||
// Handle regular type
|
||||
const type = getFirstChild(node, "type");
|
||||
if (type) {
|
||||
return this.visitor.visit(type, ctx);
|
||||
}
|
||||
|
||||
// Handle type argument union structure
|
||||
const typeArgumentUnion = getFirstChild(node, "typeArgumentUnion");
|
||||
if (typeArgumentUnion) {
|
||||
return this.visitor.visit(typeArgumentUnion, ctx);
|
||||
}
|
||||
|
||||
// Handle direct type tokens like Array[t] within type arguments
|
||||
if ("children" in node && node.children) {
|
||||
const children = node.children;
|
||||
let result = "";
|
||||
|
||||
// Find the type name token
|
||||
for (const [key, tokens] of Object.entries(children)) {
|
||||
if (
|
||||
Array.isArray(tokens) &&
|
||||
tokens.length > 0 &&
|
||||
"image" in tokens[0]
|
||||
) {
|
||||
if (!["LeftBracket", "RightBracket", "typeArgument"].includes(key)) {
|
||||
result = getNodeImage(tokens[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result) {
|
||||
// Handle type parameters like Array[t] within type arguments
|
||||
const leftBrackets = getChildNodes(node, "LeftBracket");
|
||||
const typeArguments = getChildNodes(node, "typeArgument");
|
||||
for (
|
||||
let i = 0;
|
||||
i < leftBrackets.length && i < typeArguments.length;
|
||||
i++
|
||||
) {
|
||||
result += "[" + this.visitor.visit(typeArguments[i], ctx) + "]";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitTypeLambda(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "[";
|
||||
|
||||
const parameters = getChildNodes(node, "typeLambdaParameter");
|
||||
if (parameters.length > 0) {
|
||||
const parameterStrings = parameters.map((param: CSTNode) =>
|
||||
this.visitor.visit(param, ctx),
|
||||
);
|
||||
result += parameterStrings.join(", ");
|
||||
}
|
||||
|
||||
result += "] =>> ";
|
||||
const type = getFirstChild(node, "type");
|
||||
if (type) {
|
||||
result += this.visitor.visit(type, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTypeLambdaParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Add variance annotation if present
|
||||
const plus = getChildNodes(node, "Plus");
|
||||
const minus = getChildNodes(node, "Minus");
|
||||
if (plus.length > 0) {
|
||||
result += "+";
|
||||
} else if (minus.length > 0) {
|
||||
result += "-";
|
||||
}
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
result += getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
const subtypeOf = getChildNodes(node, "SubtypeOf");
|
||||
const supertypeOf = getChildNodes(node, "SupertypeOf");
|
||||
const type = getFirstChild(node, "type");
|
||||
|
||||
if (subtypeOf.length > 0 && type) {
|
||||
result += " <: " + this.visitor.visit(type, ctx);
|
||||
} else if (supertypeOf.length > 0 && type) {
|
||||
result += " >: " + this.visitor.visit(type, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitDependentFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "(";
|
||||
|
||||
const parameters = getChildNodes(node, "dependentParameter");
|
||||
if (parameters.length > 0) {
|
||||
const parameterStrings = parameters.map((param: CSTNode) =>
|
||||
this.visitor.visit(param, ctx),
|
||||
);
|
||||
result += parameterStrings.join(", ");
|
||||
}
|
||||
|
||||
result += ") => ";
|
||||
const type = getFirstChild(node, "type");
|
||||
if (type) {
|
||||
result += this.visitor.visit(type, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitDependentParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let result = getNodeImage(identifiers[0]);
|
||||
const type = getFirstChild(node, "type");
|
||||
if (type) {
|
||||
result += ": " + this.visitor.visit(type, ctx);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
visitPolymorphicFunctionType(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "[";
|
||||
|
||||
const parameters = getChildNodes(node, "polymorphicTypeParameter");
|
||||
if (parameters.length > 0) {
|
||||
const parameterStrings = parameters.map((param: CSTNode) =>
|
||||
this.visitor.visit(param, ctx),
|
||||
);
|
||||
result += parameterStrings.join(", ");
|
||||
}
|
||||
|
||||
result += "] => ";
|
||||
const type = getFirstChild(node, "type");
|
||||
if (type) {
|
||||
result += this.visitor.visit(type, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitPolymorphicTypeParameter(node: CSTNode, ctx: PrintContext): string {
|
||||
let result = "";
|
||||
|
||||
// Handle variance annotation
|
||||
const plus = getChildNodes(node, "Plus");
|
||||
const minus = getChildNodes(node, "Minus");
|
||||
if (plus.length > 0) {
|
||||
result += "+";
|
||||
} else if (minus.length > 0) {
|
||||
result += "-";
|
||||
}
|
||||
|
||||
const identifiers = getChildNodes(node, "Identifier");
|
||||
if (identifiers.length > 0) {
|
||||
result += getNodeImage(identifiers[0]);
|
||||
}
|
||||
|
||||
// Handle type bounds
|
||||
const subtypeOf = getChildNodes(node, "SubtypeOf");
|
||||
const supertypeOf = getChildNodes(node, "SupertypeOf");
|
||||
const type = getFirstChild(node, "type");
|
||||
|
||||
if (subtypeOf.length > 0 && type) {
|
||||
result += " <: " + this.visitor.visit(type, ctx);
|
||||
}
|
||||
if (supertypeOf.length > 0 && type) {
|
||||
result += " >: " + this.visitor.visit(type, ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
visitTypeArgumentUnion(node: CSTNode, ctx: PrintContext): string {
|
||||
const typeArgumentIntersections = getChildNodes(
|
||||
node,
|
||||
"typeArgumentIntersection",
|
||||
);
|
||||
|
||||
if (typeArgumentIntersections.length === 1) {
|
||||
return this.visitor.visit(typeArgumentIntersections[0], ctx);
|
||||
}
|
||||
|
||||
// Handle union types with | operator
|
||||
if (typeArgumentIntersections.length > 1) {
|
||||
const typeStrings = typeArgumentIntersections.map((t: CSTNode) =>
|
||||
this.visitor.visit(t, ctx),
|
||||
);
|
||||
return typeStrings.join(" | ");
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitTypeArgumentIntersection(node: CSTNode, ctx: PrintContext): string {
|
||||
const typeArgumentSimples = getChildNodes(node, "typeArgumentSimple");
|
||||
|
||||
if (typeArgumentSimples.length === 1) {
|
||||
return this.visitor.visit(typeArgumentSimples[0], ctx);
|
||||
}
|
||||
|
||||
// Handle intersection types with & operator
|
||||
if (typeArgumentSimples.length > 1) {
|
||||
const typeStrings = typeArgumentSimples.map((t: CSTNode) =>
|
||||
this.visitor.visit(t, ctx),
|
||||
);
|
||||
return typeStrings.join(" & ");
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
visitTypeArgumentSimple(node: CSTNode, ctx: PrintContext): string {
|
||||
const qualifiedIdentifier = getFirstChild(node, "qualifiedIdentifier");
|
||||
if (qualifiedIdentifier) {
|
||||
let result = this.visitor.visit(qualifiedIdentifier, ctx);
|
||||
|
||||
// Handle type parameters like List[*] within type arguments
|
||||
const leftBrackets = getChildNodes(node, "LeftBracket");
|
||||
if (leftBrackets.length > 0) {
|
||||
const typeArgs = getChildNodes(node, "typeArgument");
|
||||
const typeStrings = typeArgs.map((t: CSTNode) =>
|
||||
this.visitor.visit(t, ctx),
|
||||
);
|
||||
result += "[" + typeStrings.join(", ") + "]";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle simple type structures like List[*]
|
||||
const simpleType = getFirstChild(node, "simpleType");
|
||||
if (simpleType) {
|
||||
return this.visitor.visit(simpleType, ctx);
|
||||
}
|
||||
|
||||
// Handle base type structures
|
||||
const baseType = getFirstChild(node, "baseType");
|
||||
if (baseType) {
|
||||
return this.visitor.visit(baseType, ctx);
|
||||
}
|
||||
|
||||
// Handle other type argument patterns
|
||||
const identifier = getFirstChild(node, "Identifier");
|
||||
if (identifier) {
|
||||
return getNodeImage(identifier);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
295
frontend/src/common/prettier/plugins/scala/visitor/utils.ts
Normal file
295
frontend/src/common/prettier/plugins/scala/visitor/utils.ts
Normal file
@@ -0,0 +1,295 @@
|
||||
import type { ScalaCstNode, IToken } from "../scala-parser";
|
||||
|
||||
/**
|
||||
* ビジターパターンで使用する共有ユーティリティとフォーマットヘルパー
|
||||
*/
|
||||
|
||||
export interface PrettierOptions {
|
||||
printWidth?: number;
|
||||
tabWidth?: number;
|
||||
useTabs?: boolean;
|
||||
semi?: boolean;
|
||||
singleQuote?: boolean;
|
||||
trailingComma?: "all" | "multiline" | "none";
|
||||
scalaLineWidth?: number; // Deprecated, for backward compatibility
|
||||
}
|
||||
|
||||
// CST要素(ノードまたはトークン)のユニオン型
|
||||
export type CSTNode = ScalaCstNode | IToken;
|
||||
|
||||
export type PrintContext = {
|
||||
path: unknown;
|
||||
options: PrettierOptions;
|
||||
print: (node: CSTNode) => string;
|
||||
indentLevel: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* nullチェック付きでノードの子要素に安全にアクセス
|
||||
* @param node - 対象ノード
|
||||
* @returns 子要素のマップ
|
||||
*/
|
||||
export function getChildren(node: CSTNode): Record<string, CSTNode[]> {
|
||||
if ("children" in node && node.children) {
|
||||
return node.children as Record<string, CSTNode[]>;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* キーで指定した子ノードを安全に取得
|
||||
* @param node - 対象ノード
|
||||
* @param key - 子ノードのキー
|
||||
* @returns 子ノードの配列
|
||||
*/
|
||||
export function getChildNodes(node: CSTNode, key: string): CSTNode[] {
|
||||
return getChildren(node)[key] || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* キーで指定した最初の子ノードを安全に取得
|
||||
* @param node - 対象ノード
|
||||
* @param key - 子ノードのキー
|
||||
* @returns 最初の子ノードまたはundefined
|
||||
*/
|
||||
export function getFirstChild(node: CSTNode, key: string): CSTNode | undefined {
|
||||
const children = getChildNodes(node, key);
|
||||
return children.length > 0 ? children[0] : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* ノードのimageプロパティを安全に取得
|
||||
* @param node - 対象ノード
|
||||
* @returns imageプロパティまたは空文字列
|
||||
*/
|
||||
export function getNodeImage(node: CSTNode): string {
|
||||
if ("image" in node && node.image) {
|
||||
return node.image;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* nullまたはundefinedの可能性があるノードのimageを安全に取得
|
||||
* @param node - 対象ノード(null/undefined可)
|
||||
* @returns imageプロパティまたは空文字列
|
||||
*/
|
||||
export function getNodeImageSafe(node: CSTNode | undefined | null): string {
|
||||
if (node && "image" in node && node.image) {
|
||||
return node.image;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 有効なprintWidthを取得(scalafmt互換性をサポート)
|
||||
* @param ctx - 印刷コンテキスト
|
||||
* @returns 有効な行幅
|
||||
*/
|
||||
export function getPrintWidth(ctx: PrintContext): number {
|
||||
// PrettierのprintWidthを使用(scalafmtのmaxColumn互換)
|
||||
if (ctx.options.printWidth) {
|
||||
return ctx.options.printWidth;
|
||||
}
|
||||
|
||||
// 後方互換性のため非推奨のscalaLineWidthにフォールバック
|
||||
if (ctx.options.scalaLineWidth) {
|
||||
// 開発環境で非推奨警告を表示
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
console.warn(
|
||||
"scalaLineWidth is deprecated. Use printWidth instead for scalafmt compatibility.",
|
||||
);
|
||||
}
|
||||
return ctx.options.scalaLineWidth;
|
||||
}
|
||||
|
||||
// デフォルト値
|
||||
return 80;
|
||||
}
|
||||
|
||||
/**
|
||||
* 有効なtabWidthを取得(scalafmt互換性をサポート)
|
||||
* @param ctx - 印刷コンテキスト
|
||||
* @returns 有効なタブ幅
|
||||
*/
|
||||
export function getTabWidth(ctx: PrintContext): number {
|
||||
// PrettierのtabWidthを使用(scalafmtのindent.main互換)
|
||||
if (ctx.options.tabWidth) {
|
||||
return ctx.options.tabWidth;
|
||||
}
|
||||
|
||||
// デフォルト値
|
||||
return 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* セミコロンのフォーマットを処理(Prettierのsemiオプションをサポート)
|
||||
* @param statement - ステートメント文字列
|
||||
* @param ctx - 印刷コンテキスト
|
||||
* @returns フォーマット済みのステートメント
|
||||
*/
|
||||
export function formatStatement(statement: string, ctx: PrintContext): string {
|
||||
// Prettierのsemiオプションを使用
|
||||
// プラグインはScala用にデフォルトsemi=falseを設定するが、明示的なユーザー選択を尊重
|
||||
const useSemi = ctx.options.semi === true;
|
||||
|
||||
// 既存の末尾セミコロンを削除
|
||||
const cleanStatement = statement.replace(/;\s*$/, "");
|
||||
|
||||
// リクエストされた場合セミコロンを追加
|
||||
if (useSemi) {
|
||||
return cleanStatement + ";";
|
||||
}
|
||||
|
||||
return cleanStatement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文字列クォートのフォーマットを処理(PrettierのsingleQuoteオプションをサポート)
|
||||
* @param content - 文字列リテラルの内容
|
||||
* @param ctx - 印刷コンテキスト
|
||||
* @returns フォーマット済みの文字列
|
||||
*/
|
||||
export function formatStringLiteral(
|
||||
content: string,
|
||||
ctx: PrintContext,
|
||||
): string {
|
||||
// PrettierのsingleQuoteオプションを使用
|
||||
const useSingleQuote = ctx.options.singleQuote === true;
|
||||
|
||||
// 文字列補間をスキップ(s"、f"、raw"などで始まる)
|
||||
if (content.match(/^[a-zA-Z]"/)) {
|
||||
return content; // 補間文字列は変更しない
|
||||
}
|
||||
|
||||
// 内容を抽出
|
||||
let innerContent = content;
|
||||
|
||||
if (content.startsWith('"') && content.endsWith('"')) {
|
||||
innerContent = content.slice(1, -1);
|
||||
} else if (content.startsWith("'") && content.endsWith("'")) {
|
||||
innerContent = content.slice(1, -1);
|
||||
} else {
|
||||
return content; // Not a string literal
|
||||
}
|
||||
|
||||
// Choose target quote based on option
|
||||
const targetQuote = useSingleQuote ? "'" : '"';
|
||||
|
||||
// Handle escaping if necessary
|
||||
if (targetQuote === "'") {
|
||||
// Converting to single quotes: escape single quotes, unescape double quotes
|
||||
innerContent = innerContent.replace(/\\"/g, '"').replace(/'/g, "\\'");
|
||||
} else {
|
||||
// Converting to double quotes: escape double quotes, unescape single quotes
|
||||
innerContent = innerContent.replace(/\\'/g, "'").replace(/"/g, '\\"');
|
||||
}
|
||||
|
||||
return targetQuote + innerContent + targetQuote;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to handle indentation using configured tab width
|
||||
*/
|
||||
export function createIndent(level: number, ctx: PrintContext): string {
|
||||
const tabWidth = getTabWidth(ctx);
|
||||
const useTabs = ctx.options.useTabs === true;
|
||||
|
||||
if (useTabs) {
|
||||
return "\t".repeat(level);
|
||||
} else {
|
||||
return " ".repeat(level * tabWidth);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to handle trailing comma formatting
|
||||
*/
|
||||
export function formatTrailingComma(
|
||||
elements: string[],
|
||||
ctx: PrintContext,
|
||||
isMultiline: boolean = false,
|
||||
): string {
|
||||
if (elements.length === 0) return "";
|
||||
|
||||
const trailingComma = ctx.options.trailingComma;
|
||||
|
||||
if (
|
||||
trailingComma === "all" ||
|
||||
(trailingComma === "multiline" && isMultiline)
|
||||
) {
|
||||
return elements.join(", ") + ",";
|
||||
}
|
||||
|
||||
return elements.join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach original comments to the formatted result
|
||||
*/
|
||||
export function attachOriginalComments(
|
||||
result: string,
|
||||
originalComments: CSTNode[],
|
||||
): string {
|
||||
if (!originalComments || originalComments.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const lines = result.split("\n");
|
||||
const commentMap = new Map<number, string[]>();
|
||||
|
||||
// Group comments by line number
|
||||
originalComments.forEach((comment) => {
|
||||
const line = ("startLine" in comment && comment.startLine) || 1;
|
||||
if (!commentMap.has(line)) {
|
||||
commentMap.set(line, []);
|
||||
}
|
||||
let commentText = "";
|
||||
if ("image" in comment && comment.image) {
|
||||
commentText = comment.image;
|
||||
} else if ("value" in comment && comment.value) {
|
||||
commentText = String(comment.value);
|
||||
}
|
||||
if (commentText) {
|
||||
commentMap.get(line)!.push(commentText);
|
||||
}
|
||||
});
|
||||
|
||||
// Insert comments into lines
|
||||
const resultLines: string[] = [];
|
||||
lines.forEach((line, index) => {
|
||||
const lineNumber = index + 1;
|
||||
if (commentMap.has(lineNumber)) {
|
||||
const comments = commentMap.get(lineNumber)!;
|
||||
comments.forEach((comment) => {
|
||||
resultLines.push(comment);
|
||||
});
|
||||
}
|
||||
resultLines.push(line);
|
||||
});
|
||||
|
||||
return resultLines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Format method or class parameters with proper line breaks
|
||||
*/
|
||||
export function formatParameterList(
|
||||
parameters: CSTNode[],
|
||||
ctx: PrintContext,
|
||||
visitFn: (param: CSTNode, ctx: PrintContext) => string,
|
||||
): string {
|
||||
if (parameters.length === 0) return "";
|
||||
|
||||
const paramStrings = parameters.map((param) => visitFn(param, ctx));
|
||||
const printWidth = getPrintWidth(ctx);
|
||||
const joined = paramStrings.join(", ");
|
||||
|
||||
// If the line is too long, break into multiple lines
|
||||
if (joined.length > printWidth * 0.7) {
|
||||
const indent = createIndent(1, ctx);
|
||||
return "\n" + indent + paramStrings.join(",\n" + indent) + "\n";
|
||||
}
|
||||
|
||||
return joined;
|
||||
}
|
||||
Reference in New Issue
Block a user